问:
Read or open a file using "fuzzy match" filename - Python
Given a list of files in a directory:

```<code>import os
os.listdir('system-outputs/newstest2016/ru-en')
</code>```

[out]:

```<code>['newstest2016.AFRL-MITLL-contrast.4524.ru-en',
 'newstest2016.AFRL-MITLL-Phrase.4383.ru-en',
 'newstest2016.AMU-UEDIN.4458.ru-en',
 'newstest2016.NRC.4456.ru-en',
 'newstest2016.online-A.0.ru-en',
 'newstest2016.online-B.0.ru-en',
 'newstest2016.online-F.0.ru-en',
 'newstest2016.online-G.0.ru-en',
 'newstest2016.PROMT-Rule-based.4277.ru-en',
 'newstest2016.uedin-nmt.4309.ru-en']
</code>```

And then I have the input:

```<code>filename, suffix = 'newstest2016.AFRL-MITLL-contrast', 'ru-en'
</code>```

Using the filename, if I want to do a regex match such that I can read the file newstest2016.AFRL-MITLL-contrast.4524.ru-en, I could do:

```<code>import re
fin = open(next(_fn for _fn in os.list('system-outputs/newstest2016/ru-en') if re.match(filename + '.*.' + suffix, _fn) for _fn in))
</code>```

But is there a way to read/open a "fuzzy match" filename? There must be a better way than the crude re.match way above.

It's okay to assume that there should always be one clear match from the os.listdir.

答:
You can use glob as suggested, but it can give several matches. I'd go with the pattern that seems to be:

```<code>filenames = [
    'newstest2016.AFRL-MITLL-contrast.4524.ru-en',
    # ...
    'newstest2016.PROMT-Rule-based.4277.ru-en',
    'newstest2016.uedin-nmt.4309.ru-en'
]
my_filename, suffix = 'newstest2016.AFRL-MITLL-contrast', 'ru-en'
for filename in filenames:
    *fn, suff = filename.split('.')
    if ('.'.join(fn[:-1]), suff) == (my_filename, suffix):
        break
else:
    filename = None
# `filename` is now set to real file name
</code>```

I use python3.x for nicer syntax but this is easy to port to python2.x.

Body:
Given a list of files in a directory:

import os
os.listdir('system-outputs/newstest2016/ru-en')

[out]:

['newstest2016.AFRL-MITLL-contrast.4524.ru-en',
 'newstest2016.AFRL-MITLL-Phrase.4383.ru-en',
 'newstest2016.AMU-UEDIN.4458.ru-en',
 'newstest2016.NRC.4456.ru-en',
 'newstest2016.online-A.0.ru-en',
 'newstest2016.online-B.0.ru-en',
 'newstest2016.online-F.0.ru-en',
 'newstest2016.online-G.0.ru-en',
 'newstest2016.PROMT-Rule-based.4277.ru-en',
 'newstest2016.uedin-nmt.4309.ru-en']

And then I have the input:

filename, suffix = 'newstest2016.AFRL-MITLL-contrast', 'ru-en'

Using the filename, if I want to do a regex match such that I can read the file newstest2016.AFRL-MITLL-contrast.4524.ru-en, I could do:

import re
fin = open(next(_fn for _fn in os.list('system-outputs/newstest2016/ru-en') if re.match(filename + '.*.' + suffix, _fn) for _fn in))

But is there a way to read/open a "fuzzy match" filename? There must be a better way than the crude re.match way above.

It's okay to assume that there should always be one clear match from the os.listdir.

Body:
You can use glob as suggested, but it can give several matches. I'd go with the pattern that seems to be:

filenames = [
    'newstest2016.AFRL-MITLL-contrast.4524.ru-en',
    # ...
    'newstest2016.PROMT-Rule-based.4277.ru-en',
    'newstest2016.uedin-nmt.4309.ru-en'
]
my_filename, suffix = 'newstest2016.AFRL-MITLL-contrast', 'ru-en'
for filename in filenames:
    *fn, suff = filename.split('.')
    if ('.'.join(fn[:-1]), suff) == (my_filename, suffix):
        break
else:
    filename = None
# `filename` is now set to real file name

I use python3.x for nicer syntax but this is easy to port to python2.x.


来源: stackexchange

问:
EntityFramework throws 'Can not start another operation while there is an asynchronous operation pending'
IRepository.cs

```<code>public interface ICommonRepository<T>
    {
        Task<int> CountAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>,IOrderedQueryable<T>> orderBy = null,List<Expression<Func<T, object>>> includes = null);
    }
</code>```

Repository.cs:

```<code>public class Repository<T> : IRepository<T> where T : class, new()
    {
        protected readonly MyDbContext _context;
        protected readonly ILogger<Repository<T>> _logger;
        protected readonly DbSet<T> _dbSet;

        public CommomRepository(MyDbContext context, ILogger<Repository<T>> logger)
        {
            _context = context;
            _logger = logger;

            if (_context != null)
            {
                _dbSet = _context.Set<T>();
            }
            else
            {

            }
        }

        internal IQueryable<T> _Select(Expression<Func<T, bool>> filter = null
                                    , Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null
                                    , List<Expression<Func<T, object>>> includes = null
                                    , int? pageIndex = null
                                    , int? pageSize = null)
        {
            IQueryable<T> query = _dbSet;

            if (includes != null)
            {
                query = includes.Aggregate(query, (current, include) => current.Include(include));
            }

            if (orderBy != null)
            {
                query = orderBy(query);
            }

            if (filter != null)
            {
                query = query.Where(filter);
            }

            if (pageIndex != null && pageSize != null)
            {
                query = query.Skip((pageIndex.Value - 1) * pageSize.Value).Take(pageSize.Value);
            }

            return query;
        }

        public async Task<int> CountAsync(Expression<Func<T, bool>> filter = null
                        , Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null
                        , List<Expression<Func<T, object>>> includes = null)
        {
            var query = _Select(filter, orderBy, includes);
            return await query.CountAsync();
        }
}
</code>```

Usage (controller):

```<code>var singleCheckTask = _Repo.CountAsync(x=> x.id== item.id);
var nameCheckTask = _Repo.CountAsync(x=> x.name== item.name);
var ipCheckTask = _Repo.CountAsync(x=> x.ip == item.ip);
await Task.WhenAll(singleCheckTask, nameCheckTask, ipCheckTask);
</code>```

And exception thowed:

Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory|ERROR|An exception occurred in the database while iterating the results of a query.
  System.InvalidOperationException: Can not start another operation while there is an asynchronous operation pending.

I'vs tested that if I do not use Task.whenAll,  var testSingleCheck = _Repo.CountAsync(x=> x.id== item.id).Result;  This would be all right.

答:
It's simple, you can't run queries in parallel with EF (neither EF6 nor EF Core).

One reasons for is, that EF isn't thread-safe.

EF 6 on Task-based pattern

Thread Safety

While thread safety would make async more useful it is an orthogonal feature. It is unclear that we could ever implement support for it in the most general case, given that EF interacts with a graph composed of user code to maintain state and there aren't easy ways to ensure that this code is also thread safe.

For the moment, EF will detect if the developer attempts to execute two async operations at one time and throw.

ContentLicense: CC BY-SA 3.0

Body:
IRepository.cs

public interface ICommonRepository<T>
    {
        Task<int> CountAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>,IOrderedQueryable<T>> orderBy = null,List<Expression<Func<T, object>>> includes = null);
    }

Repository.cs:

public class Repository<T> : IRepository<T> where T : class, new()
    {
        protected readonly MyDbContext _context;
        protected readonly ILogger<Repository<T>> _logger;
        protected readonly DbSet<T> _dbSet;

        public CommomRepository(MyDbContext context, ILogger<Repository<T>> logger)
        {
            _context = context;
            _logger = logger;

            if (_context != null)
            {
                _dbSet = _context.Set<T>();
            }
            else
            {

            }
        }

        internal IQueryable<T> _Select(Expression<Func<T, bool>> filter = null
                                    , Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null
                                    , List<Expression<Func<T, object>>> includes = null
                                    , int? pageIndex = null
                                    , int? pageSize = null)
        {
            IQueryable<T> query = _dbSet;

            if (includes != null)
            {
                query = includes.Aggregate(query, (current, include) => current.Include(include));
            }

            if (orderBy != null)
            {
                query = orderBy(query);
            }

            if (filter != null)
            {
                query = query.Where(filter);
            }

            if (pageIndex != null && pageSize != null)
            {
                query = query.Skip((pageIndex.Value - 1) * pageSize.Value).Take(pageSize.Value);
            }

            return query;
        }

        public async Task<int> CountAsync(Expression<Func<T, bool>> filter = null
                        , Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null
                        , List<Expression<Func<T, object>>> includes = null)
        {
            var query = _Select(filter, orderBy, includes);
            return await query.CountAsync();
        }
}

Usage (controller):

var singleCheckTask = _Repo.CountAsync(x=> x.id== item.id);
var nameCheckTask = _Repo.CountAsync(x=> x.name== item.name);
var ipCheckTask = _Repo.CountAsync(x=> x.ip == item.ip);
await Task.WhenAll(singleCheckTask, nameCheckTask, ipCheckTask);

And exception thowed:

Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory|ERROR|An exception occurred in the database while iterating the results of a query.
  System.InvalidOperationException: Can not start another operation while there is an asynchronous operation pending.

I'vs tested that if I do not use Task.whenAll,  var testSingleCheck = _Repo.CountAsync(x=> x.id== item.id).Result;  This would be all right.


问:
How to solve "failed: Error during WebSocket handshake: Unexpected response code: 200" in spring websockets?
I am trying to subscribe to a particular channel in spring web sockets but while pointing to a URL using SockJs i getting the following error WebSocket connection to 'ws://localhost:8080/Spring/rest/user/chat/045/jmfz3b3j/websocket' failed: Error during WebSocket handshake: Unexpected response code: 200 Please help me to avoid this.
Here is my client side code for subscription.

Index.jsp

var stompClient =null;
      function subscribe(){
var socket = new SockJS('/Spring/rest/user/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
     console.log('Connected: ' + frame);
     stompClient.subscribe('/topic/messages', function(test) {
       alert("in call back function");});
 });
 }```

答:
@Kane This is my websocket configuration in spring-servlet.xml

```<code><websocket:message-broker application-destination-prefix="/app" >
    <websocket:stomp-endpoint path="/chat" allowed-origins="*">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
</code>```

And this is my controller code

```<code>@Controller
@RequestMapping("user")
public class OptnCptController{
    @MessageMapping("topic/messages")
    public String getMsg(String s)
    {
        return s;
    }
}
</code>```

Body:
@Kane This is my websocket configuration in spring-servlet.xml

<websocket:message-broker application-destination-prefix="/app" >
    <websocket:stomp-endpoint path="/chat" allowed-origins="*">
        <websocket:sockjs />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>

And this is my controller code

@Controller
@RequestMapping("user")
public class OptnCptController{
    @MessageMapping("topic/messages")
    public String getMsg(String s)
    {
        return s;
    }
}


问:
Screen Scraping with PHP and XPath
Does anyone know how to maintain text formatting when using XPath to extract data?

I am currently extracting all blocks

title

text anchor

from a page. The problem is when I access the nodeValue, I can only get plain text. How can I capture the contents including formatting, i.e. the h5 and a still in the code?

Thanks in advance. I have searched every combination imaginable on Google and no luck.

答:
The XPath language is designed to be embedded in another language (such as DOM API, XSLT, XQuery, ...) and cannot be used standalone. The original question does not specify what is the desired embedding.

Below is a very simple and short solution when XPath is embedded in XSLT.

This transformation:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="div[@class='info']">
       <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>
</code>```

when applied on this xml document:

```<code><html>
    <body>
        <div class="info">
            <h1>title1</h1> text1
            <a href="somelink1">anchor1</a>
        </div>
        Something else here
        <div class="info">
            <h2>title2</h2> text2
            <a href="somelink2">anchor2</a>
        </div>
        Something else here
        <div class="info">
            <h3>title3</h3> text3
            <a href="somelink3">anchor3</a>
        </div>
    </body>
</html>
</code>```

produces the wanted result:

```<code><div class="info">
  <h1>title1</h1> text1
    <a href="somelink1">anchor1</a>
</div>
        Something else here
<div class="info">
  <h2>title2</h2> text2
  <a href="somelink2">anchor2</a>
</div>
        Something else here
<div class="info">
  <h3>title3</h3> text3
  <a href="somelink3">anchor3</a>
</div>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Screen Scraping with PHP and XPath

Body:
The XPath language is designed to be embedded in another language (such as DOM API, XSLT, XQuery, ...) and cannot be used standalone. The original question does not specify what is the desired embedding.

Below is a very simple and short solution when XPath is embedded in XSLT.

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="div[@class='info']">
       <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>

when applied on this xml document:

<html>
    <body>
        <div class="info">
            <h1>title1</h1> text1
            <a href="somelink1">anchor1</a>
        </div>
        Something else here
        <div class="info">
            <h2>title2</h2> text2
            <a href="somelink2">anchor2</a>
        </div>
        Something else here
        <div class="info">
            <h3>title3</h3> text3
            <a href="somelink3">anchor3</a>
        </div>
    </body>
</html>

produces the wanted result:

<div class="info">
  <h1>title1</h1> text1
    <a href="somelink1">anchor1</a>
</div>
        Something else here
<div class="info">
  <h2>title2</h2> text2
  <a href="somelink2">anchor2</a>
</div>
        Something else here
<div class="info">
  <h3>title3</h3> text3
  <a href="somelink3">anchor3</a>
</div>

OwnerDisplayName: Dimitre Novatchev


问:
ReportViewer 9 in .NET 4 application possible?
I am using ReportViewer 9 in WPF to talk to a remote SSRS server (because I have a SQL Server 2005 Reporting Services requirement) to add reports to a WPF .NET 4.0 application.

I can create a project and run ReportViewer 9 using .NET 3.5, but I cannot (either from not being possible, or my lack or knowledge) get it to run within the WPF .NET 4.0 application.  Ideally, I run the .NET 3.5 piece as a custom or user control within the 4.0 UI, but I am not making any progress with this.

Warning - The referenced assembly "Microsoft.ReportViewer.WinForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" could not be resolved because it has a dependency on "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NET Framework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project.

My next stop is to change the 4.0 application to 3.5, but I would rather not.  Is there a trick to this, or am I chasing my tail on this?

Thanks,
Brian

答: I was able to do this without any issues.  The application is a .net 4.0 application (MVVM pattern) with a SQL Server 2008 backend.  I utilized ReportViewer 9 and am running reports in remote mode using the .rdl.  If you are interested in going back to .net 4.0 and I can be of assistance, let me know.</p>


问:
Pre-processor to remove data

I have a data in flat file, which contains a trailer which needs to be removed. I am trying to create a external table in oracle and this trailer record needs to be removed before processing the file.

What I have noticed about the file is , the trailer always starts with the string "Note:". I tried to write a oracle preprocessor which will remove all the data after encountering the string "Note:". I wrote it using sed but its not working.

Please suggest me how can I remove the trailer from the flat file before creating an external table.

```<code>#!/bin/bash
filename="$1"
/bin/sed -i '/Notes:/Q' "$filename"
</code>```

Above is the sed block i am using.

sample data

    |a| 2| 3| 5

    |f| g| h| d

    |d| f| g| g

    |Notes:

    this is the trailer data i want to remove from the file.

答:
If you want to remove lines with keyword starting with |Notes: then use

```<code>sed -i '/^|Notes:/d' file
</code>```

If you want to delete last line irrespective of Notes: keyword,

```<code>sed -i '$ d' file
</code>```

Suggest you to test both of them outside the script, without -i and once satisfied, plug it in the script. Cheers!

Title: Pre-processor to remove data

Body:
I have a data in flat file, which contains a trailer which needs to be removed. I am trying to create a external table in oracle and this trailer record needs to be removed before processing the file.

What I have noticed about the file is , the trailer always starts with the string "Note:". I tried to write a oracle preprocessor which will remove all the data after encountering the string "Note:". I wrote it using sed but its not working.

Please suggest me how can I remove the trailer from the flat file before creating an external table.

#!/bin/bash
filename="$1"
/bin/sed -i '/Notes:/Q' "$filename"

Above is the sed block i am using.

sample data

    |a| 2| 3| 5

    |f| g| h| d

    |d| f| g| g

    |Notes:

    this is the trailer data i want to remove from the file.

Body:
If you want to remove lines with keyword starting with |Notes: then use

sed -i '/^|Notes:/d' file

If you want to delete last line irrespective of Notes: keyword,

sed -i '$ d' file

Suggest you to test both of them outside the script, without -i and once satisfied, plug it in the script. Cheers!


问:
How to use multiples files for the Meteor server?
I'm trying to split my server in multiples files, and actually I want to make cmdb_login.js  and main.js.

The thing is that I don't know and I don't find how to say in main.js, use cmdb_login.js.

I have tried import './cmdb_login.js';

My app structure is:

If you need the code of the two .js files just ask me.

Thank you for the help

答:
As always, Meteor combines all files eagerly, unless they are placed in a path which includes a folder named imports.

I.e. in your case, your cmdb_login.js will be combined (and then executed) before main.js in the server JavaScript code.

A proper way is to put almost all your files in an imports folder, and explicitly call them in a single main.js file (or whatever its name, provided that it is not in an imports folder), using an import statement like the one you tried (e.g. import './imports/cmdb_login.js').


问:
uploadComplete event of the sap.ui.unified.FileUploader is not fired

Control definition:

<unified:FileUploader width="300px" id="fileUploader" change="documentChanged"
    uploadComplete="handleUploadComplete">
```

<p>Function's definition:</p>

<pre class="lang-js prettyprint-override"><code>handleUploadComplete: function(oEvent) {
    console.log("oUploader complete oEvent----> ",oEvent);
    console.log("oUploader complete oEvent.params----> ",oEvent.getParameters());
}
</code>```

In my upload function:

oUploader.setUploadUrl(sUrl);// url is defined before
oUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
     name: "slug",
     value: encodeURIComponent(oUploader.getValue())
}));
oUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
     name: "x-csrf-token",
     value: this._sToken // defined before
}));
oUploader.setSendXHR(true);
oUploader.upload();
```

The event is just not fired (I have a breakpoint inside the function, and it's not triggered, no console.log messages). The file is uploaded fine.

What do I miss? Thanks.

upd: I'm using sapui5 version 1.28.44 and I'm limitied to this version.

答:
You can try upload collection . It is work for me.
Upload Collection</p>

Body:
Control definition:

<unified:FileUploader width="300px" id="fileUploader" change="documentChanged"
    uploadComplete="handleUploadComplete">

Function's definition:

handleUploadComplete: function(oEvent) {
    console.log("oUploader complete oEvent----> ",oEvent);
    console.log("oUploader complete oEvent.params----> ",oEvent.getParameters());
}

In my upload function:

oUploader.setUploadUrl(sUrl);// url is defined before
oUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
     name: "slug",
     value: encodeURIComponent(oUploader.getValue())
}));
oUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
     name: "x-csrf-token",
     value: this._sToken // defined before
}));
oUploader.setSendXHR(true);
oUploader.upload();

The event is just not fired (I have a breakpoint inside the function, and it's not triggered, no console.log messages). The file is uploaded fine.

What do I miss? Thanks.

upd: I'm using sapui5 version 1.28.44 and I'm limitied to this version.


问:
warning: invalid credential line: [0x7FFEF7EABC10] ANOMALY: meaningless REX prefix used?
I'm following this guide:
https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-sails-cli-nodejs

I'm getting this error when i try to

```<code> git push azure master
</code>```

Error:
warning: invalid credential line: [0x7FFEF7EABC10] ANOMALY: meaningless REX prefix
used?

What is exactly happening?

Thanks,

答:
You can try to create a Web Apps application directly on Azure Portal, and set some configurations on portal and your local project, to instead of the Step 2 of https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-sails-cli-nodejs.

Create a Web Apps application on Azure portal

Modify the user\passwd for your git deployment credential.

Set the Deployment options to Local Git

Configure your local project as Step 3 at https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-sails-cli-nodejs

Deploy to Azure via Git.

It works fine on my side.

Body:
I'm following this guide:
https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-sails-cli-nodejs

I'm getting this error when i try to

 git push azure master

Error:
warning: invalid credential line: [0x7FFEF7EABC10] ANOMALY: meaningless REX prefix
used?

What is exactly happening?

Thanks,


问:
Unfortunately, Simple app is stopped
I'm new to android development and im making a simple calculator app... Whenever i'm running the code in the android emulator it's showing me Unfortunately, SimpleApp has Stopped.... I'm Using Android Studio to write the code Please help me...
Following is my code....

activity_main.xml

```<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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapp.simpleapp.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="337dp"
        android:layout_height="58dp"
        android:contextClickable="false"
        android:cursorVisible="false"
        android:fontFamily="serif"
        android:longClickable="true"
        android:text="Calculator"
        android:textAlignment="center"
        android:textAllCaps="true"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="36sp"
        android:visibility="visible"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="31dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="194dp"
        android:layout_height="43dp"
        android:text="Number 1: "
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="140dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="194dp"
        android:layout_height="44dp"
        android:text="Number 2: "
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="217dp" />

    <EditText
        android:id="@+id/number2"
        android:layout_width="99dp"
        android:layout_height="43dp"
        android:ems="10"
        android:hint="Number 2"
        android:inputType="number|numberSigned|numberDecimal"
        android:singleLine="true"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textIsSelectable="true"
        android:textSize="20sp"
        tools:layout_editor_absoluteX="262dp"
        tools:layout_editor_absoluteY="217dp" />

    <EditText
        android:id="@+id/number1"
        android:layout_width="99dp"
        android:layout_height="43dp"
        android:ems="10"
        android:hint="Number 1"
        android:inputType="number|numberSigned|numberDecimal"
        android:linksClickable="false"
        android:longClickable="true"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="20sp"
        tools:layout_editor_absoluteX="262dp"
        tools:layout_editor_absoluteY="140dp" />

    <TextView
        android:id="@+id/result"
        android:layout_width="175dp"
        android:layout_height="40dp"
        tools:layout_editor_absoluteX="176dp"
        tools:layout_editor_absoluteY="430dp" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="103dp"
        android:layout_height="40dp"
        android:text="Result: "
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="59dp"
        tools:layout_editor_absoluteY="433dp" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="152dp"
        android:layout_height="49dp"
        android:text="+"
        android:textColor="@android:color/black"
        android:textSize="30sp"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="292dp" />

    <Button
        android:id="@+id/btnSub"
        android:layout_width="152dp"
        android:layout_height="49dp"
        android:text="-"
        android:textColor="@android:color/black"
        android:textIsSelectable="false"
        android:textSize="30sp"
        tools:layout_editor_absoluteX="216dp"
        tools:layout_editor_absoluteY="292dp" />

    <Button
        android:id="@+id/btnDiv"
        android:layout_width="152dp"
        android:layout_height="49dp"
        android:text="/"
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="362dp" />

    <Button
        android:id="@+id/btnMul"
        android:layout_width="152dp"
        android:layout_height="49dp"
        android:text="*"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="216dp"
        tools:layout_editor_absoluteY="362dp" />
</android.support.constraint.ConstraintLayout>
</code>```

MainActivity.java

```<code>package com.myapp.simpleapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    EditText number1= (EditText) findViewById(R.id.number1);
    EditText number2= (EditText) findViewById(R.id.number2);

    Button add= (Button) findViewById(R.id.btnAdd);
    Button sub= (Button) findViewById(R.id.btnSub);
    Button div= (Button) findViewById(R.id.btnDiv);
    Button mul= (Button) findViewById(R.id.btnMul);

    TextView txtresult= (TextView) findViewById(R.id.result);

    double num1,num2,result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        num1=Double.parseDouble(number1.getText().toString());
        num2=Double.parseDouble(number2.getText().toString());

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result=num1+num2;

                txtresult.setText(Double.toString(result));
            }
        });

        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result=num1-num2;

                txtresult.setText(Double.toString(result));
            }
        });

        div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result=num1/num2;

                txtresult.setText(Double.toString(result));
            }
        });

        mul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result=num1*num2;

                txtresult.setText(Double.toString(result));
            }
        });

    }
}
</code>```

LogCat

```<code>04-03 12:25:38.913 3927-3927/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-03 12:25:38.913 3927-3927/? E/android.os.Debug: failed to load memtrack module: -2
04-03 12:25:39.372 3952-3952/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-03 12:25:39.373 3952-3952/? E/android.os.Debug: failed to load memtrack module: -2
04-03 12:25:49.078 4097-4097/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-03 12:25:49.078 4097-4097/? E/android.os.Debug: failed to load memtrack module: -2
04-03 12:25:49.647 4122-4122/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-03 12:25:49.648 4122-4122/? E/android.os.Debug: failed to load memtrack module: -2
04-03 12:25:58.059 3666-3666/com.myapp.simpleapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: com.myapp.simpleapp, PID: 3666
                                                                   java.lang.NumberFormatException: Invalid double: ""
                                                                       at java.lang.StringToReal.invalidReal(StringToReal.java:63)
                                                                       at java.lang.StringToReal.parseDouble(StringToReal.java:267)
                                                                       at java.lang.Double.parseDouble(Double.java:301)
                                                                       at com.myapp.simpleapp.MainActivity$4.onClick(MainActivity.java:70)
                                                                       at android.view.View.performClick(View.java:4780)
                                                                       at android.view.View$PerformClick.run(View.java:19866)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:135)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
04-03 12:25:58.079 1163-1163/? E/EGL_emulation: tid 1163: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE)
04-03 12:26:02.452 1810-2202/system_process E/InputDispatcher: channel '21dd8534 com.myapp.simpleapp/com.myapp.simpleapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
04-03 12:26:02.581 1175-1175/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
</code>```

答:
Use findViewById inside onCreate and use Double.parse only after values have been entered in the edittexts.

Try this code:

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText number1 = (EditText) findViewById(R.id.number1);
        final EditText number2 = (EditText) findViewById(R.id.number2);

        Button add = (Button) findViewById(R.id.btnAdd);
        Button sub = (Button) findViewById(R.id.btnSub);
        Button div = (Button) findViewById(R.id.btnDiv);
        Button mul = (Button) findViewById(R.id.btnMul);

        final TextView txtresult = (TextView) findViewById(R.id.result);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double num1, num2, result;

                num1 = Double.parseDouble(number1.getText().toString());
                num2 = Double.parseDouble(number2.getText().toString());

                result = num1 + num2;

                txtresult.setText(Double.toString(result));
            }
        });

        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double num1, num2, result;

                num1 = Double.parseDouble(number1.getText().toString());
                num2 = Double.parseDouble(number2.getText().toString());

                result = num1 - num2;

                txtresult.setText(Double.toString(result));
            }
        });

        div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double num1, num2, result;

                num1 = Double.parseDouble(number1.getText().toString());
                num2 = Double.parseDouble(number2.getText().toString());

                result = num1 / num2;

                txtresult.setText(Double.toString(result));
            }
        });

        mul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double num1, num2, result;

                num1 = Double.parseDouble(number1.getText().toString());
                num2 = Double.parseDouble(number2.getText().toString());

                result = num1 * num2;

                txtresult.setText(Double.toString(result));
            }
        });

    }
}
</code>```

Title: Unfortunately, Simple app is stopped

Body:
I'm new to android development and im making a simple calculator app... Whenever i'm running the code in the android emulator it's showing me Unfortunately, SimpleApp has Stopped.... I'm Using Android Studio to write the code Please help me...
Following is my code....

activity_main.xml

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapp.simpleapp.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="337dp"
        android:layout_height="58dp"
        android:contextClickable="false"
        android:cursorVisible="false"
        android:fontFamily="serif"
        android:longClickable="true"
        android:text="Calculator"
        android:textAlignment="center"
        android:textAllCaps="true"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="36sp"
        android:visibility="visible"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="31dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="194dp"
        android:layout_height="43dp"
        android:text="Number 1: "
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="140dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="194dp"
        android:layout_height="44dp"
        android:text="Number 2: "
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="217dp" />

    <EditText
        android:id="@+id/number2"
        android:layout_width="99dp"
        android:layout_height="43dp"
        android:ems="10"
        android:hint="Number 2"
        android:inputType="number|numberSigned|numberDecimal"
        android:singleLine="true"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textIsSelectable="true"
        android:textSize="20sp"
        tools:layout_editor_absoluteX="262dp"
        tools:layout_editor_absoluteY="217dp" />

    <EditText
        android:id="@+id/number1"
        android:layout_width="99dp"
        android:layout_height="43dp"
        android:ems="10"
        android:hint="Number 1"
        android:inputType="number|numberSigned|numberDecimal"
        android:linksClickable="false"
        android:longClickable="true"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="20sp"
        tools:layout_editor_absoluteX="262dp"
        tools:layout_editor_absoluteY="140dp" />

    <TextView
        android:id="@+id/result"
        android:layout_width="175dp"
        android:layout_height="40dp"
        tools:layout_editor_absoluteX="176dp"
        tools:layout_editor_absoluteY="430dp" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="103dp"
        android:layout_height="40dp"
        android:text="Result: "
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="59dp"
        tools:layout_editor_absoluteY="433dp" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="152dp"
        android:layout_height="49dp"
        android:text="+"
        android:textColor="@android:color/black"
        android:textSize="30sp"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="292dp" />

    <Button
        android:id="@+id/btnSub"
        android:layout_width="152dp"
        android:layout_height="49dp"
        android:text="-"
        android:textColor="@android:color/black"
        android:textIsSelectable="false"
        android:textSize="30sp"
        tools:layout_editor_absoluteX="216dp"
        tools:layout_editor_absoluteY="292dp" />

    <Button
        android:id="@+id/btnDiv"
        android:layout_width="152dp"
        android:layout_height="49dp"
        android:text="/"
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="24dp"
        tools:layout_editor_absoluteY="362dp" />

    <Button
        android:id="@+id/btnMul"
        android:layout_width="152dp"
        android:layout_height="49dp"
        android:text="*"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="25sp"
        tools:layout_editor_absoluteX="216dp"
        tools:layout_editor_absoluteY="362dp" />
</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.myapp.simpleapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    EditText number1= (EditText) findViewById(R.id.number1);
    EditText number2= (EditText) findViewById(R.id.number2);

    Button add= (Button) findViewById(R.id.btnAdd);
    Button sub= (Button) findViewById(R.id.btnSub);
    Button div= (Button) findViewById(R.id.btnDiv);
    Button mul= (Button) findViewById(R.id.btnMul);

    TextView txtresult= (TextView) findViewById(R.id.result);

    double num1,num2,result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        num1=Double.parseDouble(number1.getText().toString());
        num2=Double.parseDouble(number2.getText().toString());

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result=num1+num2;

                txtresult.setText(Double.toString(result));
            }
        });

        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result=num1-num2;

                txtresult.setText(Double.toString(result));
            }
        });

        div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result=num1/num2;

                txtresult.setText(Double.toString(result));
            }
        });

        mul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result=num1*num2;

                txtresult.setText(Double.toString(result));
            }
        });

    }
}

LogCat

04-03 12:25:38.913 3927-3927/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-03 12:25:38.913 3927-3927/? E/android.os.Debug: failed to load memtrack module: -2
04-03 12:25:39.372 3952-3952/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-03 12:25:39.373 3952-3952/? E/android.os.Debug: failed to load memtrack module: -2
04-03 12:25:49.078 4097-4097/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-03 12:25:49.078 4097-4097/? E/android.os.Debug: failed to load memtrack module: -2
04-03 12:25:49.647 4122-4122/? E/memtrack: Couldn't load memtrack module (No such file or directory)
04-03 12:25:49.648 4122-4122/? E/android.os.Debug: failed to load memtrack module: -2
04-03 12:25:58.059 3666-3666/com.myapp.simpleapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: com.myapp.simpleapp, PID: 3666
                                                                   java.lang.NumberFormatException: Invalid double: ""
                                                                       at java.lang.StringToReal.invalidReal(StringToReal.java:63)
                                                                       at java.lang.StringToReal.parseDouble(StringToReal.java:267)
                                                                       at java.lang.Double.parseDouble(Double.java:301)
                                                                       at com.myapp.simpleapp.MainActivity$4.onClick(MainActivity.java:70)
                                                                       at android.view.View.performClick(View.java:4780)
                                                                       at android.view.View$PerformClick.run(View.java:19866)
                                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:135)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
04-03 12:25:58.079 1163-1163/? E/EGL_emulation: tid 1163: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE)
04-03 12:26:02.452 1810-2202/system_process E/InputDispatcher: channel '21dd8534 com.myapp.simpleapp/com.myapp.simpleapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
04-03 12:26:02.581 1175-1175/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000

Body:
Use findViewById inside onCreate and use Double.parse only after values have been entered in the edittexts.

Try this code:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText number1 = (EditText) findViewById(R.id.number1);
        final EditText number2 = (EditText) findViewById(R.id.number2);

        Button add = (Button) findViewById(R.id.btnAdd);
        Button sub = (Button) findViewById(R.id.btnSub);
        Button div = (Button) findViewById(R.id.btnDiv);
        Button mul = (Button) findViewById(R.id.btnMul);

        final TextView txtresult = (TextView) findViewById(R.id.result);

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double num1, num2, result;

                num1 = Double.parseDouble(number1.getText().toString());
                num2 = Double.parseDouble(number2.getText().toString());

                result = num1 + num2;

                txtresult.setText(Double.toString(result));
            }
        });

        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double num1, num2, result;

                num1 = Double.parseDouble(number1.getText().toString());
                num2 = Double.parseDouble(number2.getText().toString());

                result = num1 - num2;

                txtresult.setText(Double.toString(result));
            }
        });

        div.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double num1, num2, result;

                num1 = Double.parseDouble(number1.getText().toString());
                num2 = Double.parseDouble(number2.getText().toString());

                result = num1 / num2;

                txtresult.setText(Double.toString(result));
            }
        });

        mul.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                double num1, num2, result;

                num1 = Double.parseDouble(number1.getText().toString());
                num2 = Double.parseDouble(number2.getText().toString());

                result = num1 * num2;

                txtresult.setText(Double.toString(result));
            }
        });

    }
}


问:
Javascript: How can I add the values of an object that belong to a shared key?
Let's say I have an object containing states and their balances.

```<code>    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }
</code>```

How could I add the amounts that belong to each state, for example OH would have 587603.26 + 657617.83. I believe the map() method is to be used here but I am not sure how to go about using it. Thanks!

答:
This is a perfect use-case for filter, map and reduce used together.

let input = [{
  "amount": "822370.71",
  "state": "ME"
},
{
  "amount": "968817.53",
  "state": "FL"
},
{
  "amount": "587603.26",
  "state": "OH"
},
{
  "amount": "657617.83",
  "state": "OH"
},
{
  "amount": "657617.83",
  "state": "FL"
}];

let map = input
  // Create a map from each state to all its entries
  .reduce((all, a) => {
    all[a.state] = all[a.state] || [];
    all[a.state].push(a);
    return all;
  }, {});

for(let state in map) {
  map[state] = map[state]
    // Get the amount from each entry
    .map(a => a.amount)
    // Turn into a number
    .map(parseFloat)
    // Add each number in turn
    .reduce((acc, a) => a+acc, 0);
}

console.log(map);```

Body:
Let's say I have an object containing states and their balances.

    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }

How could I add the amounts that belong to each state, for example OH would have 587603.26 + 657617.83. I believe the map() method is to be used here but I am not sure how to go about using it. Thanks!


问:
rename directory as atomic operation
I am working in C# in visual studio.

I am using the command  Directory.Move

I have an operational folder and i sometimes need to replace it.

what i do is to create a backup folder with the new content in the same directory the operational folder is, delete the operational and rename the folder.

if both folders (operational and backup) exists its ok because i know to read from the backup first.

BUT after deleting the operational and rename the backup folder to operational can there be a situation (if restart occures) that only part of the backup files / folders will be be in the new operational folder, or is move folder is atomic operational.

I need to operational to be successful meaning the operational folder contains everything, or failed to rename, BUT NO SOMETHING IN BETWEEN

答:
File operations are already atomic at the file system level under NTFS (Windows Vista+).

See this for details: Atomic file copy under .NET

For WinXP and below, it's like you thought.

Title: rename directory as atomic operation


问:
javascript check values are same or not within double quotes?
In javascript if any variable has multiple values seperated by comma within double quotes,then how to check that values are same or not

```<code>      var str= "0,1,-1";
</code>```

How to check this variable.

答:
you can split and then check for every item in splitted array.

check the fiddle

code is below -

```<code>var val = "1, 01, 0001";
var result = function(val)
{
    var l = val.length;
    if(l == 0)
    {
      return false;
    }
    else
    {
      //because all the values in 'val' fields are number
      var f = Number.parseInt(val[0]) ;
      for(i=1; i< l; i++)
      {
         if(Number.parseInt(val[i]) != f)
         {
           return false;
         }
      }
      return true;
    }
}(val.split(','))

alert(result);
</code>```

Body:
In javascript if any variable has multiple values seperated by comma within double quotes,then how to check that values are same or not

      var str= "0,1,-1";

How to check this variable.

Body:
you can split and then check for every item in splitted array.

check the fiddle

code is below -

var val = "1, 01, 0001";
var result = function(val)
{
    var l = val.length;
    if(l == 0)
    {
      return false;
    }
    else
    {
      //because all the values in 'val' fields are number
      var f = Number.parseInt(val[0]) ;
      for(i=1; i< l; i++)
      {
         if(Number.parseInt(val[i]) != f)
         {
           return false;
         }
      }
      return true;
    }
}(val.split(','))

alert(result);


问:
ggplot not plotting the correct color
```<code>gb <- read.csv('results-gradient-boosting.csv')
p <- ggplot(gb) + geom_point(aes(x = pred, y = y),alpha = 0.4, fill = 'darkgrey', size = 2) +
geom_line(aes(x = pred, y = pred,color = 'darkgrey'),size = 0.6) +
geom_line(aes(x = pred, y = pred + 3,color = I("darkgrey")), linetype = 'dashed',size = 0.6) +
geom_line(aes(x = pred, y = pred -3,color = 'darkgrey'),linetype = 'dashed',size = 0.6)
</code>```

My code is above. I have no idea why when I put color inside aes, the color turns out to be red. But if I put it outside of aes, it is correct. Thanks for your help!

答:
When you put color="darkgrey" outside aes, ggplot takes it literally to mean that the line should be colored "darkgrey". But when you put color="darkgrey" inside aes, ggplot takes it to mean that you want to map color to a variable. In this case, the variable has only one value: "darkgrey". But that's not the color "darkgrey". It's just a string. You could call it anything. The color ggplot chooses will be based on the default palette. Map color to a variable when you want different colors for different levels of that variable.

For example, see what happens in the example below. The colors are chosen from ggplot's default palette and are completely independent of the names we've used for colour in each call to geom_line. You will get the same three colors when you have any color aesthetic that takes on three different unique values:

```<code>library(ggplot2)
theme_set(theme_classic())

ggplot(mtcars) +
  geom_line(aes(mpg, wt, colour="green")) +
  geom_line(aes(mpg, wt - 1, colour="blue")) +
  geom_line(aes(mpg, wt + 1, colour="star trek"))
</code>```

But now we put the colors outside aes so they are taken literally, and we comment out the third line, because it will cause an error if we don't use a valid colour.

```<code>ggplot(mtcars) +
  geom_line(aes(mpg, wt), colour="green") +
  geom_line(aes(mpg, wt - 1), colour="blue") #+
  #geom_line(aes(mpg, wt + 1), colour="star trek")
</code>```

Note that if we map colour to an actual column of mtcars (one that has three unique levels), we get the same three colors as in the first example, but now they are mapped to an actual feature of the data:

```<code>ggplot(mtcars) +
  geom_line(aes(mpg, wt, colour=factor(cyl)))
</code>```

And finally, what if we want to set those mapped colors to different values:

```<code>ggplot(mtcars) +
  geom_line(aes(mpg, wt, colour=factor(cyl))) +
  scale_colour_manual(values=c("purple", hcl(150,100,80), rgb(0.9,0.5,0.3)))
</code>```

Title: ggplot not plotting the correct color

Body:
gb <- read.csv('results-gradient-boosting.csv')
p <- ggplot(gb) + geom_point(aes(x = pred, y = y),alpha = 0.4, fill = 'darkgrey', size = 2) +
geom_line(aes(x = pred, y = pred,color = 'darkgrey'),size = 0.6) +
geom_line(aes(x = pred, y = pred + 3,color = I("darkgrey")), linetype = 'dashed',size = 0.6) +
geom_line(aes(x = pred, y = pred -3,color = 'darkgrey'),linetype = 'dashed',size = 0.6)

My code is above. I have no idea why when I put color inside aes, the color turns out to be red. But if I put it outside of aes, it is correct. Thanks for your help!

Body:
When you put color="darkgrey" outside aes, ggplot takes it literally to mean that the line should be colored "darkgrey". But when you put color="darkgrey" inside aes, ggplot takes it to mean that you want to map color to a variable. In this case, the variable has only one value: "darkgrey". But that's not the color "darkgrey". It's just a string. You could call it anything. The color ggplot chooses will be based on the default palette. Map color to a variable when you want different colors for different levels of that variable.

For example, see what happens in the example below. The colors are chosen from ggplot's default palette and are completely independent of the names we've used for colour in each call to geom_line. You will get the same three colors when you have any color aesthetic that takes on three different unique values:

library(ggplot2)
theme_set(theme_classic())

ggplot(mtcars) +
  geom_line(aes(mpg, wt, colour="green")) +
  geom_line(aes(mpg, wt - 1, colour="blue")) +
  geom_line(aes(mpg, wt + 1, colour="star trek"))

But now we put the colors outside aes so they are taken literally, and we comment out the third line, because it will cause an error if we don't use a valid colour.

ggplot(mtcars) +
  geom_line(aes(mpg, wt), colour="green") +
  geom_line(aes(mpg, wt - 1), colour="blue") #+
  #geom_line(aes(mpg, wt + 1), colour="star trek")

Note that if we map colour to an actual column of mtcars (one that has three unique levels), we get the same three colors as in the first example, but now they are mapped to an actual feature of the data:

ggplot(mtcars) +
  geom_line(aes(mpg, wt, colour=factor(cyl)))

And finally, what if we want to set those mapped colors to different values:

ggplot(mtcars) +
  geom_line(aes(mpg, wt, colour=factor(cyl))) +
  scale_colour_manual(values=c("purple", hcl(150,100,80), rgb(0.9,0.5,0.3)))


问:
Converting FORTRAN to C / C++
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

```<code>copy makefile.vc makefile
nmake
</code>```

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?

答:
I'm going to answer only the very last part of your question:

is there any way of converting that
  FORTRAN code into C or C++?

Yes there is:  Read the fortran code, and write the equivalent C statements in a C file.
They are both imperative languages.  The syntax is different but not impossible to decode.  This will likely give you much better results than an auto-converter, and will also give you an much deeper understanding of how the original program works.

Title: Converting FORTRAN to C / C++

Body:
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

copy makefile.vc makefile
nmake

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?


问:
It is currently in use by another Gradle instance
I want to do some basic functions. I'm running/building it in command line. I am referring User guide. And, doing some simple tasks.

When I start to run simple tasks, it was build successfully. But, After some times, it is showing "It is currently in use by another Gradle instance" and becomes BUILD FAILED. I'm using a terminal for run the task. I didn't run anything at that time.

If I closed the terminal which generate the error, this problem would be solved. But, I know that it is not the solution for that.

Why is this error coming frequently?

How to solve it?

And, Please refer any link to improve my knowledge on Gradle Build system in Android.

答:
Its Work for me for
Problem:-

"Error:Timeout waiting to lock jars It is currently in use by another Gradle instance. Owner PID: 6896 Our PID: 5048 Owner Operation: Our operation: Lock"

Solution:-

close the Android Studio and  Open Task manager and end the process java.exe

open the derectory ....gradle\caches.

Delete the jar2.lock file.

Open android Studion and clean the project.

ContentLicense: CC BY-SA 4.0


问:
How to send a key with a XMLHttpRequest when trying to access an API ?
Hey Guys I'm tying to access the Web API for the MTA. I do have the key but I'm unable to make the call since I don't know how to pass the key properly. I replaced my real key with the string "This is my key" in the code sample below.

code

```<code> var myRequest = new XMLHttpRequest();
    myRequest.open('GET','http://bustime.mta.info/api/siri/vehicle-monitoring.json', 'This is my key');
    myRequest.onload = function(){

var data = JSON.parse(myRequest.responseText);
console.log(data[0].comments);

};
myRequest.send();
</code>```

Error

```<code>XMLHttpRequest cannot load http://bustime.mta.info/api/siri/vehicle-monitoring.json. Redirect from 'http://bustime.mta.info/api/siri/vehicle-monitoring.json' to 'http://api.prod.obanyc.com/api/siri/vehicle-monitoring.json' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
</code>```

答:
As explained in the documentation, the API key must be passed as a GET parameter called key, e.g.

```<code>http://bustime.mta.info/api/siri/vehicle-monitoring.json?key=<your key>…
</code>```

However, the API you are trying to access has not enabled cross-domain access. It cannot be used directly from a Javascript web application -- the key will not make a difference.

Body:
Hey Guys I'm tying to access the Web API for the MTA. I do have the key but I'm unable to make the call since I don't know how to pass the key properly. I replaced my real key with the string "This is my key" in the code sample below.

code

 var myRequest = new XMLHttpRequest();
    myRequest.open('GET','http://bustime.mta.info/api/siri/vehicle-monitoring.json', 'This is my key');
    myRequest.onload = function(){

var data = JSON.parse(myRequest.responseText);
console.log(data[0].comments);

};
myRequest.send();

Error

XMLHttpRequest cannot load http://bustime.mta.info/api/siri/vehicle-monitoring.json. Redirect from 'http://bustime.mta.info/api/siri/vehicle-monitoring.json' to 'http://api.prod.obanyc.com/api/siri/vehicle-monitoring.json' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Body:
As explained in the documentation, the API key must be passed as a GET parameter called key, e.g.

http://bustime.mta.info/api/siri/vehicle-monitoring.json?key=<your key>…

However, the API you are trying to access has not enabled cross-domain access. It cannot be used directly from a Javascript web application -- the key will not make a difference.


答:
The most common cause of this problem is a NullPointerException at runtime.

Steps to follow:

Observe the Stack trace on Android Studio as shown below:

You can then analyze the Stack trace, and zero in on what exactly caused the exception, and the line that caused it. Alternatively, you can post the screenshot of your stack trace so it can be easier to answer the question.

Title: Unfortunately, Simple app is stopped


问:
Find the end of the month of a Pandas DataFrame Series
I have a series within a DataFrame that I read in initially as an object, and then need to convert it to a date in the form of yyyy-mm-dd where dd is the end of the month.

As an example, I have DataFrame df with a column Date as an object:

```<code>...      Date    ...
...     200104   ...
...     200508   ...
</code>```

What I want when this is all said and done is a date object:

```<code>...      Date    ...
...  2001-04-30  ...
...  2005-08-31  ...
</code>```

such that df['Date'].item() returns

```<code>datetime.date(2001, 04, 30)
</code>```

I've used the following code to get almost there, but all my dates are at the beginning of the month, not the end. Please advise.

```<code>df['Date'] = pd.to_datetime(df['Date'], format="%Y%m").dt.date
</code>```

Note: I've already imported Pandas (pd), and datetime (dt)

答:
Agreed that root offers is the right method. However, readers who blindly use  MonthEnd(1) are in for a surprise if they use the last date of the month as an input:

```<code>In [4]: pd.Timestamp('2014-01-01') + MonthEnd(1)
Out[4]: Timestamp('2014-01-31 00:00:00')

In [5]: pd.Timestamp('2014-01-31') + MonthEnd(1)
Out[5]: Timestamp('2014-02-28 00:00:00')
</code>```

Using MonthEnd(0) instead gives this:

```<code>In [7]: pd.Timestamp('2014-01-01') + MonthEnd(0)
Out[7]: Timestamp('2014-01-31 00:00:00')

In [8]: pd.Timestamp('2014-01-31') + MonthEnd(0)
Out[8]: Timestamp('2014-01-31 00:00:00')
</code>```

Example to obtain the month end as a string:

```<code>from pandas.tseries.offsets import MonthEnd
(pd.Timestamp.now() + MonthEnd(0)).strftime('%Y-%m-%dT00:00:00')
# '2014-01-31T00:00:00'
</code>```

Body:
I have a series within a DataFrame that I read in initially as an object, and then need to convert it to a date in the form of yyyy-mm-dd where dd is the end of the month.

As an example, I have DataFrame df with a column Date as an object:

...      Date    ...
...     200104   ...
...     200508   ...

What I want when this is all said and done is a date object:

...      Date    ...
...  2001-04-30  ...
...  2005-08-31  ...

such that df['Date'].item() returns

datetime.date(2001, 04, 30)

I've used the following code to get almost there, but all my dates are at the beginning of the month, not the end. Please advise.

df['Date'] = pd.to_datetime(df['Date'], format="%Y%m").dt.date

Note: I've already imported Pandas (pd), and datetime (dt)

Body:
Agreed that root offers is the right method. However, readers who blindly use  MonthEnd(1) are in for a surprise if they use the last date of the month as an input:

In [4]: pd.Timestamp('2014-01-01') + MonthEnd(1)
Out[4]: Timestamp('2014-01-31 00:00:00')

In [5]: pd.Timestamp('2014-01-31') + MonthEnd(1)
Out[5]: Timestamp('2014-02-28 00:00:00')

Using MonthEnd(0) instead gives this:

In [7]: pd.Timestamp('2014-01-01') + MonthEnd(0)
Out[7]: Timestamp('2014-01-31 00:00:00')

In [8]: pd.Timestamp('2014-01-31') + MonthEnd(0)
Out[8]: Timestamp('2014-01-31 00:00:00')

Example to obtain the month end as a string:

from pandas.tseries.offsets import MonthEnd
(pd.Timestamp.now() + MonthEnd(0)).strftime('%Y-%m-%dT00:00:00')
# '2014-01-31T00:00:00'


问:
Pattern is not getting matched, showing 'Sanjay' is not recognized as an internal or external command, operable program or batch file
```<code>perl -n -e'if(/Avinash/../Sanjay/){next if(/Avinash|Sanjay/);    print "$_";}' avinash.txt>sumeet.txt
</code>```

I want to write content between the Words Avinash and Sanjay in a file sumeet.txt, but when i am giving the pattern in next if ,it is throwing this error:

Sanjay' is not recognized as an internal or external command, operable program or batch file.
```

答:
That error message sounds like you're in cmd on Windows. cmd doesn't recognize ' ' as quoting symbols; you have to use double quotes (") instead:

```<code>perl -n -e "if(/Avinash/../Sanjay/){next if(/Avinash|Sanjay/); print $_;}" avinash.txt>sumeet.txt
</code>```

If your code uses " " strings internally, they can normally replaced by qq( ). But in your case I could just remove them entirely because print $_ is perfectly valid code.

Body:
perl -n -e'if(/Avinash/../Sanjay/){next if(/Avinash|Sanjay/);    print "$_";}' avinash.txt>sumeet.txt

I want to write content between the Words Avinash and Sanjay in a file sumeet.txt, but when i am giving the pattern in next if ,it is throwing this error:

Sanjay' is not recognized as an internal or external command, operable program or batch file.

Body:
That error message sounds like you're in cmd on Windows. cmd doesn't recognize ' ' as quoting symbols; you have to use double quotes (") instead:

perl -n -e "if(/Avinash/../Sanjay/){next if(/Avinash|Sanjay/); print $_;}" avinash.txt>sumeet.txt

If your code uses " " strings internally, they can normally replaced by qq( ). But in your case I could just remove them entirely because print $_ is perfectly valid code.


问:
MongoDB Many To One Relation
I am new to mongodb,Lets say User can create many Events,where Each Event Belongs to  only one User.So in Relational Database I created Events Table Where I store UserId  who created the Event, with details about event , what's the best way to handle this relation in monogdb?

答: In general, use embedded data models when: you have one-to-one or one-to-many model, more information you can find here.

Title: MongoDB Many To One Relation


问:
How can I italicise a certain word (which occurs multiple times) in my string in Swift?
I have a text that reads "Hello world. The world is so beautiful." I want to change it to "Hello world. The world is so beautiful."

I tried the following code but it only changes the first word.

```<code> let string : NSString =  "Hello world. The world is so beautiful."
 let attributedString = NSMutableAttributedString(string: string! as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17.0)])
 let italicFontAttribute = [NSFontAttributeName: UIFont.italicSystemFont(ofSize: 17.0)]
 attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "world")))
</code>```

答:
Another solution added to the others, but which makes a search for the specific term and replaces all of the occurrences, could help you creating a general method for this:</p>

```<code>var sampleString : String = "Hello world. The world is so beautiful."
let searchTerm : String = "world"

var searchRange : NSRange = NSMakeRange(0, sampleString.characters.count)
var positionRange : NSRange = ((sampleString as NSString).substring(with: searchRange) as NSString).range(of: searchTerm)
var actualRange : NSRange = positionRange

var attributedString : NSMutableAttributedString = NSMutableAttributedString(string: sampleString)

while (positionRange.location != NSNotFound)
{
    // Update attributed string
    actualRange.location = searchRange.location + positionRange.location
    attributedString.addAttributes([ NSFontAttributeName : UIFont(name: "Helvetica-Italic", size: CGFloat(22)) ], range: actualRange)

    // Proceed to the next position
    searchRange.location += positionRange.location + searchTerm.characters.count
    searchRange.length = sampleString.characters.count - searchRange.location

    positionRange = ((sampleString as NSString).substring(with: searchRange) as NSString).range(of: searchTerm)
}
</code>```

Body:
I have a text that reads "Hello world. The world is so beautiful." I want to change it to "Hello world. The world is so beautiful."

I tried the following code but it only changes the first word.

 let string : NSString =  "Hello world. The world is so beautiful."
 let attributedString = NSMutableAttributedString(string: string! as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17.0)])
 let italicFontAttribute = [NSFontAttributeName: UIFont.italicSystemFont(ofSize: 17.0)]
 attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "world")))

Body:
Another solution added to the others, but which makes a search for the specific term and replaces all of the occurrences, could help you creating a general method for this:

var sampleString : String = "Hello world. The world is so beautiful."
let searchTerm : String = "world"

var searchRange : NSRange = NSMakeRange(0, sampleString.characters.count)
var positionRange : NSRange = ((sampleString as NSString).substring(with: searchRange) as NSString).range(of: searchTerm)
var actualRange : NSRange = positionRange

var attributedString : NSMutableAttributedString = NSMutableAttributedString(string: sampleString)

while (positionRange.location != NSNotFound)
{
    // Update attributed string
    actualRange.location = searchRange.location + positionRange.location
    attributedString.addAttributes([ NSFontAttributeName : UIFont(name: "Helvetica-Italic", size: CGFloat(22)) ], range: actualRange)

    // Proceed to the next position
    searchRange.location += positionRange.location + searchTerm.characters.count
    searchRange.length = sampleString.characters.count - searchRange.location

    positionRange = ((sampleString as NSString).substring(with: searchRange) as NSString).range(of: searchTerm)
}


问:
Validation Of UserEmail Is not working in php
I am going to validate the POST variable userEmail. But the problem is even though I used filter_var to validate, it is not working even when inputting a wrong email and instead gets inserted. Can you help me in getting the solution.

insert_dummy.php

```<code><html>
<head><title>Insertion</title>

</head>
<body>
<style>

#colour {
text-decoration:none;
}
</style>
<div id="display">
<?php
include('header/page_header.php');
include('db.php');

if(isset($_POST['add']))
{
$userName=mysql_real_escape_string($_POST['userName']);

$userEmail=mysql_real_escape_string($_POST['userEmail']);
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
{
echo "Please Enter The Valid Email Address";
}

$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}

else
{
$display= "Failed";
}

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="<table border='1' align='center'>";
$display.="<tr><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>ExpiryDate</th><th>RegistrationKey</th><th colspan='3'>Action</th></tr>";
while($result=mysql_fetch_array($query2))
{
$display.="<tr>";

$display.="<td>".$result['userName']."</td>";
$display.="<td>".$result['userEmail']."</td>";
$display.="<td>".$result['userPassword']."</td>";
$display.="<td>".$result['regDate']."</td>";
$display.="<td>".$result['expiry_date']."</td>";
$display.="<td>".$result['registration_key']."</td>";
$display.="<td><a id='colour' class='tooltip' title='Edit' href='user_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='user_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='insert' href='chapter_subscription_search.php?user_Id=".$result['userId']." '>i</a></td>";
$display.="</tr>";

$display.="</table>";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

<table align='center' border='1'>

    <tr>

           <td> <label for="userId">UserId</label></td>
            <td ><input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/></td>

        </tr>
        <tr>
        <td> <label for="userName">UserName</label></td>
        <td ><input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userEmail">UserEmail</label></td>
        <td ><input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userPassword">UserPassword</label></td>
        <td ><input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="expiry_date">ExpiryDate</label></td>
        <td ><input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="end_date">EndDate</label></td>
        <td >  <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>
</td>
        </tr>

        </table>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="<table border='1' align='center'>";
$display.="<tr><th>ChapterNumber</th><th>StartDate</th><th>EndDate</th><th colspan='2'>Action</th></tr>";
while($result=mysql_fetch_array($query9))
{
$display.="<tr>";
$display.="<td>".$result['chapter_no']."</td>";
$display.="<td>".$result['start_date']."</td>";

$display.="<td>".$result['end_date']."</td>";

$display.="<td><a id='colour' class='tooltip' title='Edit' href='chapter_subscription_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='chapter_subscription_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="</tr>";
}
$display.="</table>";

echo $display;
}

?>
</div>
 <script type="text/javascript">
    $(document).ready(function() {
    $( "#expiry_date" ).datepicker();
    $("#menuwrapper").hide();
    $("#unicode").click(function() {
        $("#menuwrapper").slideToggle(500);
    });
    });

</script>

</body>
</html>
</code>```

答:
Please replace this

```<code>   if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
   {
      echo "Please Enter The Valid Email Address";
   }
</code>```

with following

```<code>    $userEmail=mysql_real_escape_string($_POST['userEmail']);
    $email = (preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $userEmail))?$userEmail:"invalid email";
    if($email == "invalid email")
    {
        echo "Please Enter The Valid Email Address";
        return;
    }
</code>```

Body:
I am going to validate the POST variable userEmail. But the problem is even though I used filter_var to validate, it is not working even when inputting a wrong email and instead gets inserted. Can you help me in getting the solution.

insert_dummy.php

<title>Insertion</title>

<?php
include('header/page_header.php');
include('db.php');

if(isset($_POST['add']))
{
$userName=mysql_real_escape_string($_POST['userName']);

$userEmail=mysql_real_escape_string($_POST['userEmail']);
if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
{
echo "Please Enter The Valid Email Address";
}

$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}

else
{
$display= "Failed";
}

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="
";
$display.="
UserName	UserEmail	UserPassword	RegDate	ExpiryDate	RegistrationKey	Action
";
while($result=mysql_fetch_array($query2))
{
$display.="
";

$display.="".$result['userName']."	";
$display.="".$result['userEmail']."	";
$display.="".$result['userPassword']."	";
$display.="".$result['regDate']."	";
$display.="".$result['expiry_date']."	";
$display.="".$result['registration_key']."	";
$display.="	";
$display.="	";

$display.="i	";
$display.="
";

$display.="
";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

            UserId
            <input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/>

         UserName
        <input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/>

         UserEmail
        <input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/>

         UserPassword
        <input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/>

         ExpiryDate
        <input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/>

         EndDate
          <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="
";
$display.="
ChapterNumber	StartDate	EndDate	Action
";
while($result=mysql_fetch_array($query9))
{
$display.="
";
$display.="".$result['chapter_no']."	";
$display.="".$result['start_date']."	";

$display.="".$result['end_date']."	";

$display.="	";
$display.="	";

$display.="
";
}
$display.="
";

echo $display;
}

?>

Body:
Please replace this

   if(!filter_var($userEmail, FILTER_VALIDATE_EMAIL))
   {
      echo "Please Enter The Valid Email Address";
   }

with following

    $userEmail=mysql_real_escape_string($_POST['userEmail']);
    $email = (preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $userEmail))?$userEmail:"invalid email";
    if($email == "invalid email")
    {
        echo "Please Enter The Valid Email Address";
        return;
    }


答:
Short solution using String.prototype.split() and Set object:

var hasSameValues = function (s) {
    return (new Set(s.split(','))).size === 1;
};

console.log(hasSameValues("0,1,-1"));
console.log(hasSameValues("1,1,1"));
console.log(hasSameValues("2,-2,2"));```

Title: javascript check values are same or not within double quotes?


问:
How to Deal With Dapper return Key Value pair with Dynamic from LINQ
I am new to Dapper. Let me explain what i am trying to achieve. I have simple query which is returning columns from DB, i don't want to create Entity(Property) class for it to fill the data. I want to use Dynamic Type for this. Below is my code:

```<code>public dynamic GetABC(int year)
    {

        using (var db = new MySql.Data.MySqlClient.MySqlConnection(ClsConnectionString.connectionString))
        {

            string query = string.Format(@"SELECT * FROM ranking where YEAR(eventdate)='{0}') ORDER BY eventdate DESC, eventid ASC",year);
            //return db.Query<RankingEntity>(query, commandType: System.Data.CommandType.Text).AsList();
            var a = (IEnumerable<dynamic>)db.Query(query, null, null, true, null, CommandType.Text).ToList();
            return a;
       }
    }
</code>```

It returns me Key Value pair. like below:

Is there any way, i just write one common method to get List as "Property" = "Value" As normally we get when we use any Entity Class.

I am not sure, if it is achievable but i wish to learn if it is possible and want to implement in our application.

I can achieve this by implementing loop through the dapperrows which i don't want. because if there will be 10000 rows loop will iterate 10000 times.

Thanks in advance.

答:
As I have mentioned DapperRow is an internal class of the Dapper, which can be directly typecast to IDictionary<string,object>, since it implements IDictionary interface. All that you have to do is:

```<code>var a = db.Query(query, null, null, true, null, CommandType.Text).Select(x => x as IDictionary<string,object>);
</code>```

Now result would be of type IEnumerable<IDictionary<string,object>>, which can be used to extract all the required information, since column names are keys and respective row value is the value of each element in the IEnumerable.

Also check, this may too work, but I am not sure:

```<code> var a = (IEnumerable<IDictionary<string,object>>)db.Query(query, null, null, true, null, CommandType.Text);
</code>```

Body:
I am new to Dapper. Let me explain what i am trying to achieve. I have simple query which is returning columns from DB, i don't want to create Entity(Property) class for it to fill the data. I want to use Dynamic Type for this. Below is my code:

public dynamic GetABC(int year)
    {

        using (var db = new MySql.Data.MySqlClient.MySqlConnection(ClsConnectionString.connectionString))
        {

            string query = string.Format(@"SELECT * FROM ranking where YEAR(eventdate)='{0}') ORDER BY eventdate DESC, eventid ASC",year);
            //return db.Query<RankingEntity>(query, commandType: System.Data.CommandType.Text).AsList();
            var a = (IEnumerable<dynamic>)db.Query(query, null, null, true, null, CommandType.Text).ToList();
            return a;
       }
    }

It returns me Key Value pair. like below:

Is there any way, i just write one common method to get List as "Property" = "Value" As normally we get when we use any Entity Class.

I am not sure, if it is achievable but i wish to learn if it is possible and want to implement in our application.

I can achieve this by implementing loop through the dapperrows which i don't want. because if there will be 10000 rows loop will iterate 10000 times.

Thanks in advance.

Body:
As I have mentioned DapperRow is an internal class of the Dapper, which can be directly typecast to IDictionary<string,object>, since it implements IDictionary interface. All that you have to do is:

var a = db.Query(query, null, null, true, null, CommandType.Text).Select(x => x as IDictionary<string,object>);

Now result would be of type IEnumerable<IDictionary<string,object>>, which can be used to extract all the required information, since column names are keys and respective row value is the value of each element in the IEnumerable.

Also check, this may too work, but I am not sure:

 var a = (IEnumerable<IDictionary<string,object>>)db.Query(query, null, null, true, null, CommandType.Text);