问:
string.equals not working for me
This is the useful part of code:

```<code>java.util.List<Element> elems = src.getAllElements();
Iterator it = elems.iterator();
Element el;
String key,value,date="",place="";
String [] data;
int k=0;
Segment content;
String contentstr;
String classname;

while(it.hasNext()){

    el = (Element)it.next();

    if(el.getName().equals("span"))
    {

            classname=el.getAttributeValue("class");
        if(classname.equals("edit_body"))
        {
            //java.util.List<Element> elemsinner = el.getChildElements();
            //Iterator itinner = elemsinner.iterator();

            content=el.getContent();

            contentstr=content.toString();

            if(true)
            {

                System.out.println("Done!");

                System.out.println(classname);

                System.out.println(contentstr);

            }
       }
    }

}
</code>```

No output. But if I remove the if(classname.equals("edit_body")) condition it does print (in one of the iterations):

```<code>Done!
edit_body
"I honestly think it is better to be a failure at something you love than to be a success at something you hate."
</code>```

Can't get the bug part... help!

I am using an external java library BTW for html parsing.

BTW there are two errors at the start of the output, which is there in both the cases, with or without if condition.:

```<code>Dec 20, 2012 11:53:11 AM net.htmlparser.jericho.LoggerProviderJava$JavaLogger error SEVERE: EndTag br at (r1992,c60,p94048) not recognised as type '/normal' because its name and closing delimiter are separated by characters other than white space

Dec 20, 2012 11:53:11 AM net.htmlparser.jericho.LoggerProviderJava$JavaLogger error SEVERE: Encountered possible EndTag at (r1992,c60,p94048) whose content does not match a registered EndTagType
</code>```

Hope that wont cause the error

Ok guys, Somebody explain me please! "edit_body".equals(el.getAttributeValue("class")) worked!!

答:
equals() is a method of String class. So, it works with double quotes.</p>

```<code> if(someString.equals("something")) ✓
 if(someString.equals('something')) ×
</code>```

Title: string.equals not working for me

Body:
This is the useful part of code:

java.util.List<Element> elems = src.getAllElements();
Iterator it = elems.iterator();
Element el;
String key,value,date="",place="";
String [] data;
int k=0;
Segment content;
String contentstr;
String classname;

while(it.hasNext()){

    el = (Element)it.next();

    if(el.getName().equals("span"))
    {

            classname=el.getAttributeValue("class");
        if(classname.equals("edit_body"))
        {
            //java.util.List<Element> elemsinner = el.getChildElements();
            //Iterator itinner = elemsinner.iterator();

            content=el.getContent();

            contentstr=content.toString();

            if(true)
            {

                System.out.println("Done!");

                System.out.println(classname);

                System.out.println(contentstr);

            }
       }
    }

}

No output. But if I remove the if(classname.equals("edit_body")) condition it does print (in one of the iterations):

Done!
edit_body
"I honestly think it is better to be a failure at something you love than to be a success at something you hate."

Can't get the bug part... help!

I am using an external java library BTW for html parsing.

BTW there are two errors at the start of the output, which is there in both the cases, with or without if condition.:

Dec 20, 2012 11:53:11 AM net.htmlparser.jericho.LoggerProviderJava$JavaLogger error SEVERE: EndTag br at (r1992,c60,p94048) not recognised as type '/normal' because its name and closing delimiter are separated by characters other than white space

Dec 20, 2012 11:53:11 AM net.htmlparser.jericho.LoggerProviderJava$JavaLogger error SEVERE: Encountered possible EndTag at (r1992,c60,p94048) whose content does not match a registered EndTagType

Hope that wont cause the error

Ok guys, Somebody explain me please! "edit_body".equals(el.getAttributeValue("class")) worked!!

Body:
equals() is a method of String class. So, it works with double quotes.

 if(someString.equals("something")) ✓
 if(someString.equals('something')) ×


来源: stackexchange

问:
Minimum size of swt shell and components
How can I set a minimum size of the shell in swt? For example I have added a search field in my shell but I can shrink the shell almost completely and then the search field isn't completely visible. Can I change a property of the search field to stop resizing if it would be unseen?</p>

答:
No, there isn't any property or anything like that to prevent the resizing.

About the only thing you can do is add a resize listener to the shell and stop the resize if the shell is too small:

```<code>shell.addListener(SWT.Resize, event -> {
  Shell eventShell = (Shell)event.widget;

  Point size = eventShell.getSize();

  if (size.x < 100 || size.y < 100)
   {
     // Stop the resize event
     event.doit = false;
   }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
No, there isn't any property or anything like that to prevent the resizing.

About the only thing you can do is add a resize listener to the shell and stop the resize if the shell is too small:

shell.addListener(SWT.Resize, event -> {
  Shell eventShell = (Shell)event.widget;

  Point size = eventShell.getSize();

  if (size.x < 100 || size.y < 100)
   {
     // Stop the resize event
     event.doit = false;
   }
});


问:
how to find/replace in a json file using jtc?
I have the file below. Using jtc how to I replace all occurrences of "value": 1234.56 with "value": {"$numberDecimal":"1234.56"}; that is, wrap the numbers. This is for mongoimport, I want to require values to be imported as decimals not floats.

Or maybe there's a better solution using jq?

An example file:

```<code>{
  "data": {
    "slice": [
      {
        "source": {
          "id": "foo"
        },
        "value": 1.0
      },
      {
        "source": {
          "id": "bar"
        },
        "value": 2.0
      }
    ]
  }
}
</code>```

答:
The following jq program will convert numbers to JSON objects of the form {"$numberDecimal": <STRING>}:

```<code>walk(if type == "number" then {"$numberDecimal": tostring} else . end)
</code>```

If you don't mind 1.0 becoming "1", then the above will do the job with any version of jq that has walk, assuming that conversion to IEEE 754 numbers does not present any issues.

Otherwise, the simplest option might be to upgrade to the current master version of jq (> 1.6), since this version should retain precision.

Body:
I have the file below. Using jtc how to I replace all occurrences of "value": 1234.56 with "value": {"$numberDecimal":"1234.56"}; that is, wrap the numbers. This is for mongoimport, I want to require values to be imported as decimals not floats.

Or maybe there's a better solution using jq?

An example file:

{
  "data": {
    "slice": [
      {
        "source": {
          "id": "foo"
        },
        "value": 1.0
      },
      {
        "source": {
          "id": "bar"
        },
        "value": 2.0
      }
    ]
  }
}

Body:
The following jq program will convert numbers to JSON objects of the form {"$numberDecimal": <STRING>}:

walk(if type == "number" then {"$numberDecimal": tostring} else . end)

If you don't mind 1.0 becoming "1", then the above will do the job with any version of jq that has walk, assuming that conversion to IEEE 754 numbers does not present any issues.

Otherwise, the simplest option might be to upgrade to the current master version of jq (> 1.6), since this version should retain precision.


问:
Use external REST API with ReactJS and NodeJS
I am still learning about ReactJS and NodeJS.

My devs have created a boilerplate with create-react-app
We have an External REST API service , and we want to make calls (GET, PUT ...) to their APIs and retrieve and put data.

My question is, ReactJS can also consume REST APIs (external ones, from another web site). Why do I need NodeJS then? I think ideal would be that NodeJS makes those calls for ReactJS and makes server side rendering.

What is the best practice here with this stack. I do not need (or maybe do I?) to buld internal APIs with ExpressJS, since I have external ones from another web service provider which retrieves data for me out of their data store.

Can someone elaborate on the best practice here ?

Thanks in advance.

答:
React can easily make API calls. this is typically done through componentDidMount method or in useEffect if using hooks.

You can of course use a backend to make these requests too like you said with NodeJS. but whether you do or don't is completely up to you and your use case

typically you would use NodeJS and a backend to help separate out logic, especially if you need to make calls to a database and stuff.

another good reason would be if you are handling sensitive information you would want to do this server side and not client side.

so in summary, it's completely up to you and what you need. personally I use react with lambda/api gateway in aws to separate logic out

example node js endpoint (returning an array to react)

```<code>app.get('/api/my-route', (req, res, next) => {
    const array = [1,2,3,4,5]
    res.json(array)
})
</code>```

Body:
React can easily make API calls. this is typically done through componentDidMount method or in useEffect if using hooks.

You can of course use a backend to make these requests too like you said with NodeJS. but whether you do or don't is completely up to you and your use case

typically you would use NodeJS and a backend to help separate out logic, especially if you need to make calls to a database and stuff.

another good reason would be if you are handling sensitive information you would want to do this server side and not client side.

so in summary, it's completely up to you and what you need. personally I use react with lambda/api gateway in aws to separate logic out

example node js endpoint (returning an array to react)

app.get('/api/my-route', (req, res, next) => {
    const array = [1,2,3,4,5]
    res.json(array)
})


问:
Code Contracts trying to get build errors instead of warnings
I'm trying to get VS2010 Ultimate with Code Contracts to generate Errors instead of Warnings.

I have this simple test program:

using System.Diagnostics.Contracts;

namespace MyError
{
  public class Program
  {
     static void Main(string[] args)
     {
         Program prog = new Program();
         prog.Log(null);
     }

     public void Log(string msg)
     {
         Contract.Requires(msg != null);
     }
  }
}
```

<p>It correctly determines there is a violation of the contract:</p>

```C:\...\Program.cs(10,13): warning : CodeContracts: requires is false: msg != null
```

In my csproj file there is this property field for Debug:

TreatWarningsAsErrors>true

Is there something else I have to set in the project settings to turn these into errors?

答:
It looks like at this point Microsoft has elected not to make this possible, but they are considering it for the future:
http://connect.microsoft.com/VisualStudio/feedback/details/646880/code-contracts-dont-listen-to-treat-warnings-as-errors-setting</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get VS2010 Ultimate with Code Contracts to generate Errors instead of Warnings.

I have this simple test program:

using System.Diagnostics.Contracts;

namespace MyError
{
  public class Program
  {
     static void Main(string[] args)
     {
         Program prog = new Program();
         prog.Log(null);
     }

     public void Log(string msg)
     {
         Contract.Requires(msg != null);
     }
  }
}

It correctly determines there is a violation of the contract:

C:\...\Program.cs(10,13): warning : CodeContracts: requires is false: msg != null

In my csproj file there is this property field for Debug:

TreatWarningsAsErrors>true

Is there something else I have to set in the project settings to turn these into errors?


问:
How to execute postgres function using dapper
I get an error when I try to call a postgre function using dapper. Where did i do wrong? I'll be glad if you can help me.

Error Message:

```<code> availability_list(facilityId => integer, startDate => timestamp without time zone, endDate => timestamp without time zone) does not exist"
</code>```

Call postgre function using Dapper:

```<code>var func = "public.availability_list";

var result = db.Query<ReportResponse>(
            sql: func,
            param: new { facilityId = request.FacilityId, startDate =
            DateTime.Now, endDate = DateTime.Now },
            commandType: CommandType.StoredProcedure,
            commandTimeout: 900) as List<ReportResponse>;
</code>```

My Postgre Function:

```<code>CREATE FUNCTION Availability_List(facilityId int, startDate date, endDate date)
RETURNS report_type[]
AS
$$

DECLARE
result_record report_type[];

BEGIN

result_record := array(
SELECT...
);

RETURN result_record;

 END $$ LANGUAGE plpgsql;
</code>```

答:
Try passing function parameters in lowercase, i.e.

```<code>var result = db.Query<ReportResponse>(
            sql: func,
            param: new { facilityid = request.FacilityId, startdate =
            DateTime.Now, enddate = DateTime.Now },
            commandType: CommandType.StoredProcedure,
            commandTimeout: 900) as List<ReportResponse>;
</code>```

That worked for me.

Body:
I get an error when I try to call a postgre function using dapper. Where did i do wrong? I'll be glad if you can help me.

Error Message:

 availability_list(facilityId => integer, startDate => timestamp without time zone, endDate => timestamp without time zone) does not exist"

Call postgre function using Dapper:

var func = "public.availability_list";

var result = db.Query<ReportResponse>(
            sql: func,
            param: new { facilityId = request.FacilityId, startDate =
            DateTime.Now, endDate = DateTime.Now },
            commandType: CommandType.StoredProcedure,
            commandTimeout: 900) as List<ReportResponse>;

My Postgre Function:

CREATE FUNCTION Availability_List(facilityId int, startDate date, endDate date)
RETURNS report_type[]
AS
$$

DECLARE
result_record report_type[];

BEGIN

result_record := array(
SELECT...
);

RETURN result_record;

 END $$ LANGUAGE plpgsql;

Body:
Try passing function parameters in lowercase, i.e.

var result = db.Query<ReportResponse>(
            sql: func,
            param: new { facilityid = request.FacilityId, startdate =
            DateTime.Now, enddate = DateTime.Now },
            commandType: CommandType.StoredProcedure,
            commandTimeout: 900) as List<ReportResponse>;

That worked for me.


问:
why pass null before allocating memory to sysctlbyname function ios
I have a code to get the device information on which my app is running iOS. I have a issue on understanding the below code and its working.

```<code>size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0); // what is the use of null here
char *model = malloc(size);
sysctlbyname("hw.machine", model, &size, NULL, 0);
NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];
</code>```

Why I cannot remove sysctlbyname () call before malloc? If i tried to do the below, iam getting malloc error.

```<code>size_t size;
// HAVE REMOVED THIS LINE FROM ABOVE
// sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *model = malloc(size);
s.ysctlbyname("hw.machine", model, &size, NULL, 0);
NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];
</code>```

What is the difference?

答:
man malloc:

The malloc() function allocates size bytes of memory and returns a pointer to the allocated memory.

If you remove the first sysctlbyname call:

size_t size;
char *model = malloc(size);
```

<p>How many bytes should <code>malloc</code> allocate? Do you know the size upfront? Nope.</p>

<p><code>man sysctlbyname</code>:</p>

<blockquote>
  <p>The size of the available data can be determined by calling <code>sysctl()</code>
  with the <code>NULL</code> argument for <code>oldp</code>. The size of the available data will
  be returned in the location pointed to by <code>oldlenp</code>.  For some operations,
  the amount of space may change often. For these operations, the system
  attempts to round up so that the returned size is large enough for a call
  to return the data shortly thereafter.</p>
</blockquote>

<p>The first part says that you'd like to call <code>hw.machine</code> syscall and that you're not interested in the actual value (<code>NULL</code>), but just the <code>size</code>. <code>&size</code> is pointer to your <code>size</code> variable.</p>

<pre class="lang-c prettyprint-override"><code>size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0); // Get just size
char *model = malloc(size); // Alloc required amount of memory
</code>```

The second part says that you'd like to call hw.machine syscall and that you're interested in the actual value and the size.

sysctlbyname("hw.machine", model, &size, NULL, 0);
NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];
```

<hr>

<p>There're some issues with this code. I'd rewrite it in this way:</p>

<pre class="lang-c prettyprint-override"><code>- (NSString *)deviceModel {
    size_t size;

    // Get buffer size to allocate
    if (sysctlbyname("hw.machine", NULL, &size, NULL, 0) == -1) {
        // syscall failed, return nil or handle it your way
        NSLog(@"syscall hw.machine failed with error %d", errno);
        return nil;
    }

    // Allocate memory for syscall result
    char *buffer = malloc(size);
    if (buffer == NULL) {
        NSLog(@"malloc failed with error %d", errno);
        return nil;
    }

    // Get the actual value
    if (sysctlbyname("hw.machine", buffer, &size, NULL, 0) == -1) {
        // syscall failed, return nil or handle it your way
        NSLog(@"syscall hw.machine failed with error %d", errno);
        // Buffer already allocated, free it to avoid leaks
        free(buffer);
        return nil;
    }

    // Create a NSString from C string
    NSString *deviceModel = [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];

    // Free memory, bytes were copied in the stringWithCString:encoding:
    free(buffer);

    return deviceModel;
}
</code>```

Body:
I have a code to get the device information on which my app is running iOS. I have a issue on understanding the below code and its working.

size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0); // what is the use of null here
char *model = malloc(size);
sysctlbyname("hw.machine", model, &size, NULL, 0);
NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];

Why I cannot remove sysctlbyname () call before malloc? If i tried to do the below, iam getting malloc error.

size_t size;
// HAVE REMOVED THIS LINE FROM ABOVE
// sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *model = malloc(size);
s.ysctlbyname("hw.machine", model, &size, NULL, 0);
NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];

What is the difference?

Body:
man malloc:

The malloc() function allocates size bytes of memory and returns a pointer to the allocated memory.

If you remove the first sysctlbyname call:

size_t size;
char *model = malloc(size);

How many bytes should malloc allocate? Do you know the size upfront? Nope.

man sysctlbyname:

The size of the available data can be determined by calling sysctl()
  with the NULL argument for oldp. The size of the available data will
  be returned in the location pointed to by oldlenp.  For some operations,
  the amount of space may change often. For these operations, the system
  attempts to round up so that the returned size is large enough for a call
  to return the data shortly thereafter.

The first part says that you'd like to call hw.machine syscall and that you're not interested in the actual value (NULL), but just the size. &size is pointer to your size variable.

size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0); // Get just size
char *model = malloc(size); // Alloc required amount of memory

The second part says that you'd like to call hw.machine syscall and that you're interested in the actual value and the size.

sysctlbyname("hw.machine", model, &size, NULL, 0);
NSString *deviceModel = [NSString stringWithCString:model encoding:NSUTF8StringEncoding];

There're some issues with this code. I'd rewrite it in this way:

- (NSString *)deviceModel {
    size_t size;

    // Get buffer size to allocate
    if (sysctlbyname("hw.machine", NULL, &size, NULL, 0) == -1) {
        // syscall failed, return nil or handle it your way
        NSLog(@"syscall hw.machine failed with error %d", errno);
        return nil;
    }

    // Allocate memory for syscall result
    char *buffer = malloc(size);
    if (buffer == NULL) {
        NSLog(@"malloc failed with error %d", errno);
        return nil;
    }

    // Get the actual value
    if (sysctlbyname("hw.machine", buffer, &size, NULL, 0) == -1) {
        // syscall failed, return nil or handle it your way
        NSLog(@"syscall hw.machine failed with error %d", errno);
        // Buffer already allocated, free it to avoid leaks
        free(buffer);
        return nil;
    }

    // Create a NSString from C string
    NSString *deviceModel = [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];

    // Free memory, bytes were copied in the stringWithCString:encoding:
    free(buffer);

    return deviceModel;
}


问:
Open a PowerPoint presentation from Excel with VBA and then set that presentation to a variable
I have to post a lot of Excel charts to a specific PowerPoint document and I'm building out a macro in Excel VBA to do it for me.

I'm able to correctly open the PowerPoint presentation that I want to update, however I don't know how to set the presentation I just opened to a variable called MyPresentation.

```<code>Dim myPresentation As PowerPoint.Presentation
Dim PowerPointApp As PowerPoint.Application

PowerPointApp.Presentations.Open Filename:="obscured filepath and name"`
</code>```

Obviously there's some additional code, but I'm trying to set the Presentation I just opened in line 3 set to the MyPresentation variable so I can reference the document I just opened.

答:
This one worked for me:

```<code>'devlare variables
Dim MyPPT As Object

'create PowerPoint
Set MyPPT = CreateObject("Powerpoint.application")
'make it visible
MyPPT.Visible = True
'path to powerpoint
MyPPT.presentations.Open "path\powerpoint.pptx"
</code>```

Set visible to true, before open it. otherwise it did not worked for me

Body:
I have to post a lot of Excel charts to a specific PowerPoint document and I'm building out a macro in Excel VBA to do it for me.

I'm able to correctly open the PowerPoint presentation that I want to update, however I don't know how to set the presentation I just opened to a variable called MyPresentation.

Dim myPresentation As PowerPoint.Presentation
Dim PowerPointApp As PowerPoint.Application

PowerPointApp.Presentations.Open Filename:="obscured filepath and name"`

Obviously there's some additional code, but I'm trying to set the Presentation I just opened in line 3 set to the MyPresentation variable so I can reference the document I just opened.

Body:
This one worked for me:

'devlare variables
Dim MyPPT As Object

'create PowerPoint
Set MyPPT = CreateObject("Powerpoint.application")
'make it visible
MyPPT.Visible = True
'path to powerpoint
MyPPT.presentations.Open "path\powerpoint.pptx"

Set visible to true, before open it. otherwise it did not worked for me


问:
Why a single Decision Tree algorithm out runs ensemble technique in accuracy
I have used decision tree algorithm on a "wine" dataset and this dataset predicts the quality of the wine on a scale of 1 to 10 where 1 is worst and 10 is best and the sample code is as below

```<code>import pandas as pd
data=pd.read_csv("wine.csv")
x=data.drop(columns="quality")# x has all the feature columns
y=data.quality# y has the label column
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=355)
dt=DecisionTreeClassifier()
dt.fit(x_train,y_train)
dt.score(x_test,y_test)
</code>```

now I have got an accuracy of 63% now on the same dataset I have used ensemble technique with bagging approach with the same Decision Tree algorithm as the base model and the sample code is as below

```<code>bagging=BaggingClassifier(base_estimator=DecisionTreeClassifier(),n_estimators=100,
                         bootstrap=True,oob_score=True)
bagging.fit(x_train,y_train)
bagging.score(x_test,y_test)
</code>```

surprisingly I got an accuracy of 61% ie., in ensemle approach the accuracy is decreased and my question is why did the accuracy decreased in ensemble method. Ensemble is very good approach when compared to a single Decision Tree algorithm that means accuracy has to be increased when we use ensemble technique but here why the accuracy is decreased

答:
I can't reproduce your results. For your code, I achieve 0.94 accuracy for the DecisionTreeClassifier, 0.98 of accuracy for the BaggingClassifier. Here is a link for the google colab.

One more point - the size of the dataset is too small to be able to discuss the performance of the ML algorithms.

Body:
I have used decision tree algorithm on a "wine" dataset and this dataset predicts the quality of the wine on a scale of 1 to 10 where 1 is worst and 10 is best and the sample code is as below

import pandas as pd
data=pd.read_csv("wine.csv")
x=data.drop(columns="quality")# x has all the feature columns
y=data.quality# y has the label column
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=355)
dt=DecisionTreeClassifier()
dt.fit(x_train,y_train)
dt.score(x_test,y_test)

now I have got an accuracy of 63% now on the same dataset I have used ensemble technique with bagging approach with the same Decision Tree algorithm as the base model and the sample code is as below

bagging=BaggingClassifier(base_estimator=DecisionTreeClassifier(),n_estimators=100,
                         bootstrap=True,oob_score=True)
bagging.fit(x_train,y_train)
bagging.score(x_test,y_test)

surprisingly I got an accuracy of 61% ie., in ensemle approach the accuracy is decreased and my question is why did the accuracy decreased in ensemble method. Ensemble is very good approach when compared to a single Decision Tree algorithm that means accuracy has to be increased when we use ensemble technique but here why the accuracy is decreased


问:
Check if child component rendered - Jest, Enzyme
In my unit test, I want to test whether the parent component is successfully rendering its child component. Here is the code:

```<code>describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.find(Child).length).toEqual(1);
  });
});
</code>```

Parent:

```<code>const Parent = observer(({ store }) => {
  const bookList = toJS(store.planets);
  return (
    <div>
      <div className={style.planet_container}>
        {bookList.map(book => {
          return <Child key={book.name} name={book.name} />;
        })}
      </div>
    </div>
  );
});
</code>```

Above code is taken from here, but it's not working. I am getting the following error:

Expected 1, Received 0'

Where am I going wrong? I am using Enzyme 3.3 with Jest 23.1.0.

答:
Enzyme allows finding by a component's displayName:

From Enzyme API documentation:

const wrapper = shallow(<MyComponent />);
expect(wrapper.find('Foo')).to.have.lengthOf(1);
```

<p>So, in order to test sure the Child component has been rendered you can simply reference it by its <em>displayName</em>.</p>

<p>You can print the wrapper's HTML string: <code>console.log( wrapper.debug() )</code></p>

<hr>

<p>In case your component is dynamic you can set its displayName to a fixed one, so the test would be more bulletproof:</p>

<pre class="lang-js prettyprint-override"><code>const MyComponent = props.dynamicChildComponent;
MyComponent.displayName = 'Foo';
</code>```

Body:
In my unit test, I want to test whether the parent component is successfully rendering its child component. Here is the code:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.find(Child).length).toEqual(1);
  });
});

Parent:

const Parent = observer(({ store }) => {
  const bookList = toJS(store.planets);
  return (

        {bookList.map(book => {
          return <Child key={book.name} name={book.name} />;
        })}

  );
});

Above code is taken from here, but it's not working. I am getting the following error:

Expected 1, Received 0'

Where am I going wrong? I am using Enzyme 3.3 with Jest 23.1.0.

Body:
Enzyme allows finding by a component's displayName:

From Enzyme API documentation:

const wrapper = shallow(<MyComponent />);
expect(wrapper.find('Foo')).to.have.lengthOf(1);

So, in order to test sure the Child component has been rendered you can simply reference it by its displayName.

You can print the wrapper's HTML string: console.log( wrapper.debug() )

In case your component is dynamic you can set its displayName to a fixed one, so the test would be more bulletproof:

const MyComponent = props.dynamicChildComponent;
MyComponent.displayName = 'Foo';


问:
laravel: whole migrations folder is missing
```<code>$ php artisan make:migration create_room_table
</code>```

ErrorException  : file_put_contents(D:\LaravelProjects\HotelMgmt\database\migrations/2020_06_03_060853_create_room_table.php): failed to open stream: No such file or directory

at D:\LaravelProjects\HotelMgmt\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:133

      129|      * @return int|bool
      130|      */
      131|     public function put($path, $contents, $lock = false)
      132|     {
  133|         return file_put_contents($path, $contents, $lock ? LOCK_EX : 0);
      134|     }
      135|
      136|     /**
      137|      * Write the contents of a file, replacing it atomically if it already exists.

Exception trace:

答: hey i restored my migrations folder by git restore . though some migrations are missing but it's alright for me. </p>

Body:
$ php artisan make:migration create_room_table

ErrorException  : file_put_contents(D:\LaravelProjects\HotelMgmt\database\migrations/2020_06_03_060853_create_room_table.php): failed to open stream: No such file or directory

at D:\LaravelProjects\HotelMgmt\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:133

      129|      * @return int|bool
      130|      */
      131|     public function put($path, $contents, $lock = false)
      132|     {
  133|         return file_put_contents($path, $contents, $lock ? LOCK_EX : 0);
      134|     }
      135|
      136|     /**
      137|      * Write the contents of a file, replacing it atomically if it already exists.

Exception trace:


问:
Process same file in two threads using ifstream
I have an input file in my application that contains a vast amount of information. Reading over it sequentially, and at only a single file offset at a time is not sufficient for my application's usage. Ideally, I'd like to have two threads, that have separate and distinct ifstreams reading from two unique file offsets of the same file. I can't just start one ifstream up, and then make a copy of it using its copy constructor (since its uncopyable). So, how do I handle this?

Immediately I can think of two ways,

Construct a new ifstream for the second thread, open it on the same file.

Share a single instance of an open ifstream across both threads (using for instance boost::shared_ptr<>). Seek to the appropriate file offset that current thread is currently interested in, when the thread gets a time slice.

Is one of these two methods preferred?

Is there a third (or fourth) option that I have not yet thought of?

Obviously I am ultimately limited by the hard drive having to spin back and forth, but what I am interested in taking advantage of (if possible), is some OS level disk caching at both file offsets simultaneously.

Thanks.

答:
Two std::ifstream instances will probably be the best option here.  Modern HDDs are optimized for a large queue of I/O requests, so reading from two std::ifstream instances concurrently should give quite nice performance.

If you have a single std::ifstream you'll have to worry about synchronizing access to it, plus it might defeat the operating system's automatic sequential access read-ahead caching, resulting in poorer performance.


问:
Why CustomProjectAggregationOperation Not working in SpringMongoTemplate
I trying the following query in spring onto the template, that query works in Mongoserver, but when I using the query in the SpringMongo template, the filter does not work, it gets all date, instead of filters date. If anyone knows this issue. pls, help me out this.

The Native Mongo Query:-

```<code>db.Task_Status.aggregate([{
{"$addFields":{"timeDiff": { $floor: { $divide: [ { $subtract:[ new Date() , "$currenttime" ] } , 60000 ] }  } }},
{$match:{$and:[{"timeDiff":{"$lt": 12}}]}} }]);
</code>```

The Spring MongoTempalte java Code:

```<code>String nativeFilterQuery = "{\"$addFields\":{\"timeDiff\": { $floor: { $divide: [ { $subtract:[ new Date() , \"$currenttime\" ] } , 60000 ] }  } }},{$match:{$and:[{\"timeDiff\":{\"$lt\": 12}}]}}";
List<TaskStatus> amTaskLists = Collections.EMPTY_LIST;
        List<AggregationOperation> aggregationOperations = new ArrayList<>();
        if (StringUtility.isNotNullOrEmpty(nativeFilterQuery)) {
            aggregationOperations.add(new CustomProjectAggregationOperation(nativeFilterQuery));
        }
        TypedAggregation<TaskStatus> aggregation = Aggregation.newAggregation(TaskStatus.class, aggregationOperations);
        AggregationResults result = execute(aggregation, TaskStatus.class);
        amTaskLists = result.getMappedResults();
</code>```

答:
When I split the query and Run like following its works    </p>

```<code>String queryOne = "{\"$addFields\":{\"timeDiff\": { $floor: { $divide: [ { $subtract:[ new Date() , \"$currenttime\" ] } , 60000 ] }  } }}";
            String queryTwo = "{$match:{$and:[{\"timeDiff\":{\"$lt\": 12}}]}}";
            List<AggregationOperation> aggregationOperations = new ArrayList<>();
            if (StringUtility.isNotNullOrEmpty(queryOne)) {
                aggregationOperations.add(new CustomProjectAggregationOperation(queryOne));
            }
            if (StringUtility.isNotNullOrEmpty(queryTwo)) {
                aggregationOperations.add(new CustomProjectAggregationOperation(queryTwo));
            }
</code>```

Body:
I trying the following query in spring onto the template, that query works in Mongoserver, but when I using the query in the SpringMongo template, the filter does not work, it gets all date, instead of filters date. If anyone knows this issue. pls, help me out this.

The Native Mongo Query:-

db.Task_Status.aggregate([{
{"$addFields":{"timeDiff": { $floor: { $divide: [ { $subtract:[ new Date() , "$currenttime" ] } , 60000 ] }  } }},
{$match:{$and:[{"timeDiff":{"$lt": 12}}]}} }]);

The Spring MongoTempalte java Code:

String nativeFilterQuery = "{\"$addFields\":{\"timeDiff\": { $floor: { $divide: [ { $subtract:[ new Date() , \"$currenttime\" ] } , 60000 ] }  } }},{$match:{$and:[{\"timeDiff\":{\"$lt\": 12}}]}}";
List<TaskStatus> amTaskLists = Collections.EMPTY_LIST;
        List<AggregationOperation> aggregationOperations = new ArrayList<>();
        if (StringUtility.isNotNullOrEmpty(nativeFilterQuery)) {
            aggregationOperations.add(new CustomProjectAggregationOperation(nativeFilterQuery));
        }
        TypedAggregation<TaskStatus> aggregation = Aggregation.newAggregation(TaskStatus.class, aggregationOperations);
        AggregationResults result = execute(aggregation, TaskStatus.class);
        amTaskLists = result.getMappedResults();

Body:
When I split the query and Run like following its works

String queryOne = "{\"$addFields\":{\"timeDiff\": { $floor: { $divide: [ { $subtract:[ new Date() , \"$currenttime\" ] } , 60000 ] }  } }}";
            String queryTwo = "{$match:{$and:[{\"timeDiff\":{\"$lt\": 12}}]}}";
            List<AggregationOperation> aggregationOperations = new ArrayList<>();
            if (StringUtility.isNotNullOrEmpty(queryOne)) {
                aggregationOperations.add(new CustomProjectAggregationOperation(queryOne));
            }
            if (StringUtility.isNotNullOrEmpty(queryTwo)) {
                aggregationOperations.add(new CustomProjectAggregationOperation(queryTwo));
            }


问:
Android Proguard - how to keep onClick handlers only referenced from XML layouts
In my Android app I ofter don't create a View's on-click handler in code, but rely on the ability to specify it in the XML layout file, like this:

```<code>   <Button
        ....
        android:onClick="onSearchClicked"
       ...../>
</code>```

And then have the method in the Activity like this:

```<code>    public void onSearchClicked( View v ) {
    ........}
</code>```

Meaning there is no obvious reference to this method in my own code.

When running Proguard for a production release it seems to remove this method and the on-click fails.

What can I add to my proguard config file to avoid this that won't oblige me to rename all these methods?

An annotation I could add to the method and have proguard take notice of?

Somehow specify these types of methods referenced from xml?

I suppose I can add a false reference in the code, but would like to avoid that if I can as I won't always remember to put it in!

I have looked through the proguard examples for Android and can't see anything for this particular need.

答:
```<code>-keepclasseswithmembers class * {
   public void onSearchClicked(android.view.View );
}
</code>```

but double check it from proguard doc :
http://proguard.sourceforge.net/index.html#/manual/refcard.html

Body:
In my Android app I ofter don't create a View's on-click handler in code, but rely on the ability to specify it in the XML layout file, like this:

   <Button
        ....
        android:onClick="onSearchClicked"
       ...../>

And then have the method in the Activity like this:

    public void onSearchClicked( View v ) {
    ........}

Meaning there is no obvious reference to this method in my own code.

When running Proguard for a production release it seems to remove this method and the on-click fails.

What can I add to my proguard config file to avoid this that won't oblige me to rename all these methods?

An annotation I could add to the method and have proguard take notice of?

Somehow specify these types of methods referenced from xml?

I suppose I can add a false reference in the code, but would like to avoid that if I can as I won't always remember to put it in!

I have looked through the proguard examples for Android and can't see anything for this particular need.

Body:
-keepclasseswithmembers class * {
   public void onSearchClicked(android.view.View );
}

but double check it from proguard doc :
http://proguard.sourceforge.net/index.html#/manual/refcard.html


问:
Add and remove to Local Storage
i'm creating a list with add to favorite link.
I want to store the 'foo' value on local storage using pure JS. Then once I click again it is remove.
Maybe I can not bind the identifier to the style name.
I wanted to repeat the way it is here https://jsfiddle.net/farhadB/ocgcejg2/ , but I can’t.

document.addEventListener('click', function(e) {
  if (e.target && e.target.classList.contains('photo')) {
    e.target.classList = "foo";
  } else if (e.target && e.target.classList.contains('foo')) {
    e.target.classList = "photo";
  }
});
```

答:
I think the main issue is, that you are setting the classList. classList is a readonly attribut and you can add classes by using the add method.

Maybe you mean instead of:

e.target.classList = "photo";
```

<p>This:</p>

<pre class="lang-js prettyprint-override"><code>e.target.className = "photo";
</code>```

or

e.target.classList.add("photo");
```

Title: Add and remove to Local Storage

Body:
I think the main issue is, that you are setting the classList. classList is a readonly attribut and you can add classes by using the add method.

Maybe you mean instead of:

e.target.classList = "photo";

This:

e.target.className = "photo";

or

e.target.classList.add("photo");


问:
R loop for creating data frame
I have a list of samples in the object my.ID:

```<code>head(my.ID)
</code>```

returns:

```<code>[1] PATL1 PATL2 PATL9 PCAN1 PCAN2 PCAN3
117 Levels: PATL1 PATL2 PATL9...
</code>```

For each sample, I have a file, called like that:

Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi

With the name of the sample in the middle (here PATL1)

I want to create a data frame for each sample where first column is the name of the  sample (PATL1 for instance, which is listed in my.ID), and the second column is the column called PI from its associated data frame (in my example: Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi$PI.

I tried multiple loops, changes a few stuff but never worked.
I think that it's because I don't manage to properly define the value in the data.frame command.

Can someone show me how to change the loop so that it works?

```<code>for (i in 1:(length(my.ID))){
  my.value <- noquote(paste0("Pi_Win5kb_JudDP_2020.04.29.vcf_",my.ID[i],".windowed.pi$PI"))
  cur.file <- data.frame(group=my.ID[i], value=as.name(my.value))
  my.name <- my.ID[i]
  assign(paste(my.name), cur.file)
}
</code>```

答:
It is not a good idea to generate a bunch of similar object. Use a list for that objects!

For you (with the informations from your answer) it could be:

```<code>my.files <- list.files(path="Pi1_vcftools_indv/results/", pattern = "Pi_")

my.samples <- read.table("../../Samples/JudDP_sample_info_VCFsorted.2020.05.12.txt", header=TRUE)
my.ID <- my.samples$ID

mydata3 <- function(IDi, filei) {
  cur.file <- read.table(file = paste0("Pi1_vcftools_indv/results/",filei), sep = "\t", h=T)
  data.frame(group=IDi, value=cur.file)
}
L <- mapply(mydata3, my.ID, my.files)
names(L) <- my.ID
</code>```

Here is a variant using setwd():

```<code>my.samples <- read.table("../../Samples/JudDP_sample_info_VCFsorted.2020.05.12.txt", header=TRUE)
my.ID <- my.samples$ID

setwd("Pi1_vcftools_indv/results/")
my.files <- list.files(pattern = "Pi_")

mydata3 <- function(IDi, filei) {
  cur.file <- read.table(file=filei, sep = "\t", header=TRUE)
  data.frame(group=IDi, value=cur.file)
}
L <- mapply(mydata3, my.ID, my.files)
names(L) <- my.ID
</code>```

Title: R loop for creating data frame

Body:
I have a list of samples in the object my.ID:

head(my.ID)

returns:

[1] PATL1 PATL2 PATL9 PCAN1 PCAN2 PCAN3
117 Levels: PATL1 PATL2 PATL9...

For each sample, I have a file, called like that:

Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi

With the name of the sample in the middle (here PATL1)

I want to create a data frame for each sample where first column is the name of the  sample (PATL1 for instance, which is listed in my.ID), and the second column is the column called PI from its associated data frame (in my example: Pi_Win5kb_JudDP_2020.04.29.vcf_PATL1.windowed.pi$PI.

I tried multiple loops, changes a few stuff but never worked.
I think that it's because I don't manage to properly define the value in the data.frame command.

Can someone show me how to change the loop so that it works?

for (i in 1:(length(my.ID))){
  my.value <- noquote(paste0("Pi_Win5kb_JudDP_2020.04.29.vcf_",my.ID[i],".windowed.pi$PI"))
  cur.file <- data.frame(group=my.ID[i], value=as.name(my.value))
  my.name <- my.ID[i]
  assign(paste(my.name), cur.file)
}

Body:
It is not a good idea to generate a bunch of similar object. Use a list for that objects!

For you (with the informations from your answer) it could be:

my.files <- list.files(path="Pi1_vcftools_indv/results/", pattern = "Pi_")

my.samples <- read.table("../../Samples/JudDP_sample_info_VCFsorted.2020.05.12.txt", header=TRUE)
my.ID <- my.samples$ID

mydata3 <- function(IDi, filei) {
  cur.file <- read.table(file = paste0("Pi1_vcftools_indv/results/",filei), sep = "\t", h=T)
  data.frame(group=IDi, value=cur.file)
}
L <- mapply(mydata3, my.ID, my.files)
names(L) <- my.ID

Here is a variant using setwd():

my.samples <- read.table("../../Samples/JudDP_sample_info_VCFsorted.2020.05.12.txt", header=TRUE)
my.ID <- my.samples$ID

setwd("Pi1_vcftools_indv/results/")
my.files <- list.files(pattern = "Pi_")

mydata3 <- function(IDi, filei) {
  cur.file <- read.table(file=filei, sep = "\t", header=TRUE)
  data.frame(group=IDi, value=cur.file)
}
L <- mapply(mydata3, my.ID, my.files)
names(L) <- my.ID


问:
Aggregation: Perform countBy on multiple $lookup arrays in a single query
Reproduction: https://mongoplayground.net/p/f9BraX4emor

The playground query does the job halfway. It finds the matching documents, but it doesn't aggregate bounties and emotes with a COUNT BY operation.

My desired result is this:

```<code>[
  {
    "_id": ObjectId("5e7d7bf7d86d85088863f4de"),
    "channelId": "23435553",
    "bounties": {
        "user1": 150, // user1 had 2 bounties with 100 + 50 amounts
        "user2": 200, // user2 had 1 bounty with 200 amount
    },
    "emotes": {
        "A": 2, // There were 2 docs with emoteId == A
        "B": 1, // There was 1 doc with emoteId == B
    },
  }
]
</code>```

I actually don't care about the specific data structure of the aggregated result. For ex. I'd be fine if bounties and emotes were arrays instead of dictionaries. I think the $unwind operator can be used here, but I'm just not sure how.

Currently, I'm making way too many queries to fulfill a REST API request.

For ex, my API receives a request to find 10 suggestions for a channel. First, I run 1 query that returns 10 suggestions. Then FOR EACH suggestion, I run 1 query to aggregate bounties, and another to aggregate emotes. That's 21 queries...... in a single REST API call.. :(. I want to run 1 query, not 21.

答:
To create an object based on the document values, we need to use $arrayToObject operator.

Elegant solution

Explanation

We perform $map operator to get [k:"...", v:"..."] structure.

Also, we need to count how many times emotes / bounties repeats

```<code>db.suggestions.aggregate([
  {
    $match: {
      "channelId": "23435553"
    }
  },
  {
    $lookup: {
      from: "emotes",
      localField: "_id",
      foreignField: "suggestionId",
      as: "emotes"
    }
  },
  {
    $lookup: {
      from: "bounties",
      localField: "_id",
      foreignField: "suggestionId",
      as: "bounties"
    }
  },
  {
    $project: {
      _id: 1,
      channelId: 1,
      emotes: {
        $arrayToObject: {
          $map: {
            input: "$emotes",
            as: "emote",
            in: {
              k: "$$emote.emoteId",
              v: {
                $size: {
                  $filter: {
                    input: "$emotes",
                    as: "e",
                    cond: {
                      $eq: [
                        "$$emote.emoteId",
                        "$$e.emoteId"
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      },
      bounties: {
        $arrayToObject: {
          $map: {
            input: "$bounties",
            as: "bounty",
            in: {
              k: "$$bounty.userId",
              v: {
                $sum: {
                  $map: {
                    input: {
                      $filter: {
                        input: "$bounties",
                        as: "b",
                        cond: {
                          $eq: [
                            "$$bounty.userId",
                            "$$b.userId"
                          ]
                        }
                      }
                    },
                    in: "$$this.bountyAmount"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
])
</code>```

MongoPlayground

Classic solution

Explanation

We need to flatten emotes / bounties after $lookup.

We perform $group stages to reduce duplicated values

We create [{k:"...", v:"..."}] structure to convert it into Object with $arrayToObject operator.

```<code>db.suggestions.aggregate([
  {
    $match: {
      "channelId": "23435553"
    }
  },
  {
    $lookup: {
      from: "emotes",
      localField: "_id",
      foreignField: "suggestionId",
      as: "emotes"
    }
  },
  {
    $unwind: {
      path: "$emotes",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
      _id: {
        "_id": "$_id",
        "emoteId": "$emotes.emoteId"
      },
      channelId: {
        $first: "$channelId"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      channelId: {
        $first: "$channelId"
      },
      emotes: {
        $push: {
          k: "$_id.emoteId",
          v: "$count"
        }
      }
    }
  },
  {
    $lookup: {
      from: "bounties",
      localField: "_id",
      foreignField: "suggestionId",
      as: "bounties"
    }
  },
  {
    $unwind: {
      path: "$bounties",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
      _id: {
        "_id": "$_id",
        "userId": "$bounties.userId"
      },
      channelId: {
        $first: "$channelId"
      },
      emotes: {
        $first: "$emotes"
      },
      bountyAmount: {
        $sum: "$bounties.bountyAmount"
      }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      channelId: {
        $first: "$channelId"
      },
      emotes: {
        $first: "$emotes"
      },
      bounties: {
        $push: {
          k: "$_id.userId",
          v: "$bountyAmount"
        }
      }
    }
  },
  {
    $project: {
      _id: 1,
      channelId: 1,
      emotes: {
        $arrayToObject: "$emotes"
      },
      bounties: {
        $arrayToObject: "$bounties"
      },

    }
  }
])
</code>```

MongoPlayground

Body:
Reproduction: https://mongoplayground.net/p/f9BraX4emor

The playground query does the job halfway. It finds the matching documents, but it doesn't aggregate bounties and emotes with a COUNT BY operation.

My desired result is this:

[
  {
    "_id": ObjectId("5e7d7bf7d86d85088863f4de"),
    "channelId": "23435553",
    "bounties": {
        "user1": 150, // user1 had 2 bounties with 100 + 50 amounts
        "user2": 200, // user2 had 1 bounty with 200 amount
    },
    "emotes": {
        "A": 2, // There were 2 docs with emoteId == A
        "B": 1, // There was 1 doc with emoteId == B
    },
  }
]

I actually don't care about the specific data structure of the aggregated result. For ex. I'd be fine if bounties and emotes were arrays instead of dictionaries. I think the $unwind operator can be used here, but I'm just not sure how.

Currently, I'm making way too many queries to fulfill a REST API request.

For ex, my API receives a request to find 10 suggestions for a channel. First, I run 1 query that returns 10 suggestions. Then FOR EACH suggestion, I run 1 query to aggregate bounties, and another to aggregate emotes. That's 21 queries...... in a single REST API call.. :(. I want to run 1 query, not 21.

Body:
To create an object based on the document values, we need to use $arrayToObject operator.

Elegant solution

Explanation

We perform $map operator to get [k:"...", v:"..."] structure.

Also, we need to count how many times emotes / bounties repeats

db.suggestions.aggregate([
  {
    $match: {
      "channelId": "23435553"
    }
  },
  {
    $lookup: {
      from: "emotes",
      localField: "_id",
      foreignField: "suggestionId",
      as: "emotes"
    }
  },
  {
    $lookup: {
      from: "bounties",
      localField: "_id",
      foreignField: "suggestionId",
      as: "bounties"
    }
  },
  {
    $project: {
      _id: 1,
      channelId: 1,
      emotes: {
        $arrayToObject: {
          $map: {
            input: "$emotes",
            as: "emote",
            in: {
              k: "$$emote.emoteId",
              v: {
                $size: {
                  $filter: {
                    input: "$emotes",
                    as: "e",
                    cond: {
                      $eq: [
                        "$$emote.emoteId",
                        "$$e.emoteId"
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      },
      bounties: {
        $arrayToObject: {
          $map: {
            input: "$bounties",
            as: "bounty",
            in: {
              k: "$$bounty.userId",
              v: {
                $sum: {
                  $map: {
                    input: {
                      $filter: {
                        input: "$bounties",
                        as: "b",
                        cond: {
                          $eq: [
                            "$$bounty.userId",
                            "$$b.userId"
                          ]
                        }
                      }
                    },
                    in: "$$this.bountyAmount"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
])

MongoPlayground

Classic solution

Explanation

We need to flatten emotes / bounties after $lookup.

We perform $group stages to reduce duplicated values

We create [{k:"...", v:"..."}] structure to convert it into Object with $arrayToObject operator.

db.suggestions.aggregate([
  {
    $match: {
      "channelId": "23435553"
    }
  },
  {
    $lookup: {
      from: "emotes",
      localField: "_id",
      foreignField: "suggestionId",
      as: "emotes"
    }
  },
  {
    $unwind: {
      path: "$emotes",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
      _id: {
        "_id": "$_id",
        "emoteId": "$emotes.emoteId"
      },
      channelId: {
        $first: "$channelId"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      channelId: {
        $first: "$channelId"
      },
      emotes: {
        $push: {
          k: "$_id.emoteId",
          v: "$count"
        }
      }
    }
  },
  {
    $lookup: {
      from: "bounties",
      localField: "_id",
      foreignField: "suggestionId",
      as: "bounties"
    }
  },
  {
    $unwind: {
      path: "$bounties",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
      _id: {
        "_id": "$_id",
        "userId": "$bounties.userId"
      },
      channelId: {
        $first: "$channelId"
      },
      emotes: {
        $first: "$emotes"
      },
      bountyAmount: {
        $sum: "$bounties.bountyAmount"
      }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      channelId: {
        $first: "$channelId"
      },
      emotes: {
        $first: "$emotes"
      },
      bounties: {
        $push: {
          k: "$_id.userId",
          v: "$bountyAmount"
        }
      }
    }
  },
  {
    $project: {
      _id: 1,
      channelId: 1,
      emotes: {
        $arrayToObject: "$emotes"
      },
      bounties: {
        $arrayToObject: "$bounties"
      },

    }
  }
])

MongoPlayground


问:
TextView using Spannable - ellipsize doesn't work
The issue I'm trying to fix is the following: I'm having a TextView and I'm using a Spannable to set some characters bold.
The text needs to have a maxim of 2 lines ( android:maxLines="2") and I want the text to be ellipsized, but for some reason I cannot make the text ellipsized.

Here is the simple code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <TextView android:id="@+id/name"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:gravity="center"
              android:maxLines="2"
              android:ellipsize="end"
              android:bufferType="spannable"
              android:text="@string/app_name"
              android:textSize="15dp"/>

</LinearLayout>
</code>```

and the activity:

```<code>public class MyActivity extends Activity {

    private TextView name;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        name= (TextView) findViewById(R.id.name);

        name.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy ");
        Spannable spannable = (Spannable)name.getText();
        StyleSpan boldSpan = new StyleSpan( Typeface.BOLD );
        spannable.setSpan( boldSpan, 10, 15, Spannable.SPAN_INCLUSIVE_INCLUSIVE );

    }
}
</code>```

The text is truncated, no "..." are displayed.

答:
```<code>@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (maxLength < 0) {
        Layout layout = getLayout();
        if (layout.getLineCount() > getMaxLines()) {
            maxLength = layout.getLineVisibleEnd(getMaxLines() - 1) - 1;
            setSpannableString();
        }
    }
}
</code>```

The "setSpannableString()" shows below:

```<code>private void setSpannableString() {
    // ShowString is real visible string. FullString is original string which
    // is useful when caching and calculating.
    String showString = fullString;
    if (maxLength > 0) {
        showString = fullString.substring(0, maxLength) + THREE_DOTS;
    }
    SpannableStringBuilder builder = new SpannableStringBuilder(showString);
    for (int i = 0; i < mHighLightColor.size(); i++) {
        String highLightString = mHighLightString.get(i);
        int color = mHighLightColor.get(i);
        int start = fullString.indexOf(highLightString);
        int end = Math.min(start + highLightString.length(), showString.length());
        if (mClickableSpanList.get(i) != null) {
            builder.setSpan(mClickableSpanList.get(i), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            setMovementMethod(LinkMovementMethod.getInstance());
        }
        builder.setSpan(new ColorBoldSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    setText(builder, BufferType.SPANNABLE);
}
</code>```

Body:
The issue I'm trying to fix is the following: I'm having a TextView and I'm using a Spannable to set some characters bold.
The text needs to have a maxim of 2 lines ( android:maxLines="2") and I want the text to be ellipsized, but for some reason I cannot make the text ellipsized.

Here is the simple code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <TextView android:id="@+id/name"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:gravity="center"
              android:maxLines="2"
              android:ellipsize="end"
              android:bufferType="spannable"
              android:text="@string/app_name"
              android:textSize="15dp"/>

</LinearLayout>

and the activity:

public class MyActivity extends Activity {

    private TextView name;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        name= (TextView) findViewById(R.id.name);

        name.setText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy ");
        Spannable spannable = (Spannable)name.getText();
        StyleSpan boldSpan = new StyleSpan( Typeface.BOLD );
        spannable.setSpan( boldSpan, 10, 15, Spannable.SPAN_INCLUSIVE_INCLUSIVE );

    }
}

The text is truncated, no "..." are displayed.

Body:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    if (maxLength < 0) {
        Layout layout = getLayout();
        if (layout.getLineCount() > getMaxLines()) {
            maxLength = layout.getLineVisibleEnd(getMaxLines() - 1) - 1;
            setSpannableString();
        }
    }
}

The "setSpannableString()" shows below:

private void setSpannableString() {
    // ShowString is real visible string. FullString is original string which
    // is useful when caching and calculating.
    String showString = fullString;
    if (maxLength > 0) {
        showString = fullString.substring(0, maxLength) + THREE_DOTS;
    }
    SpannableStringBuilder builder = new SpannableStringBuilder(showString);
    for (int i = 0; i < mHighLightColor.size(); i++) {
        String highLightString = mHighLightString.get(i);
        int color = mHighLightColor.get(i);
        int start = fullString.indexOf(highLightString);
        int end = Math.min(start + highLightString.length(), showString.length());
        if (mClickableSpanList.get(i) != null) {
            builder.setSpan(mClickableSpanList.get(i), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            setMovementMethod(LinkMovementMethod.getInstance());
        }
        builder.setSpan(new ColorBoldSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    setText(builder, BufferType.SPANNABLE);
}


问:
Why shutil move not working if folder exist
I have the following code:

```<code>archive = "archive"
if not os.path.exists(archive):
    os.mkdir(archive)
gzfile = "lalala.gz"
dest = join(archive, gzfile)
shutil.move(gzfile, dest)
</code>```

And is behaving quite strange.
Shutil.move works when the directoy does not exist --> thats mean my script create the folder (in current directoy) and move the gzfile to archive. But when the directoy exist (because i ran my script one time already) shutil.move does not move gzfile to the archive folder. Why the diference in behaviour here

答:
This works for me in all scenarios, but you have to change your join function to use the os.path join function

```<code>import shutil, os

archive = "archive"
if not os.path.exists(archive):
    os.mkdir(archive)
gzfile = "lalala.gz"
dest = os.path.join(archive, gzfile) # add os.path.join()
shutil.move(gzfile, dest)
</code>```

Also, be sure to recreate the "lalala.gz" file after you have executed the script. It won't move it if it's not there

Body:
I have the following code:

archive = "archive"
if not os.path.exists(archive):
    os.mkdir(archive)
gzfile = "lalala.gz"
dest = join(archive, gzfile)
shutil.move(gzfile, dest)

And is behaving quite strange.
Shutil.move works when the directoy does not exist --> thats mean my script create the folder (in current directoy) and move the gzfile to archive. But when the directoy exist (because i ran my script one time already) shutil.move does not move gzfile to the archive folder. Why the diference in behaviour here

Body:
This works for me in all scenarios, but you have to change your join function to use the os.path join function

import shutil, os

archive = "archive"
if not os.path.exists(archive):
    os.mkdir(archive)
gzfile = "lalala.gz"
dest = os.path.join(archive, gzfile) # add os.path.join()
shutil.move(gzfile, dest)

Also, be sure to recreate the "lalala.gz" file after you have executed the script. It won't move it if it's not there


问:
R - How to find closest neighbours from dissimilarity matrix?
I have a dissimilarity matrix (gower.dist) and now I would like to find the closest n neighbours to a certain datapoint (e.g. row number 50). Can anyone help me?

Sample Data
https://towardsdatascience.com/hierarchical-clustering-on-categorical-data-in-r-a27e578f2995

```<code>#----- Dummy Data -----#
library(dplyr)
set.seed(40)
id.s <- c(1:200) %>%
        factor()
budget.s <- sample(c("small", "med", "large"), 200, replace = T) %>%
            factor(levels=c("small", "med", "large"),
            ordered = TRUE)
origins.s <- sample(c("x", "y", "z"), 200, replace = T,
             prob = c(0.7, 0.15, 0.15))
area.s <- sample(c("area1", "area2", "area3", "area4"), 200,
          replace = T,
          prob = c(0.3, 0.1, 0.5, 0.2))
source.s <- sample(c("facebook", "email", "link", "app"), 200,
            replace = T,
            prob = c(0.1,0.2, 0.3, 0.4))
dow.s <- sample(c("mon", "tue", "wed", "thu", "fri", "sat", "sun"), 200, replace = T,
         prob = c(0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2)) %>%
         factor(levels=c("mon", "tue", "wed", "thu", "fri", "sat", "sun"),
        ordered = TRUE)
dish.s <- sample(c("delicious", "the one you don't like", "pizza"), 200, replace = T)

synthetic.customers <- data.frame(id.s, budget.s, origins.s, area.s, source.s, dow.s, dish.s)

#----- Dissimilarity Matrix -----#
library(cluster)
# to perform different types of hierarchical clustering
# package functions used: daisy(), diana(), clusplot()
gower.dist <- daisy(synthetic.customers[ ,2:7], metric = c("gower"))
</code>```

答:
Assuming you want the 5 closest neighbors to datapoint 50:

```<code>row_number <- 50
n <- 5

dists <- unname(as.matrix(gower.dist)[row_number,])
order(dists)[1:n]

# 50  83 112  60  75
</code>```

Indeed, number 50 is closest to itself, and the rest are the 4 next closest values.

The "trick" is to convert your object to a matrix, extract the row you're interested in, and use the base R order function to find the indices of the smallest values in that row.

Body:
I have a dissimilarity matrix (gower.dist) and now I would like to find the closest n neighbours to a certain datapoint (e.g. row number 50). Can anyone help me?

Sample Data
https://towardsdatascience.com/hierarchical-clustering-on-categorical-data-in-r-a27e578f2995

#----- Dummy Data -----#
library(dplyr)
set.seed(40)
id.s <- c(1:200) %>%
        factor()
budget.s <- sample(c("small", "med", "large"), 200, replace = T) %>%
            factor(levels=c("small", "med", "large"),
            ordered = TRUE)
origins.s <- sample(c("x", "y", "z"), 200, replace = T,
             prob = c(0.7, 0.15, 0.15))
area.s <- sample(c("area1", "area2", "area3", "area4"), 200,
          replace = T,
          prob = c(0.3, 0.1, 0.5, 0.2))
source.s <- sample(c("facebook", "email", "link", "app"), 200,
            replace = T,
            prob = c(0.1,0.2, 0.3, 0.4))
dow.s <- sample(c("mon", "tue", "wed", "thu", "fri", "sat", "sun"), 200, replace = T,
         prob = c(0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2)) %>%
         factor(levels=c("mon", "tue", "wed", "thu", "fri", "sat", "sun"),
        ordered = TRUE)
dish.s <- sample(c("delicious", "the one you don't like", "pizza"), 200, replace = T)

synthetic.customers <- data.frame(id.s, budget.s, origins.s, area.s, source.s, dow.s, dish.s)

#----- Dissimilarity Matrix -----#
library(cluster)
# to perform different types of hierarchical clustering
# package functions used: daisy(), diana(), clusplot()
gower.dist <- daisy(synthetic.customers[ ,2:7], metric = c("gower"))

Body:
Assuming you want the 5 closest neighbors to datapoint 50:

row_number <- 50
n <- 5

dists <- unname(as.matrix(gower.dist)[row_number,])
order(dists)[1:n]

# 50  83 112  60  75

Indeed, number 50 is closest to itself, and the rest are the 4 next closest values.

The "trick" is to convert your object to a matrix, extract the row you're interested in, and use the base R order function to find the indices of the smallest values in that row.


问:
missing .net framework 2.0 for svc
In my IIS 7.0, it only has svc-ISAP-4.0_32bit, svc-ISAP-4.0_64bit, and svc-integrated-4.0.

Missing the 2.0. How can I add this?

System info:

IIS7

Win 7 ultimate

VS 2008 Prof

答:
You can try these questions answers HTTP 404 when accessing .svc file in IIS.

In short the problem is that IIS ASP.net and what not was installed after installing Visual Studio not before and the mappins don't get registered.

What solved it for me is running:

```<code>C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe -i
</code>```

ContentLicense: CC BY-SA 2.5

Title: missing .net framework 2.0 for svc

Body:
You can try these questions answers HTTP 404 when accessing .svc file in IIS.

In short the problem is that IIS ASP.net and what not was installed after installing Visual Studio not before and the mappins don't get registered.

What solved it for me is running:

C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe -i


问:
Benefits of using an abstract classes vs. regular class
I have decided to start doing small coding projects on my own that focus on code quality instead of code quantity and have a question about the use of abstract classes.

Now I know the differences between abstract classes and interfaces with the biggest one (I think) being that interface allow you to only define methods that need to be implemented by classes using the interface and abstract classes allowing you to define both method and members along with default method implementation if you so desire.  My question is what the the main benefit of use an abstract class vs a normal class?  The only real difference between the two that I can think of is that you can not create an instance of an abstract class.  Are there any other differences between the two?

答: In automotive manufacturing terms, an Interface is a spec sheet for a "car" which says it has four wheels, five seats, an engine, etc, while an Abstract Class is a partially assembled car in a crate that you have to finish off to your own requirements. E.g. Subaru uses the same exact chassis for the Impreza, Forester and XV/Crosstrek. So the chassis is the "abstract class" which has common features and functions but isn't a "car" yet. The body and interior MUST be added after the fact before you can say you've built a car. The engine is also common among all three, though you can choose to swap it out for a turbocharged version IF you wish.</p>


问:
Compiling Java program in terminal causes log error
I am trying to compile a Java program in the terminal:

Long version containing all the imports:

```<code>javac -classpath bin:$OSPL_HOME/jar/dcpssaj5.jar:$OSPL_HOME/jar/dcpssaj5-sources.jar:$OSPL_HOME/jar/dcpssaj-osgi-bundle.jar:$OSPL_HOME/jar/dcpssaj-sources.jar:$OSPL_HOME/jar/dcpssaj.jar:$OSPL_HOME/jar/osplconf.jar:$OSPL_HOME/jar/tooling_common.jar:$OSPL_HOME/jar/dcpsprotobuf.jar:$OSPL_HOME/jar/cmdataadapter.jar:$OSPL_HOME/jar/cmapi.jar:$OSPL_HOME/jar/ddsface.jar:Libraries/httpclient-4.5.12.jar:Libraries/jersey-client-1.19.4.jar:Libraries/jersey-client-1.19.jar:Libraries/jersey-core-1.19.4.jar:Libraries/json-simple-1.1.1.jar:Libraries/json-simple-3.1.0.jar:Libraries/jsr311-api-1.1.1.jar:Libraries/mqtt-client-0.0.6.jar:Libraries/paho-mqtt-client-1.13.0.jar -sourcepath src/ src/afarcloud/Main/afarcloud_main.java
</code>```

Without all the imports:

```<code>javac -classpath bin:(jar_files) -sourcepath src/ src/afarcloud/Main/afarcloud_main.java
</code>```

I have added what I thought would be all the necessaries jars, however I get the following error related to a logger when I try to run the code on my Ubuntu computer:

```<code>src/afarcloud/Log/UtilLog.java:3: error: package org.apache.log4j does not exist
import org.apache.log4j.Logger;
                       ^
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                   ^
  symbol:   class Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                                ^
  symbol:   variable Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:10: error: cannot find symbol
        log = Logger.getLogger(clase);
              ^
  symbol:   variable Logger
  location: class UtilLog
4 errors
</code>```

What confuses me is that there is no folder called "Log" under src/afarcloud, so I am pretty confused about how to proceed... Any help is highly appreciated, thank you.

答:
You're missing JAR dependency on org.apache.log4j.

Of course, this JAR can have further dependencies. This can be endless game. Perhaps you can use Maven and mavenized project, which will take care of dependency tree for you.

Body:
I am trying to compile a Java program in the terminal:

Long version containing all the imports:

javac -classpath bin:$OSPL_HOME/jar/dcpssaj5.jar:$OSPL_HOME/jar/dcpssaj5-sources.jar:$OSPL_HOME/jar/dcpssaj-osgi-bundle.jar:$OSPL_HOME/jar/dcpssaj-sources.jar:$OSPL_HOME/jar/dcpssaj.jar:$OSPL_HOME/jar/osplconf.jar:$OSPL_HOME/jar/tooling_common.jar:$OSPL_HOME/jar/dcpsprotobuf.jar:$OSPL_HOME/jar/cmdataadapter.jar:$OSPL_HOME/jar/cmapi.jar:$OSPL_HOME/jar/ddsface.jar:Libraries/httpclient-4.5.12.jar:Libraries/jersey-client-1.19.4.jar:Libraries/jersey-client-1.19.jar:Libraries/jersey-core-1.19.4.jar:Libraries/json-simple-1.1.1.jar:Libraries/json-simple-3.1.0.jar:Libraries/jsr311-api-1.1.1.jar:Libraries/mqtt-client-0.0.6.jar:Libraries/paho-mqtt-client-1.13.0.jar -sourcepath src/ src/afarcloud/Main/afarcloud_main.java

Without all the imports:

javac -classpath bin:(jar_files) -sourcepath src/ src/afarcloud/Main/afarcloud_main.java

I have added what I thought would be all the necessaries jars, however I get the following error related to a logger when I try to run the code on my Ubuntu computer:

src/afarcloud/Log/UtilLog.java:3: error: package org.apache.log4j does not exist
import org.apache.log4j.Logger;
                       ^
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                   ^
  symbol:   class Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:7: error: cannot find symbol
    private static Logger log = Logger.getLogger(UtilLog.class);
                                ^
  symbol:   variable Logger
  location: class UtilLog
src/afarcloud/Log/UtilLog.java:10: error: cannot find symbol
        log = Logger.getLogger(clase);
              ^
  symbol:   variable Logger
  location: class UtilLog
4 errors

What confuses me is that there is no folder called "Log" under src/afarcloud, so I am pretty confused about how to proceed... Any help is highly appreciated, thank you.


问:
NGXS: Testing an action
I'm very new to angular & ngxs and I'm coding a small message-service giving the opportunity to send & receive Messages through an ngxs store connected to firebase.

I'm trying to write a test for the method to send messages. As I'm not really getting along with the official ngxs documentation for testing, I'm having some issues with that.

So my current (not working) attempt for that test is:

```<code>describe('SendMessage', () => {
    let store: Store;
    let testData: Message = {
    author: 'testauthor',
    text: 'testtext'
};

    beforeEach(async(() => {

        TestBed.configureTestingModule({
        imports: [NgxsModule.forRoot([MessageState]),
            NgxsModule.forRoot([AngularFirestore])],
        }).compileComponents();

        store = TestBed.get(Store);
        store.reset(TEST_STATE);
     }));

    it('sends Messages', async(() => {
        store.dispatch(new fromMessage.AddMessage(testData));
        store.selectOnce(state => MessageState.getSentMessages).subscribe(message => {
           expect(message).toEqual(testData);
    })
   }))
});
</code>```

With TEST_STATE being

```<code>export const TEST_STATE = {
    messages: [{
    author: 'testauthor',
    text: 'testtext'
    }]
}
</code>```

Running the test, I get the error Failed: States must be decorated with @State() decorator.

How can I use the TEST_STATE correctly as my state for testing AddMessage? How should my dispatches and selects look like?

As I said, I am a newbie to ngxs and testing, so sorry if my Code is not so good.
Thanks for your help!

答:
There are two lines in your testbed's imports statement that might produce the error Failed: States must be decorated with @State() decorator:

NgxsModule.forRoot([MessageState]) and

NgxsModule.forRoot([AngularFirestore])

Please double check if the classes MessageState and  AngularFirestore are decorated with @State().

Title: NGXS: Testing an action

Body:
I'm very new to angular & ngxs and I'm coding a small message-service giving the opportunity to send & receive Messages through an ngxs store connected to firebase.

I'm trying to write a test for the method to send messages. As I'm not really getting along with the official ngxs documentation for testing, I'm having some issues with that.

So my current (not working) attempt for that test is:

describe('SendMessage', () => {
    let store: Store;
    let testData: Message = {
    author: 'testauthor',
    text: 'testtext'
};

    beforeEach(async(() => {

        TestBed.configureTestingModule({
        imports: [NgxsModule.forRoot([MessageState]),
            NgxsModule.forRoot([AngularFirestore])],
        }).compileComponents();

        store = TestBed.get(Store);
        store.reset(TEST_STATE);
     }));

    it('sends Messages', async(() => {
        store.dispatch(new fromMessage.AddMessage(testData));
        store.selectOnce(state => MessageState.getSentMessages).subscribe(message => {
           expect(message).toEqual(testData);
    })
   }))
});

With TEST_STATE being

export const TEST_STATE = {
    messages: [{
    author: 'testauthor',
    text: 'testtext'
    }]
}

Running the test, I get the error Failed: States must be decorated with @State() decorator.

How can I use the TEST_STATE correctly as my state for testing AddMessage? How should my dispatches and selects look like?

As I said, I am a newbie to ngxs and testing, so sorry if my Code is not so good.
Thanks for your help!


答:
For more than one link you need</p>

```<code>let store;
document.addEventListener('click', function(e) {
  const tgt = e.target;
  const photo = tgt.classList.contains('photo');
  const foo   = tgt.classList.contains('foo');
  if (foo || photo) {
    tgt.classList.toggle("foo",photo);
    tgt.classList.toggle("photo",foo);
    store = [...document.querySelectorAll(".foo").map(ele => ele.id)
    localStorage.setItem('store',JSON.stringify(store));
  }
});
window.addEventListener("load",function() {
  store = JSON.parse(localStorage.getItem('store')) || [];
  store.forEach(id => {
    const ele = document.getElementById(id);
    ele.classList.add("foo");
    ele.classList.remove("photo");
  });
})
</code>```

Title: Add and remove to Local Storage

Body:
i'm creating a list with add to favorite link.
I want to store the 'foo' value on local storage using pure JS. Then once I click again it is remove.
Maybe I can not bind the identifier to the style name.
I wanted to repeat the way it is here https://jsfiddle.net/farhadB/ocgcejg2/ , but I can’t.

document.addEventListener('click', function(e) {
  if (e.target && e.target.classList.contains('photo')) {
    e.target.classList = "foo";
  } else if (e.target && e.target.classList.contains('foo')) {
    e.target.classList = "photo";
  }
});

Body:
For more than one link you need

let store;
document.addEventListener('click', function(e) {
  const tgt = e.target;
  const photo = tgt.classList.contains('photo');
  const foo   = tgt.classList.contains('foo');
  if (foo || photo) {
    tgt.classList.toggle("foo",photo);
    tgt.classList.toggle("photo",foo);
    store = [...document.querySelectorAll(".foo").map(ele => ele.id)
    localStorage.setItem('store',JSON.stringify(store));
  }
});
window.addEventListener("load",function() {
  store = JSON.parse(localStorage.getItem('store')) || [];
  store.forEach(id => {
    const ele = document.getElementById(id);
    ele.classList.add("foo");
    ele.classList.remove("photo");
  });
})


问:
How to use .svg in iPad application?
I am creating iPad application for showing shops in shopping mall as arial view, the application landed with normal size image. When do pinching or zoom in, to expand and show row wise shops, more zooming, it need to show shop wise and click on the shop and show information about the shop and what shop is this. How should i use svg format in this application and how to get the coordinates clicked area. Please help me out to done app? or give any other solution like whether the app may be native or web?</p>

答:
For the SVG, use a UIWebView... see this article

For the touch events you can use a Javascript framework such as jQueryTouch in coordination with the SVG.

As an alternative, check out RaphaelJS... really nice and works perfectly with iOS.

Title: How to use .svg in iPad application?


问:
Sum REGEXP_SUBSTR resulting ORA-01722: invalid number error
I'm creating a reconciliation report where I basically just want to know document value of each sent batch.

Batch ID is in its own column and sent data is in one column and it's comma separated, see randomly generated example below:

```<code>002;BATCH12345;999;TEST;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;100,00;100,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;
002;BATCH12345;999;TEST2;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;250,00;250,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;
</code>```

Each batch have minimum 2 rows and max can be 2000 rows. In this table I have two columns: Batch ID and Data

I need to sum all the document amounts together so in this case 100 + 200.

Currently I'm trying to get the job done with this query:

```<code>SELECT batch_id, SUM(to_number(REGEXP_SUBSTR(data, '[^;]+', 1, 16)))
FROM table
GROUP BY batch_id
</code>```

But end up with error ORA-01722: invalid number

Thanks in advance and I really appreciate the help I always receive from this site

Body:
I'm creating a reconciliation report where I basically just want to know document value of each sent batch.

Batch ID is in its own column and sent data is in one column and it's comma separated, see randomly generated example below:

002;BATCH12345;999;TEST;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;100,00;100,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;
002;BATCH12345;999;TEST2;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;250,00;250,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;

Each batch have minimum 2 rows and max can be 2000 rows. In this table I have two columns: Batch ID and Data

I need to sum all the document amounts together so in this case 100 + 200.

Currently I'm trying to get the job done with this query:

SELECT batch_id, SUM(to_number(REGEXP_SUBSTR(data, '[^;]+', 1, 16)))
FROM table
GROUP BY batch_id

But end up with error ORA-01722: invalid number

Thanks in advance and I really appreciate the help I always receive from this site

Body:
Here, Your data is generated like this:

SQL> select REGEXP_SUBSTR('002;BATCH12345;999;TEST;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;100,00;100,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;', '[^;]+', 1, 16) from dual;

REGEXP
------
100,00

SQL> select REGEXP_SUBSTR('002;BATCH12345;999;TEST2;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;250,00;250,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;', '[^;]+', 1, 16) from dual;

REGEXP
------
250,00

SQL>

Means , is considered as a decimal character in your string.

Let me check with the NLS_NUMERIC_CHARACTERS = '.,' (decimal_character group_separator)

SQL> alter session set NLS_NUMERIC_CHARACTERS = '.,';

Session altered.

SQL> WITH YOUR_DATA(STR) AS
  2  (
  3  SELECT '002;BATCH12345;999;TEST;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;100,00;100,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;' FROM DUAL
  4  UNION ALL
  5  SELECT '002;BATCH12345;999;TEST2;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;250,00;250,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;' FROM DUAL
  6  )
  7  select SUM(to_number(REGEXP_SUBSTR(STR, '[^;]+', 1, 16))) from YOUR_DATA;
select SUM(to_number(REGEXP_SUBSTR(STR, '[^;]+', 1, 16))) from YOUR_DATA
                     *
ERROR at line 7:
ORA-01722: invalid number

SQL>

Ohh!! I am getting the same error. So You need to use ,. as your NLS_NUMERIC_CHARACTERS parameter.

You can set it in your session and get the correct data as follows:

SQL> alter session set NLS_NUMERIC_CHARACTERS = ',.';

Session altered.
SQL>
SQL> WITH YOUR_DATA(STR) AS
  2  (
  3  SELECT '002;BATCH12345;999;TEST;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;100,00;100,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;' FROM DUAL
  4  UNION ALL
  5  SELECT '002;BATCH12345;999;TEST2;123940;9999;14052020;1234;123456789;123456;;;;;;FI;;;;;;1234567;;EUR;SPOT;10000000;;250,00;250,00;;Voucher Text;;;;;;;;;;;;;15052020;E;E;E;E;' FROM DUAL
  6  )
  7  select SUM(to_number(REGEXP_SUBSTR(STR, '[^;]+', 1, 16))) from YOUR_DATA;

SUM(TO_NUMBER(REGEXP_SUBSTR(STR,'[^;]+',1,16)))
-----------------------------------------------
                                            350

SQL>

You can learn more about NLS_NUMERIC_CHARACTERS from oracle documentation.

For checking the current setting of this NLS parameter, You can use the following query:

SELECT *
  FROM NLS_SESSION_PARAMETERS
 WHERE PARAMETER = 'NLS_NUMERIC_CHARACTERS';


问:
Bottom align not working in ConstraintLayout with different ImageView sizes
I want some different sized ImageViews in ConstraintLayout to have the same bottom line.

The smaller picture has the size: 100x140:

The larger picture has the size: 206x316:

With the xml layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#8E8392">

    <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/jbean"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/p2"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/p1"/>

    <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/jellybig"
            app:layout_constraintStart_toEndOf="@id/p1"
            app:layout_constraintEnd_toStartOf="@+id/p3"
            app:layout_constraintBottom_toBottomOf="@id/p1"
            android:id="@+id/p2"
    />

    <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/jellybig"
            app:layout_constraintStart_toEndOf="@id/p2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="@id/p2"
            android:id="@+id/p3"
    />

</android.support.constraint.ConstraintLayout>
</code>```

However it looks weird, as follows:

Update:
According to Tamir Abutbul's answer, I've updated the layout to:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#8E8392">

    <ImageView
            android:layout_width="0dp"
            app:layout_constraintWidth_percent="0.3"
            app:layout_constraintHeight_percent="0.99"
            android:layout_height="0dp"
            android:src="@drawable/jbean"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/p2"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/p1"/>

    <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintWidth_percent="0.3"
            app:layout_constraintHeight_percent="0.99"
            android:src="@drawable/jellybig"
            app:layout_constraintStart_toEndOf="@id/p1"
            app:layout_constraintEnd_toStartOf="@+id/p3"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/p2"
    />

    <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintWidth_percent="0.3"
            app:layout_constraintHeight_percent="0.99"
            android:src="@drawable/jellybig"
            app:layout_constraintStart_toEndOf="@id/p2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/p3"
    />

</android.support.constraint.ConstraintLayout>
</code>```

Which I think it couldn't work as expected.

答: I had a similar problem with an imageview that was constrained to the parents bottom but still showed some kind of margin. The solution was to add android:adjustViewBounds="true"</p>

Body:
I want some different sized ImageViews in ConstraintLayout to have the same bottom line.

The smaller picture has the size: 100x140:

The larger picture has the size: 206x316:

With the xml layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#8E8392">

    <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/jbean"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/p2"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/p1"/>

    <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/jellybig"
            app:layout_constraintStart_toEndOf="@id/p1"
            app:layout_constraintEnd_toStartOf="@+id/p3"
            app:layout_constraintBottom_toBottomOf="@id/p1"
            android:id="@+id/p2"
    />

    <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@drawable/jellybig"
            app:layout_constraintStart_toEndOf="@id/p2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="@id/p2"
            android:id="@+id/p3"
    />

</android.support.constraint.ConstraintLayout>

However it looks weird, as follows:

Update:
According to Tamir Abutbul's answer, I've updated the layout to:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="#8E8392">

    <ImageView
            android:layout_width="0dp"
            app:layout_constraintWidth_percent="0.3"
            app:layout_constraintHeight_percent="0.99"
            android:layout_height="0dp"
            android:src="@drawable/jbean"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/p2"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/p1"/>

    <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintWidth_percent="0.3"
            app:layout_constraintHeight_percent="0.99"
            android:src="@drawable/jellybig"
            app:layout_constraintStart_toEndOf="@id/p1"
            app:layout_constraintEnd_toStartOf="@+id/p3"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/p2"
    />

    <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintWidth_percent="0.3"
            app:layout_constraintHeight_percent="0.99"
            android:src="@drawable/jellybig"
            app:layout_constraintStart_toEndOf="@id/p2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:id="@+id/p3"
    />

</android.support.constraint.ConstraintLayout>

Which I think it couldn't work as expected.


问:
How to get all form input values using blur event in `addEventListener`?
I am trying to get form values dynamically using addEventListener but I am just getting first input, not getting other inputs.

This is my current code:

$(document).ready(
  function() {
    const user_input = document.querySelector('input[type="text"], input[type="password"]');

    user_input.addEventListener(
      'blur',
      function(event) {
        var target = event.target;

        if (target.name == "first_name") {
          console.log('first name : ' + target.value);
        }

        if (target.name == "mid_name") {
          console.log('mid name : ' + target.value);
        }

        if (target.name == "last_name") {
          console.log('last name : ' + target.value);
        }

        if (target.name == "password") {
          console.log('password : ' + target.value);
        }
      }
    );
  }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  first_name : <input type="text" name="first_name" value=""> <br>
  mid_name : <input type="text" name="mid_name" value=""> <br>
  last_name : <input type="text" name="last_name" value=""> <br>
  password : <input type="password" name="password" value=""> <br>
</form></code>```

Demo on JSFiddle

I can just get the fist name value; for the other inputs I am not getting anything. Any idea what I am doing wrong?

答:
To achieve what you expect you have to change two parts in your code.

The first thing to change is to use the querySelectorAll instead of the querySelector. The difference is that the querySelector selects only one element at a time, while the querySelectorAll selects all the elements matching the selectors.

The second thing you have to change is to apply the addEventListener to any element in the array as they are different components and have different events to listen to.

Here is the running code: https://jsfiddle.net/9jo1snuq/1/

I hope this helps :)

```<code>$( document ).ready( function() {
    const user_input = document.querySelectorAll('input[type="text"], input[type="password"]');

    user_input.forEach(
        function(userInput) {
            userInput.addEventListener(
                'blur',
                function ( event ) {
                    var target = event.target;

                    if( target.name == "first_name" ) {
                        console.log( 'first name : ' + target.value );
                    }

                    if ( target.name == "mid_name" ) {
                        console.log( 'mid name : ' + target.value );
                    }

                    if ( target.name == "last_name" ) {
                        console.log( 'last name : ' + target.value );
                    }

                    if ( target.name == "password" ) {
                        console.log( 'password : ' + target.value );
                    }

                }
            );
        }
    );

});
</code>```

Body:
I am trying to get form values dynamically using addEventListener but I am just getting first input, not getting other inputs.

This is my current code:

$(document).ready(
  function() {
    const user_input = document.querySelector('input[type="text"], input[type="password"]');

    user_input.addEventListener(
      'blur',
      function(event) {
        var target = event.target;

        if (target.name == "first_name") {
          console.log('first name : ' + target.value);
        }

        if (target.name == "mid_name") {
          console.log('mid name : ' + target.value);
        }

        if (target.name == "last_name") {
          console.log('last name : ' + target.value);
        }

        if (target.name == "password") {
          console.log('password : ' + target.value);
        }
      }
    );
  }
);

<form>
  first_name : <input type="text" name="first_name" value="">

  mid_name : <input type="text" name="mid_name" value="">

  last_name : <input type="text" name="last_name" value="">

  password : <input type="password" name="password" value="">

</form>

Demo on JSFiddle

I can just get the fist name value; for the other inputs I am not getting anything. Any idea what I am doing wrong?

Body:
To achieve what you expect you have to change two parts in your code.

The first thing to change is to use the querySelectorAll instead of the querySelector. The difference is that the querySelector selects only one element at a time, while the querySelectorAll selects all the elements matching the selectors.

The second thing you have to change is to apply the addEventListener to any element in the array as they are different components and have different events to listen to.

Here is the running code: https://jsfiddle.net/9jo1snuq/1/

I hope this helps :)

$( document ).ready( function() {
    const user_input = document.querySelectorAll('input[type="text"], input[type="password"]');

    user_input.forEach(
        function(userInput) {
            userInput.addEventListener(
                'blur',
                function ( event ) {
                    var target = event.target;

                    if( target.name == "first_name" ) {
                        console.log( 'first name : ' + target.value );
                    }

                    if ( target.name == "mid_name" ) {
                        console.log( 'mid name : ' + target.value );
                    }

                    if ( target.name == "last_name" ) {
                        console.log( 'last name : ' + target.value );
                    }

                    if ( target.name == "password" ) {
                        console.log( 'password : ' + target.value );
                    }

                }
            );
        }
    );

});