问:
How can i read in a comma separated file into 2D int array?
So I have a file with 4 lines which reads as follows:

1,1,1,1

1,1,1,1

1,1,1,1

1,1,1,1

I'm trying to read in all that and store in 2D int array. I can only read in the first line when I use the stoi function. Any suggestions on how I can read all the lines.

答:
```<code>#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>

std::vector<std::vector<int>> get2DVector(int n, std::string filename)
{
    std::vector<std::vector<int>> result(n);

    std::ifstream input(filename);

    std::string s;
    for (int i = 0; i < n; i++)
    {
        std::getline(input, s);
        std::istringstream iss(s);

        std::string num;
        while (std::getline(iss, num, ','))
            result[i].push_back(std::stoi(num));
    }

    return result;
}

int main()
{
    auto vec = get2DVector(4, "input.txt");

    for (auto& v : vec)
    {
        for (int i : v)
            std::cout << i << ' ';
        std::cout << '\n';
    }
}
</code>```

input.txt:

```<code>1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1
</code>```

Output:

```<code>1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
</code>```

I used std::vector here since the length of each array may vary. If the length of each array is the same, you can just use normal arrays. Don't recommend it tho.

Body:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>

std::vector<std::vector<int>> get2DVector(int n, std::string filename)
{
    std::vector<std::vector<int>> result(n);

    std::ifstream input(filename);

    std::string s;
    for (int i = 0; i < n; i++)
    {
        std::getline(input, s);
        std::istringstream iss(s);

        std::string num;
        while (std::getline(iss, num, ','))
            result[i].push_back(std::stoi(num));
    }

    return result;
}

int main()
{
    auto vec = get2DVector(4, "input.txt");

    for (auto& v : vec)
    {
        for (int i : v)
            std::cout << i << ' ';
        std::cout << '\n';
    }
}

input.txt:

1,1,1,1
1,1,1,1
1,1,1,1
1,1,1,1

Output:

1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

I used std::vector here since the length of each array may vary. If the length of each array is the same, you can just use normal arrays. Don't recommend it tho.


来源: stackexchange

问:
JMeter - Java.net.URISyntaxException: Illegal character in path at index
I'm testing an api in Jmeter

When passing the url in postman I get proper response

But when use the same in Jmeter I get error

The path I'm using:

答:
Your request payload contains characters which are not allowed to be present in URL so you need to wrap what you put in "Path" section of the HTTP Request sampler into __urlencode() function

More information: Apache JMeter Functions - An Introduction

ContentLicense: CC BY-SA 4.0


问:
How to suppress "coroutine was never awaited" warning?
All search results on "coroutine was never awaited" are for people who were either trying to fire-and-forget or actually did forget to await. This is not my case.

I want to use a coroutine the same way I often use generators: I'm creating it here while I have all the variables handy, but I'm not sure yet whether I'll ever need that to be run. Something like:

```<code>options = {
   'a': async_func_1(..., ...),
   'b': async_func_2(),
   'c': async_func_3(...),
}
</code>```

and elsewhere:

```<code>appropriate_option = figure_the_option_out(...)
result = await options[appropriate_option]
</code>```

答:
I still haven't found something that can be done at initialization, but I found a solution that can be done after all coroutines are awaited.

```<code>for coroutine in options.values():
    coroutine.close()
</code>```

This close() function will work on all coroutines, whether awaited or not.

Body:
All search results on "coroutine was never awaited" are for people who were either trying to fire-and-forget or actually did forget to await. This is not my case.

I want to use a coroutine the same way I often use generators: I'm creating it here while I have all the variables handy, but I'm not sure yet whether I'll ever need that to be run. Something like:

options = {
   'a': async_func_1(..., ...),
   'b': async_func_2(),
   'c': async_func_3(...),
}

and elsewhere:

appropriate_option = figure_the_option_out(...)
result = await options[appropriate_option]

Body:
I still haven't found something that can be done at initialization, but I found a solution that can be done after all coroutines are awaited.

for coroutine in options.values():
    coroutine.close()

This close() function will work on all coroutines, whether awaited or not.


问:
Reverse search an image in Yandex Images using Python
I'm interested in automatizing reverse image search. Yandex in particular is great for busting catfishes, even better than Google Images. So, consider this Python code:

```<code>import requests
import webbrowser

try:
    filePath = "C:\\path\\whateverThisIs.png"
    searchUrl = 'https://yandex.ru/images/'
    multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
    response = requests.post(searchUrl, files=multipart, allow_redirects=False)
    #fetchUrl = response.headers['Location']
    print(response)
    print(dir(response))
    print(response.content)
    input()
except Exception as e:
    print(e)
    print(e.with_traceback)
    input()```
```

The script fails with KeyError, 'location' is not found. I know the code works cause if you substitute searchUrl with http://www.google.hr/searchbyimage/upload then the script returns the correct url.
So, in short the expected outcome would be a url with an image search. In actuality we get a KeyError where that url was supposed to be stored.
Evidently, Yandex doesn't work in exactly the same way, maybe the url is off (although I tried a heap ton of variations) or the reason may be completely different.

Regardless of that, help in solving this problem is much appreciated!

答:
There are no API for developers. You can try reverse inginer queries from your browser, but you will have to deal with anty robot protect.

Another way to speed up process (but still manual)

As described here
https://yandex.com/support/images/loaded-image.html install
Yandex.Browser where you have hot key for image search

Host/make your site with all source images foe search queries

Open your site in Yandex.Browser use "right mouse click"+"serch image at
yandex"

Copy what you need from page with results

Body:
I'm interested in automatizing reverse image search. Yandex in particular is great for busting catfishes, even better than Google Images. So, consider this Python code:

import requests
import webbrowser

try:
    filePath = "C:\\path\\whateverThisIs.png"
    searchUrl = 'https://yandex.ru/images/'
    multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
    response = requests.post(searchUrl, files=multipart, allow_redirects=False)
    #fetchUrl = response.headers['Location']
    print(response)
    print(dir(response))
    print(response.content)
    input()
except Exception as e:
    print(e)
    print(e.with_traceback)
    input()```

The script fails with KeyError, 'location' is not found. I know the code works cause if you substitute searchUrl with http://www.google.hr/searchbyimage/upload then the script returns the correct url.
So, in short the expected outcome would be a url with an image search. In actuality we get a KeyError where that url was supposed to be stored.
Evidently, Yandex doesn't work in exactly the same way, maybe the url is off (although I tried a heap ton of variations) or the reason may be completely different.

Regardless of that, help in solving this problem is much appreciated!


问:
How to create complex anagram using Streams
I have a task

```<code>Write an application that reverses all the words of input text:

E.g. "abcd efgh" => "dcba hgfe"

All non-letter symbols should stay on the same places:

E.g. "a1bcd efg!h" => "d1cba hgf!e"
</code>```

and it is successfully solved using core java. The core method is as follows:

private String reverseSeparateWord(String word) {

        char sentencePart[] = new char[word.length()];
        sentencePart = word.toCharArray();

        int firstIndex = 0;
        int lastIndex = sentencePart.length - 1;

        for (int i = 0; i < sentencePart.length; i++) {

            char symbolToBeSwapped = sentencePart[lastIndex];

            if (firstIndex < lastIndex) {

                if (!Character.isLetter(sentencePart[firstIndex])) {
                    firstIndex++;

                } else {
                    if (!Character.isLetter(symbolToBeSwapped)) {
                        lastIndex--;
                        symbolToBeSwapped = sentencePart[lastIndex];

                    } else {
                        sentencePart[lastIndex] = sentencePart[firstIndex];
                        sentencePart[firstIndex] = symbolToBeSwapped;

                        firstIndex++;
                        lastIndex--;

                        symbolToBeSwapped = sentencePart[lastIndex];
                    }
                }
            }
        }
        return new String(sentencePart);
    }

```

Now I sould solve this task using Streams and it is where I'm struggling.
I will appreciate any thoughts.

答:
Using your method, do the following:

str is your string of words

newStr is the converted string of words

reverse is your method that takes a String.

```<code>String newStr = Arrays.stream(str.split("\\s+"))
                       .map(s->reverse(s))
                       .collect(Collectors.joining(" "));

System.out.println(str);
System.out.println(newStr);
</code>```

No need to force fit a stream solution (streams are supposed to make your task easier and your code more readable).

Body:
I have a task

Write an application that reverses all the words of input text:

E.g. "abcd efgh" => "dcba hgfe"

All non-letter symbols should stay on the same places:

E.g. "a1bcd efg!h" => "d1cba hgf!e"

and it is successfully solved using core java. The core method is as follows:

private String reverseSeparateWord(String word) {

        char sentencePart[] = new char[word.length()];
        sentencePart = word.toCharArray();

        int firstIndex = 0;
        int lastIndex = sentencePart.length - 1;

        for (int i = 0; i < sentencePart.length; i++) {

            char symbolToBeSwapped = sentencePart[lastIndex];

            if (firstIndex < lastIndex) {

                if (!Character.isLetter(sentencePart[firstIndex])) {
                    firstIndex++;

                } else {
                    if (!Character.isLetter(symbolToBeSwapped)) {
                        lastIndex--;
                        symbolToBeSwapped = sentencePart[lastIndex];

                    } else {
                        sentencePart[lastIndex] = sentencePart[firstIndex];
                        sentencePart[firstIndex] = symbolToBeSwapped;

                        firstIndex++;
                        lastIndex--;

                        symbolToBeSwapped = sentencePart[lastIndex];
                    }
                }
            }
        }
        return new String(sentencePart);
    }

Now I sould solve this task using Streams and it is where I'm struggling.
I will appreciate any thoughts.

Body:
Using your method, do the following:

str is your string of words

newStr is the converted string of words

reverse is your method that takes a String.

String newStr = Arrays.stream(str.split("\\s+"))
                       .map(s->reverse(s))
                       .collect(Collectors.joining(" "));

System.out.println(str);
System.out.println(newStr);

No need to force fit a stream solution (streams are supposed to make your task easier and your code more readable).


问:
Android Studio Multiple onCreate methods in MainActivity.java
For a school project I am creating a simple app. However, I run into one problem to finalize the app.

I've been trying to make two buttons on my main layout. The buttons are supposed to open a second layout, one called barcode_scanner.xml and another called vragen.xml

However, only the first button opens the scanner. The second button does not do anything.

This is my current code from MainActivity.java

```<code>package com.kvprasad.zbarbarcodescanner;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button scannerButton;

@Override
        //Barcodescanner knop
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button next = (Button) findViewById(R.id.scannerButton);
            next.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
                    startActivityForResult(myIntent, 0);
                }
            });
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

public class bovenbouw extends MainActivity{

    @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    Button next = (Button) findViewById(R.id.bovenbutton);
                    next.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View view) {
                            Intent myIntent = new Intent(view.getContext(), Vragen.class);
                            startActivityForResult(myIntent, 0);}});}}}
</code>```

I don't see any problems in the code. What am I possibly doing wrong?
Thank you.

答:
```<code>package com.example.photosapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For a school project I am creating a simple app. However, I run into one problem to finalize the app.

I've been trying to make two buttons on my main layout. The buttons are supposed to open a second layout, one called barcode_scanner.xml and another called vragen.xml

However, only the first button opens the scanner. The second button does not do anything.

This is my current code from MainActivity.java

package com.kvprasad.zbarbarcodescanner;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button scannerButton;

@Override
        //Barcodescanner knop
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button next = (Button) findViewById(R.id.scannerButton);
            next.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
                    startActivityForResult(myIntent, 0);
                }
            });
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

public class bovenbouw extends MainActivity{

    @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    Button next = (Button) findViewById(R.id.bovenbutton);
                    next.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View view) {
                            Intent myIntent = new Intent(view.getContext(), Vragen.class);
                            startActivityForResult(myIntent, 0);}});}}}

I don't see any problems in the code. What am I possibly doing wrong?
Thank you.


问:
how to transform Gridview into Listview in flutter?
i would like to transform a GridView into a Listview, here is the Gridview code:

and here is what i tried to do :

```<code>      return ListView.builder(
 itemBuilder: (context,index){
     _buildGridCards(context);
   }

   );
  }

    List<dynamic> _buildGridCards(BuildContext context) {
   if (widget.productsToDisplay == null || widget.productsToDisplay.isEmpty) {
    return const <Card>[];
     }
   final ThemeData theme = Theme.of(context);
    return widget.productsToDisplay.map((product) {
    Uint8List img64;
    try {
    img64 = base64Decode(product.image);
    } catch (e) {
    print(e);
    }

  return Card(
    clipBehavior: Clip.antiAlias,
    child: InkWell(
      onTap: () {
        Navigator.push(
          context,
             ...
</code>```

when i executed the code, nothing appeared

答:
the item builder requires you to return a widget of which it will render the widget in the list at a defined index...

you could keep calling the function _buildGridCards for each time the builder executes and have the following...

```<code>return ListView.builder(
  // Not forgetting to add the length ofcourse
  itemCount: _buildGridCards(context).length,
  itemBuilder: (context,index){
    return _buildGridCards(context)[index];
  }
);
</code>```

or you could keep the list somewhere and only execute the function once like down here...

```<code>
@Override
Widget build(BuildContext context) {
  List<Card> cards = _buildGridCards(context);

  return ListView.builder(
    // Not forgetting the length ofcourse
    itemCount: cards.length,
    itemBuilder: (context,index){
      return cards[index];
    }
  );
}
</code>```

Hope this helps

Body:
i would like to transform a GridView into a Listview, here is the Gridview code:

and here is what i tried to do :

      return ListView.builder(
 itemBuilder: (context,index){
     _buildGridCards(context);
   }

   );
  }

    List<dynamic> _buildGridCards(BuildContext context) {
   if (widget.productsToDisplay == null || widget.productsToDisplay.isEmpty) {
    return const <Card>[];
     }
   final ThemeData theme = Theme.of(context);
    return widget.productsToDisplay.map((product) {
    Uint8List img64;
    try {
    img64 = base64Decode(product.image);
    } catch (e) {
    print(e);
    }

  return Card(
    clipBehavior: Clip.antiAlias,
    child: InkWell(
      onTap: () {
        Navigator.push(
          context,
             ...

when i executed the code, nothing appeared

Body:
the item builder requires you to return a widget of which it will render the widget in the list at a defined index...

you could keep calling the function _buildGridCards for each time the builder executes and have the following...

return ListView.builder(
  // Not forgetting to add the length ofcourse
  itemCount: _buildGridCards(context).length,
  itemBuilder: (context,index){
    return _buildGridCards(context)[index];
  }
);

or you could keep the list somewhere and only execute the function once like down here...

@Override
Widget build(BuildContext context) {
  List<Card> cards = _buildGridCards(context);

  return ListView.builder(
    // Not forgetting the length ofcourse
    itemCount: cards.length,
    itemBuilder: (context,index){
      return cards[index];
    }
  );
}

Hope this helps


问:
Assign role by default in liquibase
How can i add particular user to changeSet and assign a role so when user access the service he/she can be ROLE_ADMIN by the default. I am using Liquibase and Postgres </p>

答:
There's no tags for user management, but you can run anything you want in the generic <sql> tag, e.g.

```<code><sql>
CREATE ROLE ROLE_ADMIN SUPERUSER;
</sql>
</code>```

Title: Assign role by default in liquibase

Body:
There's no tags for user management, but you can run anything you want in the generic <sql> tag, e.g.

<sql>
CREATE ROLE ROLE_ADMIN SUPERUSER;
</sql>


问:
Why don't Parameters<Func> extend unknown[] (Array<unknown>) in ts strict mode
The title pretty much says it all really. I have this code:

```<code>  type testNoArgsF = () => number;
  type testArgsF = (arg1: boolean, arg2: string) => number;
  type unknownArgsF = (...args: unknown[]) => number;
  type anyArgsF = (...args: any[]) => number;

  type testII = testArgsF extends anyArgsF ? true : false; // true
  type testIII = Parameters<testArgsF> extends Parameters<unknownArgsF>
    ? true
    : false; // true

  // unexpected:
  type testIV = testArgsF extends unknownArgsF ? true : false; // false <- why?
  // even though:
  type testV = testNoArgsF extends unknownArgsF ? true : false; // true
</code>```

It is written in typescript (version 3.8), and I have strict mode enabled. The unexpected result is that a test function doesn't extend a function type with spread args of unknown[], yet if you just check the parameters they do extend unknown[]. Since the return type is always number, I don't understand what else could possibly be different to falsify the extends statement.

Other notes:

The extend statement is true only if your test function has 0 arguments.

This behaviour is not seen if you turn off strict mode.

答:
```<code>type testIV = testArgsF extends unknownArgsF ? true : false; // false
type testIVa = unknownArgsF extends testArgsF  ? true : false; // true!

// because
type testIII = Parameters<testArgsF> extends Parameters<unknownArgsF>
    ? true
    : false; // true
</code>```

Extends really means 'is assignable to'.
And f(p:A)=> is assignable to f(p:B)=> if B is assignable to A. I think it's called 'contravariant'.

```<code>// Imagine your function expects callback that has some type as a paramter:

var f = (cb: ({ a, b }: { a: number, b: number }) => void) => { cb({ a:1, b: 1}); };

// you can safely call it giving it the function that accepts parameter
// that the original parameter is assignable to but not the other way around
// because that's the way to guarantee that when our function f calls the callback
// it will provide sufficient amount of data
f(({ a }: { a: number }) => { })

var x = { a: 1, b: 1 };
var y = { a: 1 }

x = y; // error because x would have no b property after that assignment
y = x; // works because y has all it needs after that assignment and it doesn't matter it has property b too

// in other words:
type F = { a: number } extends { a: number, b: number } ? true : false; // false
type T = { a: number, b: number } extends { a: number } ? true : false; // true

// read 'extends' as 'is assignable to'
</code>```

Body:
The title pretty much says it all really. I have this code:

  type testNoArgsF = () => number;
  type testArgsF = (arg1: boolean, arg2: string) => number;
  type unknownArgsF = (...args: unknown[]) => number;
  type anyArgsF = (...args: any[]) => number;

  type testII = testArgsF extends anyArgsF ? true : false; // true
  type testIII = Parameters<testArgsF> extends Parameters<unknownArgsF>
    ? true
    : false; // true

  // unexpected:
  type testIV = testArgsF extends unknownArgsF ? true : false; // false <- why?
  // even though:
  type testV = testNoArgsF extends unknownArgsF ? true : false; // true

It is written in typescript (version 3.8), and I have strict mode enabled. The unexpected result is that a test function doesn't extend a function type with spread args of unknown[], yet if you just check the parameters they do extend unknown[]. Since the return type is always number, I don't understand what else could possibly be different to falsify the extends statement.

Other notes:

The extend statement is true only if your test function has 0 arguments.

This behaviour is not seen if you turn off strict mode.

Body:
type testIV = testArgsF extends unknownArgsF ? true : false; // false
type testIVa = unknownArgsF extends testArgsF  ? true : false; // true!

// because
type testIII = Parameters<testArgsF> extends Parameters<unknownArgsF>
    ? true
    : false; // true

Extends really means 'is assignable to'.
And f(p:A)=> is assignable to f(p:B)=> if B is assignable to A. I think it's called 'contravariant'.

// Imagine your function expects callback that has some type as a paramter:

var f = (cb: ({ a, b }: { a: number, b: number }) => void) => { cb({ a:1, b: 1}); };

// you can safely call it giving it the function that accepts parameter
// that the original parameter is assignable to but not the other way around
// because that's the way to guarantee that when our function f calls the callback
// it will provide sufficient amount of data
f(({ a }: { a: number }) => { })

var x = { a: 1, b: 1 };
var y = { a: 1 }

x = y; // error because x would have no b property after that assignment
y = x; // works because y has all it needs after that assignment and it doesn't matter it has property b too

// in other words:
type F = { a: number } extends { a: number, b: number } ? true : false; // false
type T = { a: number, b: number } extends { a: number } ? true : false; // true

// read 'extends' as 'is assignable to'


问:
Unable to add firebase storage to my SwiftUI app using Cocoapod
I'm trying to add firebase to my SwiftUI app using cocoapods. I already added 'Firebase/Auth' and   'Firebase/Firestore' to my podfile and everything was fine. but when I tried to add 'Firebase/Storage' I got error  " CDN: trunk Repo update failed - 31 error(s):"

I tried pod repo remove trunk and then pod install and now get the same error even when try to add 'Firebase/Auth' and   'Firebase/Firestore'

My pod file

```<code># Uncomment the next line to define a global platform for your project
 platform :ios, '13.0'

target 'SwiftUI-Chat' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for SwiftUI-Chat
pod 'Firebase/Auth'
pod 'Firebase/Firestore'
pod 'Firebase/Storage'
end
</code>```

Error:

```<code> [!] CDN: trunk Repo update failed - 31 error(s):
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.1/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.2/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.3/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.4/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.5/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.6/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.1.0/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
</code>```

答:
Please try again.

This looks like a region-specific issue that was resolved. More detail at https://github.com/CocoaPods/CocoaPods/issues/9834#issuecomment-636947377

Body:
I'm trying to add firebase to my SwiftUI app using cocoapods. I already added 'Firebase/Auth' and   'Firebase/Firestore' to my podfile and everything was fine. but when I tried to add 'Firebase/Storage' I got error  " CDN: trunk Repo update failed - 31 error(s):"

I tried pod repo remove trunk and then pod install and now get the same error even when try to add 'Firebase/Auth' and   'Firebase/Firestore'

My pod file

# Uncomment the next line to define a global platform for your project
 platform :ios, '13.0'

target 'SwiftUI-Chat' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for SwiftUI-Chat
pod 'Firebase/Auth'
pod 'Firebase/Firestore'
pod 'Firebase/Storage'
end

Error:

 [!] CDN: trunk Repo update failed - 31 error(s):
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.1/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.2/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.3/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.4/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.5/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.0.6/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK
    CDN: trunk URL couldn't be downloaded: https://cdn.jsdelivr.net/cocoa/Specs/3/c/c/FirebaseStorage/1.1.0/FirebaseStorage.podspec.json Response: SSL peer certificate or SSH remote key was not OK


问:
Remove repetition from if-else statement
I have written an if...else statement which uses an array myArr and a string myStr as follows:

```<code>If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If
</code>```

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

答:
I guess this would do the trick:</p>

```<code>If myArr.Length > 0 Then
   If myArr(0) = "-1" Then
      'Do stuff
   Else
      'Do stuff
   End If
ElseIf myStr= "xyz" Then
  'Do stuff
Else
  'Do Nothing
End If
</code>```

Body:
I have written an if...else statement which uses an array myArr and a string myStr as follows:

If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

Body:
I guess this would do the trick:

If myArr.Length > 0 Then
   If myArr(0) = "-1" Then
      'Do stuff
   Else
      'Do stuff
   End If
ElseIf myStr= "xyz" Then
  'Do stuff
Else
  'Do Nothing
End If


问:
Search tabs in laravel
I'm building an app in Laravel and everything is working fine except one thing.

I want to make some search tabs (don't know if this is the right term to use) so it is easier to search for information. My objective is to do something like this:

And this is what I have:

This is the code of my page:

```<code>@extends('layouts.app')
@section('css')
<link rel="stylesheet" href="{{ asset('css/bootstrap-datepicker.min.css') }}">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
@endsection

@section('js')
<script src="{{ asset('js/sweetalert.min.js') }}" defer></script>
<script src="{{ asset('js/jquery.dataTables.js') }}" defer></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js" defer></script>
<script src="{{ asset('js/bootstrap-datepicker.min.js') }}" defer></script>
<script src="{{ asset('js/bootstrap-datepicker.pt.min.js') }}" defer></script>
@endsection

@section('content')
<div class="container">
<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between">
        <span>
            <i class="fas fa-building"></i>
            <strong class="text-uppercase">Gestão de Obras</strong>
        </span>

        <a href="{{ route('constructions.create') }}" class="btn btn-outline-primary">
            <i class="fas fa-plus"></i>
            Criar obra
        </a>
    </div>

    <div class="card-body">
        <table class="table table-striped table-bordered guaca-table">
            <thead>
                <tr>
                    <th>Referência</th>
                    <th>Nome</th>
                    <th>Descrição</th>
                    <th>Morada</th>
                    <th>Terminada em</th>
                    <th class="guaca-table-head-actions" style="text-align:center">Ações</th>
                </tr>
            </thead>

            <tbody>
                @foreach ($constructions as $construction)
                    <tr>
                        <td>{{ $construction->reference }}</td>
                        <td>{{ $construction->name }}</td>
                        <td>{{ \Illuminate\Support\Str::limit($construction->description, 50, '...') }}</td>
                        <td>{{ \Illuminate\Support\Str::limit($construction->address, 100, '...') }}</td>
                        <td>
                            @if ($construction->has_ended)
                                {{ $construction->end_date }}
                            @else
                                -
                            @endif
                        </td>
                        <td class="d-flex justify-content-around">
                            @if (!$construction->is_system)
                                    <a href="{{ route('constructions.edit', $construction->id) }}" class="btn btn-sm btn-outline-primary">
                                        <i class="far fa-edit"></i>
                                    </a>
                                    @if (!$construction->has_ended)
                                        <!-- BOTÂO DE TERMINAR OBRAS -->
                                        <button type="button" class="btn btn-sm btn-outline-primary"
                                            data-toggle="modal" data-target="#end-modal-{{ $construction->id }}">
                                            <i class="far fa-calendar-times"></i>
                                        </button>
                                        <!-- MODAL DE TERMINAR OBRAS -->
                                        <div class="modal fade" id="end-modal-{{ $construction->id }}" tabindex="-1" role="dialog"
                                            aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                                            <div class="modal-dialog modal-dialog-centered" role="document">
                                                <div class="modal-content">
                                                    <form method="POST" action="{{ route('constructions.end', ['id' => $construction->id]) }}">
                                                        @csrf
                                                        <div class="modal-header">
                                                            <h5 class="modal-title" id="exampleModalLongTitle">
                                                                Terminar obra
                                                            </h5>
                                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                <span aria-hidden="true">×</span>
                                                            </button>
                                                        </div>

                                                        <div class="modal-body">
                                                            <strong>
                                                                Referência:
                                                            </strong>
                                                            <div>
                                                                {{ $construction->reference }}
                                                            </div>
                                                            <br>
                                                            <strong>
                                                                Nome:
                                                            </strong>
                                                            <div>
                                                                {{ $construction->name }}
                                                            </div>
                                                            <br>
                                                            <strong>
                                                                Morada:
                                                            </strong>
                                                            <div>
                                                                {{ $construction->address }}
                                                            </div>
                                                            <br>
                                                            <strong>
                                                                Data de Término:
                                                            </strong>
                                                            <input id="end_date"
                                                                type="date" class="form-control datepicker {{ $errors->has('end_date') ? 'is-invalid' : '' }}"
                                                                name="end_date" value="{{ old('end_date') }}" required>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
                                                            <button type="submit" class="btn btn-primary">Terminar obra</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    @endif
                                    <form method="POST" class="delete-form"
                                        action="{{ route('constructions.destroy', $construction->id) }}">
                                        @csrf
                                        @method('delete')
                                        <button type="submit" class="btn btn-sm btn-outline-danger">
                                            <i class="far fa-trash-alt"></i>
                                        </button>
                                    </form>
                            @else
                                <span class="badge badge-primary">
                                    SISTEMA
                                </span>
                            @endif
                        </td>
                    </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>
</code>```

          @endsection

I have tried to create a app.js inside the assets folder and then inside the JS folder and this is my code, but it's not working:

```<code>require('./bootstrap');

$(document).ready(function () {
var $datepickers = $('.datepicker');

$datepickers.each(function () {
    $(this).datepicker({
        language: 'pt',
        format: 'yyyy-mm-dd',
        useCurrent: true
    });
});

//ao mexer na dropdown no formulario de COMPRAS
$('.form-group-slider').on('change', function () {
    var $target = $(this.dataset.sliderTarget);

    if (!!this.value) {
        $target.slideUp();
    } else {
        $target.slideDown();
    }
});

$('.delete-form').on('submit', function (e) {
    var $form = $(this);

    if ($form.data('allow') !== true) {
        e.preventDefault();

        swal({
          title: "Tem a certeza que pretende apagar?",
          text: "Esta operação é irreversível!",
          icon: "warning",
          dangerMode: true,
          buttons: ["Cancelar", "Sim, tenho a certeza"],
        })
        .then((willDelete) => {
          if (willDelete) {
            $form.data('allow', true);
            $form.submit();
          }
        });
    }
});

$('.select2').each(function () {
    $(this).select2();
});

$('.guaca-table').each(function () {
    var $table = $(this);

    if (!$table) {
        return;
    }

    var initialHeadCount = $table.find('th').length;
    var orderableArray = [];

    for (var i = initialHeadCount - 2; i >= 0; i--) {
        orderableArray.push(i);
    }

    $('.guaca-table thead tr').clone(true).appendTo( '.guaca-table thead' );
    $('.guaca-table thead tr:eq(1) th').each(function (i) {
        var $th = $(this);

        if ($th.hasClass('guaca-table-head-actions')) {
            return;
        }

        var title = $th.text();
        $th.html( '<input type="text" class="form-control form-control-sm" placeholder="Pesquisar ' + title + '" />');

        $('input', this).on('keyup change', function () {
            if (dataTable.column(i).search() !== this.value) {
                dataTable.column(i).search(this.value).draw();
            }
        });
    });

    dataTable = $table.DataTable({
        responsive: true,
        fixedHeader: true,
        orderCellsTop: true,
        columnDefs: [
            { targets: orderableArray, orderable: true },
            { targets: ["_all"], orderable: false }
        ],
        language: {
            decimal: "",
            emptyTable: "Não existem items.",
            info: "Mostrar _START_ a _END_ de um total de _TOTAL_ items",
            infoEmpty: "Mostrar 0 a 0 de um total de 0 items",
            infoFiltered: "(Filtrado de um total de _MAX_ items)",
            infoPostFix: "",
            thousands: ",",
            lengthMenu: "Mostrar _MENU_ items",
            loadingRecords: "A carregar...",
            processing: "A processar...",
            search: "Pesquisar:",
            zeroRecords: "A pesquisa não retornou resultados.",
            paginate: {
                first: "Primeiro",
                last: "Último",
                next: "Próximo",
                previous: "Anterior"
            },
            aria: {
                sortAscending: "Ativar para ordenar coluna por ordem ascendente.",
                sortDescending: "Ativar para ordenar coluna por ordem descendente."
            }
        }
    });
});
});
</code>```

答:
What you are referencing in your "want" is part of "DataTables" there is a laravel package for integrating the server side of DataTables. ( https://github.com/yajra/laravel-datatables ).

Please see www.datatables.net to learn how to set it up like you want.  It is a very powerful table package with several different ways to initialize it.  It does not appear that datatables is actually initializing the table - likely you have an error in your datatables initialization code.

Title: Search tabs in laravel

Body:
I'm building an app in Laravel and everything is working fine except one thing.

I want to make some search tabs (don't know if this is the right term to use) so it is easier to search for information. My objective is to do something like this:

And this is what I have:

This is the code of my page:

@extends('layouts.app')
@section('css')
<link rel="stylesheet" href="{{ asset('css/bootstrap-datepicker.min.css') }}">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
@endsection

@section('js')

@endsection

@section('content')

            Gestão de Obras

            Criar obra

                    Referência
                    Nome
                    Descrição
                    Morada
                    Terminada em
                    Ações

                @foreach ($constructions as $construction)

                        {{ $construction->reference }}
                        {{ $construction->name }}
                        {{ \Illuminate\Support\Str::limit($construction->description, 50, '...') }}
                        {{ \Illuminate\Support\Str::limit($construction->address, 100, '...') }}

                            @if ($construction->has_ended)
                                {{ $construction->end_date }}
                            @else
                                -
                            @endif

                            @if (!$construction->is_system)
                                    id) }}" class="btn btn-sm btn-outline-primary">

                                    @if (!$construction->has_ended)

                                        <button type="button" class="btn btn-sm btn-outline-primary"
                                            data-toggle="modal" data-target="#end-modal-{{ $construction->id }}">

                                        </button>

id }}" tabindex="-1" role="dialog"
                                            aria-labelledby="exampleModalCenterTitle" aria-hidden="true">

                                                    <form method="POST" action="{{ route('constructions.end', ['id' => $construction->id]) }}">
                                                        @csrf

                                                                Terminar obra

                                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                ×
                                                            </button>

                                                                Referência:

                                                                {{ $construction->reference }}

                                                                Nome:

                                                                {{ $construction->name }}

                                                                Morada:

                                                                {{ $construction->address }}

                                                                Data de Término:

                                                            <input id="end_date"
                                                                type="date" class="form-control datepicker {{ $errors->has('end_date') ? 'is-invalid' : '' }}"
                                                                name="end_date" value="{{ old('end_date') }}" required>

                                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
                                                            <button type="submit" class="btn btn-primary">Terminar obra</button>

                                                    </form>

                                    @endif
                                    <form method="POST" class="delete-form"
                                        action="{{ route('constructions.destroy', $construction->id) }}">
                                        @csrf
                                        @method('delete')
                                        <button type="submit" class="btn btn-sm btn-outline-danger">

                                        </button>
                                    </form>
                            @else

                                    SISTEMA

                            @endif

                @endforeach

          @endsection

I have tried to create a app.js inside the assets folder and then inside the JS folder and this is my code, but it's not working:

require('./bootstrap');

$(document).ready(function () {
var $datepickers = $('.datepicker');

$datepickers.each(function () {
    $(this).datepicker({
        language: 'pt',
        format: 'yyyy-mm-dd',
        useCurrent: true
    });
});

//ao mexer na dropdown no formulario de COMPRAS
$('.form-group-slider').on('change', function () {
    var $target = $(this.dataset.sliderTarget);

    if (!!this.value) {
        $target.slideUp();
    } else {
        $target.slideDown();
    }
});

$('.delete-form').on('submit', function (e) {
    var $form = $(this);

    if ($form.data('allow') !== true) {
        e.preventDefault();

        swal({
          title: "Tem a certeza que pretende apagar?",
          text: "Esta operação é irreversível!",
          icon: "warning",
          dangerMode: true,
          buttons: ["Cancelar", "Sim, tenho a certeza"],
        })
        .then((willDelete) => {
          if (willDelete) {
            $form.data('allow', true);
            $form.submit();
          }
        });
    }
});

$('.select2').each(function () {
    $(this).select2();
});

$('.guaca-table').each(function () {
    var $table = $(this);

    if (!$table) {
        return;
    }

    var initialHeadCount = $table.find('th').length;
    var orderableArray = [];

    for (var i = initialHeadCount - 2; i >= 0; i--) {
        orderableArray.push(i);
    }

    $('.guaca-table thead tr').clone(true).appendTo( '.guaca-table thead' );
    $('.guaca-table thead tr:eq(1) th').each(function (i) {
        var $th = $(this);

        if ($th.hasClass('guaca-table-head-actions')) {
            return;
        }

        var title = $th.text();
        $th.html( '<input type="text" class="form-control form-control-sm" placeholder="Pesquisar ' + title + '" />');

        $('input', this).on('keyup change', function () {
            if (dataTable.column(i).search() !== this.value) {
                dataTable.column(i).search(this.value).draw();
            }
        });
    });

    dataTable = $table.DataTable({
        responsive: true,
        fixedHeader: true,
        orderCellsTop: true,
        columnDefs: [
            { targets: orderableArray, orderable: true },
            { targets: ["_all"], orderable: false }
        ],
        language: {
            decimal: "",
            emptyTable: "Não existem items.",
            info: "Mostrar _START_ a _END_ de um total de _TOTAL_ items",
            infoEmpty: "Mostrar 0 a 0 de um total de 0 items",
            infoFiltered: "(Filtrado de um total de _MAX_ items)",
            infoPostFix: "",
            thousands: ",",
            lengthMenu: "Mostrar _MENU_ items",
            loadingRecords: "A carregar...",
            processing: "A processar...",
            search: "Pesquisar:",
            zeroRecords: "A pesquisa não retornou resultados.",
            paginate: {
                first: "Primeiro",
                last: "Último",
                next: "Próximo",
                previous: "Anterior"
            },
            aria: {
                sortAscending: "Ativar para ordenar coluna por ordem ascendente.",
                sortDescending: "Ativar para ordenar coluna por ordem descendente."
            }
        }
    });
});
});


问:
Why not define functions as singleton functions?
Consider definition of a singleton function found in shapeless repo:

```<code>/** Polymorphic function selecting an arbitrary element from a non-empty `Set`. */
object choose extends (Set ~> Option) {
  def apply[T](s : Set[T]) = s.headOption
}
</code>```

Contrast it with the traditional def syntax in the following example:

```<code>package utils

object UtilWithASingleMethod {
  def isSatisfyingSomePredicate(foo: Foo): Boolean = ???
}
</code>```

versus

```<code>package utils

object isSatisfyingSomePredicate extends (Foo => Boolean) {
  def apply(foo: Foo): Boolean = ???
}
</code>```

Note how call-site now becomes

```<code>isSatisfyingSomePredicate(foo)
</code>```

instead of

```<code>UtilWithASingleMethod.isSatisfyingSomePredicate(foo)
</code>```

or

```<code>import UtilWithASingleMethod._

isSatisfyingSomePredicate(foo)
</code>```

Personally, UtilWithASingleMethod package seems forced just to be able to use familiar def syntax but does not add any useful information.

Besides subjective downsides such as unfamiliarity, or confusion with object+apply style used in factory pattern, are there any technical downsides with singleton function definitions?

答:
Scala 3 (Dotty) supports toplevel definitions so instead of

```<code>package utils

object UtilWithASingleMethod {
  def isSatisfyingSomePredicate(foo: Foo): Boolean = ???
}
</code>```

we can remove the indirection and write

```<code>package utils

def isSatisfyingSomePredicate(foo: Foo): Boolean = ???
</code>```

which indeed addresses my question.

Body:
Consider definition of a singleton function found in shapeless repo:

/** Polymorphic function selecting an arbitrary element from a non-empty `Set`. */
object choose extends (Set ~> Option) {
  def apply[T](s : Set[T]) = s.headOption
}

Contrast it with the traditional def syntax in the following example:

package utils

object UtilWithASingleMethod {
  def isSatisfyingSomePredicate(foo: Foo): Boolean = ???
}

versus

package utils

object isSatisfyingSomePredicate extends (Foo => Boolean) {
  def apply(foo: Foo): Boolean = ???
}

Note how call-site now becomes

isSatisfyingSomePredicate(foo)

instead of

UtilWithASingleMethod.isSatisfyingSomePredicate(foo)

or

import UtilWithASingleMethod._

isSatisfyingSomePredicate(foo)

Personally, UtilWithASingleMethod package seems forced just to be able to use familiar def syntax but does not add any useful information.

Besides subjective downsides such as unfamiliarity, or confusion with object+apply style used in factory pattern, are there any technical downsides with singleton function definitions?

Body:
Scala 3 (Dotty) supports toplevel definitions so instead of

package utils

object UtilWithASingleMethod {
  def isSatisfyingSomePredicate(foo: Foo): Boolean = ???
}

we can remove the indirection and write

package utils

def isSatisfyingSomePredicate(foo: Foo): Boolean = ???

which indeed addresses my question.


问:
Cannot upgrade feathers CLI
I am desperately trying to upgrade the feathers CLI from 3.9 to 4.x+, however

```<code>npm remove -g @feathersjs/cli  <-- even after doing this I still can use feathersCLI? (feathers -V)
npm install -g @feathersjs/cli  <-- should install latest
feathers -V <--- 3.9 ?!
</code>```

How do I manually remove it?

Os: Mac OS

答:
okay, had to do it manually. I had to alter the config myself</p>

```<code> nano ~/.config/yarn/global/package.json <- add the package here using nano or any other text editor

 yarn global add <- to update everything
</code>```

Title: Cannot upgrade feathers CLI

Body:
I am desperately trying to upgrade the feathers CLI from 3.9 to 4.x+, however

npm remove -g @feathersjs/cli  <-- even after doing this I still can use feathersCLI? (feathers -V)
npm install -g @feathersjs/cli  <-- should install latest
feathers -V <--- 3.9 ?!

How do I manually remove it?

Os: Mac OS

Body:
okay, had to do it manually. I had to alter the config myself

 nano ~/.config/yarn/global/package.json <- add the package here using nano or any other text editor

 yarn global add <- to update everything


问:
SQL Formula Query | (DATEDIFF / DATEDIFF) Returning 0
I have a conundrum surrounding the DATEDIFF SQL Function, essentially i have a list of customers with policies, such as insurance. I can obtain the following Details:

Policy End Date

Policy Start Date

Today's Date

I'm trying to extract the % of which the policy term has reached, essentially to get this i have converted the above into "Days" using the DATEDIFF function to get how many days have passed and how many days in total. I want to divide these to get the % but the output is coming in at 0

My formula, were both sides of the division work separately but not together is as below:

```<code>,   (DATEDIFF(DD,DATEADD(YY,-1,P.RDAT#),GETDATE()))
    /
    DATEDIFF(DD,DATEADD(YY,-1,P.RDAT#),P.Rdat#)
</code>```

Have tried casting / converting thinking it was something do do with this but to no avail, if anyone can help that would be super.

Thanks in advance

答:
SQL Server does integer division, so 1/2 is 0 rather than 0.5.  I think you want:

```<code>(DATEDIFF(DAY, DATEADD(YEAR, -1, P.RDAT#), GETDATE())) * 1.0 /
 DATEDIFF(DAY, DATEADD(YEAR, -1, P.RDAT#), P.Rdat#)
</code>```

I am not sure what the dateadd() is supposed to be doing.  You may be able to simplify this logic.  For that, I would recommend asking a new question with sample data and desired results.

Body:
I have a conundrum surrounding the DATEDIFF SQL Function, essentially i have a list of customers with policies, such as insurance. I can obtain the following Details:

Policy End Date

Policy Start Date

Today's Date

I'm trying to extract the % of which the policy term has reached, essentially to get this i have converted the above into "Days" using the DATEDIFF function to get how many days have passed and how many days in total. I want to divide these to get the % but the output is coming in at 0

My formula, were both sides of the division work separately but not together is as below:

,   (DATEDIFF(DD,DATEADD(YY,-1,P.RDAT#),GETDATE()))
    /
    DATEDIFF(DD,DATEADD(YY,-1,P.RDAT#),P.Rdat#)

Have tried casting / converting thinking it was something do do with this but to no avail, if anyone can help that would be super.

Thanks in advance

Body:
SQL Server does integer division, so 1/2 is 0 rather than 0.5.  I think you want:

(DATEDIFF(DAY, DATEADD(YEAR, -1, P.RDAT#), GETDATE())) * 1.0 /
 DATEDIFF(DAY, DATEADD(YEAR, -1, P.RDAT#), P.Rdat#)

I am not sure what the dateadd() is supposed to be doing.  You may be able to simplify this logic.  For that, I would recommend asking a new question with sample data and desired results.


问:
ASP - how to remove single quote from user input text
```<code>answer  = Request.Form("Text" & i)
</code>```

In a form a user inputs random text which is inserted into a database. Currently if the user puts in single quotes it creates an error. How do i remove just single quotes' from the users answer?

答: answer was to use ... Replace(answer, "'", "")</p>

Body:
answer  = Request.Form("Text" & i)

In a form a user inputs random text which is inserted into a database. Currently if the user puts in single quotes it creates an error. How do i remove just single quotes' from the users answer?


问:
get_attribute problem with selenium python
I've been suing Selenium-Python for about 2 months. I want to get 'rel' attribute value. Every other values are working, but 'rel' value returns none
i.e

```<code><span class="isOdd" data-ratio="-1" data-outcome="1.85" data-percentage="23" data-market-id="1677954" data-outcomeno="1" data-id="undefined" rel="[{'fixedoddsweb':'1.62','ratiostatus':0},{'fixedoddsweb':'1.90','ratiostatus':-1},{'fixedoddsweb':'1.85','ratiostatus':-1}]" style="" xpath="1">1.85
</code>```

and if I try like;

```<code>link = browser.find_element_by_xpath("//*[@id='eventContentContainer']/div[2]/div[1]/span[4]/ul/li[1]/span")
print(str(link.get_attribute("class")))
</code>```

it returns, isOdd and its correct .
Or if I try to take data-id it returns undefined which is correct value again. Now,

If I try to take rel attribute it returns "None"

I searched on the internet, they always same thing again and again about get_attribute value. I am not good in HTML. Is there any special thing for rel attribute?

Edit 1:
I also used execute.script() for another element, and the output like;

```<code>{'class': 'isOdd', 'data-id': 'undefined', 'data-market-id': '1679546', 'data-outcome': '3.10', 'data-outcomeno': '1', 'data-percentage': '3', 'data-ratio': '-1'}
</code>```

every attribute was printed except 'rel'

Edit 2:
I found the REAL problem, if you wait on the element about 1-2 seconds, then some tags pops on the elenment then it has rel attribute. Do you know how to wait on the element about 1 sec then click? I guess it is about dynamic element

答:
I found my solution. There is 'rel' attribute at first. If you hover on element, then it has 'rel' attribute.
Thank to @0buz for the patience. But I found the solution. </p>

```<code>link = browser.find_element_by_xpath("//*[@id='eventContentContainer']/div[2]/div[1]/span[4]/ul/li[1]/span")
hov = ActionChains(browser).move_to_element(link)
hov.perform()
time.sleep(3)

print(link.get_attribute("rel"))
</code>```

<p>That's all my basic mistake shortly :) </p>

Body:
I've been suing Selenium-Python for about 2 months. I want to get 'rel' attribute value. Every other values are working, but 'rel' value returns none
i.e

1.85

and if I try like;

link = browser.find_element_by_xpath("//*[@id='eventContentContainer']/div[2]/div[1]/span[4]/ul/li[1]/span")
print(str(link.get_attribute("class")))

it returns, isOdd and its correct .
Or if I try to take data-id it returns undefined which is correct value again. Now,

If I try to take rel attribute it returns "None"

I searched on the internet, they always same thing again and again about get_attribute value. I am not good in HTML. Is there any special thing for rel attribute?

Edit 1:
I also used execute.script() for another element, and the output like;

{'class': 'isOdd', 'data-id': 'undefined', 'data-market-id': '1679546', 'data-outcome': '3.10', 'data-outcomeno': '1', 'data-percentage': '3', 'data-ratio': '-1'}

every attribute was printed except 'rel'

Edit 2:
I found the REAL problem, if you wait on the element about 1-2 seconds, then some tags pops on the elenment then it has rel attribute. Do you know how to wait on the element about 1 sec then click? I guess it is about dynamic element

Body:
I found my solution. There is 'rel' attribute at first. If you hover on element, then it has 'rel' attribute.
Thank to @0buz for the patience. But I found the solution.

link = browser.find_element_by_xpath("//*[@id='eventContentContainer']/div[2]/div[1]/span[4]/ul/li[1]/span")
hov = ActionChains(browser).move_to_element(link)
hov.perform()
time.sleep(3)

print(link.get_attribute("rel"))

That's all my basic mistake shortly :)


问:
R: if_else and timezone forcing
I have a weird problem (maybe I'm missing something?), when trying to force timezone within if_else (as ifelse does not seem to handle POSIXct well). It seems to force only when TRUE, but convert when FALSE. Why? How to fix it?

```<code>library(lubridate)
library(dplyr)
some_date = ymd_hm("2020-06-01 17:45", tz = "America/New_York")

if_else(TRUE, force_tz(some_date, tz = "GMT"), force_tz(some_date, tz = "Singapore"))
[1] "2020-06-01 17:45:00 GMT"

if_else(FALSE, force_tz(some_date, tz = "GMT"), force_tz(some_date, tz = "Singapore"))
[1] "2020-06-01 09:45:00 GMT"
</code>```

I would expect the same outcome as running force_tz alone:

```<code># if TRUE
force_tz(some_date, tz = "GMT")
[1] "2020-06-01 17:45:00 GMT"

# if FALSE
force_tz(some_date, tz = "Singapore")
[1] "2020-06-01 17:45:00 +08"
</code>```

Thanks!

答:
The culprit is in how dplyr::if_else is making the adjustments.

First, my original comment about vectors and TZ still stands, and is still at the heart of this problem. For the record:

When you're dealing with POSIXt in a vector, the TZ is an attribute of the whole vector, not each independent element. This means that either (a) you must accept that all timestamps within a vector will have the same TZ; or (b) you need to adapt your process to deal with a list of timestamps, in which case each time can have its own TZ.

If you look at if_else:

function (condition, true, false, missing = NULL)
{
    if (!is.logical(condition)) {
        bad_args("condition", "must be a logical vector, not {friendly_type_of(condition)}")
    }
    out <- true[rep(NA_integer_, length(condition))]
```

<p>which prepopulates the <code>out</code> vector with <code>NA</code> variants of the first ("true") vector. (This is necessary because R really has at least 6 types of <code>NA</code>: logical (<code>NA</code>), integer (<code>NA_integer_</code>), real/float (<code>NA_real_</code>), string (<code>NA_character_</code>), date (<code>c.Date(NA)</code>), and time (<code>c.POSIXct(NA)</code>); so <em>how</em> one forms a vector of <code>NA</code> is important.) Once the vector of <code>NA</code>s is prepopulated, though, realize that this is being based on the first vector, so its attributes are brought into the <code>out</code> vector.</p>

<pre class="lang-r prettyprint-override"><code>Sys.time()
# [1] "2020-06-01 09:02:06 PDT"
now <- Sys.time()
attr(now, "tzone") <- "GMT"
dput(now)
# structure(1591027335.41804, class = c("POSIXct", "POSIXt"), tzone = "GMT")
dput(now[NA])
# structure(NA_real_, class = c("POSIXct", "POSIXt"), tzone = "GMT")
</code>```

(see how tzone= is still the same). This means that the output vector (when operating on POSIXt vectors)will always carry forward the TZ of thetrueargument toif_else`.

From here, if_else works in replacement (using its internal replace_with, which effectively just does out[condition] <- false[condition]). Replacement does not affect the TZ; in fact, the numeric equivalents of the false times are assimilated without regard to their TZ. Granted, the "absolute time in the world" for the false vector is preserved.

The only workaround is to change your workflow to deal with a list of POSIXt instead of a vector. if_else still works there.

now
# [1] "2020-06-01 16:02:15 GMT"
now1 <- list(now, now+1) ; now2 <- list(now+86400, now+86401)
now1
# [[1]]
# [1] "2020-06-01 16:02:15 GMT"
# [[2]]
# [1] "2020-06-01 16:02:16 GMT"
now2
# [[1]]
# [1] "2020-06-02 16:02:15 GMT"
# [[2]]
# [1] "2020-06-02 16:02:16 GMT"
attr(now1[[2]], "tzone") <- "Singapore"
attr(now2[[2]], "tzone") <- "US/Pacific"
now1
# [[1]]
# [1] "2020-06-01 16:02:15 GMT"
# [[2]]
# [1] "2020-06-02 00:02:16 +08"
now2
# [[1]]
# [1] "2020-06-02 16:02:15 GMT"
# [[2]]
# [1] "2020-06-02 09:02:16 PDT"
if_else(c(TRUE, FALSE), now1, now2)
# [[1]]
# [1] "2020-06-01 16:02:15 GMT"
# [[2]]
# [1] "2020-06-02 09:02:16 PDT"
```

Title: R: if_else and timezone forcing

Body:
I have a weird problem (maybe I'm missing something?), when trying to force timezone within if_else (as ifelse does not seem to handle POSIXct well). It seems to force only when TRUE, but convert when FALSE. Why? How to fix it?

library(lubridate)
library(dplyr)
some_date = ymd_hm("2020-06-01 17:45", tz = "America/New_York")

if_else(TRUE, force_tz(some_date, tz = "GMT"), force_tz(some_date, tz = "Singapore"))
[1] "2020-06-01 17:45:00 GMT"

if_else(FALSE, force_tz(some_date, tz = "GMT"), force_tz(some_date, tz = "Singapore"))
[1] "2020-06-01 09:45:00 GMT"

I would expect the same outcome as running force_tz alone:

# if TRUE
force_tz(some_date, tz = "GMT")
[1] "2020-06-01 17:45:00 GMT"

# if FALSE
force_tz(some_date, tz = "Singapore")
[1] "2020-06-01 17:45:00 +08"

Thanks!

Body:
The culprit is in how dplyr::if_else is making the adjustments.

First, my original comment about vectors and TZ still stands, and is still at the heart of this problem. For the record:

When you're dealing with POSIXt in a vector, the TZ is an attribute of the whole vector, not each independent element. This means that either (a) you must accept that all timestamps within a vector will have the same TZ; or (b) you need to adapt your process to deal with a list of timestamps, in which case each time can have its own TZ.

If you look at if_else:

function (condition, true, false, missing = NULL)
{
    if (!is.logical(condition)) {
        bad_args("condition", "must be a logical vector, not {friendly_type_of(condition)}")
    }
    out <- true[rep(NA_integer_, length(condition))]

which prepopulates the out vector with NA variants of the first ("true") vector. (This is necessary because R really has at least 6 types of NA: logical (NA), integer (NA_integer_), real/float (NA_real_), string (NA_character_), date (c.Date(NA)), and time (c.POSIXct(NA)); so how one forms a vector of NA is important.) Once the vector of NAs is prepopulated, though, realize that this is being based on the first vector, so its attributes are brought into the out vector.

Sys.time()
# [1] "2020-06-01 09:02:06 PDT"
now <- Sys.time()
attr(now, "tzone") <- "GMT"
dput(now)
# structure(1591027335.41804, class = c("POSIXct", "POSIXt"), tzone = "GMT")
dput(now[NA])
# structure(NA_real_, class = c("POSIXct", "POSIXt"), tzone = "GMT")

(see how tzone= is still the same). This means that the output vector (when operating on POSIXt vectors)will always carry forward the TZ of thetrueargument toif_else`.

From here, if_else works in replacement (using its internal replace_with, which effectively just does out[condition] <- false[condition]). Replacement does not affect the TZ; in fact, the numeric equivalents of the false times are assimilated without regard to their TZ. Granted, the "absolute time in the world" for the false vector is preserved.

The only workaround is to change your workflow to deal with a list of POSIXt instead of a vector. if_else still works there.

now
# [1] "2020-06-01 16:02:15 GMT"
now1 <- list(now, now+1) ; now2 <- list(now+86400, now+86401)
now1
# [[1]]
# [1] "2020-06-01 16:02:15 GMT"
# [[2]]
# [1] "2020-06-01 16:02:16 GMT"
now2
# [[1]]
# [1] "2020-06-02 16:02:15 GMT"
# [[2]]
# [1] "2020-06-02 16:02:16 GMT"
attr(now1[[2]], "tzone") <- "Singapore"
attr(now2[[2]], "tzone") <- "US/Pacific"
now1
# [[1]]
# [1] "2020-06-01 16:02:15 GMT"
# [[2]]
# [1] "2020-06-02 00:02:16 +08"
now2
# [[1]]
# [1] "2020-06-02 16:02:15 GMT"
# [[2]]
# [1] "2020-06-02 09:02:16 PDT"
if_else(c(TRUE, FALSE), now1, now2)
# [[1]]
# [1] "2020-06-01 16:02:15 GMT"
# [[2]]
# [1] "2020-06-02 09:02:16 PDT"


问:
flash cannot access the webservice
I am using flex/actionscript. i have created a webservice with following path http://192.168.0.110/cgi/reg.cgi? When i run the above url its works fine. but when i use it using httpservice and send method it is giving me error. event: registerFailure
Error description: HTTP update error </p>

```<code>mHttpService = new HTTPService();
mHttpService.url = mWebServiceUrl;
mHttpService.method = "POST";
mHttpService.addEventListener("result", httpResult);
mHttpService.addEventListener("fault", httpFault);

var request:Object = new Object();
request.username = user;
request.identity = id;
mHttpService.cancel();
mHttpService.send(request);
</code>```

答:
As far as i understand the webservice should be of format.
eg: http://www.w3schools.com/webservices/tempconvert.asmx?WSDL (This works try!).

And link for this web service is page is http://www.w3schools.com/webservices/tempconvert.asmx.

So, i think. There is problem with the web service link.
Hope , this helps.

Title: flash cannot access the webservice

Body:
I am using flex/actionscript. i have created a webservice with following path http://192.168.0.110/cgi/reg.cgi? When i run the above url its works fine. but when i use it using httpservice and send method it is giving me error. event: registerFailure
Error description: HTTP update error

mHttpService = new HTTPService();
mHttpService.url = mWebServiceUrl;
mHttpService.method = "POST";
mHttpService.addEventListener("result", httpResult);
mHttpService.addEventListener("fault", httpFault);

var request:Object = new Object();
request.username = user;
request.identity = id;
mHttpService.cancel();
mHttpService.send(request);


问:
How to get domain of words using WordNet in Python?
How can I find domain of words using nltk Python module and WordNet?

Suppose I have words like (transaction, Demand Draft, cheque, passbook) and the domain for all these words is "BANK". How can we get this using nltk and WordNet in Python?

I am trying through hypernym and hyponym relationship:

For example:

```<code>from nltk.corpus import wordnet as wn
sports = wn.synset('sport.n.01')
sports.hyponyms()
[Synset('judo.n.01'), Synset('athletic_game.n.01'), Synset('spectator_sport.n.01'),    Synset('contact_sport.n.01'), Synset('cycling.n.01'), Synset('funambulism.n.01'), Synset('water_sport.n.01'), Synset('riding.n.01'), Synset('gymnastics.n.01'), Synset('sledding.n.01'), Synset('skating.n.01'), Synset('skiing.n.01'), Synset('outdoor_sport.n.01'), Synset('rowing.n.01'), Synset('track_and_field.n.01'), Synset('archery.n.01'), Synset('team_sport.n.01'), Synset('rock_climbing.n.01'), Synset('racing.n.01'), Synset('blood_sport.n.01')]
</code>```

and

```<code>bark = wn.synset('bark.n.02')
bark.hypernyms()
[Synset('noise.n.01')]
</code>```

答:
As @alvas suggests, you can use WordNetDomains. You have to download both WordNet2.0 (in its current status WordNetDomains does not support the sense inventory of WordNet3.0, which is the default version of WordNet used by NLTK) and WordNetDomains.

WordNet2.0 can be downloaded from here

WordNetDomains can be downloaded from here (after having being granted permission).

I have created a very simple Python API that loads both resources in Python3.x and provides some common routines you might need (such as getting a set of domains linked to a given term, or to a given synset, etc.). The data load of WordNetDomains is from @alvas.

This is how it looks like (with most comments omitted):

```<code>from collections import defaultdict
from nltk.corpus import WordNetCorpusReader
from os.path import exists

class WordNetDomains:
    def __init__(self, wordnet_home):
        #This class assumes you have downloaded WordNet2.0 and WordNetDomains and that they are on the same data home.
        assert exists(f'{wordnet_home}/WordNet-2.0'), f'error: missing WordNet-2.0 in {wordnet_home}'
        assert exists(f'{wordnet_home}/wn-domains-3.2'), f'error: missing WordNetDomains in {wordnet_home}'

        # load WordNet2.0
        self.wn = WordNetCorpusReader(f'{wordnet_home}/WordNet-2.0/dict', 'WordNet-2.0/dict')

        # load WordNetDomains (based on https://stackoverflow.com/a/21904027/8759307)
        self.domain2synsets = defaultdict(list)
        self.synset2domains = defaultdict(list)
        for i in open(f'{wordnet_home}/wn-domains-3.2/wn-domains-3.2-20070223', 'r'):
            ssid, doms = i.strip().split('\t')
            doms = doms.split()
            self.synset2domains[ssid] = doms
            for d in doms:
                self.domain2synsets[d].append(ssid)

    def get_domains(self, word, pos=None):
        word_synsets = self.wn.synsets(word, pos=pos)
        domains = []
        for synset in word_synsets:
            domains.extend(self.get_domains_from_synset(synset))
        return set(domains)

    def get_domains_from_synset(self, synset):
        return self.synset2domains.get(self._askey_from_synset(synset), set())

    def get_synsets(self, domain):
        return [self._synset_from_key(key) for key in self.domain2synsets.get(domain, [])]

    def get_all_domains(self):
        return set(self.domain2synsets.keys())

    def _synset_from_key(self, key):
        offset, pos = key.split('-')
        return self.wn.synset_from_pos_and_offset(pos, int(offset))

    def _askey_from_synset(self, synset):
        return self._askey_from_offset_pos(synset.offset(), synset.pos())

    def _askey_from_offset_pos(self, offset, pos):
        return str(offset).zfill(8) + "-" + pos
</code>```

Body:
How can I find domain of words using nltk Python module and WordNet?

Suppose I have words like (transaction, Demand Draft, cheque, passbook) and the domain for all these words is "BANK". How can we get this using nltk and WordNet in Python?

I am trying through hypernym and hyponym relationship:

For example:

from nltk.corpus import wordnet as wn
sports = wn.synset('sport.n.01')
sports.hyponyms()
[Synset('judo.n.01'), Synset('athletic_game.n.01'), Synset('spectator_sport.n.01'),    Synset('contact_sport.n.01'), Synset('cycling.n.01'), Synset('funambulism.n.01'), Synset('water_sport.n.01'), Synset('riding.n.01'), Synset('gymnastics.n.01'), Synset('sledding.n.01'), Synset('skating.n.01'), Synset('skiing.n.01'), Synset('outdoor_sport.n.01'), Synset('rowing.n.01'), Synset('track_and_field.n.01'), Synset('archery.n.01'), Synset('team_sport.n.01'), Synset('rock_climbing.n.01'), Synset('racing.n.01'), Synset('blood_sport.n.01')]

and

bark = wn.synset('bark.n.02')
bark.hypernyms()
[Synset('noise.n.01')]

Body:
As @alvas suggests, you can use WordNetDomains. You have to download both WordNet2.0 (in its current status WordNetDomains does not support the sense inventory of WordNet3.0, which is the default version of WordNet used by NLTK) and WordNetDomains.

WordNet2.0 can be downloaded from here

WordNetDomains can be downloaded from here (after having being granted permission).

I have created a very simple Python API that loads both resources in Python3.x and provides some common routines you might need (such as getting a set of domains linked to a given term, or to a given synset, etc.). The data load of WordNetDomains is from @alvas.

This is how it looks like (with most comments omitted):

from collections import defaultdict
from nltk.corpus import WordNetCorpusReader
from os.path import exists

class WordNetDomains:
    def __init__(self, wordnet_home):
        #This class assumes you have downloaded WordNet2.0 and WordNetDomains and that they are on the same data home.
        assert exists(f'{wordnet_home}/WordNet-2.0'), f'error: missing WordNet-2.0 in {wordnet_home}'
        assert exists(f'{wordnet_home}/wn-domains-3.2'), f'error: missing WordNetDomains in {wordnet_home}'

        # load WordNet2.0
        self.wn = WordNetCorpusReader(f'{wordnet_home}/WordNet-2.0/dict', 'WordNet-2.0/dict')

        # load WordNetDomains (based on https://stackoverflow.com/a/21904027/8759307)
        self.domain2synsets = defaultdict(list)
        self.synset2domains = defaultdict(list)
        for i in open(f'{wordnet_home}/wn-domains-3.2/wn-domains-3.2-20070223', 'r'):
            ssid, doms = i.strip().split('\t')
            doms = doms.split()
            self.synset2domains[ssid] = doms
            for d in doms:
                self.domain2synsets[d].append(ssid)

    def get_domains(self, word, pos=None):
        word_synsets = self.wn.synsets(word, pos=pos)
        domains = []
        for synset in word_synsets:
            domains.extend(self.get_domains_from_synset(synset))
        return set(domains)

    def get_domains_from_synset(self, synset):
        return self.synset2domains.get(self._askey_from_synset(synset), set())

    def get_synsets(self, domain):
        return [self._synset_from_key(key) for key in self.domain2synsets.get(domain, [])]

    def get_all_domains(self):
        return set(self.domain2synsets.keys())

    def _synset_from_key(self, key):
        offset, pos = key.split('-')
        return self.wn.synset_from_pos_and_offset(pos, int(offset))

    def _askey_from_synset(self, synset):
        return self._askey_from_offset_pos(synset.offset(), synset.pos())

    def _askey_from_offset_pos(self, offset, pos):
        return str(offset).zfill(8) + "-" + pos


问:
Issue with model classes after database updates,
I have created one application which can able to perform a DML operation on database. Now there is one condition the user created new table in that database(by using front-end) but that table is not accessible due to model class is not available, so there is any type of Framework in JAVA which can able to perform this type of operations without respective model classes dependencies.

In short there is any framework which handle all types of DLL and DML operation without model classes?
i know its stupid question.

答:
I'll provide an answer for a few APIs that you've tagged your question with, plus JDBC:

JPA

JPA requires a model at compile time (technically at the time when you load the entities), so it doesn't work well with ad-hoc models like yours. You could, of course, use runtime Java compilation and load those runtime generated entities dynamically, but that seems quite complicated.

jOOQ

jOOQ can work that way as stated e.g. in the tutorial. You can use jOOQ:

without code generation

with code generation

In jOOQ, generated code is completely optional, adding additional type safety to your client code, but you don't have to use it. All DDL and DML statements can be expressed with ad-hoc identifiers, or even plain SQL templating.

JDBC

When using Java/Spring/etc. you can always resort to using JDBC, the lower level API that is used by most of the above APIs behind the scenes. In Spring, there's also a thin API on top of JDBC called JdbcTemplate, which makes using JDBC a bit more convenient.

(Disclaimer: I work for the company behind jOOQ)


问:
Centering rotated text in
How to vertically center "There is information text" here?

Better - without changing html.

Also why doesn't max-width: 15px!important limit the width of the first  (tall) to 15px? How to limit it without changing the general width parameter?

td {width: 60px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
    <tbody>
        <tr>
            <td style="max-width: 15px!important;" rowspan="12">
                <p style="transform: rotate(270deg); white-space: nowrap">There is information text</p>
            </td>
            <td>1</td>
        </tr>
        <tr>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
        </tr>
        <tr>
            <td>4</td>
        </tr>
        <tr>
            <td>5</td>
        </tr>
        <tr>
            <td>6</td>
        </tr>
        <tr>
            <td>7</td>
        </tr>
        <tr>
            <td>8</td>
        </tr>
        <tr>
            <td>9</td>
        </tr>
        <tr>
            <td>10</td>
        </tr>
        <tr>
            <td>11</td>
        </tr>
        <tr>
            <td>12</td>
        </tr>
    </tbody>
</table></code>```

It is need to center it so without rotation to make it work with:

Is it possible? It is the most interesting for me.

答:
Since you are using transform: rotate(270) to rotate your text, the vertical-align: middle doesn't work anymore for the content of your .

What  you can use is add translateX(...) to adjust your text's placement. This won't work for dynamic content though.

Title: Centering rotated text in <td>

Body:
How to vertically center "There is information text" here?

Better - without changing html.

Also why doesn't max-width: 15px!important limit the width of the first  (tall) to 15px? How to limit it without changing the general width parameter?

td {width: 60px}

There is information text

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

It is need to center it so without rotation to make it work with:

Is it possible? It is the most interesting for me.

Body:
Since you are using transform: rotate(270) to rotate your text, the vertical-align: middle doesn't work anymore for the content of your <td>.

What  you can use is add translateX(...) to adjust your text's placement. This won't work for dynamic content though.


问:
Using json style sheets in UWP MapControl with Aerial3D view
I'm drawing polygons in the UWP MapControl in Win 10.  I saw you can change the appearance of map elements by generating a custom style sheet then assigning styles to elements.  I found the Map Style Sheet Editor and created a new style sheet with extension styles:

```<code>{
    "version": "1.*",
    "settings": {
    },
    "elements": {
    },
    "extensions": {
        "sxMapView": {
            "polyRemoveArea": {
                "fillColor": "#80FF0000",
                "strokeColor": "#FFFF0000",
                "strokeWidthScale": 5,
                "visible": true
            },
            "polyProcessArea": {
                "strokeColor": "#FF00FFFF",
                "strokeWidthScale": 5,
                "visible": true
            },
            "ptRemoveArea": {
                "visible": true
            },
            "ptProcessArea": {
                "visible": true
            }
        }
    }
}
</code>```

If I follow this example and assign "sxMapView.polyRemoveArea" in 2D map view everything works fine.

However if I switch to 3D map view with:

```<code>myMapControl.Style = MapStyle.Aerial3D;
</code>```

The style seems to get ignored and a default of blue is used (I tested this by not applying a style to the polygon and it was filled with blue).

Also if you try and set the map to 3D before assigning the custom style sheet the custom style sheet reverts the map back to 2D view even though there's no styles describing that.

```<code>myMapControl.Style = MapStyle.Aerial3D; // <- Set map to 3D
string styleSheetJson = "{...json style sheet from above ...}"
...
myMapControl.StyleSheet = MapStyleSheet.ParseFromJson(styleSheetJson); // <-  Map reverts to 2D
</code>```

How do I define extension styles for map elements in the maps control style sheet and use the Aerial3D view?

答:
You need to use the Combine method to add your style to an existing style like Aerial3D.
Setting the style will completely reset anything you previously set which is why your JSON is overriding the set call for Aerial3D.

The sample code in MapStyleSheetEditor should show you how to do this (the little i button)

```<code>myMap.StyleSheet = MapStyleSheet.Combine(new List<MapStyleSheet>
{
    MapStyleSheet.AerialWithOverlay(),
    MapStyleSheet.ParseFromJson(jsonText)
});
</code>```

Body:
I'm drawing polygons in the UWP MapControl in Win 10.  I saw you can change the appearance of map elements by generating a custom style sheet then assigning styles to elements.  I found the Map Style Sheet Editor and created a new style sheet with extension styles:

{
    "version": "1.*",
    "settings": {
    },
    "elements": {
    },
    "extensions": {
        "sxMapView": {
            "polyRemoveArea": {
                "fillColor": "#80FF0000",
                "strokeColor": "#FFFF0000",
                "strokeWidthScale": 5,
                "visible": true
            },
            "polyProcessArea": {
                "strokeColor": "#FF00FFFF",
                "strokeWidthScale": 5,
                "visible": true
            },
            "ptRemoveArea": {
                "visible": true
            },
            "ptProcessArea": {
                "visible": true
            }
        }
    }
}

If I follow this example and assign "sxMapView.polyRemoveArea" in 2D map view everything works fine.

However if I switch to 3D map view with:

myMapControl.Style = MapStyle.Aerial3D;

The style seems to get ignored and a default of blue is used (I tested this by not applying a style to the polygon and it was filled with blue).

Also if you try and set the map to 3D before assigning the custom style sheet the custom style sheet reverts the map back to 2D view even though there's no styles describing that.

myMapControl.Style = MapStyle.Aerial3D; // <- Set map to 3D
string styleSheetJson = "{...json style sheet from above ...}"
...
myMapControl.StyleSheet = MapStyleSheet.ParseFromJson(styleSheetJson); // <-  Map reverts to 2D

How do I define extension styles for map elements in the maps control style sheet and use the Aerial3D view?

Body:
You need to use the Combine method to add your style to an existing style like Aerial3D.
Setting the style will completely reset anything you previously set which is why your JSON is overriding the set call for Aerial3D.

The sample code in MapStyleSheetEditor should show you how to do this (the little i button)

myMap.StyleSheet = MapStyleSheet.Combine(new List<MapStyleSheet>
{
    MapStyleSheet.AerialWithOverlay(),
    MapStyleSheet.ParseFromJson(jsonText)
});


问:
Value of Queryset doesn't populate template-tag in Django
I am missing a detail somewhere when trying to populate a simple template-tag with a value returned by a queryset.

Views.py

```<code>def render_cube_app(request, template="cube_app.html"):
    user_equity = serializers.serialize('json', Profile.objects.all())
    context = {
        'user_equity': user_equity
    }
    print(context)
    return render(request, template, context)
</code>```

HTML

```<code>{% for user_equity in user_equity %}
  <p id="money_metrics_box_equity_figure">{{ user_equity.fields.equity }}</p>
{% endfor %}
</code>```

which doesn't populate anything as of yet. Also I think I could get rid of the for-each loop basically?

答:
You pass a JSON blob, so a string, not a list of dictionaries. Furthermore, please do not use the same variable name for both the iterator and the iterable.

You can parse the JSON blob to a list of dictionaries:

```<code>from json import loads as <b>jsonloads</b>

def render_cube_app(request, template="cube_app.html"):
    user_equity = <b>jsonloads(</b>serializers.serialize('json', Profile.objects.all())<b>)</b>
    context = {
        <b>'user_equities'</b>: user_equity
    }
    print(user_equity)
    return render(request, template, context)</code>```

In the template, we then iterate over it, but better with a different name for the iterator than for the iterable:

```<code>{% for <b>user_equity</b> in <b>user_equities</b> %}
  <p id="money_metrics_box_equity_figure">{{ user_equity.fields.equity }}</p>
{% endfor %}</code>```

Body:
I am missing a detail somewhere when trying to populate a simple template-tag with a value returned by a queryset.

Views.py

def render_cube_app(request, template="cube_app.html"):
    user_equity = serializers.serialize('json', Profile.objects.all())
    context = {
        'user_equity': user_equity
    }
    print(context)
    return render(request, template, context)

HTML

{% for user_equity in user_equity %}

{{ user_equity.fields.equity }}

{% endfor %}

which doesn't populate anything as of yet. Also I think I could get rid of the for-each loop basically?

Body:
You pass a JSON blob, so a string, not a list of dictionaries. Furthermore, please do not use the same variable name for both the iterator and the iterable.

You can parse the JSON blob to a list of dictionaries:

from json import loads as jsonloads

def render_cube_app(request, template="cube_app.html"):
    user_equity = jsonloads(serializers.serialize('json', Profile.objects.all()))
    context = {
        'user_equities': user_equity
    }
    print(user_equity)
    return render(request, template, context)

In the template, we then iterate over it, but better with a different name for the iterator than for the iterable:

{% for user_equity in user_equities %}
  <p id="money_metrics_box_equity_figure">{{ user_equity.fields.equity }}</p>
{% endfor %}


问:
How can I determine if a file upload is a valid CSV file - or at least text - in ColdFusion 8?
I have a form which allows a user to upload a file to the server. How can I validate that the uploaded file is in fact the expected format (CSV, or at least validate that it is a text file) in ColdFusion 8?</p>

答:
I dont know if it can help you but Ben Nadel wrote excellents posts about CSV:

http://www.bennadel.com/blog/483-Parsing-CSV-Data-Using-ColdFusion.htm

http://www.bennadel.com/blog/976-Regular-Expressions-Make-CSV-Parsing-In-ColdFusion-So-Much-Easier-And-Faster-.htm

http://www.bennadel.com/blog/501-Parsing-CSV-Values-In-To-A-ColdFusion-Query.htm


问:
Trouble passing props to imported component
I have a "main" component which imports two other components, which contain a form each, and I'm having trouble passing some values which I get from an API call in the main component.

This is an example of what's happening on the "main" component with one of the imported forms:

```<code>user_id = null;
email = "";

componentDidMount() {
    get(`user-data/`, this.token).then((response) => {
        this.user_id = response.user_id;
        this.email = response.email;
        // Doing a console.log at this point shows both values are assigned properly
        // And that they exist
    }).catch((error) => notify.notifyError(error.message));
}

<UserForm
  email={this.email}
  id={this.user_id}
></UserForm>;
</code>```

Edit: I'm including the API call logic since I believe it has something to do with the issue.

```<code>export const get = async (url, authToken) => {
  try {
    const response = await axiosInstance.get(`${url}`, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `${BEARER} ${authToken}`,
      },
    });
    return response;
  } catch (error) {
    throw new Error();
  }
};
</code>```

On the UserForm component:

```<code>id = null;
email = "";

constructor(props) {
    super(props);
    this.id = props.id;
    this.email = props.email;
    // Doing a console.log here shows both props are empty
    // Trying to use either of them from here on out breaks the page
}
</code>```

I assume the issue has to do with the components rendering before the value gets assigned, but I'm not entirely sure about it.

Why aren't the props received properly on the imported form, and how can I make sure they are?

Edit 2: Waiting for props to be set on componentDidUpdate works, but operating the way I need to creates and endless loop of execution of componentDidUpdate

```<code>  componentDidUpdate() {
    if (this.props.id) {
      console.log("props are set!");
      this.getData();
    }
  }

  getData() {
    get(`user-data/${this.props.id}`, this.token)
      .then((user) => {
        // This creates and endless loop of updating
        this.setState({
          ...user.data
        });
      })
      .catch((error) => notify.notifyError(error.message));
  }
</code>```

答:
in your main component do like this

```<code>state = {
    email: '',
    user_id: null
}

componentDidMount() {
    get(`user-data/`, this.token).then((response) => {
        this.setState({
            email: response.email,
            user_id: response.user_id
        })
        // Doing a console.log at this point shows both values are assigned properly
        // And that they exist
    }).catch((error) => notify.notifyError(error.message));
}
</code>```

and in your userform print your props like

```<code>componentDidUpdate(prevProps){
    console.log('this.props', this.props);
    console.log('prevProps', prevProps)
}
</code>```

Body:
I have a "main" component which imports two other components, which contain a form each, and I'm having trouble passing some values which I get from an API call in the main component.

This is an example of what's happening on the "main" component with one of the imported forms:

user_id = null;
email = "";

componentDidMount() {
    get(`user-data/`, this.token).then((response) => {
        this.user_id = response.user_id;
        this.email = response.email;
        // Doing a console.log at this point shows both values are assigned properly
        // And that they exist
    }).catch((error) => notify.notifyError(error.message));
}

<UserForm
  email={this.email}
  id={this.user_id}
></UserForm>;

Edit: I'm including the API call logic since I believe it has something to do with the issue.

export const get = async (url, authToken) => {
  try {
    const response = await axiosInstance.get(`${url}`, {
      headers: {
        "Content-Type": "application/json",
        Authorization: `${BEARER} ${authToken}`,
      },
    });
    return response;
  } catch (error) {
    throw new Error();
  }
};

On the UserForm component:

id = null;
email = "";

constructor(props) {
    super(props);
    this.id = props.id;
    this.email = props.email;
    // Doing a console.log here shows both props are empty
    // Trying to use either of them from here on out breaks the page
}

I assume the issue has to do with the components rendering before the value gets assigned, but I'm not entirely sure about it.

Why aren't the props received properly on the imported form, and how can I make sure they are?

Edit 2: Waiting for props to be set on componentDidUpdate works, but operating the way I need to creates and endless loop of execution of componentDidUpdate

  componentDidUpdate() {
    if (this.props.id) {
      console.log("props are set!");
      this.getData();
    }
  }

  getData() {
    get(`user-data/${this.props.id}`, this.token)
      .then((user) => {
        // This creates and endless loop of updating
        this.setState({
          ...user.data
        });
      })
      .catch((error) => notify.notifyError(error.message));
  }

Body:
in your main component do like this

state = {
    email: '',
    user_id: null
}

componentDidMount() {
    get(`user-data/`, this.token).then((response) => {
        this.setState({
            email: response.email,
            user_id: response.user_id
        })
        // Doing a console.log at this point shows both values are assigned properly
        // And that they exist
    }).catch((error) => notify.notifyError(error.message));
}

and in your userform print your props like

componentDidUpdate(prevProps){
    console.log('this.props', this.props);
    console.log('prevProps', prevProps)
}