问:
Creating a menu in iOS
I'm currently creating an update of my iOS application and I'm a bit stuck. I've tried to googling around but cannot find a decent answer on this.

I've a menu which links to different views. And I'm not really sure if I've done it the best method.

I've created a view, and added the links into a stack view. Should I considering changing it all to a tableview? or a collection view? Or maybe there's another way?

The current look:

Should I change this to a tableview? collection view? or something else? Or just let it stay as it is?

答:
If the number of items in your menu changes at runtime and is large, you should use a table view, because a table view is good for efficiently displaying a screen's worth of items from a large list of items.

If the contents of your menu is small (under maybe two screenfuls of items) and fixed at compile time and you are using a storyboard, then you could use a table view with static cells, if you can make it look the way you want.

If the contents of your menu is small, then you can use a stack view (inside a scroll view) if that is easier for you. There is no particular advantage to using a table view over a stack view to display a small amount of content, unless you need other features of the table view (like the ability to select/deselect rows).

Based on the screen shot you posted, I'd either use a table view with static cells (since the screen shot is from a storyboard) or a stack view, depending on whether I can get the appearance I want from a table view. If, as in the screen shot, the buttons must be centered vertically, I'd use a stack view, because it's easier to vertically center the content with a stack view.

Title: Creating a menu in iOS


来源: stackexchange

问:
Can Web-bluetooth provision nodes in a BLE-mesh?
I have a web-app that needs to communicate with about 48 BLE devices in a BLE-mesh.

I found that Web-bluetooth can work with one bluetooth device, but could not find if there is a way to provision BLE-mesh and then send messages to nodes in the mesh with Web-bluetooth.

If it matters, I am putting it here for information, that the web-app is an Angular app written in Typescript. For Web-bluetooth, I am using this library https://github.com/manekinekko/angular-web-bluetooth.

答:
https://github.com/aircable/SmartMesh "Bluetooth SmartMesh Controller lets you interact with the smart mesh from your iPhone, Android, or from Chrome."

Via Michael Lawton's comment referencing this discussion thread:
https://developer.qualcomm.com/forum/qdn-forums/hardware/bluetooth-connectivity-iot/csr101x-product-family/csrmesh-development-k-59

I have not verified this.

I see that it is using:
const MESH_SERVICE_UUID                     = 0xFEF1

Which isn't org.bluetooth.service.mesh_provisioning 0x1827

Next steps are likely to attempt using Web Bluetooth with org.bluetooth.service.mesh_provisioning service.

ContentLicense: CC BY-SA 4.0


问:
pandas datareader pulling from 'morningstar' results in 404 (was fine 7/27/2018)
I assume the Morningstar API URL panda's is pulling from is no longer available. Can anyone recommend a replacement?

My code (which worked on 7/27/2018);

df = web.DataReader(ticker, 'morningstar', start, end)

Is causing error message:

File "C:...\site-packages\pandas_datareader\mstar\daily.py", line 130, in _dl_mult_symbols
      resp.status_code, resp.reason))

Exception: Request Error!: 404 : Not Found

The 404 is coming from lines 91-94 in daily.py;

```<code>def url(self):
    """API URL"""
    return "http://globalquote.morningstar.com/globalcomponent/" \
           "RealtimeHistoricalStockData.ashx"
</code>```

答:
try to update your "pandas_datereader"
and then use "stooq" or "iex" instead of "morningstar":

df = web.DataReader("TSLA", 'stooq', start, end)
df = web.DataReader("TSLA", 'iex', start, end)

hope that helps!

Body:
I assume the Morningstar API URL panda's is pulling from is no longer available. Can anyone recommend a replacement?

My code (which worked on 7/27/2018);

df = web.DataReader(ticker, 'morningstar', start, end)

Is causing error message:

File "C:...\site-packages\pandas_datareader\mstar\daily.py", line 130, in _dl_mult_symbols
      resp.status_code, resp.reason))

Exception: Request Error!: 404 : Not Found

The 404 is coming from lines 91-94 in daily.py;

def url(self):
    """API URL"""
    return "http://globalquote.morningstar.com/globalcomponent/" \
           "RealtimeHistoricalStockData.ashx"


问:
Is it possible to perform a select into table of object type?
So i have a type

```<code>create or replace type body T_Some_type is object
  (...fields)
</code>```

and i have a table type made of rows of type T_Some_type

```<code>create or replace TYPE T_Some_Table IS TABLE OF T_Some_type;
</code>```

and i would like to select rows from some view to this T_Some_Table

```<code>select *
        into T_Some_Table
        from V_Some_View
</code>```

Is this even possible, and are there any cons for doing it this way (if possible at all).
Do columns in T_Some_Type have to be in same order as in V_Some_View or will plsql do binding here if names of columns are the same?

If not possible, what would be alternative?

Edit : Having bodies defined is assumed, they are not here as they are not relevant to the question.

答:
you can set fields from select by example</p>

```<code>CREATE OR REPLACE TYPE t_some_type AS OBJECT(f varchar2(10), y varchar2(10))
/

CREATE OR REPLACE TYPE t_some_table IS TABLE OF t_some_type
/

DECLARE
   v_some_table t_some_table;
   v_counter int;
BEGIN
   SELECT t_some_type (column_1, column_2)
   BULK   COLLECT INTO v_some_table
   FROM   some_table;

   -- show the count data fetched

   dbms_output.put_line( 'counter value: ' || to_char(v_counter));

END;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So i have a type

create or replace type body T_Some_type is object
  (...fields)

and i have a table type made of rows of type T_Some_type

create or replace TYPE T_Some_Table IS TABLE OF T_Some_type;

and i would like to select rows from some view to this T_Some_Table

select *
        into T_Some_Table
        from V_Some_View

Is this even possible, and are there any cons for doing it this way (if possible at all).
Do columns in T_Some_Type have to be in same order as in V_Some_View or will plsql do binding here if names of columns are the same?

If not possible, what would be alternative?

Edit : Having bodies defined is assumed, they are not here as they are not relevant to the question.

Body:
you can set fields from select by example

CREATE OR REPLACE TYPE t_some_type AS OBJECT(f varchar2(10), y varchar2(10))
/

CREATE OR REPLACE TYPE t_some_table IS TABLE OF t_some_type
/

DECLARE
   v_some_table t_some_table;
   v_counter int;
BEGIN
   SELECT t_some_type (column_1, column_2)
   BULK   COLLECT INTO v_some_table
   FROM   some_table;

   -- show the count data fetched

   dbms_output.put_line( 'counter value: ' || to_char(v_counter));

END;


问:
How can I check if any of my boolean variable is false in VB.NET
Can I ask if is this is the only way to check if a variable is false in VB.net?

here is my code

```<code>if a = true and b = true and c = true then
     msgbox("ok")
else if a= true and b = true and c = false then
     msgbox("c has errors")
else if a= true and b = false and c = true then
     msgbox("b has errors")
else if a= false and b = true and c = true then
     msgbox("a has errors")
end if
</code>```

答:
My approach would be to put the Booleans in an array. The loop through checking for the value = False. The index of the False values are added to lstIndexes. </p>

```<code>    Dim lstIndexes As New List(Of Integer)
    Dim bools = {a, b, c}
    For i = 0 To bools.Length - 1
        If Not bools(i) Then
            lstIndexes.Add(i)
        End If
    Next
</code>```

Body:
Can I ask if is this is the only way to check if a variable is false in VB.net?

here is my code

if a = true and b = true and c = true then
     msgbox("ok")
else if a= true and b = true and c = false then
     msgbox("c has errors")
else if a= true and b = false and c = true then
     msgbox("b has errors")
else if a= false and b = true and c = true then
     msgbox("a has errors")
end if

Body:
My approach would be to put the Booleans in an array. The loop through checking for the value = False. The index of the False values are added to lstIndexes.

    Dim lstIndexes As New List(Of Integer)
    Dim bools = {a, b, c}
    For i = 0 To bools.Length - 1
        If Not bools(i) Then
            lstIndexes.Add(i)
        End If
    Next


问:
Is it really all about message passing in smalltalk
I'm new to smalltalk and I'm impressed with the fact that there are only just 6 keywords in the language (self, super, true, false, nil & thisContext), and how pure it is in having almost everything as message passing, eg. looping using whileTrue, if/else using ifTrue, etc ... which are way different from what I'm used to in other languages.

Yet, there are cases where I just cannot make sense of how message passing really fit in, these include:

the assignment operator :=

the cascading operator ;

the period operator .

the way to create a set #( ... )

These aren't message passing, right?

答:
As you've discovered, there's still some actual Smalltalk syntax. Block construction, literal strings/symbols/comments, local variable declaration (|...|), and returning (^) are a few things you didn't mention which are also syntax.

Some extensions (e.g. #(...), which typically creates an Array, not a set) are certainly expressible otherwise, for example #(1 2 3) is equivalent to Array with: 1 with: 2 with: 3; they're just there to make the code easier to read and write.


问:
Could not find Corda FAQ page using the published URL
The "Frequently Asked Questions" document on Corda at link
"https://docs.corda.net/faq.html" says -

A list of frequently asked questions can be found here: https://discourse.corda.net/c/faq.

However on clicking the link - "https://discourse.corda.net/c/faq", the page says -

"This site can’t be reached"

Is the FAQ document available?

If yes, please share the link to that document.

答:
Discourse is no longer in use - I guess you could say that the FAQ are now somewhat here on StackOverflow :)

On a serious note, a lot of the old FAQ from discourse has now been integrated into the docs themselves.


问:
String subdivision and data return problem
in addition to returning the db2.get (i) .getEnumDesc () strings which are normal strings.
there are some strings like: 1 - Selected house in db2.get (i) .getEnumDesc ()
I have to cut -> 1 -
I have translated the selected part of the house and then reassembled it.
1 - select house

in practice, in output, not only normal strings have to be returned, but also strings with numbers, ie 1 - select house
in printed output:
es.
house
hello
1 - select
2 - bye
etc...

```<code>public void getTraduttoreIt_ENUM_NLS() throws Exception {
        List<EnumNls> db2 = getListEnumNls();
        List<DizioPt> sqlServer = getListDizioPt();

        BufferedWriter scrivi = new BufferedWriter(
                new FileWriter("C:/Users/francesco/Desktop/Table_THERA.ENUM_NLS_Sez4.txt"));
        System.out.println("-------------------WRITE FILE N°4--------TRANSLATION------------------------");
        for (int i = 0; i < db2.size(); i++) {
            for (int j = 0; j < sqlServer.size(); j++) {
                if (db2.get(i).getEnumDesc().equals(sqlServer.get(j).getKeyword())) {

                    System.out.println(
                            "INSERT INTO THERA.ENUM_NLS VALUES" + "(" + "'" + db2.get(i).getAttributeRef().trim() + "'"
                                    + "," + "'" + db2.get(i).getEnumValue().trim() + "'" + "," + "'" + "en" + "'" + ","
                                    + "'" + sqlServer.get(j).getTraduzione().trim() + "'" + ")" + ";");

                    scrivi.write("INSERT INTO THERA.ENUM_NLS VALUES" + "(" + "'" + db2.get(i).getAttributeRef().trim()
                            + "'" + "," + "'" + db2.get(i).getEnumValue().trim() + "'" + "," + "'" + "en" + "'" + ","
                            + "'" + sqlServer.get(j).getTraduzione().trim() + "'" + ")" + ";");

                    scrivi.newLine();
                    scrivi.flush();
                }
            }

        }
        scrivi.close();
    }

}
</code>```

in practice, in output, not only normal strings have to be returned, but also strings with numbers, ie 1 - select house
in printed output:
es.
house
hello
1 - select
2 - bye
etc...

答:
What error(s) are you getting?

Could the string returned from db2.get(i).getEnumValue().trim() or sqlServer.get(j).getTraduzione().trim() have a single quote (') in it?  In which case your SQL statement has a syntax error.  If this is the case, after trim() you could insert a .replaceAll("'", "''") which should solve your the problem.

So db2.get(i).getEnumValue().trim().replaceAll("'", "''") - This is ("\u0027", "\u0027\u0027")

If you are getting a number back, what you have should work, even if the number is part of the string.

Unless your data has to do with "house", I think you are using the wrong English word in describing your situation.

In any case, explain the errors you are seeing and that might help people understand your problem.

Body:
in addition to returning the db2.get (i) .getEnumDesc () strings which are normal strings.
there are some strings like: 1 - Selected house in db2.get (i) .getEnumDesc ()
I have to cut -> 1 -
I have translated the selected part of the house and then reassembled it.
1 - select house

in practice, in output, not only normal strings have to be returned, but also strings with numbers, ie 1 - select house
in printed output:
es.
house
hello
1 - select
2 - bye
etc...

public void getTraduttoreIt_ENUM_NLS() throws Exception {
        List<EnumNls> db2 = getListEnumNls();
        List<DizioPt> sqlServer = getListDizioPt();

        BufferedWriter scrivi = new BufferedWriter(
                new FileWriter("C:/Users/francesco/Desktop/Table_THERA.ENUM_NLS_Sez4.txt"));
        System.out.println("-------------------WRITE FILE N°4--------TRANSLATION------------------------");
        for (int i = 0; i < db2.size(); i++) {
            for (int j = 0; j < sqlServer.size(); j++) {
                if (db2.get(i).getEnumDesc().equals(sqlServer.get(j).getKeyword())) {

                    System.out.println(
                            "INSERT INTO THERA.ENUM_NLS VALUES" + "(" + "'" + db2.get(i).getAttributeRef().trim() + "'"
                                    + "," + "'" + db2.get(i).getEnumValue().trim() + "'" + "," + "'" + "en" + "'" + ","
                                    + "'" + sqlServer.get(j).getTraduzione().trim() + "'" + ")" + ";");

                    scrivi.write("INSERT INTO THERA.ENUM_NLS VALUES" + "(" + "'" + db2.get(i).getAttributeRef().trim()
                            + "'" + "," + "'" + db2.get(i).getEnumValue().trim() + "'" + "," + "'" + "en" + "'" + ","
                            + "'" + sqlServer.get(j).getTraduzione().trim() + "'" + ")" + ";");

                    scrivi.newLine();
                    scrivi.flush();
                }
            }

        }
        scrivi.close();
    }

}

in practice, in output, not only normal strings have to be returned, but also strings with numbers, ie 1 - select house
in printed output:
es.
house
hello
1 - select
2 - bye
etc...


问:
DescribeFunction Parameters With Variadic Template Types
I want to write a template function which takes in a function pointer and all but the last 2 arguments to that function. Something like this:

```<code>template <typename T, typename... ARGS>
void foo(void(*func)(ARGS..., T*, int*), ARGS... params);
</code>```

I'd like to do something like the following:

Given a function of the signature void bar(bool, char*, int*), I'd like to call: foo(bar, false)

Given a function of the signature void bar(bool, int*, int*), I'd like to call: foo(bar, false)

Given a function of the signature void bar(char*, int*), I'd like to call: foo(bar)

But when I try to define foo like this I get the error:

error C2672: foo: no matching overloaded function found

  error C2784: void foo(void (__cdecl *)(ARGS...,T* ,int *),ARGS...): could not deduce template argument for void (__cdecl* )(ARGS...,T *,int* ) from void (bool,char *,int* )

What can I do to help with the deduction?

答:
The reason this is not working is because ARGS... is a variadic pack, and when used for deduction it can only be used at the end of a function signature. For example, you could deduce:

```<code>void(*)(int,Args...)
</code>```

But you cannot deduce

```<code>void(*)(Args...,int)
</code>```

Since your problem requires the last argument to be a specific kind, and the second-last to be deduced specifically, you will need to deduce the entire function signature of func, and use SFINAE to prevent accidentally invoking this function with the wrong arguments.

To do that, we first need a way to extract out the nth last parameter. A simple type trait for this could be written as follows:

```<code>#include <type_traits>

// A simple type-trait that gets the Nth type from a variadic pack
// If N is negative, it extracts from the opposite end of the pack
// (e.g. -1 == the last entry)
template<int N, bool IsPositive, typename...Args>
struct extract_nth_impl;

template<typename Arg0, typename...Args>
struct extract_nth_impl<0,true,Arg0,Args...> {
  using type = Arg0;
};

template<int N, typename Arg0, typename...Args>
struct extract_nth_impl<N,true,Arg0,Args...>
  : extract_nth_impl<N-1,true,Args...>{};

template<int N, typename...Args>
struct extract_nth_impl<N,false,Args...> {
  using type = typename extract_nth_impl<(sizeof...(Args)+N),true,Args...>::type;
};

// A type-trait wrapper to avoid the need for 'typename'
template<int N, typename...Args>
using extract_nth_t = typename extract_nth_impl<N,(N>=0),Args...>::type;
</code>```

We can use this to extract the last parameter to ensure it's int*, and the second-last parameter to know it's type (T*). Then we can just use std::enable_if to SFINAE-away any bad-inputs, so that this function will fail to compile if misused.

```<code>template<
  typename...Args,
  typename...UArgs,
  typename=std::enable_if_t<
    (sizeof...(Args) >= 2) &&
    (sizeof...(Args)-2)==(sizeof...(UArgs)) &&
    std::is_same_v<extract_nth_t<-1,Args...>,int*> &&
    std::is_pointer_v<extract_nth_t<-2,Args...>>
  >
>
void foo(void(*func)(Args...), UArgs&&...params)
{
    // your code here, e.g.:
    // bar(func, std::forward<UArgs>(params)...);
}
</code>```

Note: The template and the signature has changed in the following ways:

We now have Args... and UArgs.... This is because we want to capture N arguments types for func, but we only want N-2 arguments for params

We now match void(*func)(Args...) instead of void(*func)(Args...,T*,int*). T* is no longer a template parameter

We have this long std::enable_if_t which is used to SFINAE away bad cases, such as N<2, too many params for the number of signature args, T* (second-last argument) not being a pointer, and the last signature arg being int*

But overall this works. If T was needed in the definition of the function, you can extract it easily with:

```<code>    using T = std::remove_point_t<extract_nth_t<-2,Args...>>;
</code>```

(Note: remove_pointer_t used to match only against the type, and not the pointer)

The following test cases work for me using clang-8.0 and -std=c++17:

```<code>void example1(bool, char*, int*){}
void example2(bool, int*, int*){}
void example3(char*, int*){}
void example4(char*, char*){}

int main() {
  foo(&::example1,false);
  // foo(&::example1); -- fails to compile - too few arguments (correct)
  foo(&::example2,false);
  // foo(&::example2,false,5); -- fails to compile - too many arguments (correct)
  foo(&::example3);
  // foo(&::example4); -- fails to compile - last argument is not int* (correct)
}
</code>```

Edit: As pointed out by @max66, this solution does not constrain convertible types as input to param. This does mean that it may fail if any param is not properly convertible. A separate condition to std::enable_if could be added to rectify this, if this is an important quality attribute of the API.

Body:
I want to write a template function which takes in a function pointer and all but the last 2 arguments to that function. Something like this:

template <typename T, typename... ARGS>
void foo(void(*func)(ARGS..., T*, int*), ARGS... params);

I'd like to do something like the following:

Given a function of the signature void bar(bool, char*, int*), I'd like to call: foo(bar, false)

Given a function of the signature void bar(bool, int*, int*), I'd like to call: foo(bar, false)

Given a function of the signature void bar(char*, int*), I'd like to call: foo(bar)

But when I try to define foo like this I get the error:

error C2672: foo: no matching overloaded function found

  error C2784: void foo(void (__cdecl *)(ARGS...,T* ,int *),ARGS...): could not deduce template argument for void (__cdecl* )(ARGS...,T *,int* ) from void (bool,char *,int* )

What can I do to help with the deduction?

Body:
The reason this is not working is because ARGS... is a variadic pack, and when used for deduction it can only be used at the end of a function signature. For example, you could deduce:

void(*)(int,Args...)

But you cannot deduce

void(*)(Args...,int)

Since your problem requires the last argument to be a specific kind, and the second-last to be deduced specifically, you will need to deduce the entire function signature of func, and use SFINAE to prevent accidentally invoking this function with the wrong arguments.

To do that, we first need a way to extract out the nth last parameter. A simple type trait for this could be written as follows:

#include <type_traits>

// A simple type-trait that gets the Nth type from a variadic pack
// If N is negative, it extracts from the opposite end of the pack
// (e.g. -1 == the last entry)
template<int N, bool IsPositive, typename...Args>
struct extract_nth_impl;

template<typename Arg0, typename...Args>
struct extract_nth_impl<0,true,Arg0,Args...> {
  using type = Arg0;
};

template<int N, typename Arg0, typename...Args>
struct extract_nth_impl<N,true,Arg0,Args...>
  : extract_nth_impl<N-1,true,Args...>{};

template<int N, typename...Args>
struct extract_nth_impl<N,false,Args...> {
  using type = typename extract_nth_impl<(sizeof...(Args)+N),true,Args...>::type;
};

// A type-trait wrapper to avoid the need for 'typename'
template<int N, typename...Args>
using extract_nth_t = typename extract_nth_impl<N,(N>=0),Args...>::type;

We can use this to extract the last parameter to ensure it's int*, and the second-last parameter to know it's type (T*). Then we can just use std::enable_if to SFINAE-away any bad-inputs, so that this function will fail to compile if misused.

template<
  typename...Args,
  typename...UArgs,
  typename=std::enable_if_t<
    (sizeof...(Args) >= 2) &&
    (sizeof...(Args)-2)==(sizeof...(UArgs)) &&
    std::is_same_v<extract_nth_t<-1,Args...>,int*> &&
    std::is_pointer_v<extract_nth_t<-2,Args...>>
  >
>
void foo(void(*func)(Args...), UArgs&&...params)
{
    // your code here, e.g.:
    // bar(func, std::forward<UArgs>(params)...);
}

Note: The template and the signature has changed in the following ways:

We now have Args... and UArgs.... This is because we want to capture N arguments types for func, but we only want N-2 arguments for params

We now match void(*func)(Args...) instead of void(*func)(Args...,T*,int*). T* is no longer a template parameter

We have this long std::enable_if_t which is used to SFINAE away bad cases, such as N<2, too many params for the number of signature args, T* (second-last argument) not being a pointer, and the last signature arg being int*

But overall this works. If T was needed in the definition of the function, you can extract it easily with:

    using T = std::remove_point_t<extract_nth_t<-2,Args...>>;

(Note: remove_pointer_t used to match only against the type, and not the pointer)

The following test cases work for me using clang-8.0 and -std=c++17:

void example1(bool, char*, int*){}
void example2(bool, int*, int*){}
void example3(char*, int*){}
void example4(char*, char*){}

int main() {
  foo(&::example1,false);
  // foo(&::example1); -- fails to compile - too few arguments (correct)
  foo(&::example2,false);
  // foo(&::example2,false,5); -- fails to compile - too many arguments (correct)
  foo(&::example3);
  // foo(&::example4); -- fails to compile - last argument is not int* (correct)
}

Edit: As pointed out by @max66, this solution does not constrain convertible types as input to param. This does mean that it may fail if any param is not properly convertible. A separate condition to std::enable_if could be added to rectify this, if this is an important quality attribute of the API.


问:
Jest testing with Node - Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout
I'm starting to test my code with Jest, and I can't make a seemingly simple test to pass. I am simply trying to check if what I receive from a Maogoose database request is an object.

The function fetchPosts() is working because I hooked it up with a React frontend and it is displaying the data correctly.

This is my function fetchPosts():

```<code>module.exports = {
    fetchPosts() {
        return new Promise((resolve, reject) => {
            Posts.find({}).then(posts => {
                if (posts) {
                    resolve(posts)
                } else {
                    reject()
                }
            })
        })
    }
}
</code>```

And my test:

```<code>it('should get a list of posts', function() {
    return posts.fetchPosts().then(result => {
        expect(typeof result).toBe('object')
    })
})
</code>```

This makes the test fail, and Jest says

'Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.'

QUESTION: How can I make this test pass?

答: It's also highly possible that you're not getting a response back from the DB at all from your test suite. Test suite's can call different environmental variables / configs that lead to different calls. This error can also be seen if no response is returned, as in - if someone blocks your IP from connecting, on and on.</p>

Body:
I'm starting to test my code with Jest, and I can't make a seemingly simple test to pass. I am simply trying to check if what I receive from a Maogoose database request is an object.

The function fetchPosts() is working because I hooked it up with a React frontend and it is displaying the data correctly.

This is my function fetchPosts():

module.exports = {
    fetchPosts() {
        return new Promise((resolve, reject) => {
            Posts.find({}).then(posts => {
                if (posts) {
                    resolve(posts)
                } else {
                    reject()
                }
            })
        })
    }
}

And my test:

it('should get a list of posts', function() {
    return posts.fetchPosts().then(result => {
        expect(typeof result).toBe('object')
    })
})

This makes the test fail, and Jest says

'Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.'

QUESTION: How can I make this test pass?


问:
Is there a way to run a Excel Macro on multiple worksheets to grab select range images and save them locally
I have an Excel workbook with 6 worksheets. One Worksheet holds the data and the remaining 5 have graphs created using the data worksheet. I'm looking to grab an image of the chart on each worksheet and save it on my webserver location, such that I can use that image on my website. However, I'm able to do it successfully only on the active sheet, but no luck when I try to specify a sheet name and range.

In the past, I did grab images from Excel but only from active sheets, as shown below.

```<code>Sub MakePicture()

    Dim rgExp As Range: Set rgExp = Range("A1:G6")
    ''' Copy range as picture onto Clipboard

    rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
    ''' Create an empty chart with exact size of range copied

    With ActiveSheet.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
    Width:=rgExp.Width, Height:=rgExp.Height)
    .Name = "Table"
    .Activate
    End With

    ''' Paste into chart area, export to file, delete the chart.
    Application.EnableEvents = False
    ActiveChart.Paste
    ActiveSheet.ChartObjects("Table").Chart.Export Filename:="C:\SavedRange.jpg", Filtername:="JPG"
    ActiveSheet.ChartObjects("Table").Delete
    Application.EnableEvents = True

End Sub
</code>```

The expected result is to grab 5 images from 5 worksheets and save them in the library.

答:
You can try something like this. </p>

```<code>Sub MakePicture()
Dim rgExp As Range
Dim WS As Worksheet
''' Copy range as picture onto Clipboard

rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
''' Create an empty chart with exact size of range copied

For each WS in ThisWorkbook.Worksheets
    Set rgExp = WS.Range("A1:G6")
    With WS.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
Width:=rgExp.Width, Height:=rgExp.Height)
    .Name = "Table"
    .Activate
End With

''' Paste into chart area, export to file, delete chart.
    Application.EnableEvents = False
    ActiveChart.Paste
    WS.ChartObjects("Table").Chart.Export Filename:="C:\SavedRange.jpeg", Filtername:="JPEG"
    WS.ChartObjects("Table").Delete
    Application.EnableEvents = True

Next WS
End Sub
</code>```

Body:
I have an Excel workbook with 6 worksheets. One Worksheet holds the data and the remaining 5 have graphs created using the data worksheet. I'm looking to grab an image of the chart on each worksheet and save it on my webserver location, such that I can use that image on my website. However, I'm able to do it successfully only on the active sheet, but no luck when I try to specify a sheet name and range.

In the past, I did grab images from Excel but only from active sheets, as shown below.

Sub MakePicture()

    Dim rgExp As Range: Set rgExp = Range("A1:G6")
    ''' Copy range as picture onto Clipboard

    rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
    ''' Create an empty chart with exact size of range copied

    With ActiveSheet.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
    Width:=rgExp.Width, Height:=rgExp.Height)
    .Name = "Table"
    .Activate
    End With

    ''' Paste into chart area, export to file, delete the chart.
    Application.EnableEvents = False
    ActiveChart.Paste
    ActiveSheet.ChartObjects("Table").Chart.Export Filename:="C:\SavedRange.jpg", Filtername:="JPG"
    ActiveSheet.ChartObjects("Table").Delete
    Application.EnableEvents = True

End Sub

The expected result is to grab 5 images from 5 worksheets and save them in the library.

Body:
You can try something like this.

Sub MakePicture()
Dim rgExp As Range
Dim WS As Worksheet
''' Copy range as picture onto Clipboard

rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
''' Create an empty chart with exact size of range copied

For each WS in ThisWorkbook.Worksheets
    Set rgExp = WS.Range("A1:G6")
    With WS.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
Width:=rgExp.Width, Height:=rgExp.Height)
    .Name = "Table"
    .Activate
End With

''' Paste into chart area, export to file, delete chart.
    Application.EnableEvents = False
    ActiveChart.Paste
    WS.ChartObjects("Table").Chart.Export Filename:="C:\SavedRange.jpeg", Filtername:="JPEG"
    WS.ChartObjects("Table").Delete
    Application.EnableEvents = True

Next WS
End Sub


问:
Iframe load everything after receiving postMessage content
I have an iframe that receives some information trough a contentWindow.postMessage function to it can login into a page that i am also making. however the i am assuming the page loads before the contentWindow.postMessage message shows up. How do i load the page AFTER the domain receives the information?

here is the code.

Page with the Iframe:

```<code><template>
    <iframe
        id="iframe"
        name="iframe"
        src="http://localhost:8081/login"
        frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"
        >
        ></iframe>
</template>

<script>
    let show = true;
export default {

  name: 'appFrame',

    function(){ document.getElementById('iframe').contentWindow.postMessage({
      userData: {
        info1: localStorage.info1,
        info2: localStorage.info2,
        info3: localStorage.info3
        }},
      'http://localhost:8081/list');
      },
  data () {
    return {
      //
    }
  }
}
</script>

<style scoped>

</style>
</code>```

this is the window.onmessage on my other page that i want to load with the information:

```<code>window.onmessage = function(event)
{
  if(event.origin == 'http://localhost:8080')

  document.getElementById('output').innerHTML = event.data;
  localStorage.setItem("info1", event.data.userData.info1);
  localStorage.setItem("info2", event.data.userData.info2);
  localStorage.setItem("info3", event.data.userData.info3);

  console.log("LOCALSTORAGE: ", localStorage.getItem("info1"), localStorage.getItem("info2"), localStorage.getItem("info3") )

};
</code>```

How would i go about that?

答:
Assuming that your second application (running at http://localhost:8081) is Vue.js application, you would have the following code:

```<code>window.addEventListener('message', function(event) {
  if (event.origin == 'http://localhost:8080') {
    document.getElementById('output').innerHTML = event.data;
    localStorage.setItem("info1", event.data.userData.info1);
    localStorage.setItem("info2", event.data.userData.info2);
    localStorage.setItem("info3", event.data.userData.info3);

    console.log("LOCALSTORAGE: ", localStorage.getItem("info1"), localStorage.getItem("info2"), localStorage.getItem("info3") )
  }
});
</code>```

In a typical Vue.js application, the root instance needs to be created. The initial code is something like:

```<code>const rootInstance = {
  data() {
    return { /* Declare reactive properties */ };
  },

  methods: {
    attemptAfterLogin() {
      // do something here.
    }
  }

  template: `<div>Hello App</div>`
};

const app = new Vue(rootInstance);
</code>```

The goal here is to put this initialization code inside the message event handler. Combining this into one code, it will be:

```<code>const rootInstance = {
  data() {
    return { /* Reactive properties */ };
  },

  methods: {
    attemptAfterLogin() {
      // do something here.
    }
  }

  template: `<div>Hello App</div>`
};

// Initialize Vue.js app
const app = new Vue(rootInstance);

window.addEventListener('message', function(event) {
  if (event.origin == 'http://localhost:8080') {
    document.getElementById('output').innerHTML = event.data;
    localStorage.setItem("info1", event.data.userData.info1);
    localStorage.setItem("info2", event.data.userData.info2);
    localStorage.setItem("info3", event.data.userData.info3);

    // Mount the application
    app.$mount(document.querySelector("#app"));

    // Tell the Vue.js app that localStorage is now set.
    app.attemptAfterLogin();
  }
});
</code>```

This is just one way of doing things. Also, till the time your inner iframe receives the message, you can have a simple loader animation.

On a side note, prefer addEventListener over onmessage when listening for events.

In a nutshell, irrespective of the front-end framework, the goal is to have a single entry point/function to load your application.

Body:
I have an iframe that receives some information trough a contentWindow.postMessage function to it can login into a page that i am also making. however the i am assuming the page loads before the contentWindow.postMessage message shows up. How do i load the page AFTER the domain receives the information?

here is the code.

Page with the Iframe:

<template>

        >
</template>

this is the window.onmessage on my other page that i want to load with the information:

window.onmessage = function(event)
{
  if(event.origin == 'http://localhost:8080')

  document.getElementById('output').innerHTML = event.data;
  localStorage.setItem("info1", event.data.userData.info1);
  localStorage.setItem("info2", event.data.userData.info2);
  localStorage.setItem("info3", event.data.userData.info3);

  console.log("LOCALSTORAGE: ", localStorage.getItem("info1"), localStorage.getItem("info2"), localStorage.getItem("info3") )

};

How would i go about that?

Body:
Assuming that your second application (running at http://localhost:8081) is Vue.js application, you would have the following code:

window.addEventListener('message', function(event) {
  if (event.origin == 'http://localhost:8080') {
    document.getElementById('output').innerHTML = event.data;
    localStorage.setItem("info1", event.data.userData.info1);
    localStorage.setItem("info2", event.data.userData.info2);
    localStorage.setItem("info3", event.data.userData.info3);

    console.log("LOCALSTORAGE: ", localStorage.getItem("info1"), localStorage.getItem("info2"), localStorage.getItem("info3") )
  }
});

In a typical Vue.js application, the root instance needs to be created. The initial code is something like:

const rootInstance = {
  data() {
    return { /* Declare reactive properties */ };
  },

  methods: {
    attemptAfterLogin() {
      // do something here.
    }
  }

  template: `<div>Hello App</div>`
};

const app = new Vue(rootInstance);

The goal here is to put this initialization code inside the message event handler. Combining this into one code, it will be:

const rootInstance = {
  data() {
    return { /* Reactive properties */ };
  },

  methods: {
    attemptAfterLogin() {
      // do something here.
    }
  }

  template: `<div>Hello App</div>`
};

// Initialize Vue.js app
const app = new Vue(rootInstance);

window.addEventListener('message', function(event) {
  if (event.origin == 'http://localhost:8080') {
    document.getElementById('output').innerHTML = event.data;
    localStorage.setItem("info1", event.data.userData.info1);
    localStorage.setItem("info2", event.data.userData.info2);
    localStorage.setItem("info3", event.data.userData.info3);

    // Mount the application
    app.$mount(document.querySelector("#app"));

    // Tell the Vue.js app that localStorage is now set.
    app.attemptAfterLogin();
  }
});

This is just one way of doing things. Also, till the time your inner iframe receives the message, you can have a simple loader animation.

On a side note, prefer addEventListener over onmessage when listening for events.

In a nutshell, irrespective of the front-end framework, the goal is to have a single entry point/function to load your application.


问:
How do you detect a string within a file name in batch?
I am trying to sort a series of folders containing thousands of company documents into an alphabetically sorted list of individual folders with the naming scheme "last name, first name".

The documents I am trying to sort have the name of their subject in the file's name. For example, one file could be called "Baggins_Frodo_Resume" or "Snow, Jon - Resume". I need to sort those files into folders called "Snow, John" and "Baggins, Frodo" respectively.

I have the name of each folder on a text file called "list of names.txt" in the format:

```<code>Last First
Baggins Frodo
Snow Jon
</code>```

Written out in plain English, I would like to have the batch file follow the steps outlined below. I used brackets around terms that should be variables.

Read the first line in the file "list of names.txt"

Assign the last name from the list to the variable [last name] and the first name to the variable [first name]

Within directory [C:\folder that needs sorting]...

if [file name] contains the text [last name] AND [first name] then...

Copy [file] to a folder called [last name, first name]

Repeat until no more files containing the name exist

Move on to the next line on "list of names.txt" and repeat.

I apologize in advance for my erroneous code, I am usually just barely able to figure out the basics of batch when I need it but this time I'm really struggling.

I had some trouble formatting the code below so here is a link to what I have with adjusted spacing and highlights.

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
rem Read the first name on the list and assign it to a variable
for /f "tokens=*" %%f in ("list of names.txt") do (
    for /f "tokens=*" %%F in ('dir /S /B /A:-D "%%f"') do (
        for %%N in ("%%F") do (
            set name=%%~NN
            set dest="%%~NN"
            set the directory
            cd /d %userprofile%\desktop\"folder to sort"
            rem find each file within the directory that contains the current name from the list
            find /I . -name "*%%~NN*" ! -name "*:*" -print if errorlevel 0 then(
                rem copy matching files to their respective folder
                copy "%%F" "%%~NN"\!name!!ext!"
            ) else (
echo No additional matches found
pause
end
            )
        )
    )
)
</code>```

There are a couple of issues here that I would really appreciate help fixing.

As my question suggests I'm not sure how to search just the name of each file for matches and not the entire contents of the file.

Additionally, I'm not sure how to separate the first/last names from "list of names.txt" to assign them to separate variables.

This is my first post on stackoverflow and in the future, I would like to be able to adjust the color of my code properly. I see in the help section that " In many cases, the syntax highlighting language will be inferred from the question's tags," but that didn't occur in my case. Is there anything obvious I'm missing?

Thanks in advance for your time, I really appreciate it!

答:
Since you tagged this with powershell, I assume you are open to a solution using it. This code reads in the list of names.txt file as a CSV file, then iterates of the the files in the directory to see if there are matches. If there is, it moves the file to the new directory. When you are confident that the correct directories will be created and files moved appropriately, remove the -WhatIf from both the mkdir and Move-Item commands.

```<code>$thedir = 'C:\src\t\nc\files'
$newdir = 'C:\src\t\nc\new'
$listfile = 'list of names.txt'
$thefiles = Get-ChildItem -File -Path $thedir

Import-Csv -Path (Join-Path -Path $thedir -ChildPath $listfile) -Delimiter ' ' |
    ForEach-Object {
        foreach ($file in $thefiles) {
            if (($file.Name -match $_.Last) -and ($file.Name -match $_.First) -and ($file.Name -ne $listfile)) {
                $dirname = $_.Last + ', ' + $_.first
                $newpath = Join-Path -Path $newdir -ChildPath $dirname
                if (-not (Test-Path -Path $newpath)) { mkdir -Path $newpath -WhatIf }
                Move-Item -Path $file.fullname -Destination $newpath -WhatIf
            }
        }
    }
</code>```

Body:
I am trying to sort a series of folders containing thousands of company documents into an alphabetically sorted list of individual folders with the naming scheme "last name, first name".

The documents I am trying to sort have the name of their subject in the file's name. For example, one file could be called "Baggins_Frodo_Resume" or "Snow, Jon - Resume". I need to sort those files into folders called "Snow, John" and "Baggins, Frodo" respectively.

I have the name of each folder on a text file called "list of names.txt" in the format:

Last First
Baggins Frodo
Snow Jon

Written out in plain English, I would like to have the batch file follow the steps outlined below. I used brackets around terms that should be variables.

Read the first line in the file "list of names.txt"

Assign the last name from the list to the variable [last name] and the first name to the variable [first name]

Within directory [C:\folder that needs sorting]...

if [file name] contains the text [last name] AND [first name] then...

Copy [file] to a folder called [last name, first name]

Repeat until no more files containing the name exist

Move on to the next line on "list of names.txt" and repeat.

I apologize in advance for my erroneous code, I am usually just barely able to figure out the basics of batch when I need it but this time I'm really struggling.

I had some trouble formatting the code below so here is a link to what I have with adjusted spacing and highlights.

SETLOCAL ENABLEDELAYEDEXPANSION
rem Read the first name on the list and assign it to a variable
for /f "tokens=*" %%f in ("list of names.txt") do (
    for /f "tokens=*" %%F in ('dir /S /B /A:-D "%%f"') do (
        for %%N in ("%%F") do (
            set name=%%~NN
            set dest="%%~NN"
            set the directory
            cd /d %userprofile%\desktop\"folder to sort"
            rem find each file within the directory that contains the current name from the list
            find /I . -name "*%%~NN*" ! -name "*:*" -print if errorlevel 0 then(
                rem copy matching files to their respective folder
                copy "%%F" "%%~NN"\!name!!ext!"
            ) else (
echo No additional matches found
pause
end
            )
        )
    )
)

There are a couple of issues here that I would really appreciate help fixing.

As my question suggests I'm not sure how to search just the name of each file for matches and not the entire contents of the file.

Additionally, I'm not sure how to separate the first/last names from "list of names.txt" to assign them to separate variables.

This is my first post on stackoverflow and in the future, I would like to be able to adjust the color of my code properly. I see in the help section that " In many cases, the syntax highlighting language will be inferred from the question's tags," but that didn't occur in my case. Is there anything obvious I'm missing?

Thanks in advance for your time, I really appreciate it!

Body:
Since you tagged this with powershell, I assume you are open to a solution using it. This code reads in the list of names.txt file as a CSV file, then iterates of the the files in the directory to see if there are matches. If there is, it moves the file to the new directory. When you are confident that the correct directories will be created and files moved appropriately, remove the -WhatIf from both the mkdir and Move-Item commands.

$thedir = 'C:\src\t\nc\files'
$newdir = 'C:\src\t\nc\new'
$listfile = 'list of names.txt'
$thefiles = Get-ChildItem -File -Path $thedir

Import-Csv -Path (Join-Path -Path $thedir -ChildPath $listfile) -Delimiter ' ' |
    ForEach-Object {
        foreach ($file in $thefiles) {
            if (($file.Name -match $_.Last) -and ($file.Name -match $_.First) -and ($file.Name -ne $listfile)) {
                $dirname = $_.Last + ', ' + $_.first
                $newpath = Join-Path -Path $newdir -ChildPath $dirname
                if (-not (Test-Path -Path $newpath)) { mkdir -Path $newpath -WhatIf }
                Move-Item -Path $file.fullname -Destination $newpath -WhatIf
            }
        }
    }


问:
Python: Why is this regular expression not working?
So I have this regex working as expected on pythex.org but it refuses to work in pycharm.</p>

```<code>somepath = 'C:\Work_stuff\common\something\anything\cool_stuff'
path_without_common = re.sub('.*\\common\\', "", somepath)
</code>```

答:
Bad escape.

This is an example working:

```<code>somepath = r'C:\Work_stuff\common\something\anything\cool_stuff'
path_without_common = re.sub(r"\\common", "", somepath)
</code>```

Body:
So I have this regex working as expected on pythex.org but it refuses to work in pycharm.

somepath = 'C:\Work_stuff\common\something\anything\cool_stuff'
path_without_common = re.sub('.*\\common\\', "", somepath)

Body:
Bad escape.

This is an example working:

somepath = r'C:\Work_stuff\common\something\anything\cool_stuff'
path_without_common = re.sub(r"\\common", "", somepath)


问:
How allocate memory limit to python thread?
How do we allocate memory limit to a python thread?

How does one use the threading and subprocess module to limit memory on that process? When I start threads ala the first answer here: How to use threading in Python?, the bash processes run sequentially instead of in parallel.

答:
For the last bit of that question, if you want them to run sequentially, i think you can use Popen

and use .wait()

I did something like this in a recent code

```<code>    script='/some/script.exe'
    my_args = [
        "--endpoint",endpoint,
        "--userid", userid,
        "--password", password,
        ....
    ]

    #1. Run the command that gets docs from Docusign Retrieve
    #https://stackoverflow.com/questions/7681715/whats-the-difference-between-subprocess-popen-and-call-how-can-i-use-them
    subprocess.Popen([script] + my_args).wait()
</code>```

As you can see, I decided to use Popen here because from What's the difference between subprocess Popen and call (how can I use them)? I saw that it was synchronous (call is non-blocking analogue)

Body:
For the last bit of that question, if you want them to run sequentially, i think you can use Popen

and use .wait()

I did something like this in a recent code

    script='/some/script.exe'
    my_args = [
        "--endpoint",endpoint,
        "--userid", userid,
        "--password", password,
        ....
    ]

    #1. Run the command that gets docs from Docusign Retrieve
    #https://stackoverflow.com/questions/7681715/whats-the-difference-between-subprocess-popen-and-call-how-can-i-use-them
    subprocess.Popen([script] + my_args).wait()

As you can see, I decided to use Popen here because from What's the difference between subprocess Popen and call (how can I use them)? I saw that it was synchronous (call is non-blocking analogue)


问:
Where do I put html bold tags in this php code sample?
I need to have the word "Located:" in bold but can't figure out where to put the tags so they don't either print or break the code.

Read other threads here, put the bold tags around Located: but they just print. Tried moving the tags but it breaks the code.

```<code>/* translators: used between list items, there is a space after the comma
*/
$tags_list = get_the_tag_list( '', esc_html__( ', ', 'vogue' ) );
if ( $tags_list ) {
    printf( '<br /><br /><span class="tags-links">' . esc_html__( '<b>Located:</b> %1$s', 'vogue' ) . '</span>', $tags_list ); // WPCS: XSS OK
}
</code>```

答:
esc_html will escape any HTML you give it, so don't put the HTML in. Simple enough! You're using esc_html__ and not just esc_html so I assume localization is important to you.

```<code>$tags_list = get_the_tag_list( '', esc_html__( ', ', 'vogue' ) );
if ( $tags_list ) {
    printf(
        '<br /><br /><span class="tags-links"><b>%s</b>%s</span>',
        __( 'Located:', 'vogue' ),
        $tags_list
    );
}
</code>```

printf will replace each %s with a string representation of the argument, so all I've done is moved the translation of "Located:" into a separate argument. I'm not sure what you were going for with %1$s so I took it out and replaced it with a standard %s.

Body:
I need to have the word "Located:" in bold but can't figure out where to put the tags so they don't either print or break the code.

Read other threads here, put the bold tags around Located: but they just print. Tried moving the tags but it breaks the code.

/* translators: used between list items, there is a space after the comma
*/
$tags_list = get_the_tag_list( '', esc_html__( ', ', 'vogue' ) );
if ( $tags_list ) {
    printf( '

' . esc_html__( 'Located: %1$s', 'vogue' ) . '', $tags_list ); // WPCS: XSS OK
}

Body:
esc_html will escape any HTML you give it, so don't put the HTML in. Simple enough! You're using esc_html__ and not just esc_html so I assume localization is important to you.

$tags_list = get_the_tag_list( '', esc_html__( ', ', 'vogue' ) );
if ( $tags_list ) {
    printf(
        '<br /><br /><span class="tags-links"><b>%s</b>%s</span>',
        __( 'Located:', 'vogue' ),
        $tags_list
    );
}

printf will replace each %s with a string representation of the argument, so all I've done is moved the translation of "Located:" into a separate argument. I'm not sure what you were going for with %1$s so I took it out and replaced it with a standard %s.


问:
incorrect table rendering in FireFox
A table's formatting is broken when the page is refreshed, but works fine when it's resized.

I have tried to run the same piece of code in Chrome, IE and Edge, without any issues of this sort.

The SASS that handles the table formatting is the following snippet:

.cv-table {
  border-collapse: separate;
  border-spacing: 0 $line-spacing;
}

.cv-section-cell {
  text-align: center;
  vertical-align: middle;

  border-right: thin solid #000;
  padding: $line-spacing / 2;

  margin: 0;

  span {
    -ms-writing-mode: tb-rl;
    -webkit-writing-mode: vertical-rl;
    writing-mode: vertical-rl;
    transform: rotate(180deg);
    white-space: nowrap;
  }
}
```

<p>The table itself looks as such:</p>

<pre class="lang-html prettyprint-override"><code><table class="cv-table">
  <tr>
    <td rowspan="2" class="cv-section-cell">
      <span>
        Experience
      </span>
    </td>
    <td class="cv-section-cell">
      <span>
        2016/2017
      </span>
    </td>
    <td class="cv-content-cell">
      Some other text.
    </td>
  </tr>
  <tr>
    <td class="cv-section-cell">
      <span>
        2017/2018
      </span>
    </td>
    <td class="cv-content-cell">
      Some text.
    </td>
  </tr>
</table>
</code>```

This is how the page looks before reloading:

And this is how it looks after:

答:
give some width and height to td

add this css to your class may it works for you

```<code> .cv-section-cell {
          width: 1.5em;
          height: 1.5em;
       }
</code>```

open this fiddle in firefox https://jsfiddle.net/fwz7k20q/4/

Title: incorrect table rendering in FireFox

Body:
A table's formatting is broken when the page is refreshed, but works fine when it's resized.

I have tried to run the same piece of code in Chrome, IE and Edge, without any issues of this sort.

The SASS that handles the table formatting is the following snippet:

.cv-table {
  border-collapse: separate;
  border-spacing: 0 $line-spacing;
}

.cv-section-cell {
  text-align: center;
  vertical-align: middle;

  border-right: thin solid #000;
  padding: $line-spacing / 2;

  margin: 0;

  span {
    -ms-writing-mode: tb-rl;
    -webkit-writing-mode: vertical-rl;
    writing-mode: vertical-rl;
    transform: rotate(180deg);
    white-space: nowrap;
  }
}

The table itself looks as such:

        Experience

        2016/2017

      Some other text.

        2017/2018

      Some text.

This is how the page looks before reloading:

And this is how it looks after:

Body:
give some width and height to td

add this css to your class may it works for you

 .cv-section-cell {
          width: 1.5em;
          height: 1.5em;
       }

open this fiddle in firefox https://jsfiddle.net/fwz7k20q/4/


问:
AJAX - OnSubmit Problem
I am fairly new to AJAX so please forgive me.

I have to forms - the fist one works but the second does not and I don't know why. The fist html form does not have submit button but the second does. They both use the same javascript function.

```<code><script type="text/javascript">
function showUser(str)
{
if (str=="")
 {
 document.getElementById("txtHint").innerHTML="";
 return;
 }
if (window.XMLHttpRequest)
 {// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
else
 {// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
xmlhttp.onreadystatechange=function()
 {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
   document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
   }
 }
xmlhttp.open("GET","server_script.php?q="+str,true);
xmlhttp.send();
}
</script>
</code>```

From 1:

```<code><form>
<select name="users" onchange="showUser(this.value)">
<option value="0001">0001</option>
</code>```

0002

   Person info will be listed here.

From 2:

```<code><form onsubmit="showUser(this.foo.value)">
<input type="foo" >
<input type="submit" >
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</code>```

答: Make showUser return false, otherwise the form will be submitted by the browser by the usual means.

Title: AJAX - OnSubmit Problem

Body:
I am fairly new to AJAX so please forgive me.

I have to forms - the fist one works but the second does not and I don't know why. The fist html form does not have submit button but the second does. They both use the same javascript function.

From 1:

<form>
<select name="users" onchange="showUser(this.value)">
<option value="0001">0001</option>

0002

   Person info will be listed here.

From 2:

<form onsubmit="showUser(this.foo.value)">
<input type="foo" >
<input type="submit" >
</form>

Person info will be listed here.


问:
How to denormalized data in SQL query
I have a table that has Clinic Names and Doctor Names.  one clinic can have many doctors.  I need to split this data into two tables.  one with clinic info and the other with Doctor info

trying to do this in a SQL query

Table CLINIC_DOC:

```<code>ID  ClinicName  Doctor
------------------------
1   xyz         Dr Joe
2   xyz         Dr Bob
3   abc         Dr Mary
4   abc         Dr John
</code>```

I want to split the data into the following tables like this:

Table ClinicsData:

```<code>ClinicID    ClinicName
----------------------
1           xyz
2           abc
</code>```

Table DoctorData:

```<code>DocId   ClinicID    Doctor
--------------------------
1       1           Dr Joe
2       1           Dr Bob
3       2           Dr Mary
4       2           Dr John
</code>```

答:
Assuming that the ID columns (ClinicID and DocID) are automatically generated and that the clinic names are unique (i.e there are no two clinics with the same name in the portion of the real world your data represents) you can try:

```<code>INSERT INTO clinicsdata
            (clinicname)
            SELECT DISTINCT
                   cd.clinicname
                   FROM clinic_doc cd;

INSERT INTO doctordata
            (clinicid,
             doctor)
            SELECT c.clinicid,
                   cd.doctor
                   FROM clinic_doc cd
                        INNER JOIN clinicsdata c
                                   ON c.clinicname = cd.clinicname;
</code>```

Title: How to denormalized data in SQL query

Body:
I have a table that has Clinic Names and Doctor Names.  one clinic can have many doctors.  I need to split this data into two tables.  one with clinic info and the other with Doctor info

trying to do this in a SQL query

Table CLINIC_DOC:

ID  ClinicName  Doctor
------------------------
1   xyz         Dr Joe
2   xyz         Dr Bob
3   abc         Dr Mary
4   abc         Dr John

I want to split the data into the following tables like this:

Table ClinicsData:

ClinicID    ClinicName
----------------------
1           xyz
2           abc

Table DoctorData:

DocId   ClinicID    Doctor
--------------------------
1       1           Dr Joe
2       1           Dr Bob
3       2           Dr Mary
4       2           Dr John

Body:
Assuming that the ID columns (ClinicID and DocID) are automatically generated and that the clinic names are unique (i.e there are no two clinics with the same name in the portion of the real world your data represents) you can try:

INSERT INTO clinicsdata
            (clinicname)
            SELECT DISTINCT
                   cd.clinicname
                   FROM clinic_doc cd;

INSERT INTO doctordata
            (clinicid,
             doctor)
            SELECT c.clinicid,
                   cd.doctor
                   FROM clinic_doc cd
                        INNER JOIN clinicsdata c
                                   ON c.clinicname = cd.clinicname;


问:
Changing the text of item from loop
I want to change the text, or remove one letter from a list of items coming from the database, I have tried different simple jQuery methods, but none seems to be working.

I have tried jQuery .find(), .children(), .text(), .html().

```<code>if(requiredVisits == 1){
  $(`.upcoming-item${i + 1} `).find('.how-earned').text('EARNED FROM 1 VISIT')
}

$('#upcoming-rewards').append(`
    <item class="upcoming-reward-item upcoming-item${i + 1} available">
    <span>
        <p style="line-height: 16px" class="reward-item reward${i + 1}">${reward}</p>
    <span id="how-earned" class="how-earned">EARNED FROM ${requiredVisits} VISITS</span>
    </span>
   </item>
`)
</code>```

I also tried just to console.log the text written and I get a 'undefined' or just blank result. So maybe I'm not traveling correctly to the span wanted. Any help would be great! :)

The expected result would be "EARNED FROM 1 VISIT" not "EARNED FROM 1 VISITS"

答:
One option would be to use the appropriate verbiage initially instead of trying to update it...</p>

```<code>var visitsText = (requiredVisits === 1) ? 'VISIT' : 'VISITS';

$('#upcoming-rewards').append(`
    <item class="upcoming-reward-item upcoming-item${i + 1} available">
    <span>
        <p style="line-height: 16px" class="reward-item reward${i + 1}">${reward}</p>
    <span id="how-earned" class="how-earned">EARNED FROM ${requiredVisits} ${visitsText}</span>
    </span>
   </item>
`)
</code>```

Title: Changing the text of item from loop

Body:
I want to change the text, or remove one letter from a list of items coming from the database, I have tried different simple jQuery methods, but none seems to be working.

I have tried jQuery .find(), .children(), .text(), .html().

if(requiredVisits == 1){
  $(`.upcoming-item${i + 1} `).find('.how-earned').text('EARNED FROM 1 VISIT')
}

$('#upcoming-rewards').append(`
    <item class="upcoming-reward-item upcoming-item${i + 1} available">

${reward}

    EARNED FROM ${requiredVisits} VISITS

   </item>
`)

I also tried just to console.log the text written and I get a 'undefined' or just blank result. So maybe I'm not traveling correctly to the span wanted. Any help would be great! :)

The expected result would be "EARNED FROM 1 VISIT" not "EARNED FROM 1 VISITS"

Body:
One option would be to use the appropriate verbiage initially instead of trying to update it...

var visitsText = (requiredVisits === 1) ? 'VISIT' : 'VISITS';

$('#upcoming-rewards').append(`
    <item class="upcoming-reward-item upcoming-item${i + 1} available">
    <span>
        <p style="line-height: 16px" class="reward-item reward${i + 1}">${reward}</p>
    <span id="how-earned" class="how-earned">EARNED FROM ${requiredVisits} ${visitsText}</span>
    </span>
   </item>
`)


问:
Is there a way to calculate how far you have scrolled inside a div with overflow set to auto?
I need to find out how far I have scrolled inside a div. I can't use the window property to find this value as the window hasn't scrolled. Is there a way to accomplish this?</p>

答:
You can do this with JQuery by using $(document).scrollTop() :

```<code>$(document).scroll(function() {
    console.log($(document).scrollTop());
})
</code>```

Body:
You can do this with JQuery by using $(document).scrollTop() :

$(document).scroll(function() {
    console.log($(document).scrollTop());
})


答:
Here is a query that will set DATE_END. It looks like you are using SQL Server, but without or small modifications it will run almost on every db.

```<code>with grouped_data as
(
    select ID, START_DATE, END_DATE from #TEST group by ID, START_DATE, END_DATE
)
,cte as
(
    select
        *,
        ROW_NUMBER() over (partition by ID order by start_date) as nr
    from grouped_data
)
select
     c1.ID
    ,c1.START_DATE
    ,case when c1.nr <> 1 then isnull(DATEADD(DAY, -1, c2.START_DATE), c1.END_DATE) ELSE c1.END_DATE end as END_DATE
from cte as c1
left join cte as c2
    on c1.ID = c2.ID
    and c1.nr = c2.nr -1
order by c1.ID
</code>```

If you have SQL Server 2017 you can easly transform FEATURE using STRING_AGG.

Title: Create new date ranges from overlapping date ranges and assign an ID

Body:
I have the following table

ID  | START_DATE | END_DATE   | FEATURE
---------------------------------------
001 | 1995-08-01 | 1997-12-31 | 1
001 | 1998-01-01 | 2017-03-31 | 4
001 | 2000-06-14 | 2017-03-31 | 5
001 | 2013-04-01 | 2017-03-31 | 8
002 | 1929-10-01 | 2006-05-25 | 1
002 | 2006-05-26 | 2016-11-10 | 4
002 | 2006-05-26 | 2016-11-10 | 7
002 | 2013-04-01 | 2016-11-10 | 8

I want to convert this table into a consolidated table which will look for overlapping date ranges and then combine these into new rows. Creating a non-overlapping set of date ranges.

The bit that I need the most help with is the consolidations of the 'feature' column which will concatenate each feature into the format below.

ID  | START_DATE | END_DATE   | FEATURE
---------------------------------------
001 | 1995-08-01 | 1997-12-31 | 1
001 | 1998-01-01 | 2000-06-13 | 4
001 | 2000-06-14 | 2013-03-31 | 45
001 | 2013-04-01 | 2017-03-31 | 458
002 | 1929-10-01 | 2006-05-25 | 1
002 | 2006-05-26 | 2013-03-31 | 47
002 | 2013-04-01 | 2016-11-10 | 478

I've used the following to create the test data.

CREATE TABLE #TEST (
    [ID] [varchar](10) NULL,
    [START_DATE] [date] NULL,
    [END_DATE] [date] NULL,
    [FEATURE] [int] NOT NULL
) ON [PRIMARY]
GO

INSERT INTO #TEST

VALUES

('001','1998-01-01','2017-03-31',4),
('001','2000-06-14','2017-03-31',5),
('001','2013-04-01','2017-03-31',8),
('001','1995-08-01','1997-12-31',1),
('002','2006-05-26','2016-11-10',4),
('002','2006-05-26','2016-11-10',7),
('002','2013-04-01','2016-11-10',8),
('002','1929-10-01','2006-05-25',1)

Body:
Here is a query that will set DATE_END. It looks like you are using SQL Server, but without or small modifications it will run almost on every db.

with grouped_data as
(
    select ID, START_DATE, END_DATE from #TEST group by ID, START_DATE, END_DATE
)
,cte as
(
    select
        *,
        ROW_NUMBER() over (partition by ID order by start_date) as nr
    from grouped_data
)
select
     c1.ID
    ,c1.START_DATE
    ,case when c1.nr <> 1 then isnull(DATEADD(DAY, -1, c2.START_DATE), c1.END_DATE) ELSE c1.END_DATE end as END_DATE
from cte as c1
left join cte as c2
    on c1.ID = c2.ID
    and c1.nr = c2.nr -1
order by c1.ID

If you have SQL Server 2017 you can easly transform FEATURE using STRING_AGG.


答:
You seem to attempt changing the text of an element before actually creating it. Try moving

```<code>if(requiredVisits == 1){
    $(`.upcoming-item${i + 1} `).find('.how-earned').text('EARNED FROM 1 VISIT')
}
</code>```

to AFTER the .append() action.

Title: Changing the text of item from loop

Body:
You seem to attempt changing the text of an element before actually creating it. Try moving

if(requiredVisits == 1){
    $(`.upcoming-item${i + 1} `).find('.how-earned').text('EARNED FROM 1 VISIT')
}

to AFTER the .append() action.


答:
It's not difficult to do:

Grab the element that scrolls

Set an event listener for scroll to that element

Get the element's scrollTop value

```<code>const scrollyDiv = document.getElementById('scrollyDiv');

scrollyDiv.addEventListener('scroll', (e) => {
  console.log(e.target.scrollTop)
})
</code>```

Demo:
https://codepen.io/koralarts/pen/LoXYmZ

Title: Is there a way to calculate how far you have scrolled inside a div with overflow set to auto?

Body: I need to find out how far I have scrolled inside a div. I can't use the window property to find this value as the window hasn't scrolled. Is there a way to accomplish this?

Body:
It's not difficult to do:

Grab the element that scrolls

Set an event listener for scroll to that element

Get the element's scrollTop value

const scrollyDiv = document.getElementById('scrollyDiv');

scrollyDiv.addEventListener('scroll', (e) => {
  console.log(e.target.scrollTop)
})

Demo:
https://codepen.io/koralarts/pen/LoXYmZ


问:
How do I delete a docker image from docker hub via command line?
I create docker image for testing in my Jenkins pipeline, uploading this to Docker hub and deploy those to Kubernetes. At the end of the testing process, I want to delete the test image from Docker hub (not from test machine). How do I delete docker hub image from command line?</p>

答:
Dockerhub has a REST backEnd, then you can use it... it is just skipping the FE...

For example:

export USERNAME=myuser
export PASSWORD=mypass
export ORGANIZATION=myorg # (if it's personal, then it's your username)
export REPOSITORY=myrepo
export TAG=latest

curl -u $USERNAME:$PASSWORD -X "DELETE" https://cloud.docker.com/v2/repositories/$ORGANIZATION/$REPOSITORY/tags/$TAG/
```

This will delete one tag...

In my case, I have microservices, then the REPOSITORY = the Microservice Name...

If I want to delete all the older images, I can iterate on this....

Body:
Dockerhub has a REST backEnd, then you can use it... it is just skipping the FE...

For example:

export USERNAME=myuser
export PASSWORD=mypass
export ORGANIZATION=myorg # (if it's personal, then it's your username)
export REPOSITORY=myrepo
export TAG=latest

curl -u $USERNAME:$PASSWORD -X "DELETE" https://cloud.docker.com/v2/repositories/$ORGANIZATION/$REPOSITORY/tags/$TAG/

This will delete one tag...

In my case, I have microservices, then the REPOSITORY = the Microservice Name...

If I want to delete all the older images, I can iterate on this....


问:
send push notification to device directly from a device swift 3
Is there any way to send push notification from a device to device directly using https://fcm.googleapis.com/fcm/send.

My code:

```<code>func sendPushNotification(toUser: String, message: String) {
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let paramString  = "to="

    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = paramString.data(using: String.Encoding.utf8)!
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

    let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
        do {
            if let jsonData = data {
                if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                    NSLog("Received data:\n\(jsonDataDict))")
                }
            }
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    task.resume()
}
</code>```

答:
Old post but it's worth to add to accepted solution as it can be helping others.  You can check my post Push Notifications are delivered but didReceiveRemoteNotification is never called Swift or here didReceiveRemoteNotification function doesn't called with FCM notification server.
You must have "content_available": truein your notification definition or push notification service(with underscore) or your didReceiveRemoteNotification won't be called and you won't be able to use userInfo.

Body:
Is there any way to send push notification from a device to device directly using https://fcm.googleapis.com/fcm/send.

My code:

func sendPushNotification(toUser: String, message: String) {
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let paramString  = "to="

    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = paramString.data(using: String.Encoding.utf8)!
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

    let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
        do {
            if let jsonData = data {
                if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                    NSLog("Received data:\n\(jsonDataDict))")
                }
            }
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    task.resume()
}


问:
changing css of ng-multiselect-dropdown
I want to change the css in ng-multiselect-dropdown.

```<code> <ng-multiselect-dropdown
                  [placeholder]="'Choose'"
                  [data]="dropdownList"
                  [(ngModel)]="selectedItems"
                  [settings]="dropdownSettings"
                  (onSelect)="onItemSelect($event)"
                  (onSelectAll)="onSelectAll($event)"
                   name="domain"

                  >
                </ng-multiselect-dropdown>
</code>```

I tried adding the following before i am calling the dropdown on html page but it doesnt help.

```<code><style>ng-multiselect-dropdown >.dropdown-list[_ngcontent-c6] li[_ngcontent-c6] {
         padding: 16px 10px;
         cursor: pointer;
         text-align: left;
 }
</code>```

Can someone please help me out?

答:
I'm a beginner with Angular, I started today. Was testing this today. What I did was:

```<code><ng-multiselect-dropdown
    [class]="'my-class'"
</code>```

And define your style in 'my-class'

Title: changing css of ng-multiselect-dropdown

Body:
I want to change the css in ng-multiselect-dropdown.

 <ng-multiselect-dropdown
                  [placeholder]="'Choose'"
                  [data]="dropdownList"
                  [(ngModel)]="selectedItems"
                  [settings]="dropdownSettings"
                  (onSelect)="onItemSelect($event)"
                  (onSelectAll)="onSelectAll($event)"
                   name="domain"

                  >
                </ng-multiselect-dropdown>

I tried adding the following before i am calling the dropdown on html page but it doesnt help.

Body:
I'm a beginner with Angular, I started today. Was testing this today. What I did was:

<ng-multiselect-dropdown
    [class]="'my-class'"

And define your style in 'my-class'


问:
Driver Development (Windows) : What is RTL?
Can someone explain me please what is RTL in the context of driver development for Windows ?

Development Tool : Visual studio 2019
Driver Type: Kernel Mode (kmdf).
Programming Language : C.

答: Many kernel API functions start with the Rtl prefix - that's an abbreviation of Run Time Library.


问:
Removing all instances of [] and ' ' from files
I have text file with the following content:

```<code>Hi, my name is 'James'. What is your [name]
</code>```

I wont to remove the ' ' and the [] from the text so the output looks like this:

```<code>Hi, my name is James. What is your name
</code>```

Here is my code:

```<code>s=  Hi, my name is 'James'. What is your [name]
s=s.replace("[","")
s=s.replace("'","")
</code>```

However the output leave a bracket to the right of name:

```<code>Hi, my name is James. What is your name]
</code>```

Any ideas?

答:
You forgot to replace ] in your original code. You can also chain replace statements together

```<code>In [2]: s=  "Hi, my name is 'James'. What is your [name]"

In [3]: s = s.replace("'",'').replace("[","").replace("]","")

In [4]: s
Out[4]: 'Hi, my name is James. What is your name'
</code>```

Or you can use a regex to strip of [] and ' using the regex [\[\]\'], which essentially replaces the characters []' when found in the string with an empty character using re.sub

```<code>import re

s = "Hi, my name is 'James'. What is your [name]"
out = re.sub(r"[\[\]\']", "",s)
print(out)
</code>```

The output will be

```<code>Hi, my name is James. What is your name
</code>```

Body:
I have text file with the following content:

Hi, my name is 'James'. What is your [name]

I wont to remove the ' ' and the [] from the text so the output looks like this:

Hi, my name is James. What is your name

Here is my code:

s=  Hi, my name is 'James'. What is your [name]
s=s.replace("[","")
s=s.replace("'","")

However the output leave a bracket to the right of name:

Hi, my name is James. What is your name]

Any ideas?

Body:
You forgot to replace ] in your original code. You can also chain replace statements together

In [2]: s=  "Hi, my name is 'James'. What is your [name]"

In [3]: s = s.replace("'",'').replace("[","").replace("]","")

In [4]: s
Out[4]: 'Hi, my name is James. What is your name'

Or you can use a regex to strip of [] and ' using the regex [\[\]\'], which essentially replaces the characters []' when found in the string with an empty character using re.sub

import re

s = "Hi, my name is 'James'. What is your [name]"
out = re.sub(r"[\[\]\']", "",s)
print(out)

The output will be

Hi, my name is James. What is your name


问:
Why do the inverse function from both cartopy and basemap have different results to calculate distance?
I want to calculate the distance between two points on surface of earth in meteres

I have tried with both basemap and cartopy but both result in different numbers.

Basemap:

```<code>import mpl_toolkits.basemap.pyproj as pyproj

k = pyproj.Geod(ellps="WGS84")
distance = k.inv(c0[1], c0[0], c1[1], c1[0])[-1]/1000.
</code>```

Cartopy:

```<code>import cartopy.geodesic as gd

k = gd.Geodesic() // defaults to WGS84
distance = k.inverse(c0, c1).base[0,0]/1000
</code>```

where both coord0 and coord1 are numpy arrays of size 2 having lat and lon of a coordinate.

```<code>c0 = numpy.array([77.343750, 22.593726])
c1 = numpy.array([86.945801, 23.684774])
</code>```

Cartopy Output: 990.6094719605074

Basemap Output: 1072.3456344712142

答:
With Basemap, you must use proper order of (long, lat):

```<code>distance = k.inv(c0[0], c0[1], c1[0], c1[1])[-1]/1000.
</code>```

and the result will agree with Cartopy's, which is the correct result:

```<code>990.6094719605074
</code>```

Body:
I want to calculate the distance between two points on surface of earth in meteres

I have tried with both basemap and cartopy but both result in different numbers.

Basemap:

import mpl_toolkits.basemap.pyproj as pyproj

k = pyproj.Geod(ellps="WGS84")
distance = k.inv(c0[1], c0[0], c1[1], c1[0])[-1]/1000.

Cartopy:

import cartopy.geodesic as gd

k = gd.Geodesic() // defaults to WGS84
distance = k.inverse(c0, c1).base[0,0]/1000

where both coord0 and coord1 are numpy arrays of size 2 having lat and lon of a coordinate.

c0 = numpy.array([77.343750, 22.593726])
c1 = numpy.array([86.945801, 23.684774])

Cartopy Output: 990.6094719605074

Basemap Output: 1072.3456344712142

Body:
With Basemap, you must use proper order of (long, lat):

distance = k.inv(c0[0], c0[1], c1[0], c1[1])[-1]/1000.

and the result will agree with Cartopy's, which is the correct result:

990.6094719605074


答:
Fix your html generation.  Don't try to fix it after the fact, if possible.</p>

```<code>$('#upcoming-rewards').append(`
    <item class="upcoming-reward-item upcoming-item${i + 1} available">
        <span>
            <p style="line-height: 16px" class="reward-item reward${i + 1}">${reward}</p>
            <span id="how-earned" class="how-earned">EARNED FROM ${requiredVisits} VISIT${requiredVisits > 1 ? 'S' : ''}</span>
        </span>
    </item>
`);
</code>```

Title: Changing the text of item from loop

Body:
Fix your html generation.  Don't try to fix it after the fact, if possible.

$('#upcoming-rewards').append(`
    <item class="upcoming-reward-item upcoming-item${i + 1} available">
        <span>
            <p style="line-height: 16px" class="reward-item reward${i + 1}">${reward}</p>
            <span id="how-earned" class="how-earned">EARNED FROM ${requiredVisits} VISIT${requiredVisits > 1 ? 'S' : ''}</span>
        </span>
    </item>
`);


问:
Multiple Blogs in PyroCMS (or other OpenSource CMS)
I have been looking round for an open-source CMS framework that I can use as the basis for a few web projects. I used to use Joomla, but I found it to be clunky and out-dated, certainly too complicated for the average user that would be faced with it.

My current project requires a content-managed website, with all the usual stuff, and on the whole PyroCMS seems well suited to the task. However a core requirement of the project is that it contains four blogs. A general one for news relating to news in the client's field and then one each for the three members of the company.

I can't see how to do this as it stands, but I'm sure it must be possible somehow. I'm happy to write a module myself to do it if needs be, but I'm trying to keep the project fairly simple, and I can't be the first person to want to do this!

I'd considered a Wordpress network, but a key requirement is that everything is centralised in one administrator panel.

In summary - is there any way to maintain several blogs using just PyroCMS and addons?

Thanks,
Ian

答:
There are a few outstanding features that have never really been added into PyroCMS as they have never really been needed by anyone with enough interest or ability to add them.

The blog module is VERY basic, but it has always been used by incredibly simple sites. "Mom and Pap" websites, simple "News" sections on corporate sites, developer blogs, etc.

Out of the box it CAN be done, by making a pages for "blog" and a category for each, then use the {pyro:blog:posts number="10"}{title} {summary} {/pyro:blog:posts} tags.

It's not the cleanest solution, but remember that most development on PyroCMS is done by developers finding gaps that need to be filled for client projects. I have a client project coming up soon that requires multiple categories (surprised it took so long!), which would solve this problem perfectly, but until they pay me to work on it I just don't have the time. If you want the feature added in for your job I can help you with it if needs be through giving advice on here, in the forums, on IRC etc, then we can merge it in easily enough.


问:
Kendo Jquery Grid - Filtering on comma separated values column
We have a Kendo Jquery Grid and we are trying to provide filter on Column where we are showing values in comma separated form. Code is shown below, I have tried to catch the filter object in dataBound event and try to filter out records over datasource, but couldn't help. Please suggest how can we achieve this.

Field on which we need to achieve this is ProviderSpecialty

```<code><script>
    var grid;
    var dataSource;
    var gridView = 'updatesRequired';

    $(document).ready(function () {
        $('#selectGridView').change(function () {
            gridView = $('#selectGridView').val();
            $('#grid').kendoGrid('destroy').empty();
            renderGrid();
        });
        renderGrid();
    });

    function renderGrid() {

        var fieldsSchema =
        {
            'ProviderDelegateId': { type: 'number' },
            'EndDate': {type: 'date' }
        };
        dataSource = new kendo.data.DataSource({
            transport: {
                read: {
                    url: providerProfileApiBaseUrl)
                }
            },
            error: function (e) {
                if (e.xhr.responseText != '') {
                    var jsonError = JSON.parse(e.xhr.responseText);

                    if (myApp.Web.utility.displacolumns !== undefined) {
                        myApp.Web.utility.displacolumns.push({
                            field: 'EndDate', template: '#= kendo.toString(kendo.parseDate(EndDate), "MM/dd/yyyy")#', title: 'Campaign End Dt', width: '125px', filterable: {
                                ui: function (element) {
                                    element.kendoDatePicker({
                                        format: "MM/dd/yyyy"
                                    });
                                }
                            }
                        });
                    }
                    myApp.Web.utility.displayErrorDialog(jsonError.error);
                }
            },
            pageSize: myApp.Web.config.grid.pageable.pageSize,
            schema: {
                model: {
                    id: 'UniqueId',
                    fields: fieldsSchema
                }
            },
            sort: { field: "ProviderLastName", dir: "asc" }
        });

        var columns = [];
        columns.push({ field: 'ProviderDelegateId', hidden: true });
        if (gridView === 'updatesRequired') {
            columns.push({ field: 'ProviderLastName', title: 'Last Name', width: '125px', template: '<a href="/ProviderLanding/ProviderUpdate/Index/#=CampaignTrackingId#">#=ProviderLastName#</a>' });
            columns.push({ field: 'ProviderFirstName', title: 'First Name', width: '125px', template: '<a href="/ProviderLanding/ProviderUpdate/Index/#=CampaignTrackingId#">#=ProviderFirstName#</a>' });
            columns.push({ field: 'ProviderNPI', title: 'NPI', width: '125px', template: '<a href="/ProviderLanding/ProviderUpdate/Index/#=CampaignTrackingId#">#=ProviderNPI != null ? ProviderNPI : \'\' #</a>' });
        } else {
            columns.push({ field: 'ProviderLastName', title: 'Last Name', width: '125px', template: '<a href="/ProviderUpdate/UpdateProfile?providerId=#=ProviderId#">#=ProviderLastName#</a>' });
            columns.push({ field: 'ProviderFirstName', title: 'First Name', width: '125px', template: '<a href="/ProviderUpdate/UpdateProfile?providerId=#=ProviderId#">#=ProviderFirstName#</a>' });
            columns.push({ field: 'ProviderNPI', title: 'NPI', width: '125px', template: '<a href="/ProviderUpdate/UpdateProfile?providerId=#=ProviderId#">#=ProviderNPI != null ? ProviderNPI : \'\' #</a>' });
        };
        columns.push({ field: 'ProviderSpecialty', title: 'Specialty', width: '125px', template: '#= getSpecialties(ProviderSpecialties) #' });
        columns.push({ field: 'ProviderEmail', title: 'Email', width: '125px' });
        columns.push({ field: 'LocationName', title: 'Location', width: '125px', template: '#= getLocations(ProviderLocations) #'  });
        if (gridView === 'updatesRequired') {
            columns.push({ field: 'CampaignName', title: 'Campaign', width: '125px', template: '<a href="/ProviderLanding/ProviderUpdate/Index/#=CampaignTrackingId#">#=CampaignName#</a>' });
            columns.push({
                field: 'EndDate', template: '#= kendo.toString(kendo.parseDate(EndDate), "MM/dd/yyyy")#', title: 'Campaign End Dt', width: '125px', filterable : {
                ui: function (element) {
                    element.kendoDatePicker({
                        format: "MM/dd/yyyy"
                    });
                }
            } });
        } else {
            columns.push({ field: 'IsPendingChangeAvailable', title: 'Pending Changes', width: '125px', template: '#if (IsPendingChangeAvailable) {# Yes #} else {# No #}#' });
        };

        grid = $("#grid").kendoGrid({
            dataSource: dataSource,
            columns: columns,
            scrollable: false,
            filterable: myApp.Web.config.grid.filterable,
            sortable: myApp.Web.config.grid.sortable,
            pageable: myAppWeb.config.grid.pageable,
        }).data('kendoGrid');
    };

    function getSpecialties(specialties) {
        // remove duplicates and then join...
        var result = [];
        $.each(specialties, function(i, e) {
            if ($.inArray(e.SpecialtyName, result) == -1) result.push(e.SpecialtyName);
        });
        return result.join(',');
    };

    function getLocations(locations) {
        return locations.map(function (location) {
            return location.LocationName
        }).join(',');
    };

    $(document).ajaxStart(function () {
        $('#overlay-screen').show();
    });
    $(document).ajaxStop(function () {
        $('#overlay-screen').hide();
    });
</script>
</code>```

答:
The filter box will not allow you to add in a comma. I am not sure you can do this with a comma unless you override the UI to show your own filter box and on change apply the filter via jquery/javascript like below. If I am understanding you correctly.

```<code>//After user enters their values. Imagine "Tom,John" would be what the user entered
//After you exploded the comma list yourself
$('#grid').data('kendoGrid').dataSource.filter({
    logic: "or",
    filters: [
       { field: "Name", operator: "contains", value: 'Tom' },
       { field: "Name", operator: "contains", value: 'John' },
    ]
});
</code>```

Obviously, it would be a little more advanced if you are allowing other columns to be filtered as well.  You would instead be modifying the filter rather than overriding them.  Note my example uses contains.  This could be eq if you wanted that. However, assuming that column you want to filter by is text you could instead use the "mulit: true" on the filterable object. This allows the selections to be managed by the user with kendo's UI element

```<code>//On the column property
filterable: {
    multi:true
}
</code>```

This will give you check boxes for each possible value in the column.  Note if you mode on the filterable object of your grid is set to row.  This will not work

```<code>//On the grid
filterable: {
    mode: "row"
}
</code>```

Open the code from the following link within the dojo
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/columns.filterable.multi

Hope this helps

Body:
The filter box will not allow you to add in a comma. I am not sure you can do this with a comma unless you override the UI to show your own filter box and on change apply the filter via jquery/javascript like below. If I am understanding you correctly.

//After user enters their values. Imagine "Tom,John" would be what the user entered
//After you exploded the comma list yourself
$('#grid').data('kendoGrid').dataSource.filter({
    logic: "or",
    filters: [
       { field: "Name", operator: "contains", value: 'Tom' },
       { field: "Name", operator: "contains", value: 'John' },
    ]
});

Obviously, it would be a little more advanced if you are allowing other columns to be filtered as well.  You would instead be modifying the filter rather than overriding them.  Note my example uses contains.  This could be eq if you wanted that. However, assuming that column you want to filter by is text you could instead use the "mulit: true" on the filterable object. This allows the selections to be managed by the user with kendo's UI element

//On the column property
filterable: {
    multi:true
}

This will give you check boxes for each possible value in the column.  Note if you mode on the filterable object of your grid is set to row.  This will not work

//On the grid
filterable: {
    mode: "row"
}

Open the code from the following link within the dojo
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/columns.filterable.multi

Hope this helps


问:
mysql command freezing in windows console
When xampp's MySQL is stopped. I am typing this in git bash console, I am receiving this error.

```<code>    $ mysql -v
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061 "Unknown error")
</code>```

And when it is on, console just freezing. Don't know what to do. Xammp installation is fresh and MySQL added to the PATH. Previously all commands works in ubuntu, there was no problem at all.

答: Git bash doing the same thing to me. Powershell is working better.</p>

Body:
When xampp's MySQL is stopped. I am typing this in git bash console, I am receiving this error.

    $ mysql -v
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061 "Unknown error")

And when it is on, console just freezing. Don't know what to do. Xammp installation is fresh and MySQL added to the PATH. Previously all commands works in ubuntu, there was no problem at all.


问:
While loop doesn't exit or display results
Homework assignment: I've been asked to create a method that will count all the odd numbers from 1 to value assigned to variable but it has to be with a while loop.

I've been using modulus to try and determine whether or not it's even or odd. I've tried identifying odd numbers and then just using + 2. I suspect it's a simple logic error I don't quite see.

```<code>public static void sumOddNumber(int number){

    int counter =1;

    while (counter <= number){
        if (counter % 2 !=0){
            System.out.println (+ number);
            counter++;
        }
    }

}
</code>```

My expectation was for it to compare counter to number(the user defined variable) and to keep performing the modulus operation and printing the result, until counter exceeds number. However when I enter a number it just prints that number and keeps grinding away.

答: Once I removed the counter++ statement outside of the loop, I started receiving the correct number of iterations but all showing the number that I had input. I just had to change my System.out.println to display the correct variable, in this case 'counter' not 'number' like I had. My method ended up looking like the first example hooknc put up. Thanks to everyone for all the help. </p>

Body:
Homework assignment: I've been asked to create a method that will count all the odd numbers from 1 to value assigned to variable but it has to be with a while loop.

I've been using modulus to try and determine whether or not it's even or odd. I've tried identifying odd numbers and then just using + 2. I suspect it's a simple logic error I don't quite see.

public static void sumOddNumber(int number){

    int counter =1;

    while (counter <= number){
        if (counter % 2 !=0){
            System.out.println (+ number);
            counter++;
        }
    }

}

My expectation was for it to compare counter to number(the user defined variable) and to keep performing the modulus operation and printing the result, until counter exceeds number. However when I enter a number it just prints that number and keeps grinding away.


问:
How to return an input within a def function with python
I'm new to python and defining functions!

I'm writing a code and, on it, I'll sometimes ask the same question, this is why I want to use a function for it. I'm trying like this:

```<code>def cont():
  ans = input("Continue? ")
  return ans
</code>```

But it's not storing anything on ans, cause every time I call it, I get an error saying that ans has not been declared!

Could anybody help me?

答:
There's nothing wrong with your function. Here's an example:

```<code>def cont():
    ans = input("Continue? ")
    return ans

for i in range(2):
    print(cont())
</code>```

Output:

```<code>Continue? y
y
Continue? n
n
</code>```

If you need to use it in an if-statement:

```<code>for i in range(3):
    result = cont()
    if result == 'y':
        print('yes')
    elif result == 'n':
        print('no')
    else:
        print("I don't understand")
</code>```

Output:

```<code>Continue? y
yes
Continue? n
no
Continue? p
I don't understand
</code>```

However, if you don't plan on expanding the cont() function, and doing something more complex with it, as it is now, it's pretty useless because you can simply use input("Continue? ") wherever you use cont().

Body:
I'm new to python and defining functions!

I'm writing a code and, on it, I'll sometimes ask the same question, this is why I want to use a function for it. I'm trying like this:

def cont():
  ans = input("Continue? ")
  return ans

But it's not storing anything on ans, cause every time I call it, I get an error saying that ans has not been declared!

Could anybody help me?

Body:
There's nothing wrong with your function. Here's an example:

def cont():
    ans = input("Continue? ")
    return ans

for i in range(2):
    print(cont())

Output:

Continue? y
y
Continue? n
n

If you need to use it in an if-statement:

for i in range(3):
    result = cont()
    if result == 'y':
        print('yes')
    elif result == 'n':
        print('no')
    else:
        print("I don't understand")

Output:

Continue? y
yes
Continue? n
no
Continue? p
I don't understand

However, if you don't plan on expanding the cont() function, and doing something more complex with it, as it is now, it's pretty useless because you can simply use input("Continue? ") wherever you use cont().