问:
How can I deserialize an object if I don't know the right type?
Well I want to send commands and data between client and server.

I have three projects:

Client

Server

Common - here I put common classes and network abstraction layer

I am using following data structures for communications between client and server

```<code>public class Packet<T>
{
        public string Name { get; set; }
        public string From { get; set; }
        public string To { get; set; }
        public PacketType PacketType { get; set; }
        public T Container { get; set; }

        public Packet()
        {
        }

        public Packet(string name, PacketType packetType, T container)
        {
            Name = name;
            PacketType = packetType;
            Container = container;
        }
    }

    public enum PacketType
    {
        Command,
        Data
    }
</code>```

If I need to send information about files I just create a packet with the necessary structure CreatePacket<FilesInfo>(filesInfo) and then serialize it and send it to client\server.

But how I can deserialize data on receiving side? I don't know what is object type the packet is. Is there any other way or library or something to solve my problem? Also I don't want to use WCF because my app should work on machines with .NET 2.0 installed.

答:
If you are useing XML serialization, this seems to work well....</p>

```<code>private string GetClassNameFromXMLSerializedString(string xml)
    {
        xml = xml.Substring(xml.IndexOf(">\r\n<") + 3, 50);//get second XML element
        return xml.Substring(1, xml.IndexOf(' ') - 1);//get class name
    }
</code>```

Body:
Well I want to send commands and data between client and server.

I have three projects:

Client

Server

Common - here I put common classes and network abstraction layer

I am using following data structures for communications between client and server

public class Packet<T>
{
        public string Name { get; set; }
        public string From { get; set; }
        public string To { get; set; }
        public PacketType PacketType { get; set; }
        public T Container { get; set; }

        public Packet()
        {
        }

        public Packet(string name, PacketType packetType, T container)
        {
            Name = name;
            PacketType = packetType;
            Container = container;
        }
    }

    public enum PacketType
    {
        Command,
        Data
    }

If I need to send information about files I just create a packet with the necessary structure CreatePacket<FilesInfo>(filesInfo) and then serialize it and send it to client\server.

But how I can deserialize data on receiving side? I don't know what is object type the packet is. Is there any other way or library or something to solve my problem? Also I don't want to use WCF because my app should work on machines with .NET 2.0 installed.

Body:
If you are useing XML serialization, this seems to work well....

private string GetClassNameFromXMLSerializedString(string xml)
    {
        xml = xml.Substring(xml.IndexOf(">\r\n<") + 3, 50);//get second XML element
        return xml.Substring(1, xml.IndexOf(' ') - 1);//get class name
    }


来源: stackexchange

问:
Why cant I parse this JSON output using shell/python?
Here is the output from the response I am trying to parse:

```<code>[{"name":"UsedMemory","value":{"value":"35054384","type":"java.lang.Long"}},
{"name":"FreeMemory","value":{"value":"7085264","type":"java.lang.Long"}},{"name":"Heap","value":{"value":"42139648","type":"java.lang.Long"}},{"name":"UpTime","value":{"value":"3350544","type":"java.lang.Long"}},{"name":"ProcessCPU","value":{"value":"0.3625301325982962","type":"java.lang.Double"}},{"name":"GcCount","value":{"value":"224","type":"java.lang.Long"}},{"name":"GcTime","value":{"value":"335","type":"java.lang.Long"}}]
</code>```

I am storing the response in a shell variable called $jvmStats and expect to be able to retrieve a value from it based on name like this:

```<code>$jvmStats | python -c "import sys, json; print json.load(sys.stdin)['UsedMemory']"
</code>```

but the response I get is:

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: list indices must be integers, not str
</code>```

Pretty new to working with JSON and unfortunately don't have the ability to use jq on this system - can some one point out the problem to me? This seems like a fairly standard approach according to all the other answers I see here - so perhaps nested value parts is the problem?

答:
Try this:

```<code>jvmStats | python -c "import sys, json; print json.load(sys.stdin)[0]['name']"
</code>```

This is because your JSON is first a list and then a dictionary, so you need to index the list first and then the key of the dictionary.

Also, you can only index JSON by its key, not its value.

ContentLicense: CC BY-SA 3.0

Body:
Here is the output from the response I am trying to parse:

[{"name":"UsedMemory","value":{"value":"35054384","type":"java.lang.Long"}},
{"name":"FreeMemory","value":{"value":"7085264","type":"java.lang.Long"}},{"name":"Heap","value":{"value":"42139648","type":"java.lang.Long"}},{"name":"UpTime","value":{"value":"3350544","type":"java.lang.Long"}},{"name":"ProcessCPU","value":{"value":"0.3625301325982962","type":"java.lang.Double"}},{"name":"GcCount","value":{"value":"224","type":"java.lang.Long"}},{"name":"GcTime","value":{"value":"335","type":"java.lang.Long"}}]

I am storing the response in a shell variable called $jvmStats and expect to be able to retrieve a value from it based on name like this:

$jvmStats | python -c "import sys, json; print json.load(sys.stdin)['UsedMemory']"

but the response I get is:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: list indices must be integers, not str

Pretty new to working with JSON and unfortunately don't have the ability to use jq on this system - can some one point out the problem to me? This seems like a fairly standard approach according to all the other answers I see here - so perhaps nested value parts is the problem?

Body:
Try this:

jvmStats | python -c "import sys, json; print json.load(sys.stdin)[0]['name']"

This is because your JSON is first a list and then a dictionary, so you need to index the list first and then the key of the dictionary.

Also, you can only index JSON by its key, not its value.


问:
How to save changes made on the pdf file using iText on ASP.NET?
I am creating a web application that automates our work with PDFs.

I am currently testing iText7 on .NET to test if it fits our needs.

The main problem right now is saving modifications made to the file from a web page.

Edit

The scenario is following: we work with hundreds of PDF forms daily. We fill them up, modify, save, print, etc. The tool we are currently using for that is too complex. Thus, we want to simplify.

I tested that I can fill-up the form from the database and extract information from the fields. However, after filling up we may need to change some values in the form manually, save changes and write back to database.

The simplest solution is of course fill up, download the file, edit and save locally, re-upload the file onto the server, and then extract values out of the updated form and fill-up the database. It works, but it includes too much manual work such as downloading and re-uploading. My clients want it automated.

The other approach I tried was showing the pdf document in my web app, edit, and save all modifications with a button (on a web page). But couldn't make my button save the updated pdf document. I showed the file in MVC view like this:
object data="@Url.Action("ShowPDFwithButton", "PdfTemplates", new { id = Model.FilledForm.id })"type="application/pdf">/object>

The third approach I came up with is to add a new page with a 'Save' button on it to my filled form. I wanted that button in pdf itself to save my modifications. After that I would just extract the values of the saved form and update the database. I tried this code to add some functionality to my 'Save' button, but can't understand how to make it save changes and/or send the updated file to my action controller:button.SetAction(PdfAction.CreateSubmitForm("/PdfTemplates/SavePdf/" + pdfMetadata.id, null,PdfAction.SUBMIT_EXCL_F_KEY));

I would appreciate if anyone could help making the second and third approach work. Or maybe offer other approaches.

答:
The OP clarified in comments what he meant by saving modifications made to the file from a web page:

I was talking about form fill ins. Can you please share code sample on how to send form content to target URL?

Unfortunately I could only find an example for that for iText 7 for Java:

public void manipulatePdf(String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(SUBCRIBE), new PdfWriter(dest));
    PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
    PdfButtonFormField submit1 = PdfFormField.createPushButton(pdfDoc, new Rectangle(90, 660, 50, 30), "POST", "post");
    submit1.setBackgroundColor(new DeviceGray(0.75f));
    submit1.setVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT);
    submit1.setAction(PdfAction.createSubmitForm(
            "/book/request", null,
            PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES));
    // add the button
    form.addField(submit1);
    // create a submit button that posts the form as FDF
    PdfButtonFormField submit2 = PdfFormField.createPushButton(
            pdfDoc, new Rectangle(200, 660, 50, 30), "FDF", "FDF");
    submit2.setBackgroundColor(new DeviceGray(0.7f));
    submit2.setVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT);
    submit2.setAction(PdfAction.createSubmitForm(
            "/book/request", null, PdfAction.SUBMIT_EXCL_F_KEY));
    // add the button
    form.addField(submit2);
    // create a submit button that posts the form as XFDF
    PdfButtonFormField submit3 = PdfFormField.createPushButton(
            pdfDoc, new Rectangle(310, 660, 50, 30), "XFDF", "XFDF");
    submit3.setBackgroundColor(new DeviceGray(0.7f));
    submit3.setVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT);
    submit3.setAction(PdfAction.createSubmitForm(
            "/book/request", null, PdfAction.SUBMIT_XFDF));
    // add the button
    form.addField(submit3);
    // create a reset button
    PdfButtonFormField reset = PdfFormField.createPushButton(
            pdfDoc, new Rectangle(420, 660, 50, 30), "reset", "RESET");
    reset.setBackgroundColor(new DeviceGray(0.7f));
    reset.setVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT);
    // TODO DEVSIX-573
    reset.setAction(PdfAction.createResetForm(null, 0));
    form.addField(reset);
    // close the document
    pdfDoc.close();
}
```

(SubmitForm.java example ported to iText 7 from chapter 9 of iText in Action, 2nd edition)

As you see there are multiple options depending on what exactly shall be sent to the URL.

Body:
The OP clarified in comments what he meant by saving modifications made to the file from a web page:

I was talking about form fill ins. Can you please share code sample on how to send form content to target URL?

Unfortunately I could only find an example for that for iText 7 for Java:

public void manipulatePdf(String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(SUBCRIBE), new PdfWriter(dest));
    PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
    PdfButtonFormField submit1 = PdfFormField.createPushButton(pdfDoc, new Rectangle(90, 660, 50, 30), "POST", "post");
    submit1.setBackgroundColor(new DeviceGray(0.75f));
    submit1.setVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT);
    submit1.setAction(PdfAction.createSubmitForm(
            "/book/request", null,
            PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_COORDINATES));
    // add the button
    form.addField(submit1);
    // create a submit button that posts the form as FDF
    PdfButtonFormField submit2 = PdfFormField.createPushButton(
            pdfDoc, new Rectangle(200, 660, 50, 30), "FDF", "FDF");
    submit2.setBackgroundColor(new DeviceGray(0.7f));
    submit2.setVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT);
    submit2.setAction(PdfAction.createSubmitForm(
            "/book/request", null, PdfAction.SUBMIT_EXCL_F_KEY));
    // add the button
    form.addField(submit2);
    // create a submit button that posts the form as XFDF
    PdfButtonFormField submit3 = PdfFormField.createPushButton(
            pdfDoc, new Rectangle(310, 660, 50, 30), "XFDF", "XFDF");
    submit3.setBackgroundColor(new DeviceGray(0.7f));
    submit3.setVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT);
    submit3.setAction(PdfAction.createSubmitForm(
            "/book/request", null, PdfAction.SUBMIT_XFDF));
    // add the button
    form.addField(submit3);
    // create a reset button
    PdfButtonFormField reset = PdfFormField.createPushButton(
            pdfDoc, new Rectangle(420, 660, 50, 30), "reset", "RESET");
    reset.setBackgroundColor(new DeviceGray(0.7f));
    reset.setVisibility(PdfFormField.VISIBLE_BUT_DOES_NOT_PRINT);
    // TODO DEVSIX-573
    reset.setAction(PdfAction.createResetForm(null, 0));
    form.addField(reset);
    // close the document
    pdfDoc.close();
}

(SubmitForm.java example ported to iText 7 from chapter 9 of iText in Action, 2nd edition)

As you see there are multiple options depending on what exactly shall be sent to the URL.


问:
WPF WCF MVVM OutOfMemoryException
I am working on this WCF-WPF app. I am frequently getting this error on an asynchronous XamDataGrid. Trying to make a WCF call and populate the Grid. I initially thought this is something to do with the large amounts of data returned from WCF and I made the call return data is much small pieces, by calling only for a category only. This error comes up randomly, not always on the same set of data. Reproducible enough in 15-20 tries.

I am running Windows XP (32bit), Dual Core, with 4GB of ram. When this exception is raised, client machine only uses about 2GB of RAM, and on the server W3WP is using only 800MB (of 6GB, 3 cores. Total memory use on server is ~2GB).

This is only happening on XP machines. Does not get this error on Windows 7 box.

Please guide me how to resolve this issue.

Thanks in advance

```<code>Event Viewer Logs this Message:
Event Type: Error
Event Source:   .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID:   5000
Date:       10/13/2010
Time:       10:50:07 AM
User:       N/A
Computer:   COMP-DC7800
Description:
EventType clr20r3, P1 appname.exe, P2 2.0.0.21872, P3 4cb0a1b1, P4 mscorlib, P5 2.0.0.0, P6 492b834a, P7 35df, P8 45, P9 system.outofmemoryexception, P10 NIL.
</code>```

Below id the Exception details:

```<code>System.OutOfMemoryException was unhandled
Message="Exception of type 'System.OutOfMemoryException' was thrown."
Source="mscorlib"
StackTrace:
   at System.IO.MemoryStream.set_Capacity(Int32 value)
   at System.IO.MemoryStream.EnsureCapacity(Int32 value)
   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlMtomReader.MimePart.GetBuffer(Int32 maxBuffer, Int32& remaining)
   at System.Xml.XmlMtomReader.Initialize(Stream stream, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize)
   at System.Xml.XmlMtomReader.SetInput(Stream stream, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
   at System.Xml.XmlMtomReader.SetInput(Byte[] buffer, Int32 offset, Int32 count, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
   at System.ServiceModel.Channels.MtomMessageEncoder.MtomBufferedMessageData.TakeXmlReader()
   at System.ServiceModel.Channels.BufferedMessageData.DoTakeXmlReader()
   at System.ServiceModel.Channels.BufferedMessageData.GetMessageReader()
   at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReaderAtHeaderContents(IBufferedMessageData bufferedMessageData)
   at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReader(IBufferedMessageData bufferedMessageData, Int32 bufferedMessageHeaderIndex)
   at System.ServiceModel.Channels.MessageHeaders.GetReaderAtHeader(Int32 headerIndex)
   at System.ServiceModel.Channels.WsrmMessageInfo.Get(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, IChannel channel, ISession session, Message message, Boolean csrOnly)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.HandleReceiveComplete(IAsyncResult result)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnReceiveCompletedStatic(IAsyncResult result)
   at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputComplete(IAsyncResult result)
   at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputCompleteStatic(IAsyncResult result)
   at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.Channels.InputQueue`1.AsyncQueueReader.Set(Item item)
   at System.ServiceModel.Channels.InputQueue`1.Dispatch()
   at System.ServiceModel.Channels.InputQueue`1.OnDispatchCallback(Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.OnSecurityContextCallback(Object o)
   at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</code>```

答:
OutOfMemory exceptions can happen for a lot of reasons in general, and in web apps in particular.

First, if you're running on IIS, there are settings specific to IIS to limit memory, see here: http://blogs.msdn.com/b/pfedev/archive/2009/01/22/memory-based-recycling-in-iis-6-0.aspx

Depending on your configuration, pools, etc., these limits may not apply to .NET web applications.

Now, in ASP.NET, there is also a setting memoryLimit in the machine.config file that specifies the maximum allowed memory size, as a percentage of total system memory, that the worker process can consume before ASP.NET launches a new process and reassigns existing requests.

The default is 60%, which is equal to 1.2G on a 2G machine.

However,... whatever you configure, 800M is the practical limit for ASP.NET apps on a 32-bit machine, see a good explanation here: Understanding ASP.Net memory

The solution to avoid this is to change the way your system works and break it in smaller pieces.

That's why by default, WCF has been carefully configured with so many limits (see here for an extensive list: http://weblogs.asp.net/paolopia/archive/2008/03/23/wcf-configuration-default-limits-concurrency-and-scalability.aspx) ... which almost every developer tends to change and  max-out as soon as he discovers it :-)

ContentLicense: CC BY-SA 2.5

Title: WPF WCF MVVM OutOfMemoryException

Body:
I am working on this WCF-WPF app. I am frequently getting this error on an asynchronous XamDataGrid. Trying to make a WCF call and populate the Grid. I initially thought this is something to do with the large amounts of data returned from WCF and I made the call return data is much small pieces, by calling only for a category only. This error comes up randomly, not always on the same set of data. Reproducible enough in 15-20 tries.

I am running Windows XP (32bit), Dual Core, with 4GB of ram. When this exception is raised, client machine only uses about 2GB of RAM, and on the server W3WP is using only 800MB (of 6GB, 3 cores. Total memory use on server is ~2GB).

This is only happening on XP machines. Does not get this error on Windows 7 box.

Please guide me how to resolve this issue.

Thanks in advance

Event Viewer Logs this Message:
Event Type: Error
Event Source:   .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID:   5000
Date:       10/13/2010
Time:       10:50:07 AM
User:       N/A
Computer:   COMP-DC7800
Description:
EventType clr20r3, P1 appname.exe, P2 2.0.0.21872, P3 4cb0a1b1, P4 mscorlib, P5 2.0.0.0, P6 492b834a, P7 35df, P8 45, P9 system.outofmemoryexception, P10 NIL.

Below id the Exception details:

System.OutOfMemoryException was unhandled
Message="Exception of type 'System.OutOfMemoryException' was thrown."
Source="mscorlib"
StackTrace:
   at System.IO.MemoryStream.set_Capacity(Int32 value)
   at System.IO.MemoryStream.EnsureCapacity(Int32 value)
   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlMtomReader.MimePart.GetBuffer(Int32 maxBuffer, Int32& remaining)
   at System.Xml.XmlMtomReader.Initialize(Stream stream, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize)
   at System.Xml.XmlMtomReader.SetInput(Stream stream, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
   at System.Xml.XmlMtomReader.SetInput(Byte[] buffer, Int32 offset, Int32 count, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
   at System.ServiceModel.Channels.MtomMessageEncoder.MtomBufferedMessageData.TakeXmlReader()
   at System.ServiceModel.Channels.BufferedMessageData.DoTakeXmlReader()
   at System.ServiceModel.Channels.BufferedMessageData.GetMessageReader()
   at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReaderAtHeaderContents(IBufferedMessageData bufferedMessageData)
   at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReader(IBufferedMessageData bufferedMessageData, Int32 bufferedMessageHeaderIndex)
   at System.ServiceModel.Channels.MessageHeaders.GetReaderAtHeader(Int32 headerIndex)
   at System.ServiceModel.Channels.WsrmMessageInfo.Get(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, IChannel channel, ISession session, Message message, Boolean csrOnly)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.HandleReceiveComplete(IAsyncResult result)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnReceiveCompletedStatic(IAsyncResult result)
   at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputComplete(IAsyncResult result)
   at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputCompleteStatic(IAsyncResult result)
   at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.Channels.InputQueue`1.AsyncQueueReader.Set(Item item)
   at System.ServiceModel.Channels.InputQueue`1.Dispatch()
   at System.ServiceModel.Channels.InputQueue`1.OnDispatchCallback(Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.OnSecurityContextCallback(Object o)
   at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)


问:
Undefined variable sent from Ajax to MVC Controller
I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:

```<code> [HttpPost]
    public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
    {
        if (pwd == null || repeatpwd == null)
        {
            ViewBag.Error = "Insira os campos obrigatórios";
        }
        else
        {
            if (pwd == repeatpwd)
            {
                changePwd_Entidades(Session["ID"].ToString(),pwd);
                return Json(true,JsonRequestBehavior.DenyGet);
            }
            else
            {
                ViewBag.Error = "As palavras chave precisam de ser iguais";
            }
        }

        return Json(false, JsonRequestBehavior.DenyGet);
    }
</code>```

Script:

```<code><script>

$('.alt-btn').on('click', function () {

    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: '@Url.Action("ChangePwdEnt", "Home")?pwd=' +
        $('#Info_pwd').val() + '&repeatpwd=' + $('#Info_repeatpwd').val(),

        error: function (e) {
            console.log(e);
        },

        success: function (Changed) {
            if (Changed) {
                window.location = "Entidades";
            } else if (!Changed) {
                window.location = "LoginEntidades";
            }
        }
    });
});
</code>```

答:
That would be better to Send the data in the data parameter while you're using POST method

```<code>var data = JSON.stringify({
             'pwd': $('#Info_pwd').val(),
             'repeatpwd':$('#Info_repeatpwd').val()
           });

$.ajax({
    type: 'POST',
    contentType: 'application/json',
    url: '@Url.Action("ChangePwdEnt", "Home"),
    data: data,
    error: function (e) {
        console.log(e);
    },

    success: function (Changed) {
        if (Changed) {
            window.location = "Entidades";
        } else if (!Changed) {
            window.location = "LoginEntidades";
        }
    }
});
</code>```

This is for using POST method. If you want to use GET method than it would be fine to pass data in query string.

Body:
I have a method where my users can change their password,to a new one,requiring 2 variables,one is the new password,and the other,the repetition of the password.The thing is that when i call the method, it returns the string "undefined",and uses that string as the new password,saving it on the db.
Can someone tell me what I'm doing wrong?
Controller:

 [HttpPost]
    public JsonResult ChangePwdEnt(string pwd, string repeatpwd)
    {
        if (pwd == null || repeatpwd == null)
        {
            ViewBag.Error = "Insira os campos obrigatórios";
        }
        else
        {
            if (pwd == repeatpwd)
            {
                changePwd_Entidades(Session["ID"].ToString(),pwd);
                return Json(true,JsonRequestBehavior.DenyGet);
            }
            else
            {
                ViewBag.Error = "As palavras chave precisam de ser iguais";
            }
        }

        return Json(false, JsonRequestBehavior.DenyGet);
    }

Script:

Body:
That would be better to Send the data in the data parameter while you're using POST method

var data = JSON.stringify({
             'pwd': $('#Info_pwd').val(),
             'repeatpwd':$('#Info_repeatpwd').val()
           });

$.ajax({
    type: 'POST',
    contentType: 'application/json',
    url: '@Url.Action("ChangePwdEnt", "Home"),
    data: data,
    error: function (e) {
        console.log(e);
    },

    success: function (Changed) {
        if (Changed) {
            window.location = "Entidades";
        } else if (!Changed) {
            window.location = "LoginEntidades";
        }
    }
});

This is for using POST method. If you want to use GET method than it would be fine to pass data in query string.


问:
Overload-resolution in generic constructors
I created a mockup class to ilustrate the question:

```<code> public class Anything<T>
    {
        /// <summary>
        /// Generic typed constructor
        /// </summary>
        /// <param name="param1"></param>
        public Anything(T param1)
        {
            Console.WriteLine("I'm generic typed constructor");
        }

        /// <summary>
        /// String typed constructor
        /// </summary>
        /// <param name="param1"></param>
        public Anything(string param1)
        {
            Console.WriteLine("I'm string typed constructor");
        }
    }
</code>```

Whats up if I build Anything of string object? There is no way to differentiate both constructors. It's a bad practice define another constructor with the same number of parameters?

答:
The compiler will always choose the most specific overloaded method, that is the one with the stringparameter in its signature. Even if you have a generic method (or constructor in your case) the explicitly typed string parameter is the most specific one. Thus

```<code>new Anything<string>("test");
</code>```

will output

I'm string typed constructor

From a software engineering perspective, it is indeed a bad practice because it would not be clear to the user of the class why for example the constructor with the string parameter would exhibit different behavoir than the generic one.

Body:
I created a mockup class to ilustrate the question:

 public class Anything<T>
    {
        ///
        /// Generic typed constructor
        ///
        /// <param name="param1"></param>
        public Anything(T param1)
        {
            Console.WriteLine("I'm generic typed constructor");
        }

        ///
        /// String typed constructor
        ///
        /// <param name="param1"></param>
        public Anything(string param1)
        {
            Console.WriteLine("I'm string typed constructor");
        }
    }

Whats up if I build Anything of string object? There is no way to differentiate both constructors. It's a bad practice define another constructor with the same number of parameters?

Body:
The compiler will always choose the most specific overloaded method, that is the one with the stringparameter in its signature. Even if you have a generic method (or constructor in your case) the explicitly typed string parameter is the most specific one. Thus

new Anything<string>("test");

will output

I'm string typed constructor

From a software engineering perspective, it is indeed a bad practice because it would not be clear to the user of the class why for example the constructor with the string parameter would exhibit different behavoir than the generic one.


问:
Regex: Extract specific value from URL
I am having some trouble to exact the string from URL using re library.

here's an example:

```<code>http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd"
</code>```

I have a dataframe and i want to add a column using a value from another column, in this example df['URL_REG'] contains: '123'?

```<code>df['URL_REG'] = df['URL'].map(lambda x : re.findall(r'[REGEX]+', x)[0])
</code>```

the structure of URL can change but the part that i want comes always between 'direction=vente.aspx%3pid%' and '%'.

答:
Use vectorized Series.str.extract() method:

```<code>In [50]: df['URL_REG'] = df.URL.str.extract(r'direction=vente.aspx\%3pid\%([^\%]+)\%*',
                                            expand=False)

In [51]: df
Out[51]:
                                                 URL URL_REG
0  http://www.example.it/remoteconnexion.aspx?u=x...   xx123
</code>```

UPDATE:

i want only '123' part instead of 'xx123', where 'xx' is a hexademical number

```<code>In [53]: df['URL_REG'] = df.URL.str.extract(r'direction=vente.aspx\%3pid\%\w{2}(\d+)\%*',
                                            expand=False)

In [54]: df
Out[54]:
                                                 URL URL_REG
0  http://www.example.it/remoteconnexion.aspx?u=x...     123
</code>```

Title: Regex: Extract specific value from URL

Body:
I am having some trouble to exact the string from URL using re library.

here's an example:

http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd"

I have a dataframe and i want to add a column using a value from another column, in this example df['URL_REG'] contains: '123'?

df['URL_REG'] = df['URL'].map(lambda x : re.findall(r'[REGEX]+', x)[0])

the structure of URL can change but the part that i want comes always between 'direction=vente.aspx%3pid%' and '%'.

Body:
Use vectorized Series.str.extract() method:

In [50]: df['URL_REG'] = df.URL.str.extract(r'direction=vente.aspx\%3pid\%([^\%]+)\%*',
                                            expand=False)

In [51]: df
Out[51]:
                                                 URL URL_REG
0  http://www.example.it/remoteconnexion.aspx?u=x...   xx123

UPDATE:

i want only '123' part instead of 'xx123', where 'xx' is a hexademical number

In [53]: df['URL_REG'] = df.URL.str.extract(r'direction=vente.aspx\%3pid\%\w{2}(\d+)\%*',
                                            expand=False)

In [54]: df
Out[54]:
                                                 URL URL_REG
0  http://www.example.it/remoteconnexion.aspx?u=x...     123


问:
Positioning on javascript DOM with bootstrap
I'm planning to create a dynamic textbox that will be divided into two rows equally downwards even on the odd count of textbox_value but having trouble on my code.

MY EXPECTED OUTPUT:

I need to have Reading 1 and Reading 5 on same row as well as
Reading 2 and Reading 6 on same row
Reading 3 and Reading 7 on same row
Reading 4 alone on one row.

ACCUMULATED OUTPUT ON MY CODE:

It looks like textboxes Reading 5,6 and 7 are positioned with the same row as Reading 4.

CODE SNIPPET:

```<code>var textbox_value = 7;

for (var count = 1; count <= Math.round(textbox_value/2); count++){
        var childdiv = document.createElement("div");
        childdiv.className = "row";
        var textboxdiv = document.createElement("div");
        textboxdiv.className = "col-md-6";
        var label = document.createElement("label");
        label.innerHTML = display+' '+count;
        var input = document.createElement("input");
        input.id = textbox_group+count;
        input.className = "form-control circle";
        input.type = "text";
        input.setAttribute("placeholder", display+' '+count);
        input.setAttribute("ng-model", "field."+textbox_group+"["+count+"]");
        input.setAttribute("onkeypress","ValidationNum('"+textbox_group+count+"',$(this).val())");
        input.setAttribute("onkeyup", "get_meter_data_capture('onclick','"+special_meter_tag+"')");

        textboxdiv.appendChild(label);
        textboxdiv.appendChild(input);
        childdiv.appendChild(textboxdiv);
        parentdiv.appendChild(childdiv);
    }

  for (var count2 = Math.round(textbox_value/2)+1; count2 <= textbox_value; count2++){
        var textboxdiv2 = document.createElement("div");
        textboxdiv2.className = "col-md-6"
        var label2 = document.createElement("label");
        label2.innerHTML = display+' '+count2;
        var input2 = document.createElement("input");
        input2.id = textbox_group+count2;
        input2.className = "form-control circle";
        input2.type = "text";
        input2.setAttribute("placeholder", display+' '+count2);
        input2.setAttribute("ng-model", "field."+textbox_group+"["+count2+"]");
        input2.setAttribute("onkeypress","ValidationNum('"+textbox_group+count2+"',$(this).val())");
        input2.setAttribute("onkeyup", "get_meter_data_capture('onclick','"+special_meter_tag+"')");

        textboxdiv2.appendChild(label2);
        textboxdiv2.appendChild(input2);
        childdiv.appendChild(textboxdiv2);
        parentdiv.appendChild(childdiv);
    }
</code>```

答:
u can create a row first, then 2 columns and add ur textboxes to these columns like</p>

```<code><div class="row">

<div class="col">
for(var i=1;i<=count/2;i++){
<div> ur label and textbox </div>
}
</div> end of first column

<div class="col">
for(var i=count/2+1;i<=count;i++) {
<div> ur label and textbox </div>
}
</div> end of second column

<div> end of row
</code>```

Body:
I'm planning to create a dynamic textbox that will be divided into two rows equally downwards even on the odd count of textbox_value but having trouble on my code.

MY EXPECTED OUTPUT:

I need to have Reading 1 and Reading 5 on same row as well as
Reading 2 and Reading 6 on same row
Reading 3 and Reading 7 on same row
Reading 4 alone on one row.

ACCUMULATED OUTPUT ON MY CODE:

It looks like textboxes Reading 5,6 and 7 are positioned with the same row as Reading 4.

CODE SNIPPET:

var textbox_value = 7;

for (var count = 1; count <= Math.round(textbox_value/2); count++){
        var childdiv = document.createElement("div");
        childdiv.className = "row";
        var textboxdiv = document.createElement("div");
        textboxdiv.className = "col-md-6";
        var label = document.createElement("label");
        label.innerHTML = display+' '+count;
        var input = document.createElement("input");
        input.id = textbox_group+count;
        input.className = "form-control circle";
        input.type = "text";
        input.setAttribute("placeholder", display+' '+count);
        input.setAttribute("ng-model", "field."+textbox_group+"["+count+"]");
        input.setAttribute("onkeypress","ValidationNum('"+textbox_group+count+"',$(this).val())");
        input.setAttribute("onkeyup", "get_meter_data_capture('onclick','"+special_meter_tag+"')");

        textboxdiv.appendChild(label);
        textboxdiv.appendChild(input);
        childdiv.appendChild(textboxdiv);
        parentdiv.appendChild(childdiv);
    }

  for (var count2 = Math.round(textbox_value/2)+1; count2 <= textbox_value; count2++){
        var textboxdiv2 = document.createElement("div");
        textboxdiv2.className = "col-md-6"
        var label2 = document.createElement("label");
        label2.innerHTML = display+' '+count2;
        var input2 = document.createElement("input");
        input2.id = textbox_group+count2;
        input2.className = "form-control circle";
        input2.type = "text";
        input2.setAttribute("placeholder", display+' '+count2);
        input2.setAttribute("ng-model", "field."+textbox_group+"["+count2+"]");
        input2.setAttribute("onkeypress","ValidationNum('"+textbox_group+count2+"',$(this).val())");
        input2.setAttribute("onkeyup", "get_meter_data_capture('onclick','"+special_meter_tag+"')");

        textboxdiv2.appendChild(label2);
        textboxdiv2.appendChild(input2);
        childdiv.appendChild(textboxdiv2);
        parentdiv.appendChild(childdiv);
    }

Body:
u can create a row first, then 2 columns and add ur textboxes to these columns like

<div class="row">

<div class="col">
for(var i=1;i<=count/2;i++){
<div> ur label and textbox </div>
}
</div> end of first column

<div class="col">
for(var i=count/2+1;i<=count;i++) {
<div> ur label and textbox </div>
}
</div> end of second column

<div> end of row


问:
bootstrap datetimepicker not working in DIV class
I am trying to put in a bootstrap datetimepicker in my customized table. But it just won't work. i understood that you can't placed a script in th, so i placed it in td, but it's still not working.

Simple and working datepicker.

```<code><tr>
<td>Date</td>
<td><!-- mktime(hour, minute, second, month, day, year) -->
<input type="text" name="call_date" value="<?php echo $adjdate;?>" id="datepicker" class="input-small">
</td>
</tr>
</code>```

When i tried to implement bootstrap date time picker, it just won't work. I think i've misplaced something in the code below here.

```<code><tr>
<td>Date</td>
<td>
<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            $('#datetimepicker1').datetimepicker();
        });
    </script>
</div>
</div>
</td>
</tr>
</code>```

Additional info:
i forgot to mention that i've added in

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
</code>```

But if i placed code outside instead of putting inside td, it will work

```<code><div class="container">
<div class="row">
   <div class='col-sm-6'>
    <div class="form-group">
        <div class='input-group date' id='datetimepicker1'>
            <input type='text' class="form-control" />
            <span class="input-group-addon">
                <span class="glyphicon glyphicon-calendar"></span>
            </span>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        $('#datetimepicker1').datetimepicker();
    });
</script>
</code>```

I just need advice regarding this, and thanks for showing me those examples, it helps a lot, thank you

答:
```<code><div class="modal-header__training-start">Start at
                <input type="text" id="datetimepicker-start" class="datetimepicker-start" data-function="training-start">
                <div class="datetimepicker-icon">
                        <span class="glyphicon glyphicon-calendar" style="top:3px;"></span>
                </div>
</code>```

```<code>$("#datetimepicker-start").datetimepicker(
{
    format: 'yyyy-mm-dd hh:ii:ss',
});
</code>```

I think the selector must be the input to start datetimepicker.

You have to include 2 files to project: bootstrap-datetimepicker.js &  bootstrap-datetimepicker.css

Body:
I am trying to put in a bootstrap datetimepicker in my customized table. But it just won't work. i understood that you can't placed a script in th, so i placed it in td, but it's still not working.

Simple and working datepicker.

Date

<input type="text" name="call_date" value="<?php echo $adjdate;?>" id="datepicker" class="input-small">

When i tried to implement bootstrap date time picker, it just won't work. I think i've misplaced something in the code below here.

Date

                <input type='text' class="form-control" />

Additional info:
i forgot to mention that i've added in

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

But if i placed code outside instead of putting inside td, it will work

            <input type='text' class="form-control" />

I just need advice regarding this, and thanks for showing me those examples, it helps a lot, thank you

Body:
<div class="modal-header__training-start">Start at
                <input type="text" id="datetimepicker-start" class="datetimepicker-start" data-function="training-start">
                <div class="datetimepicker-icon">
                        <span class="glyphicon glyphicon-calendar" style="top:3px;"></span>
                </div>

$("#datetimepicker-start").datetimepicker(
{
    format: 'yyyy-mm-dd hh:ii:ss',
});

I think the selector must be the input to start datetimepicker.

You have to include 2 files to project: bootstrap-datetimepicker.js &  bootstrap-datetimepicker.css


问:
Cache some map area of Google Map and then use offline. -swift3
I am working on an iOS project with Google map and want to save/cache an area/part of the map so that I can use it even if there is no internet. Please help me with this.</p>

答:
I have found some solution for my own question.

https://www.imore.com/how-cache-maps-offline-use-google-maps-20-ios

http://www.cultofmac.com/236643/heres-how-to-cache-your-maps-to-access-google-maps-offline-ios-tips/

May be this will help other.


问:
PHP SoapClient showing empty values when there is XML content
I am trying to get all the properties (GetAllProperties) of a certain job (inJobID). All the simple strings and digits show up properly, but the XML entities are just omitted, as if they are not there.

When echoing '$jobObj->__getLastResponse()' then the XML is there, but for some reason it disappears when trying to retrieve it.

The code is very basic:

```<code>$params->inUsername ='TheUser';
$params->inPassword ='ThePassword';
$params->inJobID = 184;
$jobObj = new SoapClient('http://SERVERNAME/job_ssp.asmx?wsdl', array('trace' => 1));

$Props = $jobObj->GetAllProperties($params);
print_r ($Props-> GetAllPropertiesResult);
</code>```

This is an example of an output:

```<code>stdClass Object
(
    [GetAllPropertiesResult] => stdClass Object
        (
            [Property] => Array
                (
                    [0] => stdClass Object
                        (
                            [m_Name] => jobID
                            [m_Value] => 184
                        )

                    [2] => stdClass Object
                        (
                            [m_Name] => userID
                            [m_Value] => 2
                        )

                    [21] => stdClass Object
                        (
                            [m_Name] => jobParams
                            [m_Value] =>
                        )
                )
        )
)
</code>```

The jobParams is always displayed as empty.

This is how it starts:
<?xml version='1.0' encoding='utf-16'?>

There is probably something extremely basic that I am missing here, but right now I am utterly baffled.

Help please?

Addition:
When using var_dump it shows that there are 3,579 characters in that string, but still does not show them:

```<code>[21]=> object(stdClass)#29 (2) { ["m_Name"]=> string(9) "jobParams" ["m_Value"]=> string(3579) "" }
</code>```

答:
```<code>echo htmlspecialchars(print_r ($Props-> GetAllPropertiesResult, 1));
</code>```

Body:
I am trying to get all the properties (GetAllProperties) of a certain job (inJobID). All the simple strings and digits show up properly, but the XML entities are just omitted, as if they are not there.

When echoing '$jobObj->__getLastResponse()' then the XML is there, but for some reason it disappears when trying to retrieve it.

The code is very basic:

$params->inUsername ='TheUser';
$params->inPassword ='ThePassword';
$params->inJobID = 184;
$jobObj = new SoapClient('http://SERVERNAME/job_ssp.asmx?wsdl', array('trace' => 1));

$Props = $jobObj->GetAllProperties($params);
print_r ($Props-> GetAllPropertiesResult);

This is an example of an output:

stdClass Object
(
    [GetAllPropertiesResult] => stdClass Object
        (
            [Property] => Array
                (
                    [0] => stdClass Object
                        (
                            [m_Name] => jobID
                            [m_Value] => 184
                        )

                    [2] => stdClass Object
                        (
                            [m_Name] => userID
                            [m_Value] => 2
                        )

                    [21] => stdClass Object
                        (
                            [m_Name] => jobParams
                            [m_Value] =>
                        )
                )
        )
)

The jobParams is always displayed as empty.

This is how it starts:
<?xml version='1.0' encoding='utf-16'?>

There is probably something extremely basic that I am missing here, but right now I am utterly baffled.

Help please?

Addition:
When using var_dump it shows that there are 3,579 characters in that string, but still does not show them:

[21]=> object(stdClass)#29 (2) { ["m_Name"]=> string(9) "jobParams" ["m_Value"]=> string(3579) "" }


问:
Uncaught TypeError: like is not a function at HTMLSpanElement.onclick. when i click on like its throughting error
when i click on like its throughting error

getting error:Uncaught TypeError: like is not a function at HTMLSpanElement.onclick

```<code>//In Controller
    myApp.controller('AppCtrl', ['$scope', '$http', 'chatBotService', function($scope, $http, chatBotService) {

        (function () {
            $scope.like = function (lll) {
                alert("like");
                //lll.previousSibling.style.color = 'gray';
                //lll.style.color = 'green';
            }
        });
           (function () {
            $scope.dislike = function (ddd) {
                alert("dislike");
                //ddd.style.color = 'red';
                //ddd.nextSibling.style.color = 'gray';
            }
           });

    function send_message(message) {
          $("#container").append("<div class='row msg_container base_receive'>" +
           "<div class='avatar'>" + "<img src='bot.png' alt='Chat' style='width:15px;margin-right: 10px;'/>" + "<br/>" +"</div>" + "<div class='col-md-10 col-xs-10'>" +"<div class='messages msg_receive'>" + message + "</div>" +"<small>" + DisplayCurrentTime() + "<small/>" + "<span id='dislike'
    class='glyphicon glyphicon-thumbs-down gly-flip-horizontal dislike' onclick='dislike(this)' aria-hidden='true'></span>" + "<span id='like' onclick='like(this)' class='glyphicon glyphicon-thumbs-up like' aria-hidden='true'></span>" +  "</div>" + "</div>");
            }

    }]);
</code>```

答:
remove the closure

```<code>$scope.like = function (lll) {
    alert("like");
    //lll.previousSibling.style.color = 'gray';
    //lll.style.color = 'green';
}

$scope.dislike = function (ddd) {
    alert("dislike");
    //ddd.style.color = 'red';
    //ddd.nextSibling.style.color = 'gray';
}
</code>```

or change it to IIFE

```<code>(function () {
    $scope.like = function (lll) {
        alert("like");
        //lll.previousSibling.style.color = 'gray';
        //lll.style.color = 'green';
    }
})();

(function () {
    $scope.dislike = function (ddd) {
        alert("dislike");
        //ddd.style.color = 'red';
        //ddd.nextSibling.style.color = 'gray';
    }
})();
</code>```

Body:
when i click on like its throughting error

getting error:Uncaught TypeError: like is not a function at HTMLSpanElement.onclick

//In Controller
    myApp.controller('AppCtrl', ['$scope', '$http', 'chatBotService', function($scope, $http, chatBotService) {

        (function () {
            $scope.like = function (lll) {
                alert("like");
                //lll.previousSibling.style.color = 'gray';
                //lll.style.color = 'green';
            }
        });
           (function () {
            $scope.dislike = function (ddd) {
                alert("dislike");
                //ddd.style.color = 'red';
                //ddd.nextSibling.style.color = 'gray';
            }
           });

    function send_message(message) {
          $("#container").append("
" +
           "
" + "" + "
" +"
" + "
" +"
" + message + "
" +"" + DisplayCurrentTime() + "" + "" + "" +  "
" + "
");
            }

    }]);

Body:
remove the closure

$scope.like = function (lll) {
    alert("like");
    //lll.previousSibling.style.color = 'gray';
    //lll.style.color = 'green';
}

$scope.dislike = function (ddd) {
    alert("dislike");
    //ddd.style.color = 'red';
    //ddd.nextSibling.style.color = 'gray';
}

or change it to IIFE

(function () {
    $scope.like = function (lll) {
        alert("like");
        //lll.previousSibling.style.color = 'gray';
        //lll.style.color = 'green';
    }
})();

(function () {
    $scope.dislike = function (ddd) {
        alert("dislike");
        //ddd.style.color = 'red';
        //ddd.nextSibling.style.color = 'gray';
    }
})();


问:
Using unique_ptr member variables or not?
What is a better designpattern for creating a blocking bufferqueue, that uses resources efficiently in C++11/14 without too many allocs/moves? Using Queue<std::unique_ptr<Workitem>>

OR

Queue<Workitem> and with that hiding the resource management in the implementation (a bit like stl containers). Note, the second idea (Queue) is commented out. What are the implications of the commented out version also regarding heap/stack? And what about using std::unique_ptr<Queue<Workitem>> q?

I am not very good with c++, but regardless of the version, I can't really leak memory right? (reasonging: not new/delete -> no memoryleaks)

Code here:

```<code>#include <condition_variable>
#include <mutex>
#include <queue>

template <class T> class Queue {
public:
  Queue(size_t size);

  // push item to _queue if _queue.size() < _size
  // else block
  void push(T item);
  // void push(std::unique_ptr<T> item);

  // pop item if !_queue.empty()
  // else block or return false after timeout
  bool pop(T &item);
  // bool pop(std::unique_ptr<T> &item);

private:
  std::mutex _mutex;
  std::size_t _size;

  std::queue<T> _queue;
  // std::queue<std::unique_ptr<T>> _queue;

  std::condition_variable _condition_full;
  std::condition_variable _condition_empty;
};

struct Workitem {
  size_t idx;
  void *workdetails;
};

void do_work(Queue<std::unique_ptr<Workitem>> &work_q,
             Queue<std::unique_ptr<Workitem>> &write_q,
             struct options_s &opts) {
  std::unique_ptr<Workitem> work;
  while (work_q.pop(work)) {
    // calculation w/ work
    std::unique_ptr<Workitem> res = consume(work, opts);
    write_q.push(std::move(work));
  }
}
void do_write(Queue<std::unique_ptr<Workitem>> &write_q,
              struct options_s &opts) {
  std::unique_ptr<Workitem> work;
  while (write_q.pop(work)) {
    prepare_for_writing(work, opts); // clean item
    write(work);
  }
}

auto w1 = std::thread(do_work, std::ref(work_q), std::ref(write_q),
                      std::ref(options));
auto w2 = std::thread(do_work, std::ref(work_q), std::ref(write_q),
                      std::ref(options));
auto writer = std::thread(do_write, std::ref(write_q), std::ref(options));

int main() {
  Queue<std::unique_ptr<Workitem>> work_q{4};
  Queue<std::unique_ptr<Workitem>> write_q{4};
  // Queue<Workitem> q{4};
  // ??? std::unique_ptr<Queue<Workitem>> q{4} ???

  for (size_t i, ...) { // do many iterations
    std::unique_ptr<Workitem> w{};
    // Workitem w{};

    populate(w, i); // populate work item

    work_q.push(std::move(w));
  }

  w1.join();
  w2.join();
  writer.join();
}
</code>```

I can give the implementation if that helps, I just didn't want to clutter everything so I left it out. As a remark, the queue is used by threads. I use two queues for multiple worker threads and one writer thread to spread the load across cores.

cheers

答:
What is a better designpattern for creating a blocking bufferqueue, that uses resources efficiently in C++11/14 without too many allocs/moves? Using Queue<std::unique_ptr<Workitem>> OR Queue<Workitem>

Given that criteria, Queue<Workitem> is better because it avoids one layer of dynamic allocation.

What are the implications of the commented out version also regarding heap/stack?

There aren't really any differences regarding heap versus stack. The objects are dynamically allocated in both variations.

I can't really leak memory right? (reasonging: not new/delete -> no memoryleaks)

Your reasoning is sound. The example code that you show has no memory leaks.

There however is a bare pointer member variable Workitem::workdetails that may have potential for memory leaks if it is misused (if it ever owns memory that it points to).

Body:
What is a better designpattern for creating a blocking bufferqueue, that uses resources efficiently in C++11/14 without too many allocs/moves? Using Queue<std::unique_ptr<Workitem>>

OR

Queue<Workitem> and with that hiding the resource management in the implementation (a bit like stl containers). Note, the second idea (Queue) is commented out. What are the implications of the commented out version also regarding heap/stack? And what about using std::unique_ptr<Queue<Workitem>> q?

I am not very good with c++, but regardless of the version, I can't really leak memory right? (reasonging: not new/delete -> no memoryleaks)

Code here:

#include <condition_variable>
#include <mutex>
#include <queue>

template <class T> class Queue {
public:
  Queue(size_t size);

  // push item to _queue if _queue.size() < _size
  // else block
  void push(T item);
  // void push(std::unique_ptr<T> item);

  // pop item if !_queue.empty()
  // else block or return false after timeout
  bool pop(T &item);
  // bool pop(std::unique_ptr<T> &item);

private:
  std::mutex _mutex;
  std::size_t _size;

  std::queue<T> _queue;
  // std::queue<std::unique_ptr<T>> _queue;

  std::condition_variable _condition_full;
  std::condition_variable _condition_empty;
};

struct Workitem {
  size_t idx;
  void *workdetails;
};

void do_work(Queue<std::unique_ptr<Workitem>> &work_q,
             Queue<std::unique_ptr<Workitem>> &write_q,
             struct options_s &opts) {
  std::unique_ptr<Workitem> work;
  while (work_q.pop(work)) {
    // calculation w/ work
    std::unique_ptr<Workitem> res = consume(work, opts);
    write_q.push(std::move(work));
  }
}
void do_write(Queue<std::unique_ptr<Workitem>> &write_q,
              struct options_s &opts) {
  std::unique_ptr<Workitem> work;
  while (write_q.pop(work)) {
    prepare_for_writing(work, opts); // clean item
    write(work);
  }
}

auto w1 = std::thread(do_work, std::ref(work_q), std::ref(write_q),
                      std::ref(options));
auto w2 = std::thread(do_work, std::ref(work_q), std::ref(write_q),
                      std::ref(options));
auto writer = std::thread(do_write, std::ref(write_q), std::ref(options));

int main() {
  Queue<std::unique_ptr<Workitem>> work_q{4};
  Queue<std::unique_ptr<Workitem>> write_q{4};
  // Queue<Workitem> q{4};
  // ??? std::unique_ptr<Queue<Workitem>> q{4} ???

  for (size_t i, ...) { // do many iterations
    std::unique_ptr<Workitem> w{};
    // Workitem w{};

    populate(w, i); // populate work item

    work_q.push(std::move(w));
  }

  w1.join();
  w2.join();
  writer.join();
}

I can give the implementation if that helps, I just didn't want to clutter everything so I left it out. As a remark, the queue is used by threads. I use two queues for multiple worker threads and one writer thread to spread the load across cores.

cheers


问:
Animate image opacity from 0 to 100 and back to 0
I have one image which is stacked on top of another one. I am trying to animate the top image opacity to 0 and then back to 100 and then again to 0. This should continue in a loop. Is there a way i can achieve it ?? Please help..</p>

```<code>$('.bannerHover').animate({
    opacity: 0.25
  }, 5000, function() {
  });
</code>```

答:
We can create a simple recursive function that calls jQuery's fade function, and when complete, call itself again using the callback supplied by the fade function. With jQuery 1.4.4's fadeToggle function, it can be done as simply as:

```<code>var b = $('#block');
function fade(){
    b.fadeToggle(1000, fade);
}
fade();
</code>```

See: http://www.jsfiddle.net/yijiang/FnBgL/ for a simple example

Body:
I have one image which is stacked on top of another one. I am trying to animate the top image opacity to 0 and then back to 100 and then again to 0. This should continue in a loop. Is there a way i can achieve it ?? Please help..

$('.bannerHover').animate({
    opacity: 0.25
  }, 5000, function() {
  });

Body:
We can create a simple recursive function that calls jQuery's fade function, and when complete, call itself again using the callback supplied by the fade function. With jQuery 1.4.4's fadeToggle function, it can be done as simply as:

var b = $('#block');
function fade(){
    b.fadeToggle(1000, fade);
}
fade();

See: http://www.jsfiddle.net/yijiang/FnBgL/ for a simple example


问:
ESlint in Eclipse
I have been given a web project at work that has a .eslintrc file in it and was told to use it.

I gather that this enforces code styles and sounds like a good idea, but I have never done this before.

I just switched to Eclipse Neon.  But I can find no tutorials on how to use it. I did find something that says eslint is now the default linter for Eclipse but that was for Orion.  Can someone tell me how to use my .eslintrc file for all my .js files in Eclipse?

答:
I'm using Neon myself, and this is how you configure ESLint:

Create an ESLint JSON configuration file by following these instructions.

Go to Project / Properties / JavaScript / Tern / Validation / ESLint and check "Use config files":

Enter the path to your eslint.json file (or whatever you named the file you created from step 1) and press OK.

If you want to disable ESLint (or any other module), go to Project / Properties / JavaScript / Tern / Modules and uncheck it.

Title: ESlint in Eclipse


答:
You can use this pattern:

```<code>import re

url='http://www.example.it/remoteconnexion.aspxu=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd'
output = re.findall('3pid%(.*?)%', url)

print(output)
</code>```

Output:

```<code>['xx123']
</code>```

Then apply the same pattern to your DataFrame.

For example:

```<code>import pandas as pd
import re

df = pd.DataFrame(['http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd'], columns = ['URL'])

output = df['URL'].apply(lambda x : re.findall('3pid%(.*?)%', x))

print(output)

# Or, maybe if you want to return the url and the data captured:
# output = df['URL'].apply(lambda x : (x, re.findall('3pid%(.*?)%', x)))
# output[0]
# >>> ('http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd',
#   ['xx123'])
</code>```

Output:

```<code>0    [xx123]
Name: URL, dtype: object
</code>```

Title: Regex: Extract specific value from URL

Body:
You can use this pattern:

import re

url='http://www.example.it/remoteconnexion.aspxu=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd'
output = re.findall('3pid%(.*?)%', url)

print(output)

Output:

['xx123']

Then apply the same pattern to your DataFrame.

For example:

import pandas as pd
import re

df = pd.DataFrame(['http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd'], columns = ['URL'])

output = df['URL'].apply(lambda x : re.findall('3pid%(.*?)%', x))

print(output)

# Or, maybe if you want to return the url and the data captured:
# output = df['URL'].apply(lambda x : (x, re.findall('3pid%(.*?)%', x)))
# output[0]
# >>> ('http://www.example.it/remoteconnexion.aspx?u=xxxxx@abc.it&direction=vente.aspx%3pid%xx123%63abcd',
#   ['xx123'])

Output:

0    [xx123]
Name: URL, dtype: object


问:
Check browser CSS property support with JavaScript?
Is it possible in JavaScript to know if a CSS property is supported by the client browser? I'm talking about the rotation properties of CSS3. I want to execute some functions only if the browser supports them.</p>

答:
May be try this?</p>

```<code>var temp = document.createElement('div');
var isSupport = temp.style['propName'] != undefined;
</code>```

Body:
May be try this?

var temp = document.createElement('div');
var isSupport = temp.style['propName'] != undefined;


问:
Method get a string
I am trying to make a get method in a class medicine to get the description.
As I know of that in C++, there is no data type "String" like in Java, therefore I need to make an array of char to save the description. I couldn't find a way to make a method with return type "array of chars", I use a pointer like the following.

```<code>class Medicine {
public:
    char description[100] = "testing";
    char *getDescription() {
        char *p_description;
        char *p_subDescription = (char*)malloc(100 * sizeof(char));
        strcpy(p_subDescription, description);
        p_description = p_subDescription;
        free(p_subDescription);
        return p_description;
    }
};
</code>```

I have a question: is there any other way I can do to make the code shorter? I feel like this is too much work just for a method to get a string.

Thank,

答:
You have to decided on your flavour of C++. If you want "C with classes", C++ very close to C, then you should be passing strings about as char *s to memory allocated with malloc. Your code is nearly correct (however you free memory then return it), but most people write a little function called strdup (in fact it's often provided, which means ironically it's best to call it mystrdup() to avoid collisions)

```<code>char *mystrdup(char *str)
{
   char *answer = malloc(strlen(st) +1);
   if(answer)
      strcpy(answer, str);
   return answer;
}
</code>```

If you are writing a more modern version of C++, use the std::string class. It isn't especially efficient and it's widely criticised for being over-desinged, but it's standard. It does memory management for you, and it's easy to create one.

Title: Method get a string

Body:
I am trying to make a get method in a class medicine to get the description.
As I know of that in C++, there is no data type "String" like in Java, therefore I need to make an array of char to save the description. I couldn't find a way to make a method with return type "array of chars", I use a pointer like the following.

class Medicine {
public:
    char description[100] = "testing";
    char *getDescription() {
        char *p_description;
        char *p_subDescription = (char*)malloc(100 * sizeof(char));
        strcpy(p_subDescription, description);
        p_description = p_subDescription;
        free(p_subDescription);
        return p_description;
    }
};

I have a question: is there any other way I can do to make the code shorter? I feel like this is too much work just for a method to get a string.

Thank,

Body:
You have to decided on your flavour of C++. If you want "C with classes", C++ very close to C, then you should be passing strings about as char *s to memory allocated with malloc. Your code is nearly correct (however you free memory then return it), but most people write a little function called strdup (in fact it's often provided, which means ironically it's best to call it mystrdup() to avoid collisions)

char *mystrdup(char *str)
{
   char *answer = malloc(strlen(st) +1);
   if(answer)
      strcpy(answer, str);
   return answer;
}

If you are writing a more modern version of C++, use the std::string class. It isn't especially efficient and it's widely criticised for being over-desinged, but it's standard. It does memory management for you, and it's easy to create one.


问:
Wrapping a link tag around PHP
I have the following PHP and need to make what's outputted (subheader, not thumbnail) hyperlinked to the parent directory

```<code><?php
        //$featured_img=get_template_directory_uri().'/img/default.png';
        $featured_img='';
        if(get_the_post_thumbnail_url()) {
            $featured_img=' style="background-image:url('.get_the_post_thumbnail_url().')"';
        }

        $subheader= '<p class="entry-subheader"> </p>';
        if(get_field('subheader') ) {
            $subheader= '<p class="entry-subheader">'.get_field('subheader').'</p>';
        }

    ?>
</code>```

I have no experience in PHP - only self taught in HTML and CSS so struggling as to where to put in the  link.

答:
```<code>$subheader= '<p class="entry-subheader"><a href="../">'.get_field('subheader').'</a></p>';
</code>```

Cd001's answer worked for me

Title: Wrapping a link tag around PHP

Body:
I have the following PHP and need to make what's outputted (subheader, not thumbnail) hyperlinked to the parent directory

<?php
        //$featured_img=get_template_directory_uri().'/img/default.png';
        $featured_img='';
        if(get_the_post_thumbnail_url()) {
            $featured_img=' style="background-image:url('.get_the_post_thumbnail_url().')"';
        }

        $subheader= '

';
        if(get_field('subheader') ) {
            $subheader= '
'.get_field('subheader').'
';
        }

    ?>

I have no experience in PHP - only self taught in HTML and CSS so struggling as to where to put in the  link.

Body:
$subheader= '<p class="entry-subheader"><a href="../">'.get_field('subheader').'</a></p>';

Cd001's answer worked for me


问:
Custom Calendar Date range swipe selection android
I need to design a custom calendar to choose dates while swiping over them. I need some solution on how to implement swipe on the calendar and also will be helpfull if there are any libraries which support this feature.

Any type of help will be considered. thank you!
The swipe date UI image is as shown

答:
As there are many Paid Calendars, I have developed an opensource Unpaid Calendar, which can be used to select dates while swiping over them. Which looks like this

Refer the source code at SwipeDateCalendar

which also can be further modified as per requirements.


问:
advanced search with configurable product in Magento
I have a clothing e-commerce website. I created color and size attributes and used them with configurable products. The configurable products have at least two associated products and those associated products have color and size options.

When I use advanced search to search items with a specified size attribute, nothing shows up on the result page. I guess it is because associated products' visibility is set to "Nowhere".

How do fix this?

答:
Above answer might suffice in some cases. I however experienced same problem as 'Moon' indicated in this thread, even though all visibility settings where correct for the configurable product (visibility 'catalog and search') and the attributes (show in advanced search 'yes').

E.g. a configurable product consisting of articles in size range 36 to 42 did only show size 36 in search results. Sizes 38 - 42 did not give any search result even though 'active', 'visible', 'in stock' etc..

I set up the associated products within the configurable products using the 'quick create option'

I managed to solve the issue as follows:
Setting the visibility of ONE associated product - one simple product within a configurable product - from 'not visible individually' to 'search' , saving the item and then changing back from visibility 'search' to 'not visible individually' solved the problem for ALL productvariations (thus all simple products) within the configurable products.

So changing the above for associated product size 38, suddenly revealed search results for all sizes,

It seems to be that the 'flag' in the table which should show the result in advanced search is not set correctly in first instance but only after a 're-edit'as explained above. I will dig into this further - when time allows ;-) . Don't know yet whether this is a Magento bug or is related to database or server settings.

Hope this will help someone who faces same situation.

Post-remark (edit):re-indexing ALL indexes not just the one that Magento advises to re-index might help too in this case.


问:
Trigger function on number input
I have a text input where users are able to write addresses, I want to trigger a javascript function when a number is typed in the text input, how can I achieve it?

EDIT: What I need is to know when a number has been typed, onkeyup via jquery works like a charm, this is what I did:

```<code>$("#q").keyup((e) => {

        var value = $("#q").val();

        var regex = new RegExp("[a-zA-Z0-9_ ]\\d+");

        var succeded = regex.test(value);

        ...
</code>```

答:
```<code>$('.js-input').on('keydown', function(e) {
    console.log('pressing:', e.keyCode);
});

<input type="text" class="js-input">
</code>```

DEMO

This will get you started

Title: Trigger function on number input

Body:
I have a text input where users are able to write addresses, I want to trigger a javascript function when a number is typed in the text input, how can I achieve it?

EDIT: What I need is to know when a number has been typed, onkeyup via jquery works like a charm, this is what I did:

$("#q").keyup((e) => {

        var value = $("#q").val();

        var regex = new RegExp("[a-zA-Z0-9_ ]\\d+");

        var succeded = regex.test(value);

        ...

Body:
$('.js-input').on('keydown', function(e) {
    console.log('pressing:', e.keyCode);
});

<input type="text" class="js-input">

DEMO

This will get you started


问:
How to properly remove Timer instance
I am using Timer instance in my project.

I create and add an instance to RunLoop

```<code>timer = Timer(timeInterval: 0.1, repeats: true, block: { (timer) in
    print("Hello")
})

if let timer = timer {
    RunLoop.current.add(timer, forMode: .commonModes)
}
</code>```

Now I am thinking about how to properly stop and remove Timer:

Should I trust in ARC and don't care about it?

Maybe deinit implementation is need. If is it true, what should be inside

```<code>deinit {
    longPressTimer?.invalidate()
    longPressTimer = nil
}
</code>```

invalidate is nesseccery? = nil ?

I have read serval threads from Stack about it but answers are contradictory. Could someone tell me which way is properly and explain me why?

答:
First check whether timer exist? if yes then invalidate it like

```<code> if timer!= nil {
    timer.invalidate()
 }
</code>```

Keep in mind that if you use a timer in any VC invalidate it when you leave that VC(View Controller)

Title: How to properly remove Timer instance

Body:
I am using Timer instance in my project.

I create and add an instance to RunLoop

timer = Timer(timeInterval: 0.1, repeats: true, block: { (timer) in
    print("Hello")
})

if let timer = timer {
    RunLoop.current.add(timer, forMode: .commonModes)
}

Now I am thinking about how to properly stop and remove Timer:

Should I trust in ARC and don't care about it?

Maybe deinit implementation is need. If is it true, what should be inside

deinit {
    longPressTimer?.invalidate()
    longPressTimer = nil
}

invalidate is nesseccery? = nil ?

I have read serval threads from Stack about it but answers are contradictory. Could someone tell me which way is properly and explain me why?

Body:
First check whether timer exist? if yes then invalidate it like

 if timer!= nil {
    timer.invalidate()
 }

Keep in mind that if you use a timer in any VC invalidate it when you leave that VC(View Controller)


问:
Proxy in package.json not affecting fetch request
I am trying to fetch some data from the development server using React.

I am running the client on localhost:3001 and the backend on port 3000.

The fetch request :

```<code> const users = fetch('/api/users');
    users.then((err,res) => {
      console.log(res);
    })
</code>```

When I run my development server and webpack-dev-server I get the following output:

```<code>GET http://localhost:3001/api/users 404 (Not Found)
</code>```

I tried specifying the proxy in the package.json so it would proxy the request to the API server, however nothing has changed.

Here is my package.json file:

.. and the webpack.config :

Please tell me, if you need to see anything else from my project. I apologies, if I'm missing something and not being thorough, I'm still quite new to using these technologies.

答:
You can modify your fetch request API url to give the complete hostname since

```<code> fetch('http://localhost:3000/api/users')
</code>```

also make sure that you have CORS enabled on your backend

In case your want to redirect through webpack, your can try devServer.proxy as

```<code>devServer: {
    inline: true,
    contentBase: './dist',
    port: 3001,
    proxy: { "/api/**": { target: 'http://localhost:3000', secure: false }  }
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to fetch some data from the development server using React.

I am running the client on localhost:3001 and the backend on port 3000.

The fetch request :

 const users = fetch('/api/users');
    users.then((err,res) => {
      console.log(res);
    })

When I run my development server and webpack-dev-server I get the following output:

GET http://localhost:3001/api/users 404 (Not Found)

I tried specifying the proxy in the package.json so it would proxy the request to the API server, however nothing has changed.

Here is my package.json file:

.. and the webpack.config :

Please tell me, if you need to see anything else from my project. I apologies, if I'm missing something and not being thorough, I'm still quite new to using these technologies.

Body:
You can modify your fetch request API url to give the complete hostname since

 fetch('http://localhost:3000/api/users')

also make sure that you have CORS enabled on your backend

In case your want to redirect through webpack, your can try devServer.proxy as

devServer: {
    inline: true,
    contentBase: './dist',
    port: 3001,
    proxy: { "/api/**": { target: 'http://localhost:3000', secure: false }  }
 }


问:
stockSymbols quantmod errors with hyphens with google
the R package, Quantmod seems to have trouble accessing companies from Google when using the stockSymbols() function.

Here's a list of the companies I'm after from the NYSE, it's just the first 30:

```<code> NYSE
   [1] "A"          "AA"         "AAC"        "AAN"        "AAP"        "AAT"        "AAV"        "AB"         "ABB"
  [10] "ABBV"       "ABC"        "ABEV"       "ABG"        "ABM"        "ABR"        "ABR-PA"     "ABR-PB"     "ABR-PC"
</code>```

Everything works well until it gets to ABR-PA and then returns an error message.

One of the ways I thought I could get around this was by running a Gsub over it to substitute some of the language, and that helped a bit but I'm still missing ~1% of companies from my ~3500 list.

here's the gsub:

```<code>NYSE <- gsub("-PK","-K",gsub("-PJ","-J",gsub("-PI","-I",gsub("-PH","-H",gsub("-PG","-G",gsub("-PF","-F",gsub("-PE","-E",gsub("-PD","-D",gsub("-PC","-C",gsub("-PB","-B",gsub("-PA","-A",NYSE)))))))))))
</code>```

If anyone has tackled this before I'd be keen to hear some thoughts.

答:
You can try the following two possible solutions:

```<code>getSymbols("ABR-PA", auto.assign=FALSE)
</code>```

and/or

```<code>getSymbols(`ABR-PA`)
</code>```

Download data for multiple stocks:

```<code>NYSE = c("A", "AA", "AAC", "AAN", "AAP", "AAT", "AAV", "AB", "ABB",
        "ABBV", "ABC", "ABEV", "ABG", "ABM", "ABR", "ABR-PA", "ABR-PB",
        "ABR-PC")

data = lapply(NYSE, function(x) {
  getSymbols(x, from="2007-01-01", auto.assign=FALSE)
})

df = do.call(merge, data)
df
</code>```

Body:
the R package, Quantmod seems to have trouble accessing companies from Google when using the stockSymbols() function.

Here's a list of the companies I'm after from the NYSE, it's just the first 30:

 NYSE
   [1] "A"          "AA"         "AAC"        "AAN"        "AAP"        "AAT"        "AAV"        "AB"         "ABB"
  [10] "ABBV"       "ABC"        "ABEV"       "ABG"        "ABM"        "ABR"        "ABR-PA"     "ABR-PB"     "ABR-PC"

Everything works well until it gets to ABR-PA and then returns an error message.

One of the ways I thought I could get around this was by running a Gsub over it to substitute some of the language, and that helped a bit but I'm still missing ~1% of companies from my ~3500 list.

here's the gsub:

NYSE <- gsub("-PK","-K",gsub("-PJ","-J",gsub("-PI","-I",gsub("-PH","-H",gsub("-PG","-G",gsub("-PF","-F",gsub("-PE","-E",gsub("-PD","-D",gsub("-PC","-C",gsub("-PB","-B",gsub("-PA","-A",NYSE)))))))))))

If anyone has tackled this before I'd be keen to hear some thoughts.

Body:
You can try the following two possible solutions:

getSymbols("ABR-PA", auto.assign=FALSE)

and/or

getSymbols(`ABR-PA`)

Download data for multiple stocks:

NYSE = c("A", "AA", "AAC", "AAN", "AAP", "AAT", "AAV", "AB", "ABB",
        "ABBV", "ABC", "ABEV", "ABG", "ABM", "ABR", "ABR-PA", "ABR-PB",
        "ABR-PC")

data = lapply(NYSE, function(x) {
  getSymbols(x, from="2007-01-01", auto.assign=FALSE)
})

df = do.call(merge, data)
df


问:
Why is goto poor practise?

This question is a duplicate of  Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

答: Note that Djkstra wrote "GOTO Considered Harmful", not "GOTO Considered Deadly".  It has its places.  Unfortunately, the judgement to know when to use it comes after you've got some experience in maintaining other people's code, especially code that was written years ago by people who no longer work in your company.  Thus, it's best to avoid goto as much as you can until you have that experience.</p>

Title: Why is goto poor practise?

LastEditorDisplayName: Rich B

OwnerDisplayName: Paul Tomblin


问:
How to remove/delete a large file from commit history in the Git repository?
I accidentally dropped a DVD-rip into a website project, then carelessly git commit -a -m ..., and, zap, the repo was bloated by 2.2 gigs. Next time I made some edits, deleted the video file, and committed everything, but the compressed file is still there in the repository, in history.

I know I can start branches from those commits and rebase one branch onto another. But what should I do to merge the 2 commits so that the big file doesn't show in the history and is cleaned in the garbage collection procedure?

答:
I basically did what was on this answer:
https://stackoverflow.com/a/11032521/1286423

(for history, I'll copy-paste it here)

```<code>$ git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch YOURFILENAME" HEAD
$ rm -rf .git/refs/original/
$ git reflog expire --all
$ git gc --aggressive --prune
$ git push origin master --force
</code>```

It didn't work, because I like to rename and move things a lot. So some big file were in folders that have been renamed, and I think the gc couldn't delete the reference to those files because of reference in tree objects pointing to those file.
My ultimate solution to really kill it was to:

```<code># First, apply what's in the answer linked in the front
# and before doing the gc --prune --aggressive, do:

# Go back at the origin of the repository
git checkout -b newinit <sha1 of first commit>
# Create a parallel initial commit
git commit --amend
# go back on the master branch that has big file
# still referenced in history, even though
# we thought we removed them.
git checkout master
# rebase on the newinit created earlier. By reapply patches,
# it will really forget about the references to hidden big files.
git rebase newinit

# Do the previous part (checkout + rebase) for each branch
# still connected to the original initial commit,
# so we remove all the references.

# Remove the .git/logs folder, also containing references
# to commits that could make git gc not remove them.
rm -rf .git/logs/

# Then you can do a garbage collection,
# and the hidden files really will get gc'ed
git gc --prune --aggressive
</code>```

My repo (the .git) changed from 32MB to 388KB, that even filter-branch couldn't clean.

Body:
I basically did what was on this answer:
https://stackoverflow.com/a/11032521/1286423

(for history, I'll copy-paste it here)

$ git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch YOURFILENAME" HEAD
$ rm -rf .git/refs/original/
$ git reflog expire --all
$ git gc --aggressive --prune
$ git push origin master --force

It didn't work, because I like to rename and move things a lot. So some big file were in folders that have been renamed, and I think the gc couldn't delete the reference to those files because of reference in tree objects pointing to those file.
My ultimate solution to really kill it was to:

# First, apply what's in the answer linked in the front
# and before doing the gc --prune --aggressive, do:

# Go back at the origin of the repository
git checkout -b newinit <sha1 of first commit>
# Create a parallel initial commit
git commit --amend
# go back on the master branch that has big file
# still referenced in history, even though
# we thought we removed them.
git checkout master
# rebase on the newinit created earlier. By reapply patches,
# it will really forget about the references to hidden big files.
git rebase newinit

# Do the previous part (checkout + rebase) for each branch
# still connected to the original initial commit,
# so we remove all the references.

# Remove the .git/logs folder, also containing references
# to commits that could make git gc not remove them.
rm -rf .git/logs/

# Then you can do a garbage collection,
# and the hidden files really will get gc'ed
git gc --prune --aggressive

My repo (the .git) changed from 32MB to 388KB, that even filter-branch couldn't clean.


问:
how to filter table by underscorejs
i work by underscore function ,i want to filter table by element not exist in author table
I want to finally display this [[10,20,30,50,60],[80,66],[9,70,4,3] ]   </p>

```<code>var tab=[];
 _.each([[10,20,30,5,50,60],[80,6,66,7,8,2],[9,70,4,3,1]], function (c) {

     var k=   _.filter(c, function (cel) {
         return _.some([1, 2, 5, 6, 8, 7], function (el) {
             return cel != el
         })
     })
     tab.push(k);
});

console.log(tab)
</code>```

答:
Basically, you could use

_.map for getting an array with filtered arrays,

_.filter for getting only the values who not match the given values and

_.contains for checking the item with the values array.

var array = [[10, 20, 30, 5, 50, 60], [80, 6, 66, 7, 8, 2], [9, 70, 4, 3, 1]],
    values = [1, 2, 5, 6, 8, 7],
    result = _.map(array, function (a) {
        return _.filter(a, function (v) {
            return !_.contains(values, v);
        });
    });

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

Title: how to filter table by underscorejs

Body:
i work by underscore function ,i want to filter table by element not exist in author table
I want to finally display this [[10,20,30,50,60],[80,66],[9,70,4,3] ]

var tab=[];
 _.each([[10,20,30,5,50,60],[80,6,66,7,8,2],[9,70,4,3,1]], function (c) {

     var k=   _.filter(c, function (cel) {
         return _.some([1, 2, 5, 6, 8, 7], function (el) {
             return cel != el
         })
     })
     tab.push(k);
});

console.log(tab)

Body:
Basically, you could use

_.map for getting an array with filtered arrays,

_.filter for getting only the values who not match the given values and

_.contains for checking the item with the values array.

var array = [[10, 20, 30, 5, 50, 60], [80, 6, 66, 7, 8, 2], [9, 70, 4, 3, 1]],
    values = [1, 2, 5, 6, 8, 7],
    result = _.map(array, function (a) {
        return _.filter(a, function (v) {
            return !_.contains(values, v);
        });
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


问:
variables within controller foreach returns NULL inside view
I have a web application built using codeigniter. What I'm trying to do is show a summary of results on my view. In my controller I have the below code

```<code>function index() {
    $data['summery'] = $this->Main_model->get_summery();

     foreach ($data['summery'] as $d) {

        $data['total_week']  = $this->Main_model->get_total_week($d['i_id']);

        $data['total_month'] = $this->Main_model->get_total_month($d['i_id']);

    }
}
</code>```

The problem that im having is each summery record has total weekly count and a monthly count based on the i_id

in my view i loop through the summery and it display the summery but when i echo $total_week or echo $total_month its always returns NULL

```<code>$data['total_week']  = $this->Main_model->get_total_week($d['i_id']);
$data['total_month'] = $this->Main_model->get_total_month($d['i_id']);
</code>```

When i do a var_dump on the above variables it shows the number, but when i try to echo it on the view it returns NULL

答:
I hope I under stood correct Try something like this

```<code>function index() {
    $this->load->model('main_model');

    $data['summery'] = array();

    $summery = $this->main_model->get_summery();

    foreach ($summery as $d) {

        $data['summery'][] = array(
            'total_week' => $this->main_model->get_total_week($d['i_id']),
            'total_month' => $this->main_model->get_total_month($d['i_id'])
        );

    }

    $this->load->view('the_view', $data);
}
</code>```

View

```<code><?php foreach ($summery as $something) {?>
    <?php echo $something['total_week'];?>
    <?php echo $something['total_month'];?>
<?php }?>
</code>```

Body:
I have a web application built using codeigniter. What I'm trying to do is show a summary of results on my view. In my controller I have the below code

function index() {
    $data['summery'] = $this->Main_model->get_summery();

     foreach ($data['summery'] as $d) {

        $data['total_week']  = $this->Main_model->get_total_week($d['i_id']);

        $data['total_month'] = $this->Main_model->get_total_month($d['i_id']);

    }
}

The problem that im having is each summery record has total weekly count and a monthly count based on the i_id

in my view i loop through the summery and it display the summery but when i echo $total_week or echo $total_month its always returns NULL

$data['total_week']  = $this->Main_model->get_total_week($d['i_id']);
$data['total_month'] = $this->Main_model->get_total_month($d['i_id']);

When i do a var_dump on the above variables it shows the number, but when i try to echo it on the view it returns NULL

Body:
I hope I under stood correct Try something like this

function index() {
    $this->load->model('main_model');

    $data['summery'] = array();

    $summery = $this->main_model->get_summery();

    foreach ($summery as $d) {

        $data['summery'][] = array(
            'total_week' => $this->main_model->get_total_week($d['i_id']),
            'total_month' => $this->main_model->get_total_month($d['i_id'])
        );

    }

    $this->load->view('the_view', $data);
}

View

<?php foreach ($summery as $something) {?>
    <?php echo $something['total_week'];?>
    <?php echo $something['total_month'];?>
<?php }?>


问:
Trying to center 2 groups of 2 divs each at the middle of a wrapper
I have four divs(all same sizes) i have grouped them into to blocks of 2 with classes blocka both contained in an inner container body-content float all the blocks to the left so when my page width changes,these the blocks(of 2) aligned under each other.
I am trying to get now is that those divs sit right at the middle of the main container.

Everything response well. All i need it the class body content sit at the middle of main while blocka all center themselves in the middle of body-content

.main {
  max-width: 100%;
  margin-left: 240px;
  background-color: ;
}

.body-content {
  background-color: white;
  margin: 0 auto;
  width: 95%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
}

.blocka {
  float: left;
  margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div>
</div></code>```

答:
Try the following:

.main {
  max-width: 100%;
  background-color: ;
  text-align: center;
}

.body-content {
  background-color: white;
  margin: 0 auto;
  width: 95%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
}

.blocka {
  margin: 0 auto;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">
  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div>
</div></code>```

Body:
I have four divs(all same sizes) i have grouped them into to blocks of 2 with classes blocka both contained in an inner container body-content float all the blocks to the left so when my page width changes,these the blocks(of 2) aligned under each other.
I am trying to get now is that those divs sit right at the middle of the main container.

Everything response well. All i need it the class body content sit at the middle of main while blocka all center themselves in the middle of body-content

.main {
  max-width: 100%;
  margin-left: 240px;
  background-color: ;
}

.body-content {
  background-color: white;
  margin: 0 auto;
  width: 95%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
}

.blocka {
  float: left;
  margin: 0 auto;
}

Add All

Add All

Add All

Add All

Body:
Try the following:

.main {
  max-width: 100%;
  background-color: ;
  text-align: center;
}

.body-content {
  background-color: white;
  margin: 0 auto;
  width: 95%;
  padding: 15px;
  border: 1px solid grey;
  height: 100px;
}

.blocka {
  margin: 0 auto;
  display: inline-block;
}

<div class="main">
  <div class="body-content">
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
    <div class="blocka">
      <div class="body-content-items">Add All</div>
      <div class="body-content-items">Add All</div>
    </div>
  </div>
</div>