问:
Use cursor loader for multiple data sources
I have code that fetches contact information from Android using the contact name as the selection. However, the datasource (which I guess would be ContactsContract.Contacts) does not have everything I need about the contact. I see that contact information is divided between several tables (ContactsContract.CommonDataKinds.StructuredName, ContactsContract.CommonDataKinds.Phone, etc). I have also notices that all of these sources have access to a LOOKUP_KEY field. It uniquely identifies a contact. I want to know if there is a way to perform a join on these datasources using the LOOKUP_KEY.

Below, I currently setup the projection and selection for a single datasource and query it asynchronously using a cursor loader. Is there a way to search multiple datasources at once using the LOOKUP_KEY?

```<code>private static final String[] CONTACT_PROJECTION = {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.LOOKUP_KEY,
        ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
        ContactsContract.Contacts.HAS_PHONE_NUMBER
};

private static final String CONTACT_SELECTION = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
        + " LIKE ?";

public static Loader<Cursor> getContactLoader(Context applicationContext, String searchString) {
    String[] selectionArgs = new String[1];
    selectionArgs[0] = "%" + searchString + "%";
    return new CursorLoader(
            applicationContext,
            ContactsContract.Contacts.CONTENT_URI,
            CONTACT_PROJECTION,
            CONTACT_SELECTION,
            selectionArgs,
            null
    );
}
</code>```

答:
All info on all contacts is grouped in alias tables, which are actually stored in a single big table called Data, so you can simply query that table for all info related to a specific contact (you can use CONTACT_ID, no need to mess with the more problematic LOOKUP_URI), like so:

```<code>public void getContactInfo(long contactId) {

    Uri uri = Data.CONTENT_URI;

    String[] projection = new String[]{
            Data.CONTACT_ID,
            Data.DISPLAY_NAME,
            Data.MIMETYPE,
            Data.DATA1}; // you can get additional info if needed in Data.DATA2, DATA3, etc.

    // get all relevant info about the contact
    String selection = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + " IN (?,?,?,?)"; // you can add more question marks if you need more MIMETYPES
    String[] selectionArgs = new String[]{String.valueOf(contactId), Phone.CONTENT_ITEM_TYPE, Email.CONTENT_ITEM_TYPE, Event.CONTENT_ITEM_TYPE, StructuredPostal.CONTENT_ITEM_TYPE};

    Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null);

    while (cursor.moveToNext()) {
        String name = cursor.getString(1);
        String mimetype = cursor.getString(2);
        String data = cursor.getString(3);

        // use the mimetype to figure out what kind of info is in this row

        Log.i("Contact Info", contactId + "=> " + name + " - " + mimetype + ": " + data);
    }
    cursor.close();
}
</code>```

Body:
I have code that fetches contact information from Android using the contact name as the selection. However, the datasource (which I guess would be ContactsContract.Contacts) does not have everything I need about the contact. I see that contact information is divided between several tables (ContactsContract.CommonDataKinds.StructuredName, ContactsContract.CommonDataKinds.Phone, etc). I have also notices that all of these sources have access to a LOOKUP_KEY field. It uniquely identifies a contact. I want to know if there is a way to perform a join on these datasources using the LOOKUP_KEY.

Below, I currently setup the projection and selection for a single datasource and query it asynchronously using a cursor loader. Is there a way to search multiple datasources at once using the LOOKUP_KEY?

private static final String[] CONTACT_PROJECTION = {
        ContactsContract.Contacts._ID,
        ContactsContract.Contacts.LOOKUP_KEY,
        ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
        ContactsContract.Contacts.HAS_PHONE_NUMBER
};

private static final String CONTACT_SELECTION = ContactsContract.Contacts.DISPLAY_NAME_PRIMARY
        + " LIKE ?";

public static Loader<Cursor> getContactLoader(Context applicationContext, String searchString) {
    String[] selectionArgs = new String[1];
    selectionArgs[0] = "%" + searchString + "%";
    return new CursorLoader(
            applicationContext,
            ContactsContract.Contacts.CONTENT_URI,
            CONTACT_PROJECTION,
            CONTACT_SELECTION,
            selectionArgs,
            null
    );
}

Body:
All info on all contacts is grouped in alias tables, which are actually stored in a single big table called Data, so you can simply query that table for all info related to a specific contact (you can use CONTACT_ID, no need to mess with the more problematic LOOKUP_URI), like so:

public void getContactInfo(long contactId) {

    Uri uri = Data.CONTENT_URI;

    String[] projection = new String[]{
            Data.CONTACT_ID,
            Data.DISPLAY_NAME,
            Data.MIMETYPE,
            Data.DATA1}; // you can get additional info if needed in Data.DATA2, DATA3, etc.

    // get all relevant info about the contact
    String selection = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + " IN (?,?,?,?)"; // you can add more question marks if you need more MIMETYPES
    String[] selectionArgs = new String[]{String.valueOf(contactId), Phone.CONTENT_ITEM_TYPE, Email.CONTENT_ITEM_TYPE, Event.CONTENT_ITEM_TYPE, StructuredPostal.CONTENT_ITEM_TYPE};

    Cursor cursor = getContentResolver().query(uri, projection, selection, selectionArgs, null);

    while (cursor.moveToNext()) {
        String name = cursor.getString(1);
        String mimetype = cursor.getString(2);
        String data = cursor.getString(3);

        // use the mimetype to figure out what kind of info is in this row

        Log.i("Contact Info", contactId + "=> " + name + " - " + mimetype + ": " + data);
    }
    cursor.close();
}


来源: stackexchange

问:
Can't figure out data binding in Kotlin
Recently I started developing apps in Android studio via Kotlin, because Java seemed a bit harder. I built my first app and now, for the second, I wanna try out data binding. I follow a Udacity tutorial and there it says that I have to include dataBinding{ enabled=True } which I did.

The problem is that when I try to import com.android.AppName.databinding.ActivityMainBinding
the name is red, even though I declared the variable below, in the onCreate
Everything related to data binding is red pretty much.

I can't figure out what's the problem. Any suggestion would help. Thanks!

答:
I actually know the answer to this. </p>

<p>You need to update your dependencies. You can check out the github project they recommend you download and you'll notice your dependencies are not appropriate for databinding. Can't remember exactly what it is but you need to either update a version on one of the dependencies or you need to add an entirely new dependency in. </p>

ContentLicense: CC BY-SA 4.0

Title: Can't figure out data binding in Kotlin

Body:
I actually know the answer to this.

You need to update your dependencies. You can check out the github project they recommend you download and you'll notice your dependencies are not appropriate for databinding. Can't remember exactly what it is but you need to either update a version on one of the dependencies or you need to add an entirely new dependency in.


问:
Using an existing function, how to define a new function with different default optional arguments?
Given a function fxn1()

def fxn1(a,b=1):
    return a*b
```

<p>I would like to do something like:</p>

<pre class="lang-py prettyprint-override"><code>fxn2=fxn1(.,b=2)
</code>```

In words, I would like to make a new function fxn2() which is identical to fxn1() but with different default values of optional arguments. I have not been able to find an answer/direction on web.

答:
The easiest way will be</p>

```<code>def fxn2(a, b=2):
    return fxn1(a, b)
</code>```

Body:
Given a function fxn1()

def fxn1(a,b=1):
    return a*b

I would like to do something like:

fxn2=fxn1(.,b=2)

In words, I would like to make a new function fxn2() which is identical to fxn1() but with different default values of optional arguments. I have not been able to find an answer/direction on web.

Body:
The easiest way will be

def fxn2(a, b=2):
    return fxn1(a, b)


问:
PhP's Mail Function Displays my CPanel Login Information
I am sending an e-mail from my php code when certain events occur (i.e., someone posts a reply to a message on my message board). I used this simple code:

```<code>mail (me@aol.com, 'Someone Just Posted a Reply.', 'Check the message board, because someone just posted a reply.');
</code>```

The code executes and I do receive an e-mail.  The problem is that when I get the e-mail, the "from" line in the e-mail gives away my cpanel login for my GoDaddy hosting account. I cannot seem to find anything on GoDaddy's site that explains how to disguise this or change this to just reflect the name of my website rather than give away my login to all users every time I send a push notification.

答:
You have to use the headers in the PHP's mail() function's additional_headers parameters to add more stuff, but this may possibly cause deliverability issues.

This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

With above being said, your updated code should look something like:

<?php
  $headers = array(
    'From' => 'webmaster@example.com',           // Add your from address.
    'Reply-To' => 'webmaster@example.com',       // Add your reply to address.
    'X-Mailer' => 'PHP/' . phpversion()          // Optional stuff.
  );
  mail(
    "me@aol.com",
    "Someone Just Posted a Reply.",
    "Check the message board, because someone just posted a reply.",
    $headers // This way
  );
```

Note: Make sure the above code is written in a single line.

Body:
I am sending an e-mail from my php code when certain events occur (i.e., someone posts a reply to a message on my message board). I used this simple code:

mail (me@aol.com, 'Someone Just Posted a Reply.', 'Check the message board, because someone just posted a reply.');

The code executes and I do receive an e-mail.  The problem is that when I get the e-mail, the "from" line in the e-mail gives away my cpanel login for my GoDaddy hosting account. I cannot seem to find anything on GoDaddy's site that explains how to disguise this or change this to just reflect the name of my website rather than give away my login to all users every time I send a push notification.

Body:
You have to use the headers in the PHP's mail() function's additional_headers parameters to add more stuff, but this may possibly cause deliverability issues.

This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

With above being said, your updated code should look something like:

<?php
  $headers = array(
    'From' => 'webmaster@example.com',           // Add your from address.
    'Reply-To' => 'webmaster@example.com',       // Add your reply to address.
    'X-Mailer' => 'PHP/' . phpversion()          // Optional stuff.
  );
  mail(
    "me@aol.com",
    "Someone Just Posted a Reply.",
    "Check the message board, because someone just posted a reply.",
    $headers // This way
  );

Note: Make sure the above code is written in a single line.


问:
No movement on ios - aframe.io example runs, same(?) code not? What's the different?
Under IOS, the solution no longer reacts to movements.

My solution has worked and now is no longer working.

Also the "hello world" example with the source code of Glitsch (see below) doesn't work anymore, but if you call the example from the a-frame start page (https://aframe.io/examples/showcase/helloworld/), it works.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hello, WebVR!Test VR</title>
    <meta name="description" content="Test VR">
    <script src="https://aframe.io/aframe/dist/aframe-master.min.js" ></script>
  </head>
  <body>
    <a-scene background="color: yellow">
      <a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9" shadow></a-box>
      <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E" shadow></a-sphere>
      <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D" shadow></a-cylinder>
      <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4" shadow></a-plane>
    </a-scene>
  </body>
</html>
</code>```

What's the difference? What do I have to do to make my solution work under IOS again?

答:
Unfortunately, Chrome (m74+) and Safari (iOS 12.2+) now ship with sensor access disabled by default. The user has to enable manually on settings:

chrome://flags/#enable-generic-sensor in Chrome

Settings -> Safari -> Motion & Orientation Access in Safari iOS

Content also must be served over https.

More info on: https://github.com/aframevr/aframe/issues/3976

Body:
Under IOS, the solution no longer reacts to movements.

My solution has worked and now is no longer working.

Also the "hello world" example with the source code of Glitsch (see below) doesn't work anymore, but if you call the example from the a-frame start page (https://aframe.io/examples/showcase/helloworld/), it works.

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Hello, WebVR!Test VR</title>
    <meta name="description" content="Test VR">

What's the difference? What do I have to do to make my solution work under IOS again?


问:
Are the advantages of Model-View-ViewModel (MVVM) pattern worth the overhead?
The question is stated in the subject: are the advantages of Model-View-ViewModel (MVVM) pattern worth the overhead?

In many cases, implementing the view model involves quite significant overhead of duplicating the Model properties and sometimes synchronization between Model and ViewModel data members. For example, currently in Silverlight 4 & WCF RIA, View Models are not generated (if the developer follows the MVVM pattern, it is up to him to create the view models, often duplicating the corresponding Model's properties at ViewModel, that do nothing significant but refer to Model as the storage).

Why not extending the Model class, providing additional properties to make it easy to be consumed by the View instead?

答:
If you are concerned about extra work, you can always create a ViewModelBase (INotifyPropertyChanged , Errors/Validation, generic stuff) to be inherited by your ViewModel, it will minimize things that you think may cost you time to replicate. And also, Silverlight/Wpf provides us with binding which greatly reduces our coding, besides the fact that XAML also does that by providing functionalities through markup. Besides that you can further the design by using screens, controllers, etc.

For me, I do not see any "overhead" with regards to using MVVM; if there were, it'd be worth it. It properly deals with the Separation of Concerns. It provides a good platform for development especially in teams where people may take care of different aspects of the application without affecting other team members codes (especially between developers and designers).

Hope this helps

ContentLicense: CC BY-SA 3.0


问:
how to enable api gateway logs via cloud formation template (serverless.yml)?
I want to enable api gateway logs for my api gateway which is the wraparound for my lambda function.

```<code>service: myservice

provider:
  name: aws
  runtime: python3.6
  stage: ${opt:stage}
  region: ${self:custom.AwsRegion}
  timeout: 130
  memorySize: 128

functions:
  create_user:
    handler: functions/create_user.lambda_handler

    events:
      - http:
          path: /create_user
          method: post
          authorizer: aws_iam
          private: true
</code>```

When I deploy this I do see lambda logs in cloud watch. But API gateway logs are not being recoded in cloudwatch. Can any one enlighten me on cloud formation syntax to enable logs for my api gate way?

I tried adding below code, but looks like it is trying to create new api endpoint.

resources:
  Resources:

```<code>ApiGatewayStage:
  Type: AWS::ApiGateway::Stage
  Properties:
    RestApiId:
        Ref: ApiGatewayRestApi
    StageName: ${opt:stage}
    MethodSettings:
      - DataTraceEnabled: true
        HttpMethod: "*"
        LoggingLevel: INFO
        ResourcePath: "/*"
        MetricsEnabled: true
</code>```

答:
It is now supported by Serverless framework and there is no need for a plugin. You need to add the following configuration to they serverless.yml file:

```<code>provider:
  name: aws

  logs:
    restApi: true
</code>```

Notice that it was added in version 1.42.0.

Body:
I want to enable api gateway logs for my api gateway which is the wraparound for my lambda function.

service: myservice

provider:
  name: aws
  runtime: python3.6
  stage: ${opt:stage}
  region: ${self:custom.AwsRegion}
  timeout: 130
  memorySize: 128

functions:
  create_user:
    handler: functions/create_user.lambda_handler

    events:
      - http:
          path: /create_user
          method: post
          authorizer: aws_iam
          private: true

When I deploy this I do see lambda logs in cloud watch. But API gateway logs are not being recoded in cloudwatch. Can any one enlighten me on cloud formation syntax to enable logs for my api gate way?

I tried adding below code, but looks like it is trying to create new api endpoint.

resources:
  Resources:

ApiGatewayStage:
  Type: AWS::ApiGateway::Stage
  Properties:
    RestApiId:
        Ref: ApiGatewayRestApi
    StageName: ${opt:stage}
    MethodSettings:
      - DataTraceEnabled: true
        HttpMethod: "*"
        LoggingLevel: INFO
        ResourcePath: "/*"
        MetricsEnabled: true

Body:
It is now supported by Serverless framework and there is no need for a plugin. You need to add the following configuration to they serverless.yml file:

provider:
  name: aws

  logs:
    restApi: true

Notice that it was added in version 1.42.0.


问:
Does std::vector satisfy the container requirements for Boost.Interprocess allocators?
In boost::interprocess documentation it is said as requirement for containers to be stored in shared memory:

STL containers may not assume that memory allocated with an allocator can be deallocated with other allocators of the same type. All allocators objects must compare equal only if memory allocated with one object can be deallocated with the other one, and this can only tested with operator==() at run-time.

Containers' internal pointers should be of the type allocator::pointer and containers may not assume allocator::pointer is a raw pointer.

All objects must be constructed-destroyed via allocator::construct and allocator::destroy functions.

I am using gcc 4.7.1 with -std=c++11 (and boost 1.53). Is it safe to use the below defined ShmVector type?

```<code>typedef boost::interprocess::allocator<int,
    boost::interprocess::managed_shared_memory::segment_manager>  ShmemAllocator;
typedef std::vector<int, ShmemAllocator> ShmVector;
</code>```

I tried a dummy process which uses this type, and it looks it is working, but I am still not sure that the vector in gcc4.7.1 does satisfy all the requirements. I am especially not sure about the first requirement.

```<code>#include <iostream>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <vector>
#include <cstdlib> //std::system

typedef boost::interprocess::allocator<int,
        boost::interprocess::managed_shared_memory::segment_manager>  ShmemAllocator;
typedef std::vector<int, ShmemAllocator> ShmVector;

int main(int argc, char *argv[])
{
    if(argc == 1){ //Parent process

        struct shm_remove
        {
            shm_remove() { boost::interprocess::shared_memory_object::remove("MySharedMemory"); }
            ~shm_remove(){ boost::interprocess::shared_memory_object::remove("MySharedMemory"); }
        } remover;

        //Create a new segment with given name and size
        boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only,
                "MySharedMemory", 65536);

        //Initialize shared memory STL-compatible allocator
        const ShmemAllocator allocator(segment.get_segment_manager());

        ShmVector* v = segment.construct<ShmVector>("ShmVector")(allocator);
        v->push_back(1); v->push_back(2); v->push_back(3);

        //Launch child process
        std::string s(argv[0]); s += " child ";
        if(0 != std::system(s.c_str()))
            return 1;

    } else { // Child process

        //Open the managed segment
        boost::interprocess::managed_shared_memory segment(
                boost::interprocess::open_only, "MySharedMemory");

        //Find the vector using the c-string name
        ShmVector *v = segment.find<ShmVector>("ShmVector").first;

        for (const auto& i : *v) {
            std::cout << i << " ";
        }
        std::cout << std::endl;

    }
}
</code>```

答:
I have no reputation to comment, so I have to answer.. If two allocators compare equal, they are interchangeable. Allocators of same type that compare unequal may, for example, be initialized with different (shared) memory. See Allocator:

```<code>a1 == a2 => returns true only if the storage allocated by the allocator a1 can be deallocated through a2. Establishes reflexive, symmetric, and transitive relationship. Does not throw exceptions.
</code>```

So, if your ShmVector instances are created with ShmemAllocators which compare equal, you must be safe.

Body:
In boost::interprocess documentation it is said as requirement for containers to be stored in shared memory:

STL containers may not assume that memory allocated with an allocator can be deallocated with other allocators of the same type. All allocators objects must compare equal only if memory allocated with one object can be deallocated with the other one, and this can only tested with operator==() at run-time.

Containers' internal pointers should be of the type allocator::pointer and containers may not assume allocator::pointer is a raw pointer.

All objects must be constructed-destroyed via allocator::construct and allocator::destroy functions.

I am using gcc 4.7.1 with -std=c++11 (and boost 1.53). Is it safe to use the below defined ShmVector type?

typedef boost::interprocess::allocator<int,
    boost::interprocess::managed_shared_memory::segment_manager>  ShmemAllocator;
typedef std::vector<int, ShmemAllocator> ShmVector;

I tried a dummy process which uses this type, and it looks it is working, but I am still not sure that the vector in gcc4.7.1 does satisfy all the requirements. I am especially not sure about the first requirement.

#include <iostream>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <vector>
#include <cstdlib> //std::system

typedef boost::interprocess::allocator<int,
        boost::interprocess::managed_shared_memory::segment_manager>  ShmemAllocator;
typedef std::vector<int, ShmemAllocator> ShmVector;

int main(int argc, char *argv[])
{
    if(argc == 1){ //Parent process

        struct shm_remove
        {
            shm_remove() { boost::interprocess::shared_memory_object::remove("MySharedMemory"); }
            ~shm_remove(){ boost::interprocess::shared_memory_object::remove("MySharedMemory"); }
        } remover;

        //Create a new segment with given name and size
        boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only,
                "MySharedMemory", 65536);

        //Initialize shared memory STL-compatible allocator
        const ShmemAllocator allocator(segment.get_segment_manager());

        ShmVector* v = segment.construct<ShmVector>("ShmVector")(allocator);
        v->push_back(1); v->push_back(2); v->push_back(3);

        //Launch child process
        std::string s(argv[0]); s += " child ";
        if(0 != std::system(s.c_str()))
            return 1;

    } else { // Child process

        //Open the managed segment
        boost::interprocess::managed_shared_memory segment(
                boost::interprocess::open_only, "MySharedMemory");

        //Find the vector using the c-string name
        ShmVector *v = segment.find<ShmVector>("ShmVector").first;

        for (const auto& i : *v) {
            std::cout << i << " ";
        }
        std::cout << std::endl;

    }
}

Body:
I have no reputation to comment, so I have to answer.. If two allocators compare equal, they are interchangeable. Allocators of same type that compare unequal may, for example, be initialized with different (shared) memory. See Allocator:

a1 == a2 => returns true only if the storage allocated by the allocator a1 can be deallocated through a2. Establishes reflexive, symmetric, and transitive relationship. Does not throw exceptions.

So, if your ShmVector instances are created with ShmemAllocators which compare equal, you must be safe.


问:
Why does my custom checkbox not correctly propagate change value if I set the type after view init?
I am writing some wrappers for normal form controls in my angular app by writing components / directives that have selectors like 'input[custom-input]'. By doing that I am able to setup public methods that can later be used when doing content projection.

My Html then looks like

```<code><a-component-that-handles-animating-placeholder-etc>
    <input custom-checkbox formControlName="field"/>
</<a-component-that-handles-animating-placeholder-etc>
</code>```

The advantage here is that the input is available directly to any component that might want to use it, whereas if I wrote a wrapper I would have to implement a pipeline for every functionality such as disabled e.g

```<code><custom-input [disabled]="isDisabled"]></custom-input>
</code>```

Another advantage is that I do not have to implement new custom control value accessors to bind formcontrolName on and make the framework happy, when in reality the implementation of custom-input would be to just internally use input, which for every control adds a lot of complexity to the project.

The problem is that the reactive form control is not being updated with the correct value when the checkbox is checked and unchecked. In my custom component with this selector input[custom-checkbox] I am doing this logic:

```<code>  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'checkbox');
  }
</code>```

Thats because I dont want consumers to have to specify that this element is a checkbox twice like so:

```<code><input type="checkbox" custom-checkbox/>
</code>```

But for some reason setting the type after the render is breaking the event that updated the form control. I have no idea why.

EDIT: I forked one of the stackblitz and replicated my problem.
https://stackblitz.com/edit/angular-dzqp4k

答:
You don't need to set these attributes manually when using Reactive Forms. You just need to add the  formControl Directive and it will handle the rest for you!

Snippet from the Angular checkbox_value_accessor source code:

```<code>/**
* Sets the "checked" property on the input element.
*
* @param value The checked value
*/
writeValue(value: any): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'checked', value);
}
</code>```

And a Stackblitz demo to see it in action

Body:
I am writing some wrappers for normal form controls in my angular app by writing components / directives that have selectors like 'input[custom-input]'. By doing that I am able to setup public methods that can later be used when doing content projection.

My Html then looks like

    <input custom-checkbox formControlName="field"/>
</

The advantage here is that the input is available directly to any component that might want to use it, whereas if I wrote a wrapper I would have to implement a pipeline for every functionality such as disabled e.g

<custom-input [disabled]="isDisabled"]></custom-input>

Another advantage is that I do not have to implement new custom control value accessors to bind formcontrolName on and make the framework happy, when in reality the implementation of custom-input would be to just internally use input, which for every control adds a lot of complexity to the project.

The problem is that the reactive form control is not being updated with the correct value when the checkbox is checked and unchecked. In my custom component with this selector input[custom-checkbox] I am doing this logic:

  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'checkbox');
  }

Thats because I dont want consumers to have to specify that this element is a checkbox twice like so:

<input type="checkbox" custom-checkbox/>

But for some reason setting the type after the render is breaking the event that updated the form control. I have no idea why.

EDIT: I forked one of the stackblitz and replicated my problem.
https://stackblitz.com/edit/angular-dzqp4k

Body:
You don't need to set these attributes manually when using Reactive Forms. You just need to add the  formControl Directive and it will handle the rest for you!

Snippet from the Angular checkbox_value_accessor source code:

/**
* Sets the "checked" property on the input element.
*
* @param value The checked value
*/
writeValue(value: any): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'checked', value);
}

And a Stackblitz demo to see it in action


答:
```<code>def fxn1(a,b=1):
    return a*b

def fxn2(a,b=2):
    return fxn1(a,b)
</code>```

Title: Using an existing function, how to define a new function with different default optional arguments?


答:
Do you already have tried adding all other div's to a CSS class?

Try this code:

```<code>function toggle_visibility(var id){
    $("#vooglid").addClass("hide_div");
    $("#vooghoek").addClass("hide_div");
    $("#vwimpers").addClass("hide_div");
    $("#id").removeClass("hide_div");
});
</code>```

CSS:

```<code>.hide_div{
    display: none;
}
</code>```

I did this a few months ago and it worked fine.

Title: I want to hide all other div's when i click on one div

Body:
I am making a software were i need to hide all other div's when i click on another div. what happens now is that the div's just stack on top of each other. and the div only dissapears when i click the same div again.

i already tried some of the JavaScript and jQuery code on this platform but can't quite figure it out myself.

--- THIS IS THE SCRIPT IM USING TO SHOW AND HIDE THE DIV'S ---

--- THESE ARE MY CLICKABLE AREA'S WHERE THE USER CAN CLICK ON TO SHOW AND HIDE A DIV ---

        <map name="Map" id="Map">

     <area onclick="toggle_visibility('vooglid');" alt="" title="" href="#" shape="poly" coords=170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
        <area onclick="toggle_visibility('vwimpers');" alt="" title="" href="#" shape="poly" coords="170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
        <area onclick="toggle_visibility('vwenkbrauw');" alt="" title="" href="#" shape="poly" coords="43,157,62,120,84,103,114,85,132,75,151,65,191,47,204,38,232,31,268,31,298,31,317,31,339,33,365,42,390,47,408,51,429,59,445,61,467,69,484,74,501,85,504,127,498,141,494,146,471,136,446,123,432,119,412,113,396,108,376,100,362,96,354,93,334,90,321,90,308,89,295,87,271,83,260,81,232,75,218,74,207,73,192,73,181,76,150,95,122,109,102,118,78,138,62,149,54,158,49,163,47,167" />
        <area onclick="toggle_visibility('vooghoek');" alt="" title="" href="#" shape="poly" coords="388,275,396,270,401,270,407,266,408,263,411,258,420,263,425,269,428,273,432,278,435,280,434,282,434,285,422,284,414,279" />

    </map>

--- AND THESE ARE MY DIV'S CONTAINING THE INFORMATION IT HAS TO SHOW AND HIDE ---

 Symptoom ooglid

 Symptoom wimper

 Symptoom wenkbrauw

 Symptoom ooghoek

I want the result to be that when I click one of the areas above, the corresponding div shows and all other divs hide.

Body:
Do you already have tried adding all other div's to a CSS class?

Try this code:

function toggle_visibility(var id){
    $("#vooglid").addClass("hide_div");
    $("#vooghoek").addClass("hide_div");
    $("#vwimpers").addClass("hide_div");
    $("#id").removeClass("hide_div");
});

CSS:

.hide_div{
    display: none;
}

I did this a few months ago and it worked fine.


问:
How to get most frequent word or in case of tie first alphabetically, from dictionary.values() Python
Trying to get the most frequent value for each key from a dictionary like:

{'cars': ['sedan', 'sedan', 'van', 'van'], 'snack': ['chips', 'chips', 'cheetos'], 'computer': ['laptop', 'desktop']}

However, if there is a tie it should return the first word in value list alphabetically.

Have already tried collections.Counter but that returns arbitrary values if there's a tie. I'm also aware that there are posts that show how to find the most frequent values for dictionaries, but they don't address alphabet ordering in case of a tie.

For instance, the above dictionary should return:

{'cars': 'sedan', 'snack':'chips', 'computer':'desktop'}

Any help is much appreciated.

答:
This looks simple, but needs a lot of transformations to get the proper result

Using counter is the proper way, but you have to sort the items. Note that most_common method doesn't work/is pretty useless as using 1 as parameter to limit the number of results can choose the "wrong" entry:

```<code>{k : collections.Counter(v).most_common(1) for k,v in d.items()}   # no dice!!
</code>```

yields {'cars': [('sedan', 2)], 'computer': [('desktop', 1)], 'snack': [('chips', 2)]} which is close to what we want, but it can also pick 'van' some other time...

Natural sort isn't going to work either, as you need to sort according to number of occurrences (inverted), then alphanumerical key. You need a complex sort key:

```<code>lambda i : (-i[1],i[0])
</code>```

(i is the key/value pair, so -i[1] is the opposite number of elements, so highest number comes first, and i[0] is the name)

Then, pick the first value, and the first item of the value (discarding the count)

Like this:

```<code>import collections

d = {'cars': ['sedan', 'sedan', 'van', 'van'], 'snack': ['chips', 'chips', 'cheetos'], 'computer': ['laptop', 'desktop']}

c = {k : sorted(collections.Counter(v).items(),
         key = lambda i : (-i[1],i[0]))[0][0] for k,v in d.items() if v}
</code>```

result:

```<code>>>> c
{'cars': 'sedan', 'computer': 'desktop', 'snack': 'chips'}
</code>```

Note that if v condition protected against the "one list is empty" case (else it would raise an IndexError when picking the first element).

Body:
This looks simple, but needs a lot of transformations to get the proper result

Using counter is the proper way, but you have to sort the items. Note that most_common method doesn't work/is pretty useless as using 1 as parameter to limit the number of results can choose the "wrong" entry:

{k : collections.Counter(v).most_common(1) for k,v in d.items()}   # no dice!!

yields {'cars': [('sedan', 2)], 'computer': [('desktop', 1)], 'snack': [('chips', 2)]} which is close to what we want, but it can also pick 'van' some other time...

Natural sort isn't going to work either, as you need to sort according to number of occurrences (inverted), then alphanumerical key. You need a complex sort key:

lambda i : (-i[1],i[0])

(i is the key/value pair, so -i[1] is the opposite number of elements, so highest number comes first, and i[0] is the name)

Then, pick the first value, and the first item of the value (discarding the count)

Like this:

import collections

d = {'cars': ['sedan', 'sedan', 'van', 'van'], 'snack': ['chips', 'chips', 'cheetos'], 'computer': ['laptop', 'desktop']}

c = {k : sorted(collections.Counter(v).items(),
         key = lambda i : (-i[1],i[0]))[0][0] for k,v in d.items() if v}

result:

>>> c
{'cars': 'sedan', 'computer': 'desktop', 'snack': 'chips'}

Note that if v condition protected against the "one list is empty" case (else it would raise an IndexError when picking the first element).


问:
Returning true if an object is colliding with another object
I am trying to make a function that returns true if the game object is colliding with anything that has the tag "Ground", however, return is underlined with text "Since 'PlayerController.PlayerController(Collision2d)' returns void, a return keyword must not be followed by an object expression". What changes do I need to make?</p>

```<code>private CanJump(Collision2D collision)
{
    if (collision.gameObject.tag == "Groumd") ;
    {
        return true;
    }
}
</code>```

答:
First you would need a return type bool for your method and also have a default return of false somewhere:

```<code>private bool CanJump(Collision2D collision)
{
    if(collision.gameObject.tag == "Groumd") ;
    {
        return true;
    }

    return false;
}
</code>```

Which you then can shorten to simply do

```<code>private bool CanJump(Collision2D collision)
{
    return collision.gameObject.tag == "Groumd";
}
</code>```

However .. for such a one liner a method is probably a question of taste but why not directly in the method where you call this use

```<code>collision.gameObject.tag == "Groumd"
</code>```

instead of that

```<code>CanJump(collision)
</code>```

Body:
I am trying to make a function that returns true if the game object is colliding with anything that has the tag "Ground", however, return is underlined with text "Since 'PlayerController.PlayerController(Collision2d)' returns void, a return keyword must not be followed by an object expression". What changes do I need to make?

private CanJump(Collision2D collision)
{
    if (collision.gameObject.tag == "Groumd") ;
    {
        return true;
    }
}

Body:
First you would need a return type bool for your method and also have a default return of false somewhere:

private bool CanJump(Collision2D collision)
{
    if(collision.gameObject.tag == "Groumd") ;
    {
        return true;
    }

    return false;
}

Which you then can shorten to simply do

private bool CanJump(Collision2D collision)
{
    return collision.gameObject.tag == "Groumd";
}

However .. for such a one liner a method is probably a question of taste but why not directly in the method where you call this use

collision.gameObject.tag == "Groumd"

instead of that

CanJump(collision)


问:
This is not permitted when the subquery follows Subquery returned more than 1 value
I am having problem returning values to the column checklist percentage. It is giving error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=," The tables provided are just sample from thousands of rows which have many evaluation.

The tables are 2 and I extracted this sample from thousands of rows :

```<code>╔═════════╦═══════════════╗
║ id      ║ value_integer ║
╠═════════╬═══════════════╣
║ 2059064 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2064435 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2064889 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2064893 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2086272 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2128447 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2128447 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2128447 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2134036 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2163046 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2175279 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2175279 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2186928 ║ NULL          ║
╠═════════╬═══════════════╣
</code>```

second table is :

```<code>╔═════════╦════════════╗
║ id      ║ evaluation ║
╠═════════╬════════════╣
║ 2059064 ║ 0          ║
╠═════════╬════════════╣
║ 2064435 ║ 0          ║
╠═════════╬════════════╣
║ 2064889 ║ 0          ║
╠═════════╬════════════╣
║ 2064893 ║ 0          ║
╠═════════╬════════════╣
║ 2086272 ║ 50001      ║
╠═════════╬════════════╣
║ 2128447 ║ 0          ║
╠═════════╬════════════╣
║ 2128447 ║ 0          ║
╠═════════╬════════════╣
║ 2128447 ║ 50001      ║
╠═════════╬════════════╣
║ 2134036 ║ 50001      ║
╠═════════╬════════════╣
║ 2163046 ║ 50001      ║
╠═════════╬════════════╣
║ 2175279 ║ 50006      ║
╠═════════╬════════════╣
║ 2175279 ║ 50001      ║
╠═════════╬════════════╣
║ 2186928 ║ 50004      ║
╠═════════╬════════════╣
║ 2190848 ║ 50001      ║
╠═════════╬════════════╣
║ 2190848 ║ 0          ║
╠═════════╬════════════╣
║ 2190848 ║ 0          ║
╠═════════╬════════════╣
║ 2190848 ║ 1          ║
╠═════════╬════════════╣
║ 2190848 ║ 1          ║
╠═════════╬════════════╣
║ 2222107 ║ 1          ║
╠═════════╬════════════╣
║ 2250093 ║ 1          ║
╠═════════╬════════════╣
║ 2250093 ║ 1          ║
╠═════════╬════════════╣
║ 2250093 ║ 50005      ║
╠═════════╬════════════╣
║ 2250093 ║ 0          ║
╠═════════╬════════════╣
╚═════════╩════════════╝
</code>```

The purpose is to calculate the percentage of evaluation selected / total evaluation. The evaluation 50001 is yes and 0 and 1 means not evaluated or not selected respectatively.

```<code> UPDATE DB.D_ENERGY_REFERENCE
    SET D_ENERGY_REFERENCE.VALUE_INTEGER = (SELECT  (SELECT CAST(COUNT(EVALUATION) AS FLOAT)
                                                     FROM DB.D_CHECK_LIST D_CHECK_LIST
                                                     WHERE D_CHECK_LIST.EVALUATION  = 50001
                                                     GROUP BY ID) / (SELECT CAST(COUNT(EVALUATION) AS FLOAT)
                                                                     FROM DB.D_CHECK_LIST D_CHECK_LIST
                                                                     WHERE D_CHECK_LIST.EVALUATION  NOT IN (0,1)
                                                                     GROUP BY ID) * 100
                                            FROM DB.D_CHECK_LIST D_CHECK_LIST
                                            WHERE D_CHECK_LIST.ID IN (SELECT ID
                                                                      FROM DB.D_ENERGY_REFERENCE
                                                                      WHERE ID = D_CHECK_LIST.ID))
</code>```

答:
I think you are looking for a update script as below-

Note: Please try with test data first.

```<code>UPDATE T
SET T.VALUE_INTEGER = A.Val
FROM D_ENERGY_REFERENCE T
INNER JOIN
(
    SELECT
    ID,
    CASE
        WHEN CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT) = 0 THEN 0
        ELSE
        (
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  = 50001 THEN EVALUATION ELSE NULL END) AS FLOAT)
            /
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT)
        ) * 100
    END AS Val
    FROM D_CHECK_LIST
    GROUP BY ID
)A ON T.ID = A.ID
</code>```

Body:
I am having problem returning values to the column checklist percentage. It is giving error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=," The tables provided are just sample from thousands of rows which have many evaluation.

The tables are 2 and I extracted this sample from thousands of rows :

╔═════════╦═══════════════╗
║ id      ║ value_integer ║
╠═════════╬═══════════════╣
║ 2059064 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2064435 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2064889 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2064893 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2086272 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2128447 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2128447 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2128447 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2134036 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2163046 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2175279 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2175279 ║ NULL          ║
╠═════════╬═══════════════╣
║ 2186928 ║ NULL          ║
╠═════════╬═══════════════╣

second table is :

╔═════════╦════════════╗
║ id      ║ evaluation ║
╠═════════╬════════════╣
║ 2059064 ║ 0          ║
╠═════════╬════════════╣
║ 2064435 ║ 0          ║
╠═════════╬════════════╣
║ 2064889 ║ 0          ║
╠═════════╬════════════╣
║ 2064893 ║ 0          ║
╠═════════╬════════════╣
║ 2086272 ║ 50001      ║
╠═════════╬════════════╣
║ 2128447 ║ 0          ║
╠═════════╬════════════╣
║ 2128447 ║ 0          ║
╠═════════╬════════════╣
║ 2128447 ║ 50001      ║
╠═════════╬════════════╣
║ 2134036 ║ 50001      ║
╠═════════╬════════════╣
║ 2163046 ║ 50001      ║
╠═════════╬════════════╣
║ 2175279 ║ 50006      ║
╠═════════╬════════════╣
║ 2175279 ║ 50001      ║
╠═════════╬════════════╣
║ 2186928 ║ 50004      ║
╠═════════╬════════════╣
║ 2190848 ║ 50001      ║
╠═════════╬════════════╣
║ 2190848 ║ 0          ║
╠═════════╬════════════╣
║ 2190848 ║ 0          ║
╠═════════╬════════════╣
║ 2190848 ║ 1          ║
╠═════════╬════════════╣
║ 2190848 ║ 1          ║
╠═════════╬════════════╣
║ 2222107 ║ 1          ║
╠═════════╬════════════╣
║ 2250093 ║ 1          ║
╠═════════╬════════════╣
║ 2250093 ║ 1          ║
╠═════════╬════════════╣
║ 2250093 ║ 50005      ║
╠═════════╬════════════╣
║ 2250093 ║ 0          ║
╠═════════╬════════════╣
╚═════════╩════════════╝

The purpose is to calculate the percentage of evaluation selected / total evaluation. The evaluation 50001 is yes and 0 and 1 means not evaluated or not selected respectatively.

 UPDATE DB.D_ENERGY_REFERENCE
    SET D_ENERGY_REFERENCE.VALUE_INTEGER = (SELECT  (SELECT CAST(COUNT(EVALUATION) AS FLOAT)
                                                     FROM DB.D_CHECK_LIST D_CHECK_LIST
                                                     WHERE D_CHECK_LIST.EVALUATION  = 50001
                                                     GROUP BY ID) / (SELECT CAST(COUNT(EVALUATION) AS FLOAT)
                                                                     FROM DB.D_CHECK_LIST D_CHECK_LIST
                                                                     WHERE D_CHECK_LIST.EVALUATION  NOT IN (0,1)
                                                                     GROUP BY ID) * 100
                                            FROM DB.D_CHECK_LIST D_CHECK_LIST
                                            WHERE D_CHECK_LIST.ID IN (SELECT ID
                                                                      FROM DB.D_ENERGY_REFERENCE
                                                                      WHERE ID = D_CHECK_LIST.ID))

Body:
I think you are looking for a update script as below-

Note: Please try with test data first.

UPDATE T
SET T.VALUE_INTEGER = A.Val
FROM D_ENERGY_REFERENCE T
INNER JOIN
(
    SELECT
    ID,
    CASE
        WHEN CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT) = 0 THEN 0
        ELSE
        (
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  = 50001 THEN EVALUATION ELSE NULL END) AS FLOAT)
            /
            CAST(COUNT(CASE WHEN D_CHECK_LIST.EVALUATION  NOT IN (0,1) THEN EVALUATION ELSE NULL END) AS FLOAT)
        ) * 100
    END AS Val
    FROM D_CHECK_LIST
    GROUP BY ID
)A ON T.ID = A.ID


答: Looks like you have a private function that might be defaulting to a void return type? Give it a bool return type or something and then wherever you are calling the function from check if it's result is true to know if there is a collision or not. </p>

Title: Returning true if an object is colliding with another object


问:
Read metatags from TypoScript in PHP classes
I am using TYPO3 9 and I want to implement a sharing functionality based on Fluid. Therefore I want to use the already provided metatags.

I wrote a ViewHelper class to make the metatags available to my Fluid template. Researching for possible solutions I found two things:

Setting meta data via TSFE with $GLOBALS['TSFE']->page['description'] = $newDescription;. But I can't get the data with $GLOBALS['TSFE']->page['description']

Using TYPO3's new MetaTagManager. But it seems that the Manager does not include the metatags set via TypoScript.

Is there another way to read all set metatags in PHP classes?

答:
Accessing the Meta-Tags added via page.meta TypoScript is not possible during content rendering.

The reason is simple: the content is rendered before the meta tags are processed (see method generatePageContentWithHeader in TYPO3\CMS\Frontend\Http\RequestHandler

A simple workaround would be to process all related meta tags with your Extension / View Helper only.

A more sophisticated approach is a registry of some kind (e.g. a static property) that collects all changes you want to make to existing meta tags. The registry gets filled by your view helper.

Then you can call a userFunc that is executed after the TypoScript meta tags are collected:

```<code>page.jsFooterInline.323 = USER
page.jsFooterInline.323.userFunc = My\Extension\Hooks\MetaHook->processMeta
</code>```

Within the processMeta you can now access the page meta data (e.g. page.meta.description like this:

$registry = GeneralUtility::makeInstance(MetaTagManagerRegistry::class);
$metaDataArray = $registry->getManagerForProperty('description')->getProperty('description');
```

Body:
Accessing the Meta-Tags added via page.meta TypoScript is not possible during content rendering.

The reason is simple: the content is rendered before the meta tags are processed (see method generatePageContentWithHeader in TYPO3\CMS\Frontend\Http\RequestHandler

A simple workaround would be to process all related meta tags with your Extension / View Helper only.

A more sophisticated approach is a registry of some kind (e.g. a static property) that collects all changes you want to make to existing meta tags. The registry gets filled by your view helper.

Then you can call a userFunc that is executed after the TypoScript meta tags are collected:

page.jsFooterInline.323 = USER
page.jsFooterInline.323.userFunc = My\Extension\Hooks\MetaHook->processMeta

Within the processMeta you can now access the page meta data (e.g. page.meta.description like this:

$registry = GeneralUtility::makeInstance(MetaTagManagerRegistry::class);
$metaDataArray = $registry->getManagerForProperty('description')->getProperty('description');


问:
Javascript onClick Before After Image effect with slider
I want do a before/after image effect slider like, when click on a image it will replace with another image. And again when click on replace image it will back to previous image.

Onclick function can change image only at once.
This is my working demo Codepen

```<code>  <img src="https://i.ibb.co/ccsnkJS/image-11.jpg"
    onclick="this.src ='https://i.ibb.co/R7d7Lw6/image-13.jpg';">
</code>```

Before that I've tried with mouseover and mouseout function. Demo Codepen

```<code><img src="https://i.ibb.co/wNsz0MW/image-11.jpg" onmouseover="this.src ='https://i.ibb.co/R7d7Lw6/image-13.jpg';" onmouseout="this.src = 'https://i.ibb.co/ccsnkJS/image-11.jpg';">
</code>```

But unfortunately mouseover and mouseout function does not work on mobile device. Using mouseover and mouseout , when tap on screen new image replace but when I tap on screen again image not back to previous image.

It would be a best solution if I can achieve it with mouseOver and mouseOut in all device.

答:
One way to accomplish this could be to create two seperate images.

Make one of the images perform the desired action on hover, and the other perform the desired action on click.

Finally, use CSS (or JS) to hide the element that is not required for a given screen size or device type.

```<code><style>
  .mobile {
    visibility: visible;
  }
  .desktop {
    visibility: hidden;
  }
  @media screen and (max-width: 600px) {
    .mobile {
      visibility: hidden;
    }
    .desktop {
      visibility: visible;
    }
  }
</style>

<img
  class="mobile"
  src="https://i.ibb.co/ccsnkJS/image-11.jpg"
  onclick="this.src ='https://i.ibb.co/R7d7Lw6/image-13.jpg';"
/>
<img
  class="desktop"
  src="https://i.ibb.co/ccsnkJS/image-11.jpg"
  onmouseover="this.src ='https://i.ibb.co/R7d7Lw6/image-13.jpg';"
  onmouseout="this.src = 'https://i.ibb.co/ccsnkJS/image-11.jpg';"
/>
</code>```

Body:
I want do a before/after image effect slider like, when click on a image it will replace with another image. And again when click on replace image it will back to previous image.

Onclick function can change image only at once.
This is my working demo Codepen

Before that I've tried with mouseover and mouseout function. Demo Codepen

But unfortunately mouseover and mouseout function does not work on mobile device. Using mouseover and mouseout , when tap on screen new image replace but when I tap on screen again image not back to previous image.

It would be a best solution if I can achieve it with mouseOver and mouseOut in all device.

Body:
One way to accomplish this could be to create two seperate images.

Make one of the images perform the desired action on hover, and the other perform the desired action on click.

Finally, use CSS (or JS) to hide the element that is not required for a given screen size or device type.

<style>
  .mobile {
    visibility: visible;
  }
  .desktop {
    visibility: hidden;
  }
  @media screen and (max-width: 600px) {
    .mobile {
      visibility: hidden;
    }
    .desktop {
      visibility: visible;
    }
  }
</style>

<img
  class="mobile"
  src="https://i.ibb.co/ccsnkJS/image-11.jpg"
  onclick="this.src ='https://i.ibb.co/R7d7Lw6/image-13.jpg';"
/>
<img
  class="desktop"
  src="https://i.ibb.co/ccsnkJS/image-11.jpg"
  onmouseover="this.src ='https://i.ibb.co/R7d7Lw6/image-13.jpg';"
  onmouseout="this.src = 'https://i.ibb.co/ccsnkJS/image-11.jpg';"
/>


问:
C++ move all files from one directory to another
I have a problem moving data from one directory to another.
I want to do as below (bash) but in C++:

mv /testdir/* /testdest/
```

<p>So it should basically move all files located in <code>/testdir</code> to <code>/testdest</code>.
I've already tried <code>rename</code> in C++ but it does not actually move data, it just renames directories.</p>

<p>My current code:</p>

```#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <unistd.h>
#include <dirent.h>
#include <iterator>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sys/stat.h>
#include <syslog.h>
#include <fstream>

using namespace std;

int main( int argc, char *argv[] )
{
  rename (argv[1], argv[2])
}
```

<p>I am executing this as below:</p>

<pre class="lang-sh prettyprint-override"><code>./static-mv /testdir/ /testdest/
</code>```

Effect of this is rename /testdir/ to /testdest/ (with its content).
After this, /testdir/ is no longer available which is not the expected result.

答:
```<code>void move(char const *sorc, char const *dst, bool createRoot = true) {
    namespace fs = std::experimental::filesystem;

    if (createRoot)
        fs::create_directory(dst);

    for(fs::path p: fs::directory_iterator(sorc)){
        fs::path destFile = dst/p.filename();

        if (fs::is_directory(p)) {
            fs::create_directory(destFile);
            move(p.string().c_str(), destFile.string().c_str(), false);
        } else {
            //std::cout << "updated " << p.string().c_str() << std::endl;
            fs::rename(p, destFile);
        }
    }
}
</code>```

Body:
I have a problem moving data from one directory to another.
I want to do as below (bash) but in C++:

mv /testdir/* /testdest/

So it should basically move all files located in /testdir to /testdest.
I've already tried rename in C++ but it does not actually move data, it just renames directories.

My current code:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <unistd.h>
#include <dirent.h>
#include <iterator>
#include <cstdlib>
#include <cstring>
#include <string>
#include <sys/stat.h>
#include <syslog.h>
#include <fstream>

using namespace std;

int main( int argc, char *argv[] )
{
  rename (argv[1], argv[2])
}

I am executing this as below:

./static-mv /testdir/ /testdest/

Effect of this is rename /testdir/ to /testdest/ (with its content).
After this, /testdir/ is no longer available which is not the expected result.


问:
How to get new version warning in Build.gradle with pre-defined dependencies?
When you reference a dependency directly in gradle, IntelliJ gives a lint warning if there is a newer version. i.e. implementation 'com.library:name:1.0.0' gives a warning that version 1.0.1 is available.

If, however, you reference the library via a gradle ext. property, it does not give that warning. i.e. implementation deps.library.name does not give a warning. Is there any way I can still get that warning while referencing previously defined libraries?

In my case I have several modules that re-use a lot of the same libraries, so it's important to be able to define all the libraries and their versions in one place and then just refer to them from each module that needs them. But this causes me to no longer be told by the IDE when there are new version. How can I fix this?

答:
This is actually a feature of Android Studio and indeed it does not support all the ways a dependency can be defined in Gradle.

An equivalent can be achieved with the plugin gradle-versions-plugin through its dependencyUpdates task.


问:
How to call one mainwindow to another mainwindow in Qt (or PyQt)
In my project i have created two mainwindow i want to call mainwindow2 from the mainwindow1 (which in running). in mainwindow1 i am already used the app.exec_() (PyQt) and to show maindow2 i am using the maindow2.show() in the click event of the button but does not show anything</p>

答:
Calling mainwindow2.show() should work for you. Could you give a more complete example of your code? There may be something wrong somewhere else.

EDIT:
Code updated to show an example of how to hide and show windows when opening and closing other windows.

```<code>from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, \
            QLabel, QVBoxLayout, QWidget
from PyQt4.QtCore import pyqtSignal

class MainWindow1(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        button = QPushButton('Test')
        button.clicked.connect(self.newWindow)
        label = QLabel('MainWindow1')

        centralWidget = QWidget()
        vbox = QVBoxLayout(centralWidget)
        vbox.addWidget(label)
        vbox.addWidget(button)
        self.setCentralWidget(centralWidget)

    def newWindow(self):
        self.mainwindow2 = MainWindow2(self)
        self.mainwindow2.closed.connect(self.show)
        self.mainwindow2.show()
        self.hide()

class MainWindow2(QMainWindow):

    # QMainWindow doesn't have a closed signal, so we'll make one.
    closed = pyqtSignal()

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.parent = parent
        label = QLabel('MainWindow2', self)

    def closeEvent(self, event):
        self.closed.emit()
        event.accept()

def startmain():
    app = QApplication(sys.argv)
    mainwindow1 = MainWindow1()
    mainwindow1.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    import sys
    startmain()
</code>```

Body:
Calling mainwindow2.show() should work for you. Could you give a more complete example of your code? There may be something wrong somewhere else.

EDIT:
Code updated to show an example of how to hide and show windows when opening and closing other windows.

from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, \
            QLabel, QVBoxLayout, QWidget
from PyQt4.QtCore import pyqtSignal

class MainWindow1(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        button = QPushButton('Test')
        button.clicked.connect(self.newWindow)
        label = QLabel('MainWindow1')

        centralWidget = QWidget()
        vbox = QVBoxLayout(centralWidget)
        vbox.addWidget(label)
        vbox.addWidget(button)
        self.setCentralWidget(centralWidget)

    def newWindow(self):
        self.mainwindow2 = MainWindow2(self)
        self.mainwindow2.closed.connect(self.show)
        self.mainwindow2.show()
        self.hide()

class MainWindow2(QMainWindow):

    # QMainWindow doesn't have a closed signal, so we'll make one.
    closed = pyqtSignal()

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.parent = parent
        label = QLabel('MainWindow2', self)

    def closeEvent(self, event):
        self.closed.emit()
        event.accept()

def startmain():
    app = QApplication(sys.argv)
    mainwindow1 = MainWindow1()
    mainwindow1.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    import sys
    startmain()


问:
How to extend sorting order of Team Members
I'm using Business Lounge theme by RT themes with Elementor.

Wordpress version is current (5.2.1)

On the team page (Demo: https://businesslounge-demo.rtthemes.com/our-team/) there is a list of cards of team members. I want to change the order of the team members to an option that is not currently selectable.

The team member list is done with a shortcode [staff_box]

In Elementor edit mode I looks like this:

Edit:

The edit form is defined in

wp-content/plugins/businesslounge-extensions/inc/elementor-addons/staff.php

```<code><?php
namespace Elementor;
// ...
class Widget_RT_Staff extends Widget_Base {
  // ...
  protected function _register_controls() {
    // ...
    $this->add_control(
      'list_orderby',
        [
          'label'     => esc_html_x( 'List Order By', 'Admin Panel','businesslounge' ),
          'description' => esc_html_x('Sorts the posts by this parameter', 'Admin Panel','businesslounge' ),
          'type'      =>  Controls_Manager::SELECT,
          'default'    =>  "date",
          "options"    => array(
            'date' => esc_html_x('Date',"Admin Panel","businesslounge"),
            'author' => esc_html_x('Author',"Admin Panel","businesslounge"),
            'title' => esc_html_x('Title',"Admin Panel","businesslounge"),
            'modified' => esc_html_x('Modified',"Admin Panel","businesslounge"),
            'ID' => esc_html_x('ID',"Admin Panel","businesslounge"),
            'rand' => esc_html_x('Randomized',"Admin Panel","businesslounge"),
          )
        ]
      );
      // ...
  }
  // ...
}

Plugin::instance()->widgets_manager->register_widget_type( new Widget_RT_Staff() );
</code>```

The edit form is defined in `wp-content/plugins/businesslounge-extensions/inc/editor/staff_box.php`

like so

```<code><?php
vc_map(
    array(
        'base'        => 'staff_box',
        'name'        => _x( 'Team', 'Admin Panel','businesslounge' ),
        'icon'        => 'rt_theme rt_team',
        'category'    => array(_x( 'Content', 'Admin Panel','businesslounge' ), _x( 'Theme Addons', 'Admin Panel','businesslounge' )),
        'description' => _x( 'Displays team members', 'Admin Panel','businesslounge' ),
        'params'      => array(
// ...
          array(
            'param_name'  => 'list_orderby',
            'heading'     => _x( 'List Order By', 'Admin Panel','businesslounge' ),
            "description" => _x("Sorts the posts by this parameter",'Admin Panel','businesslounge'),
            'type'        => 'dropdown',
            "value"       => array(
                                _x('Date','Admin Panel','businesslounge') => 'date',
                                _x('Author','Admin Panel','businesslounge') => 'author',
                                _x('Title','Admin Panel','businesslounge') => 'title',
                                _x('Modified','Admin Panel','businesslounge') => 'modified',
                                _x('ID','Admin Panel','businesslounge') => 'ID',
                                _x('Randomized','Admin Panel','businesslounge') => 'rand',
                            ),
            'save_always' => true
        ),
// ...
</code>```

The output is defined in

wp-content/plugins/businesslounge-extensions/inc/shortcodes/staff_box.php

like so:

```<code><?php
function rt_staff( $atts, $content = null ) {
// ...

    //defaults
    extract(shortcode_atts(array(
        "id"           => 'staff-'.rand(100000, 1000000),
        "class"        => "",
        "list_layout"  => "1/1",
        "list_orderby" => "date",
        "list_order"   => "DESC",
        "ids"          => array(),
        "box_style"    => ""
    ), $atts));

// ...

    //general query
    $args=array(
        'post_status'    => 'publish',
        'post_type'      => 'staff',
        'orderby'        => $list_orderby,
        'order'          => $list_order,
        'showposts'      => 1000
    );
// ...
    $theQuery = query_posts($args);
// ...
</code>```

What I want to do:
Add an option 'post_name' to the select box so that I can sort the team by a different field. I want to add
'Post name' => 'post_name',

How can I do this without changing the original source code?

I already have the child theme of business_lounge theme activated.

Do I need a custom extension for this?

答:
You should be able to modify your plugin without losing update abilities by 'overriding' the function as described here:

https://stackoverflow.com/a/40856197/3623080

Make a copy of the function in your child-theme's functions.php, customize and rename it, use it in place of the original function.

Hope it will help

Body:
I'm using Business Lounge theme by RT themes with Elementor.

Wordpress version is current (5.2.1)

On the team page (Demo: https://businesslounge-demo.rtthemes.com/our-team/) there is a list of cards of team members. I want to change the order of the team members to an option that is not currently selectable.

The team member list is done with a shortcode [staff_box]

In Elementor edit mode I looks like this:

Edit:

The edit form is defined in

wp-content/plugins/businesslounge-extensions/inc/elementor-addons/staff.php

<?php
namespace Elementor;
// ...
class Widget_RT_Staff extends Widget_Base {
  // ...
  protected function _register_controls() {
    // ...
    $this->add_control(
      'list_orderby',
        [
          'label'     => esc_html_x( 'List Order By', 'Admin Panel','businesslounge' ),
          'description' => esc_html_x('Sorts the posts by this parameter', 'Admin Panel','businesslounge' ),
          'type'      =>  Controls_Manager::SELECT,
          'default'    =>  "date",
          "options"    => array(
            'date' => esc_html_x('Date',"Admin Panel","businesslounge"),
            'author' => esc_html_x('Author',"Admin Panel","businesslounge"),
            'title' => esc_html_x('Title',"Admin Panel","businesslounge"),
            'modified' => esc_html_x('Modified',"Admin Panel","businesslounge"),
            'ID' => esc_html_x('ID',"Admin Panel","businesslounge"),
            'rand' => esc_html_x('Randomized',"Admin Panel","businesslounge"),
          )
        ]
      );
      // ...
  }
  // ...
}

Plugin::instance()->widgets_manager->register_widget_type( new Widget_RT_Staff() );

The edit form is defined in `wp-content/plugins/businesslounge-extensions/inc/editor/staff_box.php`

like so

<?php
vc_map(
    array(
        'base'        => 'staff_box',
        'name'        => _x( 'Team', 'Admin Panel','businesslounge' ),
        'icon'        => 'rt_theme rt_team',
        'category'    => array(_x( 'Content', 'Admin Panel','businesslounge' ), _x( 'Theme Addons', 'Admin Panel','businesslounge' )),
        'description' => _x( 'Displays team members', 'Admin Panel','businesslounge' ),
        'params'      => array(
// ...
          array(
            'param_name'  => 'list_orderby',
            'heading'     => _x( 'List Order By', 'Admin Panel','businesslounge' ),
            "description" => _x("Sorts the posts by this parameter",'Admin Panel','businesslounge'),
            'type'        => 'dropdown',
            "value"       => array(
                                _x('Date','Admin Panel','businesslounge') => 'date',
                                _x('Author','Admin Panel','businesslounge') => 'author',
                                _x('Title','Admin Panel','businesslounge') => 'title',
                                _x('Modified','Admin Panel','businesslounge') => 'modified',
                                _x('ID','Admin Panel','businesslounge') => 'ID',
                                _x('Randomized','Admin Panel','businesslounge') => 'rand',
                            ),
            'save_always' => true
        ),
// ...

The output is defined in

wp-content/plugins/businesslounge-extensions/inc/shortcodes/staff_box.php

like so:

<?php
function rt_staff( $atts, $content = null ) {
// ...

    //defaults
    extract(shortcode_atts(array(
        "id"           => 'staff-'.rand(100000, 1000000),
        "class"        => "",
        "list_layout"  => "1/1",
        "list_orderby" => "date",
        "list_order"   => "DESC",
        "ids"          => array(),
        "box_style"    => ""
    ), $atts));

// ...

    //general query
    $args=array(
        'post_status'    => 'publish',
        'post_type'      => 'staff',
        'orderby'        => $list_orderby,
        'order'          => $list_order,
        'showposts'      => 1000
    );
// ...
    $theQuery = query_posts($args);
// ...

What I want to do:
Add an option 'post_name' to the select box so that I can sort the team by a different field. I want to add
'Post name' => 'post_name',

How can I do this without changing the original source code?

I already have the child theme of business_lounge theme activated.

Do I need a custom extension for this?


问:
RegEx for capturing a pattern with new lines
I have the following string

```<code>1h 30min: Title
- Description Line 1
1h 30min: Title
- Description Line 1
- Description Line 2
- Description Line 3
</code>```

And I would like to get the following results using regex.

```<code>Match 1:
  "1h 30min: Title
  - Description Line 1"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1"
</code>```

```<code>Match 2:
  "1h 30min: Title
  - Description Line 1
  - Description Line 2
  - Description Line 3"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1
               - Description Line 2
               - Description Line 3"
</code>```

I have the following regex https://regex101.com/r/dp5zKq/1

```<code>(([0-9]{1,2}h)\s*([0-9]{1,2}min)*\:)+?((.*\n*)*)
</code>```

However I can't figure out how to make the any character / new line regex stop when it hits a new match for the hours & minutes. Any ideas?

答:
You can modify your regex a little to use a positive lookahead to stop before a time string or end of input using this regex and also use [\w\W] to capture multiple lines,

```<code>([0-9]{1,2}h)\s*([0-9]{1,2}min)*:\s*([\w\W]*?)(?=[0-9]{1,2}h\s*([0-9]{1,2}min)|$)
</code>```

Regex Demo 1

OR

Even a better regex if time can appear within a description anywhere, you can use this regex, which uses multiline mode and in lookahead uses ^ to ensure it doesn't stop if time is present in the description anywhere and uses \Z to mark the absolute end of string.

```<code>([0-9]{1,2}h)\s*([0-9]{1,2}min)*:\s*([\w\W]*?)(?=^[0-9]{1,2}h\s*[0-9]{1,2}min|\Z)
</code>```

Regex Demo 2

Let me know if this works for you.

Body:
I have the following string

1h 30min: Title
- Description Line 1
1h 30min: Title
- Description Line 1
- Description Line 2
- Description Line 3

And I would like to get the following results using regex.

Match 1:
  "1h 30min: Title
  - Description Line 1"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1"

Match 2:
  "1h 30min: Title
  - Description Line 1
  - Description Line 2
  - Description Line 3"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1
               - Description Line 2
               - Description Line 3"

I have the following regex https://regex101.com/r/dp5zKq/1

(([0-9]{1,2}h)\s*([0-9]{1,2}min)*\:)+?((.*\n*)*)

However I can't figure out how to make the any character / new line regex stop when it hits a new match for the hours & minutes. Any ideas?

Body:
You can modify your regex a little to use a positive lookahead to stop before a time string or end of input using this regex and also use [\w\W] to capture multiple lines,

([0-9]{1,2}h)\s*([0-9]{1,2}min)*:\s*([\w\W]*?)(?=[0-9]{1,2}h\s*([0-9]{1,2}min)|$)

Regex Demo 1

OR

Even a better regex if time can appear within a description anywhere, you can use this regex, which uses multiline mode and in lookahead uses ^ to ensure it doesn't stop if time is present in the description anywhere and uses \Z to mark the absolute end of string.

([0-9]{1,2}h)\s*([0-9]{1,2}min)*:\s*([\w\W]*?)(?=^[0-9]{1,2}h\s*[0-9]{1,2}min|\Z)

Regex Demo 2

Let me know if this works for you.


问:
How to fix 'list index out of range' error in ZigZag problem?
I have a list index out of range error on Line 6 upon using a list of list approach to solve the ZigZag problem (https://leetcode.com/problems/zigzag-conversion/). Why is there such an error?</p>

```<code>def convert(self, s, numRows):
        row=0
        down=True
        rows=[[] for i in range(numRows)]
        for i in range(len(s)):
            rows[row].extend(s[i])
            #print(rows)
            if(row==0):
                down=True
            elif(row==len(s)-1):
                down=False
            if down:
                row+=1
            else:
                row-=1
        st=[]
        for k in rows:
            st+=k
        return ''.join(st)
</code>```

答: The issue is solved when the 'row' parameter is updated with 'numRows' instead of with len(s). The row parameter determines whether the direction of travel is up or down and upon correctly updating the limit cases of 'row', the out of bounds error disappears.

Body:
I have a list index out of range error on Line 6 upon using a list of list approach to solve the ZigZag problem (https://leetcode.com/problems/zigzag-conversion/). Why is there such an error?

def convert(self, s, numRows):
        row=0
        down=True
        rows=[[] for i in range(numRows)]
        for i in range(len(s)):
            rows[row].extend(s[i])
            #print(rows)
            if(row==0):
                down=True
            elif(row==len(s)-1):
                down=False
            if down:
                row+=1
            else:
                row-=1
        st=[]
        for k in rows:
            st+=k
        return ''.join(st)


问:
Facing Error in installing python httpclient
Trying to install httpclient library

```<code>    $ sudo pip install httpclient
......
        urllib2.HTTPError: HTTP Error 403: SSL is required

        ----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in /mnt/tmp/pip-build-C8co4C/httpclient/
</code>```

Upgraded setup tools but still httpclient is not installing.

答:
Did you install SSH with pip ?

If not, you can do it following this response

And if it's still not solving your issue, you can always download and add the package manually (but not ideal).

Body:
Trying to install httpclient library

    $ sudo pip install httpclient
......
        urllib2.HTTPError: HTTP Error 403: SSL is required

        ----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in /mnt/tmp/pip-build-C8co4C/httpclient/

Upgraded setup tools but still httpclient is not installing.


问:
How to decompile a whole Jar file?
Does anyone know of a free decompiler that can decompile an entire Jar file instead of a single class? I have a problem with sub classes like name$1.class name$2.class name.class</p>

答:
Insert the following into decompile.jar.sh

```<code># Usage: decompile.jar.sh some.jar [-d]

# clean target folders
function clean_target {
  rm -rf $unjar $src $jad_log
}

# clean all debug stuff
function clean_stuff {
  rm -rf $unjar $jad_log
}

# the main function
function work {
  jar=$1
  unjar=`basename $jar.unjar`
  src=`basename $jar.src`
  jad_log=jad.log

  clean_target

  unzip -q $jar -d $unjar
  jad -d $src -ff -r -lnc -o -s java $unjar/**/*.class > $jad_log 2>&1

  if [ ! $debug ]; then
    clean_stuff
  fi

  if [ -d $src ]
    then
      echo "$jar has been decompiled to $src"
    else
      echo "Got some problems check output or run in debug mode"
  fi
}

function usage {
  echo "This script extract and decompile JAR file"
  echo "Usage: $0 some.jar [-d]"
  echo "    where: some.jar is the target to decompile"
  echo "    use -d for debug mode"
}

# check params
if [ -n "$1" ]
  then
    if [ "$2" == "-d" ]; then
      debug=true
      set -x
    fi
    work $1
  else
    usage
fi
</code>```

chmod +x decomplie.jar.sh //executable

ln -s ./decomplie.jar.s /usr/bin/dj

Ready to use, just type dj your.jar and you will get your.jar.src folder with sources. Use -d option for debug mode.

OwnerDisplayName: StoneHeart

ContentLicense: CC BY-SA 2.5

Title: How to decompile a whole Jar file?

LastEditorDisplayName: John Topley

Body:
Insert the following into decompile.jar.sh

# Usage: decompile.jar.sh some.jar [-d]

# clean target folders
function clean_target {
  rm -rf $unjar $src $jad_log
}

# clean all debug stuff
function clean_stuff {
  rm -rf $unjar $jad_log
}

# the main function
function work {
  jar=$1
  unjar=`basename $jar.unjar`
  src=`basename $jar.src`
  jad_log=jad.log

  clean_target

  unzip -q $jar -d $unjar
  jad -d $src -ff -r -lnc -o -s java $unjar/**/*.class > $jad_log 2>&1

  if [ ! $debug ]; then
    clean_stuff
  fi

  if [ -d $src ]
    then
      echo "$jar has been decompiled to $src"
    else
      echo "Got some problems check output or run in debug mode"
  fi
}

function usage {
  echo "This script extract and decompile JAR file"
  echo "Usage: $0 some.jar [-d]"
  echo "    where: some.jar is the target to decompile"
  echo "    use -d for debug mode"
}

# check params
if [ -n "$1" ]
  then
    if [ "$2" == "-d" ]; then
      debug=true
      set -x
    fi
    work $1
  else
    usage
fi

chmod +x decomplie.jar.sh //executable

ln -s ./decomplie.jar.s /usr/bin/dj

Ready to use, just type dj your.jar and you will get your.jar.src folder with sources. Use -d option for debug mode.


问:
How to create an output file (re)writed?
I've been trying to solve my script but I really would appreciate some help.
I have 2 input files.

The first one is a multi-fasta file with headers like this:

```<code>'>AH008024.2 Angelica acutiloba internal transcribed spacers 1 and 2, partial sequence'
'>AJ969149.1 Carthamus tinctorius partial ITS2'
....
</code>```

(the quotes are just to let the > sign visible, otherwise it is not showed...)

The second one is a primer validation file which looks like this:

```<code>AB280738.1,UniplantR,49,68,forward,CCCGHYTGAYYTGRGGTCDC,20,71.4,,,56.5 - 69.8
AB280739.1,UniplantR,49,68,forward,CCCGHYTGAYYTGRGGTCDC,20,71.4,,,56.5 - 69.8
AB280740.1,UniplantR,49,68,forward,CCCGHYTGAYYTGRGGTCDC,20,71.4,,,56.5 - 69.8
...
</code>```

I want to write a "rewrited" version of the second file, changing the accession number "AB280738.1" for the species names from the fasta file, generating a tab delimited output like this:

```<code>AB280738.1      Glycyrrhiza uralensis ITS1, 5.8S rRNA and ITS2     UniplantR 49 68 forward CCCGHYTGAYYTGRGGTCDC 20 71.4   56.5 - 69.8

AB280739.1      Glycyrrhiza glabra ITS1, 5.8S rRNA and ITS2      UniplantR 49 68 forward CCCGHYTGAYYTGRGGTCDC 20 71.4   56.5 - 69.8
...
</code>```

The final output must have the same number of lines that the second input file, the primers file, which in this case is 420 lines, but my current output is writing 292140 lines, it is doing the matching, but it is not writing properly.

I've been working on this code that I'm showing to you.
I see that the "matching" part of my script is working, but I think that I am not doing the right "push" step. Besides this, something is making my nested loops recursive, because there's multiple lines from the same match.
To know that it is working, the output must have the same number of lines that the second input, the primers input.
The second "print" tells me hou many times the pattern matched, and it is giving me 540 instead of 420.

I would like to upload my input files and my current output if someone would like to try with it, but I couldn't find where upload files..

```<code>   #!/usr/bin/perl
   use diagnostics;
   use warnings;
   use strict;

   print "multifasta:\t";
   my $arq1 = <STDIN>;
   open (MYFILE, $arq1);
   my @file = <MYFILE>;
   close (MYFILE);
   print "file to rename:\t";
   my $arq2 = <STDIN>;
   open (MYFILE2, $arq2);
   my @file2 = <MYFILE2>;
   close (MYFILE2);
   my @new_file=();
   my $count = ();
   open (NEW_FILE, '>>plant_names_primer_bind_renamed.txt');
   foreach my $line2 (@file2) {
           my @fields = split (/,/, $line2);
           my $accession2 = shift(@fields);
                   foreach my $line (@file) {
                           if ($line =~ /^>/) {
                           my $rev = reverse $line;
                           chop ($rev);
                           my $header = reverse $rev;
                           my @header = split (/ /, $header);
                           my $accession = shift (@header);
                                 if ($accession =~ /$accession2/)        {
                   $count++;
                   print "$accession2 match $accession\t@header\t@fields\n\n";
                   print "$count\n";
                   push (@new_file, ("$accession2\t@header\t@fields"));
                   print NEW_FILE @new_file;
           }
        }
      }
   }

</code>```

答:
Here is an example where I read the multi fasta file headers into a hash before I start processing the primer validation file. In this way I avoid a double for loop:

```<code>use feature qw(say);
use strict;
use warnings;
{
    my $fasta_data = read_fasta_file();
    print "file to rename:\t";
    chomp (my $fn = <STDIN>);
    open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
    my $save_fn = 'plant_names_primer_bind_renamed.txt';
    open ( my $save_fh, '>', $save_fn ) or die "Could not open file '$save_fn': $!";
    my $count = 0;
    while (my $line = <$fh>) {
        chomp $line;
        my @data = split /,/, $line;
        if (@data) {
            my $key = $data[0];
            my $def = $fasta_data->{$key};
            if (defined $def) {
                #say ++$count;
                say $save_fh join "\t", $key, $def, @data[1..$#data];
            }
        }
    }
    close $save_fh;
    close $fh;
}

sub read_fasta_file {
    print "multifasta:\t";
    chomp(my $fn = <STDIN>);
    open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
    my %data;
    while (my $line = <$fh>) {
        chomp $line;
        my ($key, $value ) = $line =~ /^>(\S+)\s+(.*)$/;
        $data{$key} = $value if defined $value;
    }
    close $fh;
    return \%data;
}
</code>```

Body:
I've been trying to solve my script but I really would appreciate some help.
I have 2 input files.

The first one is a multi-fasta file with headers like this:

'>AH008024.2 Angelica acutiloba internal transcribed spacers 1 and 2, partial sequence'
'>AJ969149.1 Carthamus tinctorius partial ITS2'
....

(the quotes are just to let the > sign visible, otherwise it is not showed...)

The second one is a primer validation file which looks like this:

AB280738.1,UniplantR,49,68,forward,CCCGHYTGAYYTGRGGTCDC,20,71.4,,,56.5 - 69.8
AB280739.1,UniplantR,49,68,forward,CCCGHYTGAYYTGRGGTCDC,20,71.4,,,56.5 - 69.8
AB280740.1,UniplantR,49,68,forward,CCCGHYTGAYYTGRGGTCDC,20,71.4,,,56.5 - 69.8
...

I want to write a "rewrited" version of the second file, changing the accession number "AB280738.1" for the species names from the fasta file, generating a tab delimited output like this:

AB280738.1      Glycyrrhiza uralensis ITS1, 5.8S rRNA and ITS2     UniplantR 49 68 forward CCCGHYTGAYYTGRGGTCDC 20 71.4   56.5 - 69.8

AB280739.1      Glycyrrhiza glabra ITS1, 5.8S rRNA and ITS2      UniplantR 49 68 forward CCCGHYTGAYYTGRGGTCDC 20 71.4   56.5 - 69.8
...

The final output must have the same number of lines that the second input file, the primers file, which in this case is 420 lines, but my current output is writing 292140 lines, it is doing the matching, but it is not writing properly.

I've been working on this code that I'm showing to you.
I see that the "matching" part of my script is working, but I think that I am not doing the right "push" step. Besides this, something is making my nested loops recursive, because there's multiple lines from the same match.
To know that it is working, the output must have the same number of lines that the second input, the primers input.
The second "print" tells me hou many times the pattern matched, and it is giving me 540 instead of 420.

I would like to upload my input files and my current output if someone would like to try with it, but I couldn't find where upload files..

   #!/usr/bin/perl
   use diagnostics;
   use warnings;
   use strict;

   print "multifasta:\t";
   my $arq1 = <STDIN>;
   open (MYFILE, $arq1);
   my @file = <MYFILE>;
   close (MYFILE);
   print "file to rename:\t";
   my $arq2 = <STDIN>;
   open (MYFILE2, $arq2);
   my @file2 = <MYFILE2>;
   close (MYFILE2);
   my @new_file=();
   my $count = ();
   open (NEW_FILE, '>>plant_names_primer_bind_renamed.txt');
   foreach my $line2 (@file2) {
           my @fields = split (/,/, $line2);
           my $accession2 = shift(@fields);
                   foreach my $line (@file) {
                           if ($line =~ /^>/) {
                           my $rev = reverse $line;
                           chop ($rev);
                           my $header = reverse $rev;
                           my @header = split (/ /, $header);
                           my $accession = shift (@header);
                                 if ($accession =~ /$accession2/)        {
                   $count++;
                   print "$accession2 match $accession\t@header\t@fields\n\n";
                   print "$count\n";
                   push (@new_file, ("$accession2\t@header\t@fields"));
                   print NEW_FILE @new_file;
           }
        }
      }
   }

Body:
Here is an example where I read the multi fasta file headers into a hash before I start processing the primer validation file. In this way I avoid a double for loop:

use feature qw(say);
use strict;
use warnings;
{
    my $fasta_data = read_fasta_file();
    print "file to rename:\t";
    chomp (my $fn = <STDIN>);
    open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
    my $save_fn = 'plant_names_primer_bind_renamed.txt';
    open ( my $save_fh, '>', $save_fn ) or die "Could not open file '$save_fn': $!";
    my $count = 0;
    while (my $line = <$fh>) {
        chomp $line;
        my @data = split /,/, $line;
        if (@data) {
            my $key = $data[0];
            my $def = $fasta_data->{$key};
            if (defined $def) {
                #say ++$count;
                say $save_fh join "\t", $key, $def, @data[1..$#data];
            }
        }
    }
    close $save_fh;
    close $fh;
}

sub read_fasta_file {
    print "multifasta:\t";
    chomp(my $fn = <STDIN>);
    open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
    my %data;
    while (my $line = <$fh>) {
        chomp $line;
        my ($key, $value ) = $line =~ /^>(\S+)\s+(.*)$/;
        $data{$key} = $value if defined $value;
    }
    close $fh;
    return \%data;
}


问:
How to align spans in one line
Hello guys I have divs in a django template which are created by a Django for loop I have 2 spans in one div divided by a lot of whitespace, what I want to do is to align the second spans the spans with the tab class in one line , how do I accomplish this ?

I have tried adding padding, margin but it did not work

HTML:

```<code><div>
     {% for entries in mylist %}
   <div class="ladder"> <span class="player"> {{ entries.0 }}</span> <span class="tab"> {{ entries.1 }} </span></div>
     {% endfor %}

</div>
</code>```

CSS:

```<code>player { margin-left: 20px;
    }

   .ladder{ width: 30%;
   border: solid 2px blue;
   margin-left: 20px;
   margin-bottom: 30px;
 }

   .tab {

       margin-left: 40%;  }
</code>```

https://i.stack.imgur.com/alGa7.png
I cant embed pictures right now so I got this link to show how it is right now, what I want is that the numbers are aligned in one line.

答:
```<code>dl {
  width: 100%;
  overflow: hidden;
  background: #ff0;
  padding: 0;
  margin: 0
}
dt {
  float: left;
  width: 50%;
  /* adjust the width; make sure the total of both is 100% */
  background: #cc0;
  padding: 0;
  margin: 0
}
dd {
  float: left;
  width: 50%;
  /* adjust the width; make sure the total of both is 100% */
  background: #dd0
  padding: 0;
  margin: 0
}

<dl>
  <dt>Mercury</dt>
  <dd>Ερμής</dd>
  <dt>Venus</dt>
  <dd>Αφροδίτη</dd>
  <dt>Earth</dt>
  <dd>Γη</dd>
</dl>
</code>```

Title: How to align spans in one line

Body:
Hello guys I have divs in a django template which are created by a Django for loop I have 2 spans in one div divided by a lot of whitespace, what I want to do is to align the second spans the spans with the tab class in one line , how do I accomplish this ?

I have tried adding padding, margin but it did not work

HTML:

     {% for entries in mylist %}

  {{ entries.0 }}  {{ entries.1 }}

     {% endfor %}

CSS:

player { margin-left: 20px;
    }

   .ladder{ width: 30%;
   border: solid 2px blue;
   margin-left: 20px;
   margin-bottom: 30px;
 }

   .tab {

       margin-left: 40%;  }

https://i.stack.imgur.com/alGa7.png
I cant embed pictures right now so I got this link to show how it is right now, what I want is that the numbers are aligned in one line.


问:
Using for loop and charAt to check if each letter appears exactly twice in a word
i'm writing a program in java that checks if a letter appers exactly twice, i was able to write it but my problem is that for some words the code doesn't check if the letter appear exactly twice.
here is my code:</p>

```<code>public class Test {

public static void main(String[] args) {
  isDoubloon("abba");
  isDoubloon("Shanghaiingss");/*it still prints out true though 's' does appear exactly twice*/}

//checks if every letter appears twice in a word
public static void isDoubloon(String s){
    String l=s.toLowerCase();
    int count=0;

    for(int i= 0; i<l.length()-1;i++){
        for(int j=i+1;j<l.length();j++){

            if(l.charAt(i)==l.charAt(j)) count++;
        }

    }
    if(count%2==0){
        System.out.println("True, This is a doubloon");
    }else
        System.err.println("False, This is not a doubloon");

}}
</code>```

答:
Obligatory Java Streams examples:

groupingBy() and counting()

```<code>public static boolean isDoubloon(String str) {
    return
        // Stream over chars, and box to Integer
        // These will be the ASCII values of the chars
        !str.chars().boxed()

        // Group by identity
        .collect(Collectors.groupingBy(Function.identity(),
        // and map each key to the count of characters
            Collectors.counting()))

        // We now have a Map<Integer, Long>, the Integer being the character
        // value and the Long being the number of occurrences.
        // Stream over the Map's values
        .values().stream()

        // Retain all values unequal to 2
        .filter(i -> !Objects.equals(i, 2L))

        // Shortcut if found and check if a value is present
        .findAny().isPresent();

        // If a value is present, that means that there are one or more
        // characters with less or more than two occurrences.
}
</code>```

https://ideone.com/PT8sQi

distinct() and count()

```<code>public static boolean isDoubloon(String str) {
    long distinct = str.chars().distinct().count();
    long length = str.length();

    return (length % 2 == 0 && length / 2 == distinct);
}
</code>```

https://ideone.com/UaOKDF

Body:
i'm writing a program in java that checks if a letter appers exactly twice, i was able to write it but my problem is that for some words the code doesn't check if the letter appear exactly twice.
here is my code:

public class Test {

public static void main(String[] args) {
  isDoubloon("abba");
  isDoubloon("Shanghaiingss");/*it still prints out true though 's' does appear exactly twice*/}

//checks if every letter appears twice in a word
public static void isDoubloon(String s){
    String l=s.toLowerCase();
    int count=0;

    for(int i= 0; i<l.length()-1;i++){
        for(int j=i+1;j<l.length();j++){

            if(l.charAt(i)==l.charAt(j)) count++;
        }

    }
    if(count%2==0){
        System.out.println("True, This is a doubloon");
    }else
        System.err.println("False, This is not a doubloon");

}}

Body:
Obligatory Java Streams examples:

groupingBy() and counting()

public static boolean isDoubloon(String str) {
    return
        // Stream over chars, and box to Integer
        // These will be the ASCII values of the chars
        !str.chars().boxed()

        // Group by identity
        .collect(Collectors.groupingBy(Function.identity(),
        // and map each key to the count of characters
            Collectors.counting()))

        // We now have a Map<Integer, Long>, the Integer being the character
        // value and the Long being the number of occurrences.
        // Stream over the Map's values
        .values().stream()

        // Retain all values unequal to 2
        .filter(i -> !Objects.equals(i, 2L))

        // Shortcut if found and check if a value is present
        .findAny().isPresent();

        // If a value is present, that means that there are one or more
        // characters with less or more than two occurrences.
}

https://ideone.com/PT8sQi

distinct() and count()

public static boolean isDoubloon(String str) {
    long distinct = str.chars().distinct().count();
    long length = str.length();

    return (length % 2 == 0 && length / 2 == distinct);
}

https://ideone.com/UaOKDF


问:
What is the proper way to include a PHP Function inside a jQuery append()?
I'm using jquery to append another row to a form which uses PHP.
The PHP in the original code uses a function to populate a SELECT input.

Sample of one input from the form;

```<code><div class="flex_container">
<div class="flex_label_rpt">Person Type</div>
    <div class="flex_data">
        <select name="person_type[]">
            <?php get_persons_type_list($incident['person_type']) ?>
        </select>
    </div>
</div>
    ... Additional Fields ...
</div>
</code>```

Can I use the same PHP function to populate the new rows that are added using jquery?

I tried something like this:

```<code>'<select name="person_type[]">'+
    "<?php get_persons_type_list($incident['person_type']) ?>"+
'</select>';
</code>```

But, it just spits out the PHP code, commented out.

Any help would be greatly appreciated.
I'm pretty good with PHP, but not so much with jquery.

Thanks.

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

```<code>var maxField_p = 10; //Input fields increment limitation
var addButton_p = $('#incident_add_person'); //Add button selector
var wrapper_p = $('#item_row_person'); //Input field wrapper
var fieldHTML_p =
    '<select name="person_type[]">'+
    "<?php get_persons_type_list($incident['person_type']) ?>"+
    '</select>';

var x_p = 1; //Initial field counter is 1

$(addButton_p).click(function(){
    //Check maximum number of input fields
    if(x_p < maxField_p){
        x_p++; //Increment field counter
        $(wrapper_p).append(fieldHTML_p); //Add field html
    }
});
</code>```

答:
You need to populate the new row by using an ajax request after creating the form element.</p>

```<code>$.ajax({
    type: "GET",
    url: "script.php",
    dataType: 'JSON',
    beforeSend: function() {
        //You can show a preloader here
    }
}).done(function(data) {
    //Hide the preloader
    //Populate the form element
}).fail(function() {
    //Show an error message
});
</code>```

Body:
I'm using jquery to append another row to a form which uses PHP.
The PHP in the original code uses a function to populate a SELECT input.

Sample of one input from the form;

Person Type

        <select name="person_type[]">
            <?php get_persons_type_list($incident['person_type']) ?>
        </select>

    ... Additional Fields ...

Can I use the same PHP function to populate the new rows that are added using jquery?

I tried something like this:

'<select name="person_type[]">'+
    "<?php get_persons_type_list($incident['person_type']) ?>"+
'</select>';

But, it just spits out the PHP code, commented out.

Any help would be greatly appreciated.
I'm pretty good with PHP, but not so much with jquery.

Thanks.

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

var maxField_p = 10; //Input fields increment limitation
var addButton_p = $('#incident_add_person'); //Add button selector
var wrapper_p = $('#item_row_person'); //Input field wrapper
var fieldHTML_p =
    '<select name="person_type[]">'+
    "<?php get_persons_type_list($incident['person_type']) ?>"+
    '</select>';

var x_p = 1; //Initial field counter is 1

$(addButton_p).click(function(){
    //Check maximum number of input fields
    if(x_p < maxField_p){
        x_p++; //Increment field counter
        $(wrapper_p).append(fieldHTML_p); //Add field html
    }
});

Body:
You need to populate the new row by using an ajax request after creating the form element.

$.ajax({
    type: "GET",
    url: "script.php",
    dataType: 'JSON',
    beforeSend: function() {
        //You can show a preloader here
    }
}).done(function(data) {
    //Hide the preloader
    //Populate the form element
}).fail(function() {
    //Show an error message
});