问:
Distributed Transaction from .NET to DB2
I have a problem where in I have to call into the AS400 db2 to call a series of insert/update stored procedures from my .net and then update a few SQL2005 tables if everything in the AS400 db goes ahead fine. The driver I am using does not have distributed transactions so I was wondering if you can use any of IBMs iSeries Drivers for DB2 to create a COM+/.NET Component which would participate in a distributed transaction. Pls let me know if any one out there has done anything like this before or any pointers would be greatly appreciated.</p>

答:
Which driver are you using?

IBM's DB2 Connect supports distributed transactions managed by Windows DTC.

The DB2 driver from Microsoft, which is packaged in Microsoft Host Integration Server, also does transactions.

I am hearing two different things from you.  You want to do a transaction that spans SQL and DB2.  and also you want to build a component that participates in a distributed transaction.  These can be done together but the former does not require the latter.

Using the System.Transactions classes in .NET 2.0, you can do this:

```<code>  TransactionOptions options = new TransactionOptions();
  options.IsolationLevel = IsolationLevel.Serializable;
  options.Timeout = TransactionManager.DefaultTimeout;
  using(var scope = new TransactionScope(TransactionScopeOption.Required,
                          options,
                          EnterpriseServicesInteropOption.Full) )
  {
      TransactionalWorkinDb2();
      TransactionalWorkinSql();
      scope.Complete();
  }
</code>```

The result will be a distributed transaction that spans DB2 and SQL, but it is not a component that participates in a distributed transaction, if you see what I mean.

The other alternative is to use the EnterpriseServices/COM+ model of defining a component that does something, and marking that component as transactional.  This works too, but is not required to do distributed transactions in .NET.

Body:
Which driver are you using?

IBM's DB2 Connect supports distributed transactions managed by Windows DTC.

The DB2 driver from Microsoft, which is packaged in Microsoft Host Integration Server, also does transactions.

I am hearing two different things from you.  You want to do a transaction that spans SQL and DB2.  and also you want to build a component that participates in a distributed transaction.  These can be done together but the former does not require the latter.

Using the System.Transactions classes in .NET 2.0, you can do this:

  TransactionOptions options = new TransactionOptions();
  options.IsolationLevel = IsolationLevel.Serializable;
  options.Timeout = TransactionManager.DefaultTimeout;
  using(var scope = new TransactionScope(TransactionScopeOption.Required,
                          options,
                          EnterpriseServicesInteropOption.Full) )
  {
      TransactionalWorkinDb2();
      TransactionalWorkinSql();
      scope.Complete();
  }

The result will be a distributed transaction that spans DB2 and SQL, but it is not a component that participates in a distributed transaction, if you see what I mean.

The other alternative is to use the EnterpriseServices/COM+ model of defining a component that does something, and marking that component as transactional.  This works too, but is not required to do distributed transactions in .NET.

OwnerDisplayName: Cheeso


来源: stackexchange

问:
Pushing app to heroku problem
I am trying to push my app to heroku and I get the following message:

```<code>$ heroku create
Creating electric-meadow-15..... done
Created http://electric-meadow-15.heroku.com/ | git@heroku.com:electric-meadow-1
5.git

$ git push heroku master

 !  No such app as fierce-fog-63

fatal: The remote end hung up unexpectedly
</code>```

It's weird that I am getting this now, I have pushed the app to heroku many times without issue.  the especially weird thing is, fierce-fog-63 is an old app that I made and deleted a long time ago.  Why is it now that heroku is trying to push to this app that doesn't exist anymore, especially when I have created a new one?  Any suggestions?

答:
For all the people who this does not work, check your ~/.heroku/credentials

If the email or token does not match the account, you won't see your apps.

ContentLicense: CC BY-SA 2.5

Title: Pushing app to heroku problem

Body:
I am trying to push my app to heroku and I get the following message:

$ heroku create
Creating electric-meadow-15..... done
Created http://electric-meadow-15.heroku.com/ | git@heroku.com:electric-meadow-1
5.git

$ git push heroku master

 !  No such app as fierce-fog-63

fatal: The remote end hung up unexpectedly

It's weird that I am getting this now, I have pushed the app to heroku many times without issue.  the especially weird thing is, fierce-fog-63 is an old app that I made and deleted a long time ago.  Why is it now that heroku is trying to push to this app that doesn't exist anymore, especially when I have created a new one?  Any suggestions?

ContentLicense: CC BY-SA 3.0


问:
Sign in with the app-specific password you generated. If you forgot the app-specific password or need to create a new one -22938

Problem

While I'm trying to send my application via Fastlane I face with this error:

Sign in with the app-specific password you generated. If you forgot
the app-specific password or need to create a new one, go to
appleid.apple.com (-22938)

Transporter transfer failed.Sign in with the app-specific password you
generated. If you forgot the app-specific password or need to create a
new one, go to appleid.apple.com (-22938)Your account has 2 step
verification enabled. Please go to
https://appleid.apple.com/account/manage and generate an application
specific password for the iTunes Transporter, which is used to upload
builds. To set the application specific password on a CI machine using
an environment variable, you can set the
FASTLANE_APPLE_APPLICATION_SPECIFIC_PASSWORD variable.

Please provide your Apple Developer Program account credentials The login information you enter will be stored in your macOS Keychain
Password (application-specific for xxx@yyy.com)

答:
Easy way to fix this issue

Question:

Answer:

step1

step2

step3

step4

https://appleid.apple.com

create App-Specific Password

enter a string like an example

got your App-Specific Password

Done:

ContentLicense: CC BY-SA 4.0


问:
Shall we always use [unowned self] inside closure in Swift
In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide

The speaker said in that case, if we don't use [unowned self] there, it will be a memory leak. Does it mean we should always use [unowned self] inside closure?

On line 64 of ViewController.swift of the Swift Weather app, I don't use [unowned self]. But I update the UI by using some @IBOutlets like self.temperature and self.loadingIndicator. It may be OK because all @IBOutlets I defined are weak. But for safety, should we always use [unowned self]?

```<code>class TempNotifier {
  var onChange: (Int) -> Void = {_ in }
  var currentTemp = 72
  init() {
    onChange = { [unowned self] temp in
      self.currentTemp = temp
    }
  }
}
</code>```

答: unowned is similar to weak they don't a retained object from being destroyed, but weak variables turned to nil when the object its a reference to no longer exists, which we can handle with the normal checking of nils, unowned will just become garbage, you can't tell they are no longer garbage and using them will crash. The problem with weak is if an object has references to it by weak variables, when its destroyed, it has to go through every reference to it and set that variable to nil, this clearly is going to be expensive, using unowned instead is going just crash and finding this kind of bug is going to be difficult. One place to use unowned is if you are creating some carefully contained datatype, which has a clear interface, and its internals are not directly accessible, for you implementation it may be useful to have lots of circular references but that are self contained, you can used unowned references to let you break those circular references, with out the expense of weak variables, for example you may have a node tree, and each node needs has to have a reference to its parent, deleting a node is going to delete all its children, so there is no point of all the children having to have all there parent references set to nil.</p>

Body:
In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide

The speaker said in that case, if we don't use [unowned self] there, it will be a memory leak. Does it mean we should always use [unowned self] inside closure?

On line 64 of ViewController.swift of the Swift Weather app, I don't use [unowned self]. But I update the UI by using some @IBOutlets like self.temperature and self.loadingIndicator. It may be OK because all @IBOutlets I defined are weak. But for safety, should we always use [unowned self]?

class TempNotifier {
  var onChange: (Int) -> Void = {_ in }
  var currentTemp = 72
  init() {
    onChange = { [unowned self] temp in
      self.currentTemp = temp
    }
  }
}


问:
How to programmatically read live bluetooth heart rate from Polar H10 chest strap
I want my iOS swift software to read live bluetooth heart rate directly from my Polar H10 chest strap.

Can't find data format of Polar's H10 chest strap, though.

I'm using Swift Corebluetooth.

答:
Polar have an open source SDK that contains Android and iOS examples for connecting to their different sensors. You can find the SDK here:-

https://github.com/polarofficial/polar-ble-sdk


问:
Error: djdt is not defined how to solve this?
I just upgraded django 2.1 to django 3.0.14:
then I got this error ModuleNotFoundError: No module named 'django.utils.lru_cache' in django-debug-toolbar, so I upgraded my django-debug-toolbar 1.9.1 to django-debug-toolbar 2.0 and run python manage.py collectstatic and clear cache from browser
after that above error is resolved but debug-toolbar is not showing and in console got the error:

toolbar.js:306 Uncaught ReferenceError: djdt is not defined

how to resolve this error?
I already have::

```<code>INSTALLED_APPS = [
    # ...
    "debug_toolbar",
    # ...
]

STATIC_URL = "static/"

from django.urls import include, path
INTERNAL_IPS = [
    # ...
    "127.0.0.1",
    # ...
]
urlpatterns = [
    # ...
    path('__debug__/', include('debug_toolbar.urls')),
]
</code>```

答: It's a browser caching problem. Delete cookies etc. and it'll help.</p>

Body:
I just upgraded django 2.1 to django 3.0.14:
then I got this error ModuleNotFoundError: No module named 'django.utils.lru_cache' in django-debug-toolbar, so I upgraded my django-debug-toolbar 1.9.1 to django-debug-toolbar 2.0 and run python manage.py collectstatic and clear cache from browser
after that above error is resolved but debug-toolbar is not showing and in console got the error:

toolbar.js:306 Uncaught ReferenceError: djdt is not defined

how to resolve this error?
I already have::

INSTALLED_APPS = [
    # ...
    "debug_toolbar",
    # ...
]

STATIC_URL = "static/"

from django.urls import include, path
INTERNAL_IPS = [
    # ...
    "127.0.0.1",
    # ...
]
urlpatterns = [
    # ...
    path('__debug__/', include('debug_toolbar.urls')),
]


问:
Cannot connect to mysql server in an Amazon EC2 instance
I have a problem in connecting to my MySQL server running on an EC2 Ubuntu instance.

In the /etc/mysql/mysql.conf.d/mysqld.cnf,

I've set the port=3306

I've set thebind-address=0.0.0.0.

Commented skip-external-locking

netstat -an | grep 3306 returns

```<code>tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN
</code>```

I allowed the connections using sudo ufw allow 3306

Still Iam getting the error as below. (I have added the db.apim.com to /etc/hosts )

```<code>ERROR 2003 (HY000): Can't connect to MySQL server on 'db.apim.com' (110)
</code>```

Note  : I followed everything in this blog

答:
This is resolved by adding a suitable inbound traffic rule.
By adding Type : TCP and Source: 0.0.0.0/0 as a new inbound traffic rule this issue resolved [1].

Thanks @GobindDeepSingh for pointing this out.

[1] https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html

Body:
I have a problem in connecting to my MySQL server running on an EC2 Ubuntu instance.

In the /etc/mysql/mysql.conf.d/mysqld.cnf,

I've set the port=3306

I've set thebind-address=0.0.0.0.

Commented skip-external-locking

netstat -an | grep 3306 returns

tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN

I allowed the connections using sudo ufw allow 3306

Still Iam getting the error as below. (I have added the db.apim.com to /etc/hosts )

ERROR 2003 (HY000): Can't connect to MySQL server on 'db.apim.com' (110)

Note  : I followed everything in this blog


问:
how do I use Symfony console with dependency injection, without the Symfony framework bundle?
I have a command-line application, which so far uses the Symfony dependency injection component. I now find that I want to add command-line options and improve the formatting of the output, and the Symfony console component seems like a good choice for that.

However, I can't fathom how to get my Symfony console command classes to receive the container object.

The documentation I have found uses the ContainerAwareCommand class, but that is from the FrameworkBundle -- which seems a huge amount of overhead to add to a pure CLI app, as it requires further bundles such as routing, http, config, cache, etc, none of which are of any relevance to me whatsoever here.

(Existing SO question How can i inject dependencies to Symfony Console commands? also assumes the FrameworkBundle, BTW.)

I've made a test repository here with a basic command that illustrates the problem: https://github.com/joachim-n/console-with-di

答:
Four years after, but intended for somebody looking for a similar solution. I had a look alike scenario and implemented my own boilerplate with Dependency Injection ready to go for a standalone symfony console application, supporting auto-wiring and auto-configure for commands and services.

composer create-project coral-media/crune crune

A sample command receiving the container it's in place.
Source code available at Github

Happy Coding!


问:
In Visual Studio 2019, how to GIT commit only specific files (only .vb or .sln or .vbxproj files)?
Today, I want to Commit my work to my local GIT repository from Visual Studio 2019.

From Solution Explorer, I active GIT context menu and Commit action and a new Modification Git panel is displayed in which ALL modified and added files are displayed.

I can see a lot of files with a lot of types

```<code>.vb
.sln
.dll
.db
.dia
.cache
.pdb
.png
</code>```

But I'm only interesting to commit .vb, .sln and .vbxprog file's types.

In Visual Studio, how can'I limit my commit to only these files ?

How can I do same thing for directory so that Release or Debug folders are never commited ?

Can I do all theses actions in Visual Studio level ?

答:
You could:

either filter the list (*.vb in the filter field), to add only those files;

or switch to command-line and git add *.vb.

How can I do same thing for directory so that Release or Debug folders are never commited?

In command-line:

```<code>cd /path/to/local/repo
git rm --cached -r Debug/
git rm --cached -r Release/
echo Debug/>>.gitignore
echo Release/>>.gitignore
git add .gitignore
git commit -m "Ignore Debug and Release folders"
</code>```

You don't need the git rm steps if no files in Debug/ or Release/ were ever tracked before.

But you need to add them to a .gitignore file.

Then you can switch back to Visual Studio: those two folders won't show up anymore.

Body:
Today, I want to Commit my work to my local GIT repository from Visual Studio 2019.

From Solution Explorer, I active GIT context menu and Commit action and a new Modification Git panel is displayed in which ALL modified and added files are displayed.

I can see a lot of files with a lot of types

.vb
.sln
.dll
.db
.dia
.cache
.pdb
.png

But I'm only interesting to commit .vb, .sln and .vbxprog file's types.

In Visual Studio, how can'I limit my commit to only these files ?

How can I do same thing for directory so that Release or Debug folders are never commited ?

Can I do all theses actions in Visual Studio level ?

Body:
You could:

either filter the list (*.vb in the filter field), to add only those files;

or switch to command-line and git add *.vb.

How can I do same thing for directory so that Release or Debug folders are never commited?

In command-line:

cd /path/to/local/repo
git rm --cached -r Debug/
git rm --cached -r Release/
echo Debug/>>.gitignore
echo Release/>>.gitignore
git add .gitignore
git commit -m "Ignore Debug and Release folders"

You don't need the git rm steps if no files in Debug/ or Release/ were ever tracked before.

But you need to add them to a .gitignore file.

Then you can switch back to Visual Studio: those two folders won't show up anymore.


问:
Bazel build: Add extra dependencies not in `WORKSPACE`
I'd like to write some profiling scripts on a project, and use action_listener or aspect to take action. However, it's better not modifying the project files. Is there any way to add some external dependencies without change WORKSPACE file?

答:
WORKSPACE

```<code>workspace(name = "my_workspace")

load("//:bazel/third_party/my_profile_deps.bzl", "my_profile_deps")

my_profile_deps()
</code>```

bazel/third_party/my_profile_deps.bzl

```<code>load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")

def my_profile_deps():
    """Fetch my profile deps."""

    if True: # Switch to turn on/off
        # ...
        maybe(
            http_archive,
            name = "some_lib",
            build_file = "...",
            sha256 = "...",
            strip_prefix = "..",
            urls = [
                "...",
                "...",
            ],
        )
</code>```

Dependencies are only fetched if needed. Therefore, you can think of introducing configurable build attributes.

Body:
WORKSPACE

workspace(name = "my_workspace")

load("//:bazel/third_party/my_profile_deps.bzl", "my_profile_deps")

my_profile_deps()

bazel/third_party/my_profile_deps.bzl

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")

def my_profile_deps():
    """Fetch my profile deps."""

    if True: # Switch to turn on/off
        # ...
        maybe(
            http_archive,
            name = "some_lib",
            build_file = "...",
            sha256 = "...",
            strip_prefix = "..",
            urls = [
                "...",
                "...",
            ],
        )

Dependencies are only fetched if needed. Therefore, you can think of introducing configurable build attributes.


问:
Whitespace at top and within body div tags
Can someone please just tell me what my sorry, stupid eyes are missing?

Whitespace appears at the top of my browser window, and between two div tag containers (all browsers.)

p, body, html, every div, all margin:0px;

Gracias.

答:
.menucontainer has margin-top: 20px;

set to margin-top: 0;

.centercontainer has margin: 10px auto;

set to margin: 0 auto;

and add overflow: hidden; (to .centercontainer)

Developer tools in Chrome is a huge help, as is Firebug in Firefox :)

EDIT: if you want your .menucontainer to be 20px lower, add padding-top: 20px; to .lightsandcolourcontainer

Also, your content width is set to 1000px - beware of this width as you're allowing only 24px for a horizontal scroll bar, which may have the side effect of an ugly and unnecessary vertical scroll bar appearing in some browsers. Sticking to 960px - 980px max page width is a web standard adopted to prevent the vertical scroll from appearing on the majority of visitors' browsers (since 1024 x 768 is/was the most prevalent resolution of visitors' monitors).


问:
Adding CSS to shadow-root element wont work
I am trying to add CSS to element inside shadow-root by adding class to it.
I have angular component where I have.
CSS

```<code>.test {
    border: 1px solid red;
}
</code>```

TS

```<code>document.getElementById('my-div').shadowRoot.querySelector('.some-wrapper').classList.add('test')
</code>```

The thing is that i can see that class is added but that class seems to be empty like it adds no CSS to element only class.
What I am doing wrong?

答:
To make your styles work in a Shadow DOM, you should use :host([selector]):

:host(.test ) {
    border: 1px solid red;
}
```

The :host selector allows to select the shadow host (the element containing the shadow tree). As a general rule, local styles work only inside the shadow tree, and document styles work outside of it. But there are few exceptions. A shadow host is a DOM node that contains a shadow root. It is a regular element node within the parent page that hosts the scoped shadow subtree. Any child nodes that reside under the shadow host are still selectable, with the exception of the shadow root.

Body:
I am trying to add CSS to element inside shadow-root by adding class to it.
I have angular component where I have.
CSS

.test {
    border: 1px solid red;
}

TS

document.getElementById('my-div').shadowRoot.querySelector('.some-wrapper').classList.add('test')

The thing is that i can see that class is added but that class seems to be empty like it adds no CSS to element only class.
What I am doing wrong?

Body:
To make your styles work in a Shadow DOM, you should use :host([selector]):

:host(.test ) {
    border: 1px solid red;
}

The :host selector allows to select the shadow host (the element containing the shadow tree). As a general rule, local styles work only inside the shadow tree, and document styles work outside of it. But there are few exceptions. A shadow host is a DOM node that contains a shadow root. It is a regular element node within the parent page that hosts the scoped shadow subtree. Any child nodes that reside under the shadow host are still selectable, with the exception of the shadow root.


问:
Numpy arange but doubling step size
I am currently looking for a way to use something similar to np.arange, but with the option of doubling the step size.

I know that np.arangecreates evenly spaced arrays and is not supposed to support variable step sizes.
What I want as an output is something similar to np.array([0,1,3,7,15,31,...]).

Is there any built-in function that does this?

I have to use this very often and therefore would prefer to avoid for-loops or similar slow approaches.

Title: Numpy arange but doubling step size

Body:
Try:

2 ** np.arange(0,10,1) - 1


问:
Creating a method that merges 2 arrays into one sorted array in ascending order in Java
For part of an assignment, I have to create a method that merges 2 arrays into one sorted array in ascending order. I have most of it done, but I am getting a bug that replaces the last element in the array with 0. Has anyone ever run into this problem and know a solution? Heres my code:

```<code>     public static OrderedArray merge(OrderedArray src1, OrderedArray src2) {

         int numLength1 = src1.array.length;
         int numLength2 = src2.array.length;

         //combined array lengths
         int myLength = (numLength1 + numLength2);
        // System.out.println(myLength);
         OrderedArray mergedArr = new OrderedArray(myLength);

         //new array
         long[] merged = new long[myLength];

         //loop to sort array
         int i = 0;
         int j = 0;
         int k = 0;
         while (k < src1.array.length + src2.array.length - 1) {
             if(src1.array[i] < src2.array[j]) {
                 merged[k] = src1.array[i];
             i++;
             }
             else {
                merged[k] = src2.array[j];
             j++;

             }
            k++;

         }

         //loop to print result
         for(int x = 0; x < myLength; x++) {
             System.out.println(merged[x]);
         }
         return mergedArr;
     }

    public static void main(String[] args) {
        int maxSize = 100; // array size
//      OrderedArray arr; // reference to array
        OrderedArray src1 = new OrderedArray(4);
        OrderedArray src2 = new OrderedArray(5);

//      arr = new OrderedArray(maxSize); // create the array

        src1.insert(1);  //insert src1
        src1.insert(17);
        src1.insert(42);
        src1.insert(55);

        src2.insert(8); //insert src2
        src2.insert(13);
        src2.insert(21);
        src2.insert(32);
        src2.insert(69);

        OrderedArray myArray = merge(src1, src2);

</code>```

This is my expected output:

```<code>1
8
13
17
21
32
42
55
69
</code>```

and this is my current output:

```<code>1
8
13
17
21
32
42
55
0
</code>```

答:
The best way to merge two arrays without repetitive items in sorted order is that insert both of them into treeSet just like the following:

```<code>  public static int[] merge(int[] src1, int[] src2) {
        TreeSet<Integer> mergedArray= new TreeSet<>();
        for (int i = 0; i < src1.length; i++) {
            mergedArray.add(src1[i]);
        }
        for (int i = 0; i < src2.length; i++) {
            mergedArray.add(src2[i]);
        }
        return mergedArray.stream().mapToInt(e->(int)e).toArray();

    }

public static void main(String[] argh) {
    int[] src1 = {1,17,42,55};
    int[] src2 = {8,13,21,32,69};
Arrays.stream(merge(src1,src2)).forEach(s-> System.out.println(s));
  }
</code>```

output:

```<code>1
8
13
17
21
32
42
55
69
</code>```

Body:
For part of an assignment, I have to create a method that merges 2 arrays into one sorted array in ascending order. I have most of it done, but I am getting a bug that replaces the last element in the array with 0. Has anyone ever run into this problem and know a solution? Heres my code:

     public static OrderedArray merge(OrderedArray src1, OrderedArray src2) {

         int numLength1 = src1.array.length;
         int numLength2 = src2.array.length;

         //combined array lengths
         int myLength = (numLength1 + numLength2);
        // System.out.println(myLength);
         OrderedArray mergedArr = new OrderedArray(myLength);

         //new array
         long[] merged = new long[myLength];

         //loop to sort array
         int i = 0;
         int j = 0;
         int k = 0;
         while (k < src1.array.length + src2.array.length - 1) {
             if(src1.array[i] < src2.array[j]) {
                 merged[k] = src1.array[i];
             i++;
             }
             else {
                merged[k] = src2.array[j];
             j++;

             }
            k++;

         }

         //loop to print result
         for(int x = 0; x < myLength; x++) {
             System.out.println(merged[x]);
         }
         return mergedArr;
     }

    public static void main(String[] args) {
        int maxSize = 100; // array size
//      OrderedArray arr; // reference to array
        OrderedArray src1 = new OrderedArray(4);
        OrderedArray src2 = new OrderedArray(5);

//      arr = new OrderedArray(maxSize); // create the array

        src1.insert(1);  //insert src1
        src1.insert(17);
        src1.insert(42);
        src1.insert(55);

        src2.insert(8); //insert src2
        src2.insert(13);
        src2.insert(21);
        src2.insert(32);
        src2.insert(69);

        OrderedArray myArray = merge(src1, src2);

This is my expected output:

1
8
13
17
21
32
42
55
69

and this is my current output:

1
8
13
17
21
32
42
55
0

Body:
The best way to merge two arrays without repetitive items in sorted order is that insert both of them into treeSet just like the following:

  public static int[] merge(int[] src1, int[] src2) {
        TreeSet<Integer> mergedArray= new TreeSet<>();
        for (int i = 0; i < src1.length; i++) {
            mergedArray.add(src1[i]);
        }
        for (int i = 0; i < src2.length; i++) {
            mergedArray.add(src2[i]);
        }
        return mergedArray.stream().mapToInt(e->(int)e).toArray();

    }

public static void main(String[] argh) {
    int[] src1 = {1,17,42,55};
    int[] src2 = {8,13,21,32,69};
Arrays.stream(merge(src1,src2)).forEach(s-> System.out.println(s));
  }

output:

1
8
13
17
21
32
42
55
69


问:
Connect-AzAccount: Cannot bind parameter 'Credential'. Cannot convert the "System.Management.Automation.PSCredential"
I understand similar questions have been asked and answered before in stack over flow itself. But I have a slightly different requirement. My requirement is to log in to Azure using service principal and I am using the below PowerShell script for the same,

```<code>$azureAppId = "#######"
$azureAppIdPassword = "######"
$userPassword = ConvertTo-SecureString -String $azureAppIdPassword -AsPlainText -Force
$azureAppCred = (New-Object System.Management.Automation.PSCredential ($azureAppId, $userPassword))

$subscriptionId = '######'
$tenantId = '######'
Connect-AzAccount -ServicePrincipal -SubscriptionId $subscriptionId -TenantId $tenantId -Credential $azureAppCred
$containerId = Invoke-Expression -Command "docker run -d  -it  mcr.microsoft.com/azure-powershell"
docker exec $containerId pwsh -c  Connect-AzAccount -ServicePrincipal -SubscriptionId $subscriptionId -TenantId $tenantId -Credential $azureAppCred
</code>```

Above script fails with the error Connect-AzAccount: Cannot bind parameter 'Credential'. Cannot convert the "System.Security.SecureString" value of type "System.String" to type "System.Management.Automation.PSCredential". If I execute the above script without docker, it works just fine.

I tried to print the type of $azureAppCred using the command docker exec $containerId pwsh -c Write-Host $azureAppCred it prints System.Management.Automation.PSCredential as expected but still the login command fails.

Can anyone suggest what could be going wrong here?

Thanks,
Tintu

答:
As mentioned in this Docker Documentation , the azure CLI login is different from docker azure cli login . As you are using service principal to connect with azure and run the docker run command, You can use something like below :

```<code>$azureAppId = "#######"
$azureAppIdPassword = "######"
$tenantId = '######'
docker login azure --client-id $azureAppId --client-secret $azureAppIdPassword --tenant-id $tenantId
docker run -d  -it  mcr.microsoft.com/azure-powershell
</code>```

Body:
I understand similar questions have been asked and answered before in stack over flow itself. But I have a slightly different requirement. My requirement is to log in to Azure using service principal and I am using the below PowerShell script for the same,

$azureAppId = "#######"
$azureAppIdPassword = "######"
$userPassword = ConvertTo-SecureString -String $azureAppIdPassword -AsPlainText -Force
$azureAppCred = (New-Object System.Management.Automation.PSCredential ($azureAppId, $userPassword))

$subscriptionId = '######'
$tenantId = '######'
Connect-AzAccount -ServicePrincipal -SubscriptionId $subscriptionId -TenantId $tenantId -Credential $azureAppCred
$containerId = Invoke-Expression -Command "docker run -d  -it  mcr.microsoft.com/azure-powershell"
docker exec $containerId pwsh -c  Connect-AzAccount -ServicePrincipal -SubscriptionId $subscriptionId -TenantId $tenantId -Credential $azureAppCred

Above script fails with the error Connect-AzAccount: Cannot bind parameter 'Credential'. Cannot convert the "System.Security.SecureString" value of type "System.String" to type "System.Management.Automation.PSCredential". If I execute the above script without docker, it works just fine.

I tried to print the type of $azureAppCred using the command docker exec $containerId pwsh -c Write-Host $azureAppCred it prints System.Management.Automation.PSCredential as expected but still the login command fails.

Can anyone suggest what could be going wrong here?

Thanks,
Tintu

Body:
As mentioned in this Docker Documentation , the azure CLI login is different from docker azure cli login . As you are using service principal to connect with azure and run the docker run command, You can use something like below :

$azureAppId = "#######"
$azureAppIdPassword = "######"
$tenantId = '######'
docker login azure --client-id $azureAppId --client-secret $azureAppIdPassword --tenant-id $tenantId
docker run -d  -it  mcr.microsoft.com/azure-powershell


问:
How to use manual cache updates using RTK Query
I have recently started working on redux toolkit, Basically i want to refetch the data from database if there is mutation. I am using flatlist in my react native project where on pull to refresh i want my "getPosts" endpoint to refetch and get updated.

Note: I know about using tags for automated cache invalidation. but on web RTK query is not implemented.

Talking about pessimistic update:

```<code> async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
    try {
      const { data: updatedPost } = await queryF`enter code here`ulfilled
      const patchResult = dispatch(
        api.util.updateQueryData('getPost', id, (draft) => {
          Object.assign(draft, updatedPost)
        })
      )
    } catch {}
  },
</code>```

just give a help how to call this function from APP.JS or anywhere from the app. Thanks

答:
You can just call refetch, you don't need anything that complicated. See the docs on useQuery

```<code>const myResult = useMyquery(args)

// in your pull to refresh trigger:
myResult.refetch()
</code>```

If you are outside of a component, you can also still

```<code>store.dispatch(api.endpoints.myEndpoint.initiate(args, { track: false })))
</code>```

to trigger a refetch

Body:
I have recently started working on redux toolkit, Basically i want to refetch the data from database if there is mutation. I am using flatlist in my react native project where on pull to refresh i want my "getPosts" endpoint to refetch and get updated.

Note: I know about using tags for automated cache invalidation. but on web RTK query is not implemented.

Talking about pessimistic update:

 async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
    try {
      const { data: updatedPost } = await queryF`enter code here`ulfilled
      const patchResult = dispatch(
        api.util.updateQueryData('getPost', id, (draft) => {
          Object.assign(draft, updatedPost)
        })
      )
    } catch {}
  },

just give a help how to call this function from APP.JS or anywhere from the app. Thanks

Body:
You can just call refetch, you don't need anything that complicated. See the docs on useQuery

const myResult = useMyquery(args)

// in your pull to refresh trigger:
myResult.refetch()

If you are outside of a component, you can also still

store.dispatch(api.endpoints.myEndpoint.initiate(args, { track: false })))

to trigger a refetch


问:
Clone a google cloud VM
I have google cloud VM with Ubuntu installed along with various services and libraries. I need to make a similar bootable VM with the same OS and all the data, libraries etc in the already configured VM. How do I clone the VM with these requirements?

I tried to create an image from the already existing VM and could not SSH into it.

So I retraced my installations step by step trying to figure out which step is breaking the image.
I created an Ubuntu(18.04) VM and used that to create an image. The instance I created using the image did allow me to SSH into.

Next installed Ubuntu desktop and xorg server and created an image after that. Using that image, I created a new VM and tried to SSH into it.
But unfortunately, the SSH connection could not be established. So I think it is these installations that are causing the error if it is not some sort of system error.

Below are the exact commands I ran to install these after creating an Ubuntu(18.04) VM:

```<code> sudo passwd username
  sudo su -
  passwd
  apt update && apt upgrade -y
  adduser username root
  adduser username admin
  adduser username sudo

  apt-get install ubuntu-desktop -y
  apt-get install xserver-xorg-video-dummy

  nano /etc/X11/xorg.conf
</code>```

and pasted the following into the .conf file

```<code>Section "Device"
    Identifier  "Configured Video Device"
    Driver      "dummy"
  EndSection
  Section "Monitor"
    Identifier  "Configured Monitor"
    HorizSync 31.5-48.5
    VertRefresh 50-70
  EndSection
  Section "Screen"
    Identifier  "Default Screen"
    Monitor     "Configured Monitor"
    Device      "Configured Video Device"
    DefaultDepth 24
    SubSection "Display"
    Depth 24
    Modes "1600x900"
    EndSubSection
  EndSection
</code>```

After this state, I created the image using which I could not instantiate a VM that I could SSH into.

答:
Just spin up a new container from a disk snapshot, if you need an exact copy. And if you cannot SSH, you may either not have a SSH public key provisioned, no external IP assigned, or :22 closed.

gcloud ssh always works. One can as well provision project-wide SSH keys, which all VM in the project will inherit then. The documentation below: About VM metadata explains this all in detail.

My personal favorite are rather startup scripts, which describe the configuration, instead of copying it.
And it's not so difficult to get started with these: cat ~/.bash_history > rocky8_startup.sh. In a software-defined data-center, it might make sense to use software-defined configurations (one simply cannot alternate the installation per VM instance, when starting with a disk snapshot).

xserver-xorg-video-dummy is questionable, because one can enable display device -
but unless recording the screen, this driver might still suffice; eg. for VNC sessions.

Title: Clone a google cloud VM

Body:
I have google cloud VM with Ubuntu installed along with various services and libraries. I need to make a similar bootable VM with the same OS and all the data, libraries etc in the already configured VM. How do I clone the VM with these requirements?

I tried to create an image from the already existing VM and could not SSH into it.

So I retraced my installations step by step trying to figure out which step is breaking the image.
I created an Ubuntu(18.04) VM and used that to create an image. The instance I created using the image did allow me to SSH into.

Next installed Ubuntu desktop and xorg server and created an image after that. Using that image, I created a new VM and tried to SSH into it.
But unfortunately, the SSH connection could not be established. So I think it is these installations that are causing the error if it is not some sort of system error.

Below are the exact commands I ran to install these after creating an Ubuntu(18.04) VM:

 sudo passwd username
  sudo su -
  passwd
  apt update && apt upgrade -y
  adduser username root
  adduser username admin
  adduser username sudo

  apt-get install ubuntu-desktop -y
  apt-get install xserver-xorg-video-dummy

  nano /etc/X11/xorg.conf

and pasted the following into the .conf file

Section "Device"
    Identifier  "Configured Video Device"
    Driver      "dummy"
  EndSection
  Section "Monitor"
    Identifier  "Configured Monitor"
    HorizSync 31.5-48.5
    VertRefresh 50-70
  EndSection
  Section "Screen"
    Identifier  "Default Screen"
    Monitor     "Configured Monitor"
    Device      "Configured Video Device"
    DefaultDepth 24
    SubSection "Display"
    Depth 24
    Modes "1600x900"
    EndSubSection
  EndSection

After this state, I created the image using which I could not instantiate a VM that I could SSH into.


问:
Docker NGiNX/PHP services not serving PHP
I have set up a docker-compose.yml file to start a NGiNX server and serve PHP content, the thing is it keeps on showing the default NGiNX welcome page when I visit localhost:8080.

Here's my docker-compose.yml

```<code>version: "3"
services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"
    volumes:
      - ./public:/public
      - ./site.conf:/etc/nginx/conf.d/site.conf
    links:
      - php
  php:
    image: php:8-fpm
    volumes:
      - ./public:/public
</code>```

And here's my site.conf

```<code>server {
    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /public;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}
</code>```

答:
If you have an index.php file inside the public folder, you just need to change the docker-compose.yml to:

```<code>volumes:
  - ./public:/public
  - ./site.conf:/etc/nginx/conf.d/default.conf
</code>```

Body:
I have set up a docker-compose.yml file to start a NGiNX server and serve PHP content, the thing is it keeps on showing the default NGiNX welcome page when I visit localhost:8080.

Here's my docker-compose.yml

version: "3"
services:
  web:
    image: nginx:latest
    ports:
      - "8080:80"
    volumes:
      - ./public:/public
      - ./site.conf:/etc/nginx/conf.d/site.conf
    links:
      - php
  php:
    image: php:8-fpm
    volumes:
      - ./public:/public

And here's my site.conf

server {
    index index.php index.html;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /public;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

Body:
If you have an index.php file inside the public folder, you just need to change the docker-compose.yml to:

volumes:
  - ./public:/public
  - ./site.conf:/etc/nginx/conf.d/default.conf


问:
Get formcontrolname of FormGroup in an FormArray
I have a FormGroup with a FormArray that has 3 FormControls. I want to iterate trough the FormArray and display the values of each one in a form. But I'm stuck on what to put on the FormControlName.

This is my FormGroup:

```<code>fg: FormGroup = new FormGroup({
    properties: new FormArray([])
  });
</code>```

This is how I add the FormControls into my FormArray,dataArray is the data I get from my response:

```<code>let formArray = this.fg.get('properties') as FormArray;
    for(let property of dataArray){
      const userPropertyGroup = new FormGroup({
        user_id: new FormControl("", Validators.required),
        name: new FormControl("", Validators.required),
        value: new FormControl("", Validators.required),
      });

      formArray.push(userPropertyGroup);
</code>```

To set the values in the FormArray:

```<code> for(let i = 0; i < dataArray.length; i++ ){
      formArray.controls[i].setValue({
          user_id: dataArray[i].user_id,
          name: dataArray[i].name,
          value: dataArray[i].value,
        })
    }
</code>```

Now I want to iterate and display all the values in the form. With {{property.value.name}} I'm able to get the values of each property of the array but I'm stuck at the formControlName. What should go there?

```<code> <form [formGroup]="fg" >
    <table *ngFor="let property of fg.get('properties')['controls']" class="full-width">
        {{property.value.name}}
      <tr>
        <td>
          <mat-form-field class="full-width">
            <input matInput formControlName="?????" placeholder="User id">
          </mat-form-field>
        </td>
</code>```

I checked a lot of similar questions at StackOverflow but none of them helps. I also tried implementing this example from Angular docs.  Any help is really appreciated! Thanks.

答:
You would need to structure your html as below:

<form [formGroup]="fg">
  <ng-container formArrayName="properties">

      <ng-container [formGroupName]="i">
          <input formControlName="user_id" type="text" />
          <input formControlName="name" type="text" />
          <input formControlName="value" type="text" />
      </ng-container>

  </ng-container>
</form>
```
<p>Define a getter within your <code>ts</code> component file to get the properties FormArray:</p>
<pre class="lang-ts prettyprint-override"><code>get properties(): FormArray {
  return this.fg.get('properties') as FormArray;
}
</code>```

PS: I haven't specified any CSS classes or Angular Material components in HTML, to keep the structure simple, so that it's easy to understand the hierarchy. Also I have used ng-container, you can use elements as per your use case.

Body:
I have a FormGroup with a FormArray that has 3 FormControls. I want to iterate trough the FormArray and display the values of each one in a form. But I'm stuck on what to put on the FormControlName.

This is my FormGroup:

fg: FormGroup = new FormGroup({
    properties: new FormArray([])
  });

This is how I add the FormControls into my FormArray,dataArray is the data I get from my response:

let formArray = this.fg.get('properties') as FormArray;
    for(let property of dataArray){
      const userPropertyGroup = new FormGroup({
        user_id: new FormControl("", Validators.required),
        name: new FormControl("", Validators.required),
        value: new FormControl("", Validators.required),
      });

      formArray.push(userPropertyGroup);

To set the values in the FormArray:

 for(let i = 0; i < dataArray.length; i++ ){
      formArray.controls[i].setValue({
          user_id: dataArray[i].user_id,
          name: dataArray[i].name,
          value: dataArray[i].value,
        })
    }

Now I want to iterate and display all the values in the form. With {{property.value.name}} I'm able to get the values of each property of the array but I'm stuck at the formControlName. What should go there?

 <form [formGroup]="fg" >

        {{property.value.name}}

          <mat-form-field class="full-width">
            <input matInput formControlName="?????" placeholder="User id">
          </mat-form-field>

I checked a lot of similar questions at StackOverflow but none of them helps. I also tried implementing this example from Angular docs.  Any help is really appreciated! Thanks.

Body:
You would need to structure your html as below:

<form [formGroup]="fg">
  <ng-container formArrayName="properties">
    <div *ngFor="let property of properties.controls; let i = index"> <!-- Iterate over FormArray controls -->
      <ng-container [formGroupName]="i"> <!-- Since each control within FormArray is a FormGroup -->
          <input formControlName="user_id" type="text" />
          <input formControlName="name" type="text" />
          <input formControlName="value" type="text" />
      </ng-container>
    </div>
  </ng-container>
</form>

Define a getter within your ts component file to get the properties FormArray:

get properties(): FormArray {
  return this.fg.get('properties') as FormArray;
}

PS: I haven't specified any CSS classes or Angular Material components in HTML, to keep the structure simple, so that it's easy to understand the hierarchy. Also I have used ng-container, you can use elements as per your use case.


问:
Void function required to return value?
I wrote a function as follows which is used to create pthread:

```<code>void *downloadfile(void *arg)
{
  char *req_path = NULL;
  char local_path[PATH_BUFFER_SIZE];
  int returncode = 0;
  gfcrequest_t *gfr = NULL;
  FILE *file = NULL;
  int i = 0;

  /* Build your queue of requests here */
  for (i = 0; i < nrequests; i++) {
    // pthread mutex locking
    // doing something
    // pthread mutex unlocking

    localPath(req_path, local_path);

    file = openFile(local_path);

    gfr = gfc_create();
    gfc_set_server(&gfr, server);
    gfc_set_path(&gfr, req_path);
    gfc_set_port(&gfr, port);
    gfc_set_writefunc(&gfr, writecb);
    gfc_set_writearg(&gfr, file);

    fprintf(stdout, "Requesting %s%s\n", server, req_path);

    if (0 > (returncode = gfc_perform(&gfr))) {
      fprintf(stdout, "gfc_perform returned an error %d\n", returncode);
      fclose(file);
      if (0 > unlink(local_path))
        fprintf(stderr, "warning: unlink failed on %s\n", local_path);
    } else {
      fclose(file);
    }

    if (gfc_get_status(&gfr) != GF_OK) {
      if (0 > unlink(local_path))
        fprintf(stderr, "warning: unlink failed on %s\n", local_path);
    }

    fprintf(stdout, "Status: %s\n", gfc_strstatus(gfc_get_status(&gfr)));
    fprintf(stdout, "Received %zu of %zu bytes\n", gfc_get_bytesreceived(&gfr),
            gfc_get_filelen(&gfr));

    gfc_cleanup(&gfr);
    req_path = NULL;
  }
//  return 0;
}
</code>```

I commented out the "return 0;" statement because this is a void function thus should not return any value.  But the compiler complains that

error: control reaches end of non-void function

If I uncomment the "return 0;" statement, the error goes away.  I am so puzzled.  How can the compiler require a void function to return value?  Could somebody please help out?

答:
From your description I assume that your function downloadfile is to be used as function-pointer argument in a pthread_create call.

So you have a basic misunderstanding. The function pointer used for pthread_create is not a function pointer to a "void function". It's a function pointer to a function that returns a void pointer. (BTW: You can get the return value using the pthread_join function if needed)

So in other other words: Your function must return a void-pointer. If you have nothing meaningful to return just use return NULL;

Extra details:

From https://man7.org/linux/man-pages/man3/pthread_create.3.html we have:

```<code>   int pthread_create(pthread_t *restrict thread,
                      const pthread_attr_t *restrict attr,
                      void *(*start_routine)(void *),
                      void *restrict arg);
</code>```

The interresting part here is void *(*start_routine)(void *) which means:

```<code> void *(*start_routine)(void *)
 \----/\--------------/\------/
    |   Function ptr       |
    |   to a function   /----------\
    |        that takes void pointer as argument
    |   and returns
/----------\
void pointer
</code>```

So again - to use a correct function pointer argument for pthread_create you need a function that returns a void-pointer.

Title: Void function required to return value?

Body:
I wrote a function as follows which is used to create pthread:

void *downloadfile(void *arg)
{
  char *req_path = NULL;
  char local_path[PATH_BUFFER_SIZE];
  int returncode = 0;
  gfcrequest_t *gfr = NULL;
  FILE *file = NULL;
  int i = 0;

  /* Build your queue of requests here */
  for (i = 0; i < nrequests; i++) {
    // pthread mutex locking
    // doing something
    // pthread mutex unlocking

    localPath(req_path, local_path);

    file = openFile(local_path);

    gfr = gfc_create();
    gfc_set_server(&gfr, server);
    gfc_set_path(&gfr, req_path);
    gfc_set_port(&gfr, port);
    gfc_set_writefunc(&gfr, writecb);
    gfc_set_writearg(&gfr, file);

    fprintf(stdout, "Requesting %s%s\n", server, req_path);

    if (0 > (returncode = gfc_perform(&gfr))) {
      fprintf(stdout, "gfc_perform returned an error %d\n", returncode);
      fclose(file);
      if (0 > unlink(local_path))
        fprintf(stderr, "warning: unlink failed on %s\n", local_path);
    } else {
      fclose(file);
    }

    if (gfc_get_status(&gfr) != GF_OK) {
      if (0 > unlink(local_path))
        fprintf(stderr, "warning: unlink failed on %s\n", local_path);
    }

    fprintf(stdout, "Status: %s\n", gfc_strstatus(gfc_get_status(&gfr)));
    fprintf(stdout, "Received %zu of %zu bytes\n", gfc_get_bytesreceived(&gfr),
            gfc_get_filelen(&gfr));

    gfc_cleanup(&gfr);
    req_path = NULL;
  }
//  return 0;
}

I commented out the "return 0;" statement because this is a void function thus should not return any value.  But the compiler complains that

error: control reaches end of non-void function

If I uncomment the "return 0;" statement, the error goes away.  I am so puzzled.  How can the compiler require a void function to return value?  Could somebody please help out?

Body:
From your description I assume that your function downloadfile is to be used as function-pointer argument in a pthread_create call.

So you have a basic misunderstanding. The function pointer used for pthread_create is not a function pointer to a "void function". It's a function pointer to a function that returns a void pointer. (BTW: You can get the return value using the pthread_join function if needed)

So in other other words: Your function must return a void-pointer. If you have nothing meaningful to return just use return NULL;

Extra details:

From https://man7.org/linux/man-pages/man3/pthread_create.3.html we have:

   int pthread_create(pthread_t *restrict thread,
                      const pthread_attr_t *restrict attr,
                      void *(*start_routine)(void *),
                      void *restrict arg);

The interresting part here is void *(*start_routine)(void *) which means:

 void *(*start_routine)(void *)
 \----/\--------------/\------/
    |   Function ptr       |
    |   to a function   /----------\
    |        that takes void pointer as argument
    |   and returns
/----------\
void pointer

So again - to use a correct function pointer argument for pthread_create you need a function that returns a void-pointer.


问:
Typescript difference between typeof class and class as property type
I have index.d.ts,

Initially, I assign a class ApplePaySession to Window, for me to be able to use window.ApplePaySession. However, when trying to access static methods, typescript complaints.

```<code>// index.d.ts
interface Window {
  ApplePaySession: ApplePaySession | undefined
}

// MyCode.ts
const isAvailable = (): boolean => {
  const ApplePay = window.ApplePaySession
  return Boolean(ApplePay) && ApplePay.canMakePayments()
}

// ApplePaySession definition
    /**
     * Indicates whether the device supports Apple Pay.
     * @returns true if the device supports making payments with Apple Pay; otherwise, false.
     */
    static canMakePayments(): boolean;

// Error
Property 'canMakePayments' does not exist on type 'ApplePaySession'. Did you mean to access the static member 'ApplePaySession.canMakePayments' instead?ts(2576)
</code>```

I have to change my definition in index.d.ts to this in order for it to work:

```<code>interface Window {
  ApplePaySession: typeof ApplePaySession | undefined
}
</code>```

Why is that? what's the difference between assigning class type using typeof Class and Class in typescript?

答:
Given following ...

```<code>interface Window {
  ApplePaySession: ApplePaySession | undefined
}

class ApplePaySession {
  constructor() {}
  static canMakePayments() {
    return false;
  }
}

const isAvailable = (): boolean => {
  const ApplePay = window.ApplePaySession   // <-- This will be treated as an instance and not as a type
  return ApplePay && ApplePay.canMakePayments() || false // <-- Error, Being a static member, canMakePayments will have to be accessed via type ApplePaySession, like ApplePaySession.canMakePayments()
  // return ApplePay && ApplePaySession.canMakePayments() || false  //<-- Ok, access via type not instance
}

</code>```

It complains because we are accessing an instance member via an interface property, and which means it needs to be a value(an object created from class ApplePlaySession). However sincecanMakePayments is a static member, it will have to be accessed via a type and not via instances of values.

Now... what will you adjust, depends upon your use case.

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET

Body:
I have index.d.ts,

Initially, I assign a class ApplePaySession to Window, for me to be able to use window.ApplePaySession. However, when trying to access static methods, typescript complaints.

// index.d.ts
interface Window {
  ApplePaySession: ApplePaySession | undefined
}

// MyCode.ts
const isAvailable = (): boolean => {
  const ApplePay = window.ApplePaySession
  return Boolean(ApplePay) && ApplePay.canMakePayments()
}

// ApplePaySession definition
    /**
     * Indicates whether the device supports Apple Pay.
     * @returns true if the device supports making payments with Apple Pay; otherwise, false.
     */
    static canMakePayments(): boolean;

// Error
Property 'canMakePayments' does not exist on type 'ApplePaySession'. Did you mean to access the static member 'ApplePaySession.canMakePayments' instead?ts(2576)

I have to change my definition in index.d.ts to this in order for it to work:

interface Window {
  ApplePaySession: typeof ApplePaySession | undefined
}

Why is that? what's the difference between assigning class type using typeof Class and Class in typescript?

Body:
Given following ...

interface Window {
  ApplePaySession: ApplePaySession | undefined
}

class ApplePaySession {
  constructor() {}
  static canMakePayments() {
    return false;
  }
}

const isAvailable = (): boolean => {
  const ApplePay = window.ApplePaySession   // <-- This will be treated as an instance and not as a type
  return ApplePay && ApplePay.canMakePayments() || false // <-- Error, Being a static member, canMakePayments will have to be accessed via type ApplePaySession, like ApplePaySession.canMakePayments()
  // return ApplePay && ApplePaySession.canMakePayments() || false  //<-- Ok, access via type not instance
}

It complains because we are accessing an instance member via an interface property, and which means it needs to be a value(an object created from class ApplePlaySession). However sincecanMakePayments is a static member, it will have to be accessed via a type and not via instances of values.

Now... what will you adjust, depends upon your use case.

WYSIWYG => WHAT YOU SHOW IS WHAT YOU GET


问:
How to change a class of edges to a list in NetworkX?
I tried to create a list from the class of edges in NetworkX using the function  list(). However, when I access the list using print(data[0]), I get the edge and all its attributes but I only want the edge. How can I access the edge alone?

```<code>edges = g.edges()
print("Type = " ,type(edges))

print("All edges: ", edges )

#Changing the class of edges into a list
data = list(edges. items())

print("First edge = ", data[0])
</code>```

This is the output of the code:

答:
You don't need to use items:

```<code>edges = list(g.edges())
print(edges)

# Output
[(0, 1),
 (0, 2),
 (0, 3),
 (0, 4),
 (0, 5),
 (0, 6),
 (0, 7),
 (0, 8),
 (0, 10),
 ...]
</code>```

items return the edges and the associated data.

Body:
I tried to create a list from the class of edges in NetworkX using the function  list(). However, when I access the list using print(data[0]), I get the edge and all its attributes but I only want the edge. How can I access the edge alone?

edges = g.edges()
print("Type = " ,type(edges))

print("All edges: ", edges )

#Changing the class of edges into a list
data = list(edges. items())

print("First edge = ", data[0])

This is the output of the code:

Body:
You don't need to use items:

edges = list(g.edges())
print(edges)

# Output
[(0, 1),
 (0, 2),
 (0, 3),
 (0, 4),
 (0, 5),
 (0, 6),
 (0, 7),
 (0, 8),
 (0, 10),
 ...]

items return the edges and the associated data.


问:
BigQuery scheduled query: Cannot create a transfer in > JURISDICTION_US when destination dataset is located in > REGION_ASIA_SOUTHEAST_1
I am getting this error quite frequently while trying to create a scheduled query

Error creating scheduled query: Cannot create a transfer in
  JURISDICTION_US when destination dataset is located in
  REGION_ASIA_SOUTHEAST_1

I just need a scheduled query to overwrite data in a table.

答:
I was using bq command when I came across this issue and was able to resolve it by adding parameter --location='europe-west1

So my final query looked like this

```<code>bq query \
--use_legacy_sql=false \
--display_name='my_table' \
--location='europe-west1' \
'''create or replace table my_dataset.my_table as (select * from external_query('projects/my_mysql_connection/locations/europe-west1/connections/bi', '(select * from my_table)'))'''
</code>```

Body:
I was using bq command when I came across this issue and was able to resolve it by adding parameter --location='europe-west1

So my final query looked like this

bq query \
--use_legacy_sql=false \
--display_name='my_table' \
--location='europe-west1' \
'''create or replace table my_dataset.my_table as (select * from external_query('projects/my_mysql_connection/locations/europe-west1/connections/bi', '(select * from my_table)'))'''


问:
AttributeError: 'Serializer' object has no attribute 'Meta' in django rest framework
I am using serializers.Serializer instead of ModelSerializer which doesn't require Meta class but it keep saying object has no attribute Meta. Iam not sure what is the issue but when I run the localserver, the main page gives error saying api fetch error and in the terminal it says  AttributeError: 'Serializer' object has no attribute 'Meta'.

My view:

```<code>class ClassView(viewsets.ModelViewSet):
    queryset = Class.objects.all().order_by('-created_at')
    serializer_class = ClassSerializer
    serializer_action_classes = {
        'get_all_students_of_a_class': ClassDetailSerializer,
    }
    # .annotate(total_students=Count('students_in_class'))
    def get_serializer_class(self):

        """
            returns a serializer class based on the action
            that has been defined.
        """
        try:
            return self.serializer_action_classes[self.action]
        except (KeyError, AttributeError):
            return super(ClassView, self).get_serializer_class()

    def get_all_students_of_a_class(self,request,pk=None):

        """
            returns a class details with all the students signed up for the
            class along with the subject.
        """

        id = pk
        if self.is_teacher(id):
            online_classes = get_object_or_404(Class, id=id)
            students = Student.objects.filter(online_class__id=id)
            subject_details = Subject.objects.get(online_class__id=id)
            total_students_in_class = online_classes.total_students_in_class
            created_at = online_classes.created_at
            updated_at = online_classes.updated_at
            data = {
                "teacher": self.get_teacher_instance(),
                'total_students_in_class': total_students_in_class,
                "students_in_class": students,
                "subject": subject_details,
                'created_at': created_at,
                'last_updated_at': updated_at,

            }
            serializer_class = self.get_serializer_class()
            serializer = serializer_class(data)
            return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

My serializer:

```<code>class ClassDetailSerializer(serializers.Serializer):
    teacher = serializers.StringRelatedField()
    subject = SubjectLevelSerializer()
    total_students_in_class = serializers.ReadOnlyField()
    students_in_class = serializers.StringRelatedField(many=True)
    created_at = serializers.DateTimeField(read_only=True)
    last_updated_at =  serializers.DateTimeField(read_only=True)
</code>```

My url:

```<code> path("class/<int:pk>/",teacher.ClassView.as_view({"get": "get_all_students_of_a_class","delete":"destroy"}),
    ),
</code>```

However it works and I can perform action if I go to localhost/admin and other api calls from localhost.

答: Try to use "ViewSet" instead of "ModelViewSet". And while using ViewSet make sure to define list, create, etc. function by your own.</p>

Body:
I am using serializers.Serializer instead of ModelSerializer which doesn't require Meta class but it keep saying object has no attribute Meta. Iam not sure what is the issue but when I run the localserver, the main page gives error saying api fetch error and in the terminal it says  AttributeError: 'Serializer' object has no attribute 'Meta'.

My view:

class ClassView(viewsets.ModelViewSet):
    queryset = Class.objects.all().order_by('-created_at')
    serializer_class = ClassSerializer
    serializer_action_classes = {
        'get_all_students_of_a_class': ClassDetailSerializer,
    }
    # .annotate(total_students=Count('students_in_class'))
    def get_serializer_class(self):

        """
            returns a serializer class based on the action
            that has been defined.
        """
        try:
            return self.serializer_action_classes[self.action]
        except (KeyError, AttributeError):
            return super(ClassView, self).get_serializer_class()

    def get_all_students_of_a_class(self,request,pk=None):

        """
            returns a class details with all the students signed up for the
            class along with the subject.
        """

        id = pk
        if self.is_teacher(id):
            online_classes = get_object_or_404(Class, id=id)
            students = Student.objects.filter(online_class__id=id)
            subject_details = Subject.objects.get(online_class__id=id)
            total_students_in_class = online_classes.total_students_in_class
            created_at = online_classes.created_at
            updated_at = online_classes.updated_at
            data = {
                "teacher": self.get_teacher_instance(),
                'total_students_in_class': total_students_in_class,
                "students_in_class": students,
                "subject": subject_details,
                'created_at': created_at,
                'last_updated_at': updated_at,

            }
            serializer_class = self.get_serializer_class()
            serializer = serializer_class(data)
            return Response(serializer.data, status=status.HTTP_200_OK)

My serializer:

class ClassDetailSerializer(serializers.Serializer):
    teacher = serializers.StringRelatedField()
    subject = SubjectLevelSerializer()
    total_students_in_class = serializers.ReadOnlyField()
    students_in_class = serializers.StringRelatedField(many=True)
    created_at = serializers.DateTimeField(read_only=True)
    last_updated_at =  serializers.DateTimeField(read_only=True)

My url:

 path("class/<int:pk>/",teacher.ClassView.as_view({"get": "get_all_students_of_a_class","delete":"destroy"}),
    ),

However it works and I can perform action if I go to localhost/admin and other api calls from localhost.


问:
Multiple time allocation and release
I am creating a quiz app for iPhone/iPad(universal app).It is working fine on simulator but on real device there are some problem i am facing..

I am creating UILabels and UIButtons programmatically and i am using them so many times for displaying questions and answers one by one.

problem is when i reach around question 20 to 22 the application crashes. I don't know why. there is no memory leak i found. I release all the labels and buttons at the -dealloc function.

may be it happens because 22 questions takes some memory and not release till dealloc function call.

What i want is , Is there any way to release labels and buttons after every question and then it will allocate again? or any way in which i can use less memory for allocation labels and buttons??

I am using this code :

```<code>//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];
</code>```

Any help??

Thank you.

答:
Once you add label as subview to the view - the view will retain the label you can release the label, In your case you are not releasing ContainerView

You should not release the autoreleased objects - it is fine

Title: Multiple time allocation and release

Body:
I am creating a quiz app for iPhone/iPad(universal app).It is working fine on simulator but on real device there are some problem i am facing..

I am creating UILabels and UIButtons programmatically and i am using them so many times for displaying questions and answers one by one.

problem is when i reach around question 20 to 22 the application crashes. I don't know why. there is no memory leak i found. I release all the labels and buttons at the -dealloc function.

may be it happens because 22 questions takes some memory and not release till dealloc function call.

What i want is , Is there any way to release labels and buttons after every question and then it will allocate again? or any way in which i can use less memory for allocation labels and buttons??

I am using this code :

//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];

Any help??

Thank you.


问:
How to rename media file before transfer from channel A to B (client.send_message)?
I'm looking to a way to rename file before it's transfer to the other channel

so what I want is:

telethon is reading texts and media(with caption) from channel "A"

then rename media to specific name "abc.jpg" or "abc.mp3"

telethon send texts and media(with caption) to channel "B"

i'm using this code

@client.on(events.NewMessage(chats=input_channels_entities))
async def handler(event):
    for output_channel in output_channel_entities:
        await client.send_message(output_channel, event.message)
```

is there specific to do? I looked over Telethon docs and searched every place but no luck

答:
In your case you didn't find it on Telethon docs out because is not related to Telegram, but to the file itself.

Since you're willing to rename the file before sending it to the other channel, the simplest way is to download the file itself via its file ID stored in the Telegram servers thanks to the getFile method.

Once you download it locally, you can rename it directly and let your chatbot send it once through the methods offered by Telegram Chatbot API.

This last point is generic, because it depends by the file type you're willing to forward (audio, image, video, zip, document, etc.): additional information could be find out here: https://core.telegram.org/bots/api#available-methods

Body:
I'm looking to a way to rename file before it's transfer to the other channel

so what I want is:

telethon is reading texts and media(with caption) from channel "A"

then rename media to specific name "abc.jpg" or "abc.mp3"

telethon send texts and media(with caption) to channel "B"

i'm using this code

@client.on(events.NewMessage(chats=input_channels_entities))
async def handler(event):
    for output_channel in output_channel_entities:
        await client.send_message(output_channel, event.message)

is there specific to do? I looked over Telethon docs and searched every place but no luck


问:
Hover on anchor link and show icon
I'm trying to copy the CSS on those "documentation" pages of those projects such as bootstrap where when you hover on anchor link(s) it would show you a certain icon

a {
font-weight: bold;
font-size: 20px;
color: #000000;
text-decoration: none;
}

/* mouse hover link */
a:hover {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 15px 15px;
  background-repeat: no-repeat;
  background-position: 200px 50%;
  background-attachment: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some Random Header Text<br>
Some Random Header Text but Longer</code>```

I want the icon to show at the right end of the text for the both instances of anchor link when hover unto them how can I achieve it?

Here's an expected result:

答:
a {
  font-weight: bold;
  font-size: 20px;
  color: #000000;
  text-decoration: none;
}

/* mouse hover link */
a:hover::after {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 20px 20px;
  display: inline-block;
  width: 20px;
  height: 20px;
  content: "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some Random Header Text<br>
Some Random Header Text but Longer</code>```

Title: Hover on anchor link and show icon

Body:
I'm trying to copy the CSS on those "documentation" pages of those projects such as bootstrap where when you hover on anchor link(s) it would show you a certain icon

a {
font-weight: bold;
font-size: 20px;
color: #000000;
text-decoration: none;
}

/* mouse hover link */
a:hover {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 15px 15px;
  background-repeat: no-repeat;
  background-position: 200px 50%;
  background-attachment: scroll;
}

Some Random Header Text

Some Random Header Text but Longer

I want the icon to show at the right end of the text for the both instances of anchor link when hover unto them how can I achieve it?

Here's an expected result:

Body:
a {
  font-weight: bold;
  font-size: 20px;
  color: #000000;
  text-decoration: none;
}

/* mouse hover link */
a:hover::after {
  background: url(https://icons.iconarchive.com/icons/custom-icon-design/mono-general-2/512/copy-icon.png);
  background-size: 20px 20px;
  display: inline-block;
  width: 20px;
  height: 20px;
  content: "";
}

<a href="#">Some Random Header Text</a><br>
<a href="#">Some Random Header Text but Longer</a>


问:
how to get android device's NPU version
I found a column called "NPU Version". I tried "adb shell getprop" to get NPU Version, but failed(there's no information adout NPU Version). so my question is how could i get the NPU Version programmely?</p>

答:
here's what the "NPU Version" looks like [enter image description here][1]

[1]: https://i.stack.imgur.com/5rCd8.jpg sorry about posting detail on the answer. i could not add image on my question.

Title: how to get android device's NPU version


问:
List all functions inside a given function
I would like to map the relations and dependencies of different functions from different scripts.

By now, I´m able to extract all the functions for a given script but I would like to get one level deeper, and try to list all the functions contained in each function.

I´m using the package "NCmisc" and list.functions.in.file function to do the first listing.

rfile <- file.choose() # choose an R script file with functions
list.functions.in.file(rfile) # list all the functions
```

As a result, it returns the list containing all the functions, but I would like to apply a similar procces to parse all functions inside a given function and complete the "mapping" to that level of detail.

Any ideas? thank you

答:
I wrote a package funspotr that lists all the functions inside a file. E.g.

funspotr::spot_funs("https://gist.githubusercontent.com/brshallo/f0cdfd38f31947b5edbe3efd8efab036/raw/5979cdc0696911eb0fced82f62c289cdc46dbc8d/if_all-if_any-examples.R")
#> # A tibble: 12 x 3
#>    funs      pkgs      in_multiple_pkgs
#>    <chr>     <chr>     <lgl>
#>  1 library   base      FALSE
#>  2 set.seed  base      FALSE
#>  3 map       purrr     FALSE
#>  4 runif     stats     FALSE
#>  5 set_names purrr     FALSE
#>  6 paste0    base      FALSE
#>  7 as_tibble dplyr     TRUE
#>  8 mutate    dplyr     FALSE
#>  9 filter    dplyr     TRUE
#> 10 if_all    dplyr     FALSE
#> 11 where     (unknown) FALSE
#> 12 if_any    dplyr     FALSE
```

Created on 2022-02-08 by the reprex package (v2.0.0)

Body:
I would like to map the relations and dependencies of different functions from different scripts.

By now, I´m able to extract all the functions for a given script but I would like to get one level deeper, and try to list all the functions contained in each function.

I´m using the package "NCmisc" and list.functions.in.file function to do the first listing.

rfile <- file.choose() # choose an R script file with functions
list.functions.in.file(rfile) # list all the functions

As a result, it returns the list containing all the functions, but I would like to apply a similar procces to parse all functions inside a given function and complete the "mapping" to that level of detail.

Any ideas? thank you

Body:
I wrote a package funspotr that lists all the functions inside a file. E.g.

funspotr::spot_funs("https://gist.githubusercontent.com/brshallo/f0cdfd38f31947b5edbe3efd8efab036/raw/5979cdc0696911eb0fced82f62c289cdc46dbc8d/if_all-if_any-examples.R")
#> # A tibble: 12 x 3
#>    funs      pkgs      in_multiple_pkgs
#>    <chr>     <chr>     <lgl>
#>  1 library   base      FALSE
#>  2 set.seed  base      FALSE
#>  3 map       purrr     FALSE
#>  4 runif     stats     FALSE
#>  5 set_names purrr     FALSE
#>  6 paste0    base      FALSE
#>  7 as_tibble dplyr     TRUE
#>  8 mutate    dplyr     FALSE
#>  9 filter    dplyr     TRUE
#> 10 if_all    dplyr     FALSE
#> 11 where     (unknown) FALSE
#> 12 if_any    dplyr     FALSE

Created on 2022-02-08 by the reprex package (v2.0.0)


问:
Getting bash completion error is a directory everytime I open the terminal
I just switched over to Linux (Ubuntu 20.04) a few days ago after using Windows for the last 13 years and I am loving it so far.

Of course I started messing around with everything, because that's how I usually learn something new and now I ran into a problem.

I installed Alacritty terminal and everything went smoothly but for one small problem.

I followed those instructions in order to install the bash completions:

mkdir -p ~/.bash_completion
cp extra/completions/alacritty.bash ~/.bash_completion/alacritty
echo "source ~/.bash_completion/alacritty" >> ~/.bashrc```

Now everytime I open the terminal I get the following error:

bash: .: /home/myname/.bash_completion: is a directory

I thought I was referencing the folder and not the file, so I opened the .bashrc file in the nano editor but I find no reference to /home/myname/.bash_completion , just source ~/.bash_completion/alacritty

I tried to search for this problem, but I didn't find anyone who had the same problem.

Here is my bashrc file: https://pastebin.pl/view/83ce4d25

答:
TLDR: Create ~/.bash_completion.d directory instead and reference it wherever it's relevant.

Following up as I stumbled upon the exact same scenario and wanted to figure out how to process this properly.

For information, I'm running Linux Mint (Debian based).

In .bash_profile, there is this line:

```<code>[ -f /etc/bash_completion ] && source /etc/bash_completion
</code>```

The sourced file contains:

```<code>. /usr/share/bash-completion/bash_completion
</code>```

So far, we got pretty much the same behavior. It's just not handled the same way.

Now, since this is default, it's better not to touch anything to avoid extra issues. Most Linux distributions assume that ~/.bash_completion is a file with user-defined completions, not a directory.

And there is this (kind of?) convention for creating directory suffixed with .d in their name to make things explicit and prevent conflicts (such as our).

The solution would then to be:

```<code>mkdir -p ~/.bash_completion.d
mv ~/.bash_completion/* ~/.bash_completion.d
rm ~/.bash_completion
vim ~/.bashrc
</code>```

Once the editor is open, update the path from:

```<code>source ~/.bash_completion/alacritty
</code>```

to:

```<code>source ~/.bash_completion.d/alacritty
</code>```

Reload and you should be good to go no matter the distribution you're working on :)

Body:
I just switched over to Linux (Ubuntu 20.04) a few days ago after using Windows for the last 13 years and I am loving it so far.

Of course I started messing around with everything, because that's how I usually learn something new and now I ran into a problem.

I installed Alacritty terminal and everything went smoothly but for one small problem.

I followed those instructions in order to install the bash completions:

mkdir -p ~/.bash_completion
cp extra/completions/alacritty.bash ~/.bash_completion/alacritty
echo "source ~/.bash_completion/alacritty" >> ~/.bashrc

Now everytime I open the terminal I get the following error:

bash: .: /home/myname/.bash_completion: is a directory

I thought I was referencing the folder and not the file, so I opened the .bashrc file in the nano editor but I find no reference to /home/myname/.bash_completion , just source ~/.bash_completion/alacritty

I tried to search for this problem, but I didn't find anyone who had the same problem.

Here is my bashrc file: https://pastebin.pl/view/83ce4d25

Body:
TLDR: Create ~/.bash_completion.d directory instead and reference it wherever it's relevant.

Following up as I stumbled upon the exact same scenario and wanted to figure out how to process this properly.

For information, I'm running Linux Mint (Debian based).

In .bash_profile, there is this line:

[ -f /etc/bash_completion ] && source /etc/bash_completion

The sourced file contains:

. /usr/share/bash-completion/bash_completion

So far, we got pretty much the same behavior. It's just not handled the same way.

Now, since this is default, it's better not to touch anything to avoid extra issues. Most Linux distributions assume that ~/.bash_completion is a file with user-defined completions, not a directory.

And there is this (kind of?) convention for creating directory suffixed with .d in their name to make things explicit and prevent conflicts (such as our).

The solution would then to be:

mkdir -p ~/.bash_completion.d
mv ~/.bash_completion/* ~/.bash_completion.d
rm ~/.bash_completion
vim ~/.bashrc

Once the editor is open, update the path from:

source ~/.bash_completion/alacritty

to:

source ~/.bash_completion.d/alacritty

Reload and you should be good to go no matter the distribution you're working on :)