text:
Q: jQuery - Remove part of a string from Form Value I'm trying to work on a 'Select Attendees' list for a website I'm working on and have got to a point where I'm getting stuck.
At the moment, what you can do is select options from the drop down list, which will show the name and populate an input field with these values (which I will be using later on to post to the database these values).
The problem I am having is that when deleting the name from the list, it is not deleting from the field value too.
Basically, when you delete one of the names, I want it to take that value out of the forms value and the appended ; to be removed too.
JS Fiddle
HTML
<select name="attendees" class="attendees">
  <option value="" disabled="disabled" selected="selected">Please Select Attendees</option>
  <option value="12" class="12">Name 1</option>
  <option value="13" class="13">Name 2</option>
  <option value="14" class="14">Name 3</option>
</select>

  <input type="text" name="theAttendees" class="theAttendees" value="" style="width: 370px;" />

jQuery
(function($) {
    $('.attendees').change(
    function() {
        var theSelect = $('.attendees option:selected');
            getName = theSelect.text();
            getClass = theSelect.val();
            theAttendees = $('input.theAttendees').val();

        if (theSelect.hasClass('noMore')) {
            $('span.'+ getClass).animate({"color":"red"}, 100);
            setTimeout(function() {$('span.'+ getClass).animate({"color":"#000"}, 500)}, 1000) ;
        } else {
            $('.attendeesList').append('' + getName + '
');
            theSelect.addClass('noMore');
            $('input.theAttendees').val(theAttendees + ' ' + getName + ';');
        }
    });
}(jQuery));

(function($) {
    $('div.attendeesList').on('click', 'a#d', function() {
        var hrefSpan = $(this).parent();
            classID = $(this).attr('class');
            getName = $('.attendees option.'+ classID).text();

            hrefSpan.remove();

            $('br.'+ classID).remove();

            if ($('.attendees option.'+ classID).hasClass('noMore')) {
                $('.attendees option.'+ classID).removeClass('noMore');
            }
    });
}(jQuery));

I appreciate that it's probably not the easiest code to read and probably isn't as good as it can be, but I'm learning jQuery and trying to use it as much as possible and this is functional, so I can work on improving it once it works. If you feel like letting me know where my code can be optimised, I'd appreciate that too!
Thanks!

A: Figured this one out myself (with some research!)
var values = attendeeBox.val().split(";");
var newValue = "";
for ( var i = 0 ; i < values.length ; i++ )
{
if ( getName != values[i] )
    {
        newValue = newValue + values[i] + ";";
    }
}
attendeeBox.val( newValue );

A: The easiest will be to store your selection in an array, and build your textbox value from that array. (using array.join(';'))

A: ok here is the trick

*

*before you delete save the text on the text field

*do a .replace() to remove the text you deleted in your list and save it to another variable

*then set the saved variable value on the text field


text:
Q: WatiN: The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer I am calling WatiN from a C# windows service. When I invoke WatiN it throws the following exception. The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer
I have tried starting up a thread and setting the apartment state via
mythread.SetApartmentState(ApartmentState.STA)

but that resulted in another error
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
I also tried adding an attribute to the Service entry point.
static class Program
{
      [STAThread]
      static void Main()
      {
          ...

Any ideas?

A: That's not an error, it is just a diagnostic from the debugger.  It is telling you that it can't give you debug info on whatever you put in the watch window.  That's common with code that is compiled in the Release configuration, the JIT compiler optimizes the machine code and commonly puts local variables in CPU registers.  Making their value unavailable to the debugger, it isn't smart enough to figure out what register was used.  It occasionally happens in the Debug release as well when there's unmanaged code on the call stack.  Which is not uncommon for WebBrowser, there's a very large chunk of unmanaged code that makes it work.
FWIW, just switching the thread's apartment state to STA is not enough.  The thread must also pump a Windows message loop to make a single-threaded apartment operate properly.  If you don't, you'll see that operations on STA objects like WebBrowser will deadlock.  For example, you'll never get the DocumentCompleted event when you navigate to a site.  Running a message loop requires calling Application.Run() or Form.ShowDialog() in a WF app.

A: The attribute that I used to get over seeing this error is:
    [TestFixture, RequiresSTA]
As per adrianbanks answer on: How to run unit tests in STAThread mode?

A: I know Benjamin's already posted a 'working' answer, but I thought I'd add a couple of things I've experienced when I've got this error when trying to execute WatiN tests:
For NUnit, you should add something like this to your app.config for the tests:
  <configSections>
    <sectionGroup name="NUnit">
      <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
  </configSections>
  <NUnit>
    <TestRunner>
      <!-- WatiN can only host IE in STA mode -->
      <add key="ApartmentState" value="STA"/>
    </TestRunner>
  </NUnit>

In MbUnit, modify your TestFixture attribute like this:
[TestFixture(ApartmentState = ApartmentState.STA)]

HTH,
Pete.
Ha - it's actually in the documentation. Doh!
http://watin.org/documentation/sta-apartmentstate/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stream output from remote kubernetes command with golang client I'm using the golang kubernetes client to create kubernetes pods and execute remote commands in them. However, I'm finding that I can't get feedback on the status of the remote execution until it's finished because I can't figure out how to stream the logs of the remote command. Here's my current implementation for executing a remote command:
func (k *KubernetesClient) RunCommand(ctx context.Context, args *RunCommandArgs) (string, int, error) {
    req := k.clientset.CoreV1().RESTClient().Post().Resource("pods").Name(args.ContainerId).Namespace(k.namespace).SubResource("exec").Param("container", CONTAINER_NAME)
    scheme := runtime.NewScheme()
    if err := v1.AddToScheme(scheme); err != nil {
        return "", 0, fmt.Errorf("could not add to scheme: %w", err)
    }
    parameterCodec := runtime.NewParameterCodec(scheme)
    req.VersionedParams(&v1.PodExecOptions{
        Stdin:     false,
        Stdout:    true,
        Stderr:    true,
        TTY:       false,
        Container: args.ContainerId,
        Command:   []string{"sh", "-c", args.Command},
    }, parameterCodec)
    exec, err := remotecommand.NewSPDYExecutor(k.config, "POST", req.URL())
    if err != nil {
        return "", 0, fmt.Errorf("could not exec command: %w", err)
    }
    var stdout, stderr bytes.Buffer
    var streamErr error
    streamErr = exec.Stream(remotecommand.StreamOptions{
        Stdin:  nil,
        Stdout: &stdout,
        Stderr: &stderr,
        Tty:    false,
    })

    if streamErr != nil {
        if strings.Contains(streamErr.Error(), "command terminated with exit code") {
            return stderr.String(), 1, nil
        } else {
            return "", 0, fmt.Errorf("could not stream results: %w", streamErr)
        }
    }
    return stdout.String(), 0, nil
}

In this implementation I don't get to know the state of the remote command until it's finished executing at which point I get all of the output logs at once.
Is there a way to read stdout/stderr while they're being written by the call to exec.Stream? In an ideal world I'd like to be able to print the output of the remote command line by line. I noticed that bytes.Buffer has a ReadString method which accepts a delimiter. That looks like a useful method but I haven't been able to figure out how to use it.

A: This is only a partial answer but if I set use the following PodExecOptions and StreamOptions then I see each log line get printed in real time (note that Tty is true and I'm using stdin and stdout, not custom buffers):
v1.PodExecOptions{
        Stdin:     true,
        Stdout:    true,
        Stderr:    false,
        TTY:       true,
        Container: args.ContainerId,
        Command:   []string{"sh", "-c", args.Command},
    }

and
remotecommand.StreamOptions{
            Stdin:  os.Stdin,
            Stdout: os.Stdout,
            Stderr: nil,
            Tty:    true,
        }

However, if I try to use something other than os.Stdin and os.Stdout then I never get any log lines. For example, the following usage doesn't print anything:
    var stdout, stdin bytes.Buffer
    var streamErr error

    go func() {
        streamErr = exec.Stream(remotecommand.StreamOptions{
            Stdin:  &stdin,
            Stdout: &stdout,
            Stderr: nil,
            Tty:    true,
        })
    }()
    time.Sleep(5*time.Second)
    log.Info("doing raw string calls on both buffers")
    log.Info(stdin.String())
    log.Info(stdout.String())
    log.Info("starting scan of stdin")
    scanner := bufio.NewScanner(&stdin)
    scanner.Split(bufio.ScanLines)
    for scanner.Scan() {
        m := scanner.Text()
        fmt.Println(m)
    }
    log.Info("starting scan of stdout")
    scanner = bufio.NewScanner(&stdout)
    scanner.Split(bufio.ScanLines)
    for scanner.Scan() {
        m := scanner.Text()
        fmt.Println(m)
    }
    log.Info("finished scanning of stdout")

I'm still trying to figure out how to use custom buffers so I can manage what's written to my logs instead of piping directly to stdout (I want to attach some custom fields to each line that gets logged).

EDIT: alright, I figured out a solution that works. Here's the full code
type LogStreamer struct{
    b bytes.Buffer
}

func (l *LogStreamer) String() string {
    return l.b.String()
}

func (l *LogStreamer) Write(p []byte) (n int, err error) {
    a := strings.TrimSpace(string(p))
    l.b.WriteString(a)
    log.Info(a)
    return len(p), nil
}

func (k *KubernetesClient) RunCommand(ctx context.Context, args *RunCommandArgs) (string, int, error) {
    req := k.clientset.CoreV1().RESTClient().Post().Resource("pods").Name(args.ContainerId).Namespace(k.namespace).SubResource("exec").Param("container", "worker")
    scheme := runtime.NewScheme()
    if err := v1.AddToScheme(scheme); err != nil {
        return "", 0, fmt.Errorf("could not add to scheme: %w", err)
    }
    parameterCodec := runtime.NewParameterCodec(scheme)
    req.VersionedParams(&v1.PodExecOptions{
        Stdin:     true,
        Stdout:    true,
        Stderr:    false,
        TTY:       true,
        Container: args.ContainerId,
        Command:   []string{"sh", "-c", args.Command},
    }, parameterCodec)
    exec, err := remotecommand.NewSPDYExecutor(k.config, "POST", req.URL())
    if err != nil {
        return "", 0, fmt.Errorf("could not exec command: %w", err)
    }
    var streamErr error
    l := &LogStreamer{}

    streamErr = exec.Stream(remotecommand.StreamOptions{
        Stdin:  os.Stdin,
        Stdout: l,
        Stderr: nil,
        Tty:    true,
    })

    if streamErr != nil {
        if strings.Contains(streamErr.Error(), "command terminated with exit code") {
            return l.String(), 1, nil
        } else {
            return "", 0, fmt.Errorf("could not stream results: %w", streamErr)
        }
    }
    return l.String(), 0, nil
}

I created a struct which implements the io.Writer interface and use that in the StreamOptions struct. Also note that I had to use os.Stdin in the StreamOptions struct or else only a single line would be streamed back for Stdout.
Also note that I had to trim the buffer passed to LogStreamer.Write because it seems that carriage returns or newlines cause problems with the logrus package. There's still more polish to add to this solution but it's definitely headed in the right direction.


text:
Q: Unable to resolve service for type I have an interface to a send mail async function which I am using for my email functions in my controller class.
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;

public AccountController(UserManager<ApplicationUser> userManager,
                         SignInManager<ApplicationUser> signInManager,
                         IEmailSender emailSender)
{
        _userManager = userManager;
        _signInManager = signInManager;
        _emailSender = emailSender;
}

As you see I am using the IEmailSender emailSender to create the object and setting it to its instance in the routine AccountController.
The interface is simply made up of one constructor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace solitude.admin.core.Interfaces
{
    public interface IEmailSender
    {
        Task SendEmailAsync(string email, string subject, string message);
    }
}

But the problem is when I come to view my view I get the following error:

InvalidOperationException: Unable to resolve service for type 'solitude.admin.core.Interfaces.IEmailSender' while attempting to activate 'solitude.admin.core.Controllers.AccountController'.
  Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

A: You need to register how the DI engine will provide an IEmailSender.  Assuming you are using asp.net core, you do this is in your Startup.cs in the ConfigureServices method:
public void ConfigureServices(IServiceCollection services) {
   ...
   services.AddSingleton<IEmailSender, EmailSenderImplementation>();
   ...
}

This is where EmailSenderImplementation is a class that implements the IEmailSender interface.
This registration tells the DI framework how to get an implementation of IEmailSender.  In my example I am telling it to instantiate a single instance of EmailSenderImplementation and reuse that instance over the lifetime of the application.  You might need to use AddTransient (if you want a new one every time you ask for one) or AddScoped (if you want a new one for each http request) instead of AddSingleton depending on how your implementation of IEmailSender works.

A: Tim was indeed correct what I had to do was add this following code to my configure startup.cs
services.AddTransient<IEmailSender, AuthMessageSender>();

The class AuthMessageSender is made up of as follows.
// This class is used by the application to send Email and SMS
// when you turn on two-factor authentication in ASP.NET Identity.
// For more details see this link http://go.microsoft.com/fwlink/?LinkID=532713
public class AuthMessageSender : IEmailSender
{
   public Task SendEmailAsync(string email, string subject, string message)
   {
            // Plug in your email service here to send an email.
            return Task.FromResult(0);
    }
}

This allowed me to call the function from the class as normal I guess old .net new how to handle this can someone explain to me why this has changed in core why do we have to hard wire like this.


text:
Q: Is there a linux tool like top, only cumulative? I would like to find a tool such as top, that runs in a terminal, but that keeps a cumulative total of real/user/system time used.

A: Found it... "top -S"

A: top already keeps a cumulative total of time spent on the cpu (user+system) I believe. That's what's listed in the TIME+ field:
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 5117 michael   20   0  508m 238m  30m R   16  6.1   7:55.47 firefox
 3135 root      20   0  194m  53m  14m S    8  1.4  26:37.08 X
 4359 michael   20   0  117m  83m  14m S    1  2.1  17:59.34 gnome-panel

'real time' probably isn't that interesting to watch - it's just the amount of elapsed time since the process started.
If you're interested in hacking it up yourself, everything you need is in /proc/*/stat :)
Or try using ps:
ps -eo pid,user,args,etime,time,%cpu --sort %cpu
watch -n1 ps -eo pid,user,args,etime,time,%cpu --sort -%cpu

(the very last line is probably closest to what you actually ask :)

A: I don't know if I understand correctly, but top -a (or top -c a) is the cumulative mode of top on Mac OS X.

A: The only problem with "top -S", "ps --cumulative" or "pidstat -T ALL" that they only add exited processes' times to parents'. Thus you can't monitor CPU time usage real time, if child processes don't exit too often.


text:
Q: display data function for my classes always return none I am doing an assignment for my OOP class in which we create a person, then create children of that class such as an employee. In my following code I always get a "None" message when I try to print some attributes or variables in my classes using my displayData function, it appears after all the attributes or variables of my object are printed, would anyone know why?.
from dataclasses import dataclass

@dataclass

class Person:
    FirstName : str
    LastName : str
    Age : int
    Address : str
    ContactNumber : int

@dataclass

class Employee(Person):
    EmployeeID : str
    OrganizationName : str
    Position : str

@dataclass

class CommissionEmployee(Employee):
    commissionRate : float

    def calculateCommission(self):
        gross_sale = input("Please enter the gross sale amount: ")
        totalEarning = float(gross_sale) * (1 + self.commissionRate)
        return totalEarning

    def displayData(self):
        print("First Name:", self.FirstName)
        print("Last Name:", self.LastName)
        print("Age:", self.Age)
        print("Address:", self.Address)
        print("Contact Number:", self.ContactNumber)
        print("Employee ID:", self.EmployeeID)
        print("Organization Name:", self.OrganizationName)
        print("Position:", self.Position)
        print("Commission Rate:", self.commissionRate)
        print("Total Earnings:", "${:,.2f}".format(self.calculateCommission()))

@dataclass

class SalariedEmployee(Employee):
    baseSalary : float

    def CalculateNetSalary(self):
        provisionalTax = 0.13 * self.baseSalary
        insurance = 0.01 * self.baseSalary
        fedTax = 0.03 * self.baseSalary
        NetSalary = self.baseSalary - provisionalTax - insurance - fedTax
        return "${:,.2f}".format(NetSalary)

    def displayData(self):
        print("First Name:", self.FirstName)
        print("Last Name:", self.LastName)
        print("Age:", self.Age)
        print("Address:", self.Address)
        print("Contact Number:", self.ContactNumber)
        print("Employee ID:", self.EmployeeID)
        print("Organization Name:", self.OrganizationName)
        print("Position:", self.Position)
        print("Base Salary:", "${:,.2f}".format(self.baseSalary))
        print("Net Salary:", self.CalculateNetSalary())

John = SalariedEmployee("John", "Smith", 21, "21 Cool Beans Dr", 123456789, "201", "Tesla", "CEO", 100.0)

print (John.displayData())

A: You are printing the value of your function. Unless you specify something with return, such as return True or return 72, the value of the function will always be None when printed. The answer is to not print John.displayData(), just run it.

A: You are printing the return value of John.displayData(). Also in the displayData function you are not returning anything. Check your function calculateCommission and CalculateNetSalary. In these two functions you are returning some value and if you call this function inside print then the value you mentioned in return statement will get printed.
In this case remove the print and just call displayData function as follows:
John.displayData()


text:
Q: Netbeans 7.x syntax highlighting for .sass files? Does anyone know of a plugin or method to add syntax highlighting to .sass files in Netbeans 7.x?
This plugin I've found http://plugins.netbeans.org/plugin/34929/scss-support adds syntax highlighting for .scss, but I need some solution for .sass files.
Thanks

A: Native support for SASS and LESS has recently been added to the Netbeans codebase - until the next major version (probably 7.4?) is released, you can get it using the current "development version".

A: Found this plugin which does what I need:
http://code.google.com/p/postcomment/downloads/detail?name=org-netbeans-modules-haml.nbm&can=2.
One drawback is that it doesn't allow to customize the syntax colors, but I found a way to do that by editing the following plugin file (you have to unzip the .nbm and .jar files to do that, and then rearchive them using zip without any compression):
org-netbeans-modules-haml.nbm/netbeans/modules/org-netbeans-modules-haml.jar/org/netbeans/modules/haml/sass.nbs
Hope this helps someone else as well


text:
Q: Is there a way to find out if an accepted answer has been re-assigned? I am creating a query on data explorer in which I want to find out how many accepted answers were re-assigned (a different answer was accepted in the same question before, but a different question was accepted later) and has a score of 15. Is there a way to do that? Here is what I have so far:
-- Print out how many answers have accepted answers that
-- have been re-assigned and have a score of fifteen.
-- Print them and the link to the answer owner

SELECT
  count(posts.AcceptedAnswerId) as [Accepted Answers]

FROM
  posts

WHERE
      posts.postTypeId = 1
  and posts.Score >= 15
  -- Peramater for having the second accepted answer (accepted answer re-awarded)

A: You might think that the following query seems to do that but renders a far by complete result.
with m_acc as (
select p.parentid as qid
, count(*) as cnt
from posts p
inner join votes  v on v.postid = p.id
where votetypeid = 1 -- AcceptedByOriginator
group by p.parentid
having count(*) > 1
)

select id as [Post Link]
     , score
     , m_acc.cnt as [# times accept switch]
from posts p
inner join m_acc on qid = p.id
order by score desc

Remarkable enough only 57 questions seem to match that for Stack Overflow. Uncertain if that was a correct number, I checked one which was correct so I assumed the other results are sound as well. But checking a couple of known positives from the Tavern and SOCVR it turns out that a lot of data is missing. The outcome here is probably due to invalid data.
Further investigation of two posts with this query only showed one accept record while the post timeline of both posts show TWO accept votes.
That leads me to conclude that the votes table is cleaned/sanitized to only contain the current accepted answer vote and not the history of those votes.
With that hope shattered on being able to answer your question I switched to looking at the posthistory table. Unfortunately that table doesn't have a record for accept votes either which leads to this unsatisfying answer:
You can't query for those questions because the data needed isn't available in any table available in SEDE.


text:
Q: WeakReference returns wrong object I've noticed a strange behavior in one of our applications recently.
Exception=System.InvalidCastException: Unable to cast object of type 'System.Data.SqlClient.SqlTransaction' to type 'System.Byte[]'.
   at ServiceStack.Text.Pools.BufferPool.GetCachedBuffer(Int32 minSize) in C:\BuildAgent\work\912418dcce86a188\src\ServiceStack.Text\Pools\BufferPool.cs:line 55
   at ServiceStack.Redis.RedisNativeClient..ctor(RedisEndpoint config) in C:\BuildAgent\work\b2a0bfe2b1c9a118\src\ServiceStack.Redis\RedisNativeClient_Utils.cs:line 447
   at ServiceStack.Redis.RedisClient..ctor(RedisEndpoint config) in C:\BuildAgent\work\b2a0bfe2b1c9a118\src\ServiceStack.Redis\RedisClient.cs:line 66
   at ServiceStack.Redis.RedisConfig.<>c.<.cctor>b__35_0(RedisEndpoint c) in C:\BuildAgent\work\b2a0bfe2b1c9a118\src\ServiceStack.Redis\RedisConfig.cs:line 22
   at ServiceStack.Redis.RedisResolver.CreateRedisClient(RedisEndpoint config, Boolean master) in C:\BuildAgent\work\b2a0bfe2b1c9a118\src\ServiceStack.Redis\RedisResolver.cs:line 76
   at ServiceStack.Redis.RedisManagerPool.GetClient() in C:\BuildAgent\work\b2a0bfe2b1c9a118\src\ServiceStack.Redis\RedisManagerPool.cs:line 214

...
Or
Exception=System.InvalidCastException: Unable to cast object of type 'System.Byte[]' to type 'System.Transactions.SafeIUnknown'.
   at System.Transactions.Transaction.JitSafeGetContextTransaction(ContextData contextData)
   at System.Transactions.Transaction.FastGetTransaction(TransactionScope currentScope, ContextData contextData, Transaction& contextTransaction)
   at System.Transactions.Transaction.get_Current()
   at System.Data.ProviderBase.DbConnectionPool.GetFromTransactedPool(Transaction& transaction)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at ServiceStack.OrmLite.OrmLiteConnection.Open() in C:\BuildAgent\work\27e4cc16641be8c0\src\ServiceStack.OrmLite\OrmLiteConnection.cs:line 86
   ...

Exceptions similar to these two, are being thrown from various parts of our application. The only thing in common to all of those exceptions is the WeakReference object, but I can see no obvious cause for this exception. For example, the ServiceStack.Text code that throws this exception is:
    private class CachedBuffer
    {
        private readonly WeakReference _reference;

        public int Size { get; }

        public bool IsAlive => _reference.IsAlive;
        public byte[] Buffer => (byte[])_reference.Target;

        public CachedBuffer(byte[] buffer)
        {
            Size = buffer.Length;
            _reference = new WeakReference(buffer);
        }
    }

Exception is thrown from Buffer property getter, apparently _reference.Target points to SqlTransaction object and not byte[], but _reference is only initialized once in the constructor and can't be changed afterwards, so how could this exception be thrown?
Additionally none of this code has changed recently, so it makes no sense, that it would suddenly start throwing errors. I also can't see any way we could have caused this bug by some change in our code, or am I wrong about that?
Could this be a bug in .net clr and if so, how could I diagnose it? Our application uses .NET 4.8 framework and we've been seeing those bugs on Windows server 2012 and Windows server 2019 machines within our testing environments, but I have not been able to reproduce them locally on my development machine.

A: I've managed to locate the problem, it was indeed our own code that caused this error and it was related to reflection. Long story short, one of our developers introduced a code, that invoked deep clone on ExpandoObject.Keys property. This property is not a simple collection of strings, but also contains a reference to entire ExpandoObject and deep inside ExpandoObject there are also some WeakReference fields. I still don't understand exactly what happens, but I guess that cloning those WeakReferences inside ExpandoObject somehow caused the bug we experienced.
Thanks for your help. I inspected that code several times, but completely missed the deep clone invocation, because that extension method had a very generic name.


text:
Q: Php submit form with select option condition I want to submitting form data into database, but firstly first it's should be filtered by select option before inserting it. Below is my form view:
<form method="POST">
<input type="text" name="name" placeholder="Your Name" />
<input type="text" name="username" placeholder="Username"/>
<select name="choose">
    <option value="1">One</option>
    <option value="2">Two</option>
</select>
<button type="submit" name="submit">Submit</button>
<!-- <input type="submit" name="submit" value="Submit" /> -->

And this is process form:
if(isset($_POST['submit'])) {
switch(true) {
    case  ( isset($_POST['choose']) == "1" ):
        echo "you choose 1";
        break;
    case  ( isset($_POST['choose']) == "2" ):
        echo "you choose 2";
        break;
    case  ( isset($_POST['choose']) == "" ):
        echo "you didn't choose anything";
        default;
}
echo "<pre>";
print_r($_POST);
echo "</pre>";

}
For example if I select Two, the result is:
you choose 1
Array
(
    [name] => aaaaaaaa
    [username] => bbbbbbbbb
    [choose] => 2
    [submit] =>
)

Which is still displaying you choose 1 refers to the first case.
What should I do to filter the data before sending it into database? At least how can I know the status of the data, whether it's in 1, 2, or you didn't choose anything? Make sense?
Thanks in advance.

A: You need to rework your switch case, the switch should be a variable that can evaluate to different values, and the cases are those values:
switch($_POST['choose']){
    case "1":
        echo "you choose 1";
        break;
    case "2":
        echo "you choose 2";
        break;
    case "":
        echo "you didn't choose anything";
        break;
}

The default keyword can be used as a last case when none of the cases match the value, it acts as an "else" in a switch case scenario:
switch($some_val){
    case "1":
        echo "you entered a 1!";
        break;
    default:
        echo "You didn't enter a 1!!";
        break;
}

A: Change this:
if(isset($_POST['submit'])) {
switch(true) {
    case  ( isset($_POST['choose']) == "1" ):
        echo "you choose 1";
        break;
    case  ( isset($_POST['choose']) == "2" ):
        echo "you choose 2";
        break;
    case  ( isset($_POST['choose']) == "" ):
        echo "you didn't choose anything";
        default;
    }
}

to this:
if(isset($_POST['submit'])) {
$choose = isset($_POST['choose']) ? $_POST['choose'] : '';
switch($choose) {
    case  "1" :
        echo "you choose 1";
        break;
    case  "2" :
        echo "you choose 2";
        break;
    default;
        echo "you didn't choose anything";
    }
}

isset() only returns true/false values. This can cause to unexpected/unintended behaviors when used the way you are using it.
If your going to use a switch case you need something to test on. and true is not a proper test. true will only ever be 1. Because 0 is false and any other value is true. But the keyword true is really just a 1.
So assigning the value to a variable is a lot safer to test with then using the $_POST['choose'] in the switch. Now we have a proper variable to test with and we can reach one of our 3 test cases. And using the ternary operator is just a short hand for an if else statement.

A: In your snippet your switch use is not correct. It should be like this:
switch($_POST['choose']) { // what is being compared
    case 1: // what if it's 1
        echo "you choose 1";
        break;
    case 2: // what if it's 2
        echo "you choose 2";
        break;
    default: // what else
        echo "you didn't choose anything";
        break;
}

But default in your case isn't anything because you have fixed options.
Also, isset() is only to know if a variable exists. It will not tell you the value of it. It's thinked to do something like
if(isset($_POST['variable'])){
    $variable = $_POST['variable'];
}else{
    $variable = "";
}

Then you would use the new $variable.
This is useful because some code will not work if you try to get undefined variables.
EDIT (thanks to GrumpyCrouton):
Or the short version:
$variable = isset($_POST['variable']) ? $_POST['variable'] : '';

Where first (after =) you are saying the condition, after ? you are saying the value if true and after the : you are saying the value if false.


text:
Q: Braintree: Creating a new subscription after the user has canceled I am trying to decide how to handle the situation where a user has subscribed through the month, lets says 6/1 they are subscribed through until 6/31. Midway through the month they decide to cancel their subscription (6/15), but then on 6/20, they decide to restart their subscription again. How is this handled in Braintree, if at all? Is there an advised route for handling this situation?
My current thought:
I'll be keeping track of their canceled subscription and checking how far they are paid through and stop providing them service once that period ends. I was considering putting the new subscription on a trial period for the difference in days between their canceled subscription paid through date (in this case 10 days). The implication here is that I have to check now if they are in a trial period on top of the paid through date if for some reason they do this n times within the month. I saw some advice to consider the implications of trial periods on the Braintree documentation and so I wanted to make sure this was the best route to go.
In relation to the 'n' repetitions, does the trial-duration decrease with each day? So trial period starts on 6/20 with ten days remaining, does the trial-duration go down to 9 on 6/21? There seems to be no indication on the documentation on what the specific case is.

A: Thanks to the Braintree Support team:
The main reason we advise you to take extra care with trial periods is that there are risk and liability issues around making sure your customer knows when they're going to be charged. However, it can get difficult to keep track of start dates when using trial periods. What I'd recommend doing, actually, is setting a first billing date instead when you create a new subscription. This allows you to specify a particular date (rather than just a day of the month or a time period into the future) to first charge your customer.
All you'd have to do is keep track of the date each subscription was paid through (which you could do via our API.) Then, if a customer canceled their subscription and created a new one before that date occurred, just create a new subscription with a first billing date of the day after the paid-through date. You then wouldn't have to do any trial period checking if the customer kept canceling and re-signing up—the only thing you'd need to keep track of was the paid-through date of the original subscription.


text: Q: *Solved* Terminology in DE, difference between Particular and Actual solution Yesterday I started studying and preparing for a course in Differential Equations and today I came across something that confuses me; I watched a lecture on IVP and they used both Actual solution and Particular solution, as you can see here https://www.youtube.com/watch?v=b6WMmmMKf3Y so could someone please explain the difference? Is it something simple like Slope fields and Direction fields, where the only difference is the direction in Direction fields? I googled this and that, but with no luck. As I understand it, particular solution is a specific solution, opposite of a general solution, like when we have a slope field.


text:
Q: Number of nodes meeting a conditional based on attributes Below is part of the XML which I am processing with PHP's XSLTProcessor:
<result>
    <uf x="20" y="0"/>
    <uf x="22" y="22"/>
    <uf x="4" y="3"/>
    <uf x="15" y="15"/>
</result>

I need to know how many "uf" nodes exist where x == y.
In the above example, that would be 2.
I've tried looping and incrementing a counter variable, but I can't redefine variables.
I've tried lots of combinations of xsl:number, with count/from, but couldn't get the XPath expression right.
Thanks!

A: <xsl:value-of select="count(/result/uf[@y=@x])" />

A: count('/result/uf[@x = @y]')


text:
Q: Unexpected empty hash I have this piece of code. The problem is in this.hash or this.getHash(). When I try to set hash value to method checkHash(), Log.d and Server (because checkHash() sends value to server) say that this.hash is "". Why this.hash becomes unexpectedly empty?
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(...) {
...
Connection conn = new Connection(getApplicationContext());
this.hash = this.getHash();
Log.d("OMG", this.getHash()); // returns correct HASH value
Log.d("OMG", this.hash); // returns correct hash value
String response = conn.checkHash(this.hash, device); // this method gets empty hash value

...
}

}

EDIT 1
public String checkHash(String hash, String device) throws ServerException, NoInternetException {
    List<NameValuePair> query = new ArrayList<NameValuePair>();
    Log.d("INTERNAL", hash + " / " + device);
    query.add(new BasicNameValuePair("hash", hash));
    query.add(new BasicNameValuePair("key", this.KEY));
    query.add(new BasicNameValuePair("device", device));
    query.add(new BasicNameValuePair("method", "checkHash"));
    return this.post(query);
}

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            // Checking hash
            String device = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);

            Connection conn = new Connection(getApplicationContext());
            this.hash = this.getHash();
            Log.d("LOVEISTRUE", this.hash);
            String response = conn.checkHash(this.hash, device);

            Log.d("HAVEALOOK", device + " / " + response);
            Log.d("HAVEALOOKRESPONSE", response);
            if (response.equals("ERR")) {
                Intent toProjects = new Intent(MainActivity.this, LoginActivity.class);
                this.startActivity(toProjects);
            }
            if (response.equals("OK")) {}
        } catch (Exceptions.ServerException e) {
            Intent toProjects = new Intent(MainActivity.this, LoginActivity.class);
            this.startActivity(toProjects);
        } catch (Exceptions.NoInternetException e) {
            Intent toProjects = new Intent(MainActivity.this, LoginActivity.class);
            this.startActivity(toProjects);
        }

}
EDIT 2
03-31 20:50:02.226 25129-19694/com.mrgeorgeous.liceraptorapp D/HAVEALOOK: 2cd3c4a50347752781db11734b44c4dc
03-31 20:50:02.236 25129-19694/com.mrgeorgeous.liceraptorapp D/HAVEALOOK: 2cd3c4a50347752781db11734b44c4dc
03-31 20:50:02.246 25129-19694/com.mrgeorgeous.liceraptorapp D/HAVEALOOK: 2cd3c4a50347752781db11734b44c4dc
03-31 20:50:02.366 25129-25129/com.mrgeorgeous.liceraptorapp D/dalvikvm: GC_FOR_ALLOC freed 732K, 10% free 8464K/9372K, paused 13ms, total 15ms
03-31 20:50:02.376 25129-25129/com.mrgeorgeous.liceraptorapp I/dalvikvm-heap: Grow heap (frag case) to 9.844MB for 1481024-byte allocation
03-31 20:50:02.396 25129-25138/com.mrgeorgeous.liceraptorapp D/dalvikvm: GC_FOR_ALLOC freed 4K, 9% free 9906K/10820K, paused 21ms, total 22ms
03-31 20:50:02.436 25129-25129/com.mrgeorgeous.liceraptorapp D/INTERNAL:  / 5136389168f5aa53
03-31 20:50:03.546 25129-25129/com.mrgeorgeous.liceraptorapp D/HAVEALOOK: 5136389168f5aa53 / ERR1
03-31 20:50:03.546 25129-25129/com.mrgeorgeous.liceraptorapp D/HAVEALOOKRESPONSE: ERR1


text:
Q: serverside protection mechanism to prevent anyone viewing javascript source I know you can use javascript obfosculator to make javascript source protected but I need a better solution on top of this.
Im investigating options to encrypt a javascript file to be placed on some websites. This javascript file is included like normal with :
<script src="http://secure.com/encryted.js"></script>

The idea is to somehow prevent users viewing the source of the javascript or at least make it much harder to do so...
Im thinking of a way to only return the javascript by doing something like
<script src="http://secure.com/validate.php"></script>

That way I could on the host secure.com check for certain conditions and only return the javascript ( encryped ) if those conditions are met.
Does anyone have an idea or done such a thing? Or knows of good way to prevent sourcecode of javascript to be exposed or make it very hard?
ETA seems a good way to encrypt it
http://www.enetplanet.com/enc/

My goal is to have people viewing the source /html not be able to "just view" the source
Any thoughts?

A: No, TEA (http://www.enetplanet.com/enc/) is not the kind of tool you can use for such a task. It is just a little bit more than a proof-of-concept or than a toy. TEA (like any other encryption system) cannot be actually used to encrypt/protect a javascript file that you send to the customer's browser.
Consider this: the user must have a copy of the encryption program to decypher the javascript file coming from your server. In other cases, this would not be a great security hole in itself. Any encryption system rely on the secretness of a key, not on the secreteness of the encryption program/algorithm.
Unfortunately, when talking of client-side javascript, this is a security hole. The encryption program (TEA) is a javascript file itself. Anybody can read it. It is trivial to modify it in a way that it just print out the encryption key or in a way that it just decrypt the "protected" javascript file without making any check.
Moreover, the end-user has total, unlimited access to the network comunication channel. He can just read the password (the key) with a network sniffer installed on its PC. No key (and no encryption system) can resist such an attack (well-known as a "man-in-the-middle" attack).
It is well known that there isn't any real way to encrypt/protect a javascript file. The best you can do is to obfuscate it.
If you really need to protect some kind of client-side software, you have to use compiled software (C/C++), encryption and some kind of hardware key. Any other system can easily be "cracked" (as the whole history of computer games can demonstrate).


text:
Q: Docker container with Python Web App - Connect to Postgres on Host machine (OSX) I can connect to my local Postgres DB in my web app, but NOT if I am running the web app inside of a Docker container.

*

*Web app running inside of a Docker container

*Postgres running in the Host machine

I am not sure if it is related to the Postgres connection settings or to the Docker network settings.
Follow my settings and commands:
Host:

*

*OSX 10.11.6

*PostgreSQL 9.6

Docker container

*

*Docker 1.13.1

*Docker-machine 0.9.0

*Docker container OS: python:3.6.0-alpine

*Python 3.6 + psycopg2==2.7

postgresql.conf:
listen_addresses = '*'

pg_hba.conf
host    all             all             127.0.0.1/32            trust
host    all             all             0.0.0.0/0               trust
host    all             all             172.17.0.0/24           trust
host    all             all             192.168.99.0/24       trust

With Docker network in HOST mode
docker run -i --net=host -h 127.0.0.1 -e POSTGRES_URI=postgresql://127.0.0.1:5432/db my/image

Error:

could not connect to server: Connection refused
    Is the server running
  on host "127.0.0.1" and accepting     TCP/IP connections on port 5432?

With Docker network in BRIDGE mode
docker run -i --add-host=dockerhost:`docker-machine ip ${DOCKER_MACHINE}` -e POSTGRES_URI=postgresql://dockerhost:5432/db -p 8000:8000 -p 5432:5432 my/image

Error:

server closed the connection unexpectedly
  This probably means the
  server terminated abnormally  before or while processing the request.

Any ideas?

A: There is a note about doing this in the docs

I want to connect from a container to a service on the host
The Mac has a changing IP address (or none if you have no network access). Our current recommendation is to attach an unused IP to the lo0 interface on the Mac; for example: sudo ifconfig lo0 alias 10.200.10.1/24, and make sure that your service is listening on this address or 0.0.0.0 (ie not 127.0.0.1). Then containers can connect to this address.


text:
Q: Vertical rule at the left of a listing I would like to draw vertical rules at a specific location in the left margin of a listing in a listings environment. Is it possible ?
======= PSEUDO EXAMPLE =======

for i in range(5):
# One comment
    if i == 2:
# One comment
        print(i)

print("Finished....")

======= OUTPUT WISHED (this is ASCII art ! ) =======

   for i in range(5):
    # One comment
|      if i == 2:
|   # One comment
|          print(i)

    print("Finished....")

A: You may use TikZ and it's overlay function …
Here's my solution.
Code
\documentclass{article}

\usepackage{xparse}
\usepackage{listings}
    \lstset{%
        escapechar=§% or what fits to your code
    }
\usepackage{tikz}
    \usetikzlibrary{calc}
    \tikzstyle{every lst line}=[line width=3pt, gray]
    % command for setting a TikZ anchor
    \newcommand{\tanc}[1]{%
        \begin{tikzpicture}[remember picture]
            \coordinate (#1) at (0,0);
%           \fill circle (0.5pt);% this line is for testing only
        \end{tikzpicture}%
    }
    % some parameters
    \def\DeltaX{4cm}
    \def\DeltaYi{6pt}
    \def\DeltaYii{0pt}
    % command for drawing the lines
    \NewDocumentCommand{\makeline}{O{0pt} m m O{}}{%
        \begin{tikzpicture}[remember picture, overlay, transform canvas={xshift=#1}]
            \draw [every lst line,#4] %
                let\p1=(#2), \p2=(#3), \p3=(current page.west) in%
                (\x3+\DeltaX,\y1+\DeltaYi) -- (\x3+\DeltaX,\y2+\DeltaYii);
            ;
        \end{tikzpicture}%
    }

\usepackage{lipsum}% for testing

\begin{document}
\lipsum[1]
%
\begin{lstlisting}
for i in range(5):
# Pu§\tanc{one}§t the anchor somewhere in the line
if i == 2:
# One comment §\tanc{two}§
    print(i) §\tanc{three}§
print("Finished....")§\tanc{four}§
\end{lstlisting}
\makeline{one}{two}\makeline{three}{four}[red]
\makeline[-7pt]{one}{four}[blue]
%
\lipsum[2]
\end{document}

Settings

*

*Choose an escape character that is never part of your listings. I choosed §.

*Adjust the every lst line style to fit your taste. This is the style applied to each line drawn with \makeline

*Adjust the parameters to fit you font and layout. \DeltaX = distance to left page border, \DeltaYi = shift between baseline of the anchored row in your listing an the start of the line and \DeltaYii same for second row.

Usage

*

*Put an anchor somewhere in the row you want the line to start with \tanc{<name 1>}
# Pu§\tanc{one}§t the anchor somewhere in the line

*Put a second anchor with \tanc{<name 2>}. The names should be unique at least for on listing.
print(i) §\tanc{two}§

*Draw the line with \makeline{<name 1>}{<name 2>}.
\makeline{one}{two}
You may change the line style of the line using the second optional argument and shift the line horizontally using the first one:
\makeline[<x shift>]{<name 1>}{<name 2>}[<style>]
\makeline[-7pt]{one}{four}[blue]
If you load a decoration library you can also add big curly braces or whatever by using the <style> argument.

*run LaTeX twice otherwise TikZ can't get the right positions of the remember picture nodes.

Result


text:
Q: Is there a way to read a csv column when its name contains spaces in Angular? I use d3.js library to read a CSV in Angular. Here's how I read it.
d3.csv('../assets/datasets/tests-per-million.csv').then((data: any) => {
  this.testsData = data;
  for (let i = 0; i < this.testsData.length; i++) {
    this.testCountries.push(this.testsData[i].Entity.split(' ')[0]);
    this.testDates.push(this.testsData[i].Date);
    this.cumulativeTests.push(this.testsData[i].Cumulative);
  }
});

The problem is that the last column of the CSV contains spaces on its name. Here is a sample of a CSV row.
Entity: "Australia - units unclear"
Code: ""
Date: "Mar 22, 2020"
Cumulative total tests per million: "5632.53024026095"

I have successfully read the three first columns but I cannot catch the last one which contains space on its name.

A: Since the key (Cumulative total tests per million) has spaces, you need to access the JSON using bracket notation:
this.cumulativeTests.push(this.testsData[i]['Cumulative total tests per million']);


text: Q: How do you edit the coordinate of a polygon in Shapely? I have a shapely polygon: polygon = Polygon([[0, 0], [1, 0], [1, 1], [0, 1]]). Is it possible to edit the coordinate of one of the vertices without recreating a new polygon?


text:
Q: Will this be considered as bad RESTFul design? I am working on designing the API's for the first time in Spring and I have the following use case:

*

*Get all the products.

*Get Products by ID.

Now, what I did was, I made a single API for this,
@Path("/products")
public interface ProductResource {

    @GET
    @ApiOperation(value = "Gets all the products by criteria")
    Response getProductsByCriteria(@Context UriInfo uriInfo);
}

What I am doing is, I take the ID in the query param. If it's value is null, I will call the method (at service layer) for returning all products, else I will call the method for returning a specific product based on its id (coming in the query param).
I just want to know, is this a bad RESTFul Design? Should I instead have two seperate API's for getting products based on their ID's and for getting all the productS?

A: I would suggest to have separate endpoints:

*

*GET /products for all products

*GET /products/{productId} for getting product by specific id which would be passed as PathParam. In this way, you could have other endpoints for manipulating product data, for example PUT /products/{productId} or DELETE /products/{productId}. They would return HTTP status NOT FOUND (404) if product is not found.

QueryParam is more suitable to filter products by some characteristic, for example GET /products?color=red.

A: You should definitely have

*

*GET /products - returns list of all products

*GET /products/:id - which returns single product or 404 in case the product is not found

In this way it's much easier to read and it's consistent with other quality APIs you find on the internet.

A: By mixing the getAll and getById, you are missing an important point: there is no way for the caller of the API to know if a productId exists.
Normally you would return a 404 on a get for a product id that does not exist.
So to answer your question: yes, it is a Restful design mistake.


text:
Q: Hide bootstrap buttons in navigation on threshold I'm currently working on making a static design responsive using bootstrap integrated in TYPO3. I started out by creating the navigation bar and am running into first problems.
Current layout (desktop view)
Current layout (resized window, smaller)
Notice how the social media buttons are jumping out of the navigation bar? I would love to hide them completely at this point.
When resized even more to a smaller width, same goes for the search field - jumps out of navigation bar at certain window width. I would love to keep this until the navigation bar switches to collapsed, so on for example iPad (768x1024) you could still search.
My html template right now
I'll adapt the template so it doesn't contain TYPO3 variables, but the generated output you would use without TYPO3:

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

        </button>

Home

About

Contact

Port

Prrrrrrrrriint

            <form class="navbar-form" action="suchergebnisse">

                    <input type="text" class="form-control" placeholder="Suche" name="q" id="srch-term">

                        <button class="btn btn-default" type="submit" name="cmd" id="submit"></button>

            </form>

I've tried playing with the collapsed classes, but being out of twitter-bootstrap business for a while hasn't been good for me. I'd appreciate any hints you might have!

A: For faster mobile-friendly development, use these utility classes for showing and hiding content by device via media query. Also included are utility classes for toggling content when printed.
For more info Bootstrap Doc
add below bootstrap class for hide html element based on your requirement.
hidden-xs for Phones (<768px) resolution
hidden-sm for Tablets (≥768px) && Desktops (<992px) resolution
hidden-md for Desktops (≥992px) && Desktops (<1200px)resolution
hidden-lg for Desktops (≥1200px) resolution


text:
Q: Call internal Web Api from a external server I built a Web Api that is hosted in a server that just allow internal access and i have a Cliente-Side aplication. I have to build something in the middle to make this connection.
Cliente-Side <-> SOMETHING <-> Web Api (internal access) -> DataBase
What i need to build ? I am a begginer and i have this problem now.

A: Make sure you can hit the URL of your web api from your device.  Easy route is to run the network capabilities sample here on your device and see you can hit the server using the IsReachable and IsRemoteReachable APIs.  Its Xamarin Forms, not pure Xamarin, but should let you see if you can hit your server.
https://blogs.msdn.microsoft.com/devfish/2016/06/22/xam-plugins-connectivity-all-apis-sample/

A: Here is an implementation of a function which show get and post data from the client app to web service, this will work on desktop app(win form etc). To access the web api from another web site using the same below code you have to enable cors in the web api project
public static  async Task UploadAsync(ReadingModel reading)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://your-api-domain.net/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // HTTP GET
        HttpResponseMessage response = await client.GetAsync("api/yourapi");
        if (response.IsSuccessStatusCode)
        {
            Product product = await response.Content.ReadAsAsync<Product>();
            Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
        }

        // HTTP POST
        try
        {
            HttpResponseMessage response = await client.PostAsJsonAsync("api/yourapi", reading);
            if (response.IsSuccessStatusCode)
            {
                // do your stuff
            }
        }
        catch (Exception)
        {

        }

    }
}


text:
Q: Trying to simplify $A'B'C'D + A'B'CD + A'BC'D + AB'CD + ABCD$ My solution so far:
$A'(B'C'D + B'CD + BC'D) + A(B'CD + BCD)$
$= A'(C'D(B' + B) + B'CD) + A(CD(B'+B))$
$= A'(C'D(1) + B'CD) + A(CD(1))$
$= A'C'D + A'B'CD + ACD$
$= D(A'C' + AC) + A'B'CD$
$= D(A\text{ xnor }C) + A'B'CD$
$= D[(A\text{ xnor }C) + A'B'C]\text{ <<< Can't seem to get any further than this.}$
Did I perhaps screw up somewhere? Or not do it as well as I could have? Maybe missed using a rule?
Thanks!
K

A: I'd start by plotting the Karnaugh map.
$A′B′C′D+A′B′CD+A′BC′D+AB′CD+ABCD$ is an sum of five minterms, thus the Karnaugh map will show five ones (I've left out zeroes for greater visual contrast):
$$
\begin{matrix}
     & A'B' & A'B & AB & AB' \\
C'D' &                       \\
C'D  &  1   &  1             \\
CD   &  1   &     &  1 &  1  \\
CD'  &
\end{matrix}
$$
This can be covered as a sum of three products, of which two are essential, in two ways.
$$
F = A'C'D + ACD + B'CD = ((A\ xnor\ C) + B'C)D \\
F = A'C'D + ACD + A'B'D = ((A\ xnor\ C) + A'B')D
$$
Which are both one term shorter than your original: $((A\ xnor\ C) + A'B'C)D$. Note how you used disjoint terms as a covering for the function. This often happens when you simplify as expression without looking at the Karnaugh map.

Starting from the same Karnaugh map, you can also choose to start with a product of sums. As a product of three sums, all essential:
$$
F = D(A'+C)(A+B'+C')
$$
Or if you prefer, an inverted sum of products:
$$ F = not(D'+AC'+A'BC) $$

A: It simplifies to $[(A+B)'C+A' + B'D +BD]'$.


text:
Q: Xelatex Crashes on item-bullets I have installed a local version of the latest TeXLive distribution and xelatex
crashes with the following error message, using the little document below.
This is XeTeX, Version 3.1415926-2.3-0.9997.5 (TeX Live 2011)
restricted \write18 enabled.
entering extended mode
...
(./xelatex-test.aux)
Output file removed.
)
Error 256 (driver return code) generating output;
file xelatex-test.pdf may not be valid.
Transcript written on xelatex-test.log.

When putting in \item[] to avoid the bullet the file compiles. However  \usepackage[T1]{fontenc} did not bring the solution.
\documentclass[a4paper,11pt]{report}

\usepackage{fontenc}
\usepackage{xunicode}
\usepackage{xltxtra}
\defaultfontfeatures{Mapping=tex-text} % To support LaTeX quoting style

%\usepackage{amssymb, amsthm}  %amsthm depends on amssymb
\usepackage{unicode-math}

\begin{document}
\begin{itemize}
 \item test
\end{itemize}

\end{document}

A: Update your TeX Live with tlmgr and try again. Your code works well on my PC.
BTW,

*

*Don't use xltxtra, it is obsolete.

*You don't need to use xunicode yourself.

*You don't need to use fontenc yourself, especially without any options.

My XeTeX version:

XeTeX, Version 3.1415926-2.3-0.9997.5 (Web2C 2011)

Packages (with \listfiles in the preamble):

  report.cls    2007/10/19 v1.4h Standard LaTeX document class
  size11.clo    2007/10/19 v1.4h Standard LaTeX file (size option)
 fontenc.sty
xunicode.sty    2011/09/09 v0.981 provides access to latin accents and many oth
er characters in Unicode lower plane
graphicx.sty    1999/02/16 v1.0f Enhanced LaTeX Graphics (DPC,SPQR)
  keyval.sty    1999/03/16 v1.13 key=value parser (DPC)
graphics.sty    2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR)
    trig.sty    1999/03/16 v1.09 sin cos tan (DPC)
graphics.cfg    2010/04/23 v1.9 graphics configuration of TeX Live
   xetex.def    2009/11/22 v0.94 LaTeX color/graphics driver for XeTeX (RRM/JK)

 xltxtra.sty    2010/09/20 v0.5e Improvements for the "XeLaTeX" format
ifluatex.sty    2010/03/01 v1.3 Provides the ifluatex switch (HO)
 ifxetex.sty    2010/09/12 v0.6 Provides ifxetex conditional
fontspec.sty    2011/09/18 v2.2a Advanced font selection for XeLaTeX/LuaLaTeX
   expl3.sty    2011/10/09 v2900 L3 Experimental code bundle wrapper
 l3names.sty    2011/10/09 v2896 L3 Experimental namespace for primitives
l3bootstrap.sty    2011/09/10 v2798 L3 Experimental bootstrap code
    etex.sty    1998/03/26 v2.0 eTeX basic definition package (PEB)
    calc.sty    2007/08/22 v4.3 Infix arithmetic (KKT,FJ)
   color.sty    2005/11/14 v1.0j Standard LaTeX Color (DPC)
   color.cfg    2007/01/18 v1.5 color configuration of teTeX/TeXLive
l3basics.sty    2011/10/09 v2896 L3 Experimental basic definitions
 l3expan.sty    2011/10/09 v2896 L3 Experimental argument expansion
    l3tl.sty    2011/09/16 v2831 L3 Experimental token lists
   l3seq.sty    2011/10/09 v2896 L3 Experimental sequences and stacks
   l3int.sty    2011/10/09 v2896 L3 Experimental integers
 l3quark.sty    2011/10/09 v2896 L3 Experimental quarks
   l3prg.sty    2011/10/09 v2896 L3 Experimental control structures
 l3clist.sty    2011/10/09 v2896 L3 Experimental comma separated lists
 l3token.sty    2011/10/09 v2896 L3 Experimental token manipulation
  l3prop.sty    2011/09/17 v2839 L3 Experimental property lists
   l3msg.sty    2011/10/09 v2896 L3 Experimental messages
    l3io.sty    2011/10/09 v2896 L3 Experimental input-output operations
  l3file.sty    2011/10/09 v2896 L3 Experimental file operations
  l3skip.sty    2011/10/09 v2896 L3 Experimental dimensions and skips
  l3keys.sty    2011/09/10 v2800 L3 Experimental key-value interfaces
    l3fp.sty    2011/09/26 v2857 L3 Experimental floating-point operations
   l3box.sty    2011/10/09 v2896 L3 Experimental boxes
l3coffins.sty    2011/09/12 v2814 L3 Experimental coffin code layer
 l3color.sty    2011/09/07 v2776 L3 Experimental colour support
l3luatex.sty    2011/09/10 v2798 L3 Experimental LuaTeX-specific functions
  xparse.sty    2011/10/09 v2900 L3 Experimental document command parser
fontspec-patches.sty    2011/09/18 v2.2a Advanced font selection for XeLaTeX/Lu
aLaTeX
fixltx2e.sty    2006/09/13 v1.1m fixes to LaTeX
fontspec-xetex.sty    2011/09/18 v2.2a Advanced font selection for XeLaTeX/LuaL
aTeX
 fontenc.sty
  eu1enc.def    2010/05/27 v0.1h Experimental Unicode font encodings
  eu1lmr.fd    2009/10/30 v1.6 Font defs for Latin Modern
fontspec.cfg
realscripts.sty    2010/09/30 v0.3 Access OpenType subscripts and superscripts
metalogo.sty    2010/05/29 v0.12 Extended TeX logo macros
unicode-math.sty    2011/09/19 v0.6a Unicode maths in XeLaTeX and LuaLaTeX
l3keys2e.sty    2011/10/09 v2900 LaTeX2e option processing using LaTeX3 keys
catchfile.sty    2011/03/01 v1.6 Catches the contents of a file (HO)
infwarerr.sty    2010/04/08 v1.3 Providing info/warning/message (HO)
 ltxcmds.sty    2011/04/18 v1.20 LaTeX kernel commands for general use (HO)
etexcmds.sty    2011/02/16 v1.5 Prefix for e-TeX command names (HO)
  fix-cm.sty    2006/09/13 v1.1m fixes to LaTeX
  ts1enc.def    2001/06/05 v3.0e (jk/car/fm) Standard LaTeX file
filehook.sty    2011/10/12 v0.5d Hooks for input files
unicode-math-xetex.sty
unicode-math-table.tex
   t3cmr.fd    2001/12/31 TIPA font definitions
  omslmr.fd    2009/10/30 v1.6 Font defs for Latin Modern
 omslmsy.fd    2009/10/30 v1.6 Font defs for Latin Modern


text:
Q: Sort array by specific value with usort I know that similar threads exist, and I have tried to understand and read them all, but I'm not getting anywhere.
Problem: I'd like to output all the films directed by Stanley Kubrick and I want the movies to be listed in descending order by year of release.
The output of the films works, but I can't sort them.
"crew": [
    {
      "id": 45966,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Day of the Fight",
      "job": "Director of Photography",
      "overview": "American short subject documentary film in black-and-white, which is notable as the first picture directed by Stanley Kubrick. Kubrick financed the film himself, and it is based on an earlier photo feature he had done as a photographer for Look magazine in 1949. 'Day of the Fight' shows Irish-American middleweight boxer Walter Cartier during the height of his career, on the day of a fight with black middleweight Bobby James, which took place on April 17, 1950.",
      "vote_count": 69,
      "video": false,
      "poster_path": "/4caX3IZkf7n2QCbxaJO3hyn0SCm.jpg",
      "backdrop_path": "/lt1Lan9bmG29JjqaMad5tkRpCHJ.jpg",
      "title": "Day of the Fight",
      "popularity": 4.701,
      "genre_ids": [
        99
      ],
      "vote_average": 5.9,
      "adult": false,
      "release_date": "1951-04-26",
      "credit_id": "55d0b196c3a3681bff007bde"
    },
    {
      "id": 10165,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Fear and Desire",
      "job": "Director of Photography",
      "overview": "After their airplane crashes behind enemy lines, four soldiers must survive and try to find a way back to their battalion. However, when they come across a local peasant girl the horrors of war quickly become apparent.",
      "vote_count": 254,
      "video": false,
      "poster_path": "/oiN9OUOGbVywUHjto30AfLpnIJ7.jpg",
      "backdrop_path": "/e3o0Dwlzzpd4kJpOOJgVyMstnII.jpg",
      "title": "Fear and Desire",
      "popularity": 6.052,
      "genre_ids": [
        18,
        10752
      ],
      "vote_average": 5.5,
      "adult": false,
      "release_date": "1953-04-01",
      "credit_id": "55d0b9c392514131a5007a4c"
    },
    {
      "id": 45314,
      "department": "Camera",
      "original_language": "en",
      "original_title": "The Seafarers",
      "job": "Director of Photography",
      "overview": "Acclaimed director Stanley Kubrick's first film made in color. The documentary focuses on the benefits of membership to the Seafarers International Union.",
      "vote_count": 44,
      "video": false,
      "release_date": "1953-10-15",
      "vote_average": 4.7,
      "title": "The Seafarers",
      "popularity": 3.009,
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "poster_path": "/nSucFIAQ5CowEE1WZ87mz3OsbQ1.jpg",
      "credit_id": "55d0cae1c3a36877570014d2"
    },
    {
      "id": 975,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Paths of Glory",
      "job": "Additional Photography",
      "overview": "A commanding officer defends three scapegoats on trial for a failed offensive that occurred within the French Army in 1916.",
      "vote_count": 1613,
      "video": false,
      "poster_path": "/peblNaHOiTR8DACYyUWsJHhK6GP.jpg",
      "backdrop_path": "/yFykLiFuBU6CrGWr2hLP0ttbQ2i.jpg",
      "title": "Paths of Glory",
      "popularity": 11.573,
      "genre_ids": [
        18,
        10752
      ],
      "vote_average": 8.3,
      "adult": false,
      "release_date": "1957-09-18",
      "credit_id": "5706f1259251412b1400065c"
    },
    {
      "id": 45970,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Flying Padre",
      "job": "Director of Photography",
      "overview": "Two days in the life of priest Father Fred Stadtmuller whose New Mexico parish is so large he can only spread goodness and light among his flock with the aid of a mono-plane. The priestly pilot is seen dashing from one province to the next at the helm of his trusty Piper Club administering guidance (his plane, the Flying Padre) to unruly children, sermonizing at funerals and flying a sickly child and its mother to a hospital.",
      "vote_count": 56,
      "video": false,
      "release_date": "1951-03-23",
      "vote_average": 5.2,
      "title": "Flying Padre",
      "popularity": 4.033,
      "genre_ids": [
        99
      ],
      "backdrop_path": "/5HisBYhc75h0DYXSMJWN1eFaxse.jpg",
      "adult": false,
      "poster_path": "/5aog5qVlMFakpogT1Nar9Z7gqq4.jpg",
      "credit_id": "5e94991dccb15f001571103c"
    },
    {
      "id": 10056,
      "department": "Camera",
      "original_language": "en",
      "original_title": "Killer's Kiss",
      "job": "Director of Photography",
      "overview": "The film revolves around Davey Gordon, a 29 year old welterweight New York boxer in the end of his career, and his relationship with a dancer and her violent employer.",
      "vote_count": 283,
      "video": false,
      "poster_path": "/jc5EjvQywJqS8Xm0RWMoblJvCM6.jpg",
      "backdrop_path": "/6VhN0ScAA8VgK3qyRnZ7azD9XEV.jpg",
      "title": "Killer's Kiss",
      "popularity": 10.353,
      "genre_ids": [
        80,
        18,
        53
      ],
      "vote_average": 6.4,
      "adult": false,
      "release_date": "1955-09-21",
      "credit_id": "5e9499448e87020013ce555f"
    },
    {
      "id": 185,
      "department": "Directing",
      "original_language": "en",
      "original_title": "A Clockwork Orange",
      "job": "Director",
      "overview": "In a near-future Britain, young Alexander DeLarge and his pals get their kicks beating and raping anyone they please. When not destroying the lives of others, Alex swoons to the music of Beethoven. The state, eager to crack down on juvenile crime, gives an incarcerated Alex the option to undergo an invasive procedure that'll rob him of all personal agency. In a time when conscience is a commodity, can Alex change his tune?",
      "vote_count": 8571,
      "video": false,
      "release_date": "1971-12-19",
      "vote_average": 8.2,
      "title": "A Clockwork Orange",
      "popularity": 25.023,
      "genre_ids": [
        878,
        18
      ],
      "backdrop_path": "/keblhZFIZYiWflmURWNHEuS2jqL.jpg",
      "adult": false,
      "poster_path": "/4sHeTAp65WrSSuc05nRBKddhBxO.jpg",
      "credit_id": "52fe4224c3a36847f80071db"
    },

My code so far
$data = file_get_contents($url); // put the contents of the file into a variable
$director = json_decode($data); // decode the JSON feed

echo '
';
print_r($director);

foreach ($director->crew as $showDirector) {
    if ($showDirector->department == 'Directing') {
        usort($showDirector, function ($item1, $item2) {
            return $item2['release_date'] <=> $item1['release_date'];
        });
        echo $showDirector->release_date . ' / ' . $showDirector->title . '
';
   }
}

A: usort gets  passed the elements from the array exactly as they are. i.e. in this case your array contains objects - therefore you need to do the comparison on the properties of the objects and not as elements in an array.
Instead of comparing the items as array elements like this:
 return $item2['release_date'] <=> $item1['release_date']);

...your function should be checking the object properties like this:
usort($showDirector, function ($item1, $item2) {
    /* Check the release_date property of the objects passed in */
    return $item2->release_date <=> $item1->release_date;
});

Also, you are also trying to sort the array in the wrong place - each time you find a director, you are sorting that single array (and there is only one element so nothing changes).
You need to:

*

*Add all of the required director items into a separate array for sorting

*When you have all items for sorting, you sort this array

*Then you can loop through this sorted array to process the results, e.g. display them.

See the code below - the steps are commented so you can see what you need to do:
$data = file_get_contents($url); // put the contents of the file into a variable
$director = json_decode($data); // decode the JSON feed

/* 1. Create an array with the items you want to sort */
$directors_to_sort = array();
foreach ($director->crew as $showDirector) {
    if ($showDirector->department == 'Directing') {
        $directors_to_sort[] = $showDirector;
    }
}

/* 2. Now sort those items
   note, we compare the object properties instead of trying to use them as arrays */
usort($directors_to_sort, function ($item1, $item2) {
    return $item2->release_date <=> $item1->release_date;
});

/* 3. Loop through the sorted array to display them */
foreach ($directors_to_sort as $director_to_display){
    echo $director_to_display->release_date . ' / ' . $director_to_display->title . '
';
}


text:
Q: Point data structure for a sketching application I am currently developing a little sketching application based on HTML5 Canvas element. There is one particular problem I haven't yet managed to find a proper solution for.
The idea is that the user will be able to manipulate existing stroke data (points) quite freely. This includes pushing point data around (ie. magnet tool) and manipulating it at whim otherwise (ie. altering color).
Note that the current brush engine is able to shade by taking existing stroke data in count. It's a quick and dirty solution as it just iterates the points in the current stroke and checks them against a distance rule.
Now the problem is how to do this in a nice manner. It is extremely important to be able to perform efficient queries that return all points within given canvas coordinate and radius. Other features, such as space usage, should be secondary to this. I don't mind doing some extra processing between strokes while the user is not painting.
Any pointers are welcome. :)

A: the standard solution for working with arbitrary points lists in 2d is a quadtree space partitioning: http://en.wikipedia.org/wiki/Quadtree

A: You want to have a look at spatial indexing in general.  Johan has a good suggestion with the quadtree.  Other data structures that might work:

*

*kd-tree

*vp tree

*simple grid index

A: I would go with simple matrix int pixels[][] where for given pixel at x,y the value of the matrix is its color.
I do not see any clear advantage of using more sophisticated data structures, matrix is very fast and easy to use. As for operations, for instance getting points for given coordinate and radius you just perform the math on matrix indices and only retrieve only matchings pixels etc. Bleeding fast.

A: I'd basically just wrap an array in an object with some special functions for moving the pixels' data around - or sampling them. I did something fairly similar in a weather-erosion project...just used a Gaussian function to both sample and push data down based on some sort of circumference / weighting principle.
You'd have to have a list of pixels mapping to each 'brushstroke' if you wanted to have undo / brushstroke interactions, but that seems like a different object - you'd just have all your brushstrokes pointing at that central matrix (for the actual contents of the points they influenced - they'd maybe have 'weights' concerning how much color they contributed to the point, or something).


text:
Q: SignalR not allow to use Autorize in the method I have some asp.net core application.
It uses Bearer authentication.
My auth and SignalR seattings.  Also I use OpenIddict.
ConfigureServices
       services.AddMvc();
       ...
        services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
        {
            builder
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowAnyOrigin()
            .AllowCredentials();
        }));

        //services.AddSignalR();
        services.AddSignalR(hubOptions =>
        {
            hubOptions.EnableDetailedErrors = true;
        });
        ...
services.AddDefaultIdentity<Account>(opt =>
        {
            opt.Password.RequiredUniqueChars = 1;
            opt.Password.RequireNonAlphanumeric = false;
            opt.Password.RequireLowercase = false;
            opt.Password.RequireDigit = false;
            opt.Password.RequireUppercase = false;
            opt.Password.RequiredLength = Account.MinPasswordLength;

            opt.Lockout.AllowedForNewUsers = false;

            opt.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
            opt.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
            opt.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
        })
        .AddUserManager<AccountManager>()
        .AddRoles<AccountRole>()
        .AddEntityFrameworkStores<ApplicationContext>()
        .AddDefaultTokenProviders();

        services.AddOpenIddict()
          .AddCore(opt =>
          {
              opt.UseEntityFrameworkCore()
                 .UseDbContext<ApplicationContext>();
          })
          .AddServer(opt =>
          {
              opt.SetAccessTokenLifetime(TimeSpan.FromMinutes(5));
              opt.UseMvc();
              opt.AllowCustomFlow(WebConstants.AdminGrantType)
                 .EnableTokenEndpoint("/api/common/auth/Token")
                 .AllowRefreshTokenFlow()
                 .DisableHttpsRequirement()
                 .AcceptAnonymousClients();
          });

        services.AddAuthentication()
            .AddOAuthValidation(options =>
            {
                options.Events.OnRetrieveToken = context =>
                {
                    context.Token = context.Request.Query["access_token"];
                    return Task.CompletedTask;
                };
            });

Configure
 app.UseCors("CorsPolicy");
            app.UseAuthentication();

            app.UseSignalR(routes =>
            {
                routes.MapHub<SomeHub >("/someHub");
            });

AuthAccountTypeAttribute
public class AuthAccountTypeAttribute : AuthorizeAttribute
{
    public AuthAccountTypeAttribute(params AccountType[] accountType)
    {
        if (accountType.Any())
        {
            Roles = string.Join(',', accountType.Select(x => x.ToString()));
        }
        AuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme;
    }
}

And directly Hub
[AuthAccountType(AccountType.Admin)]
public class SomeHub : Hub
{
    private readonly AccountManager _accountManager;
    private readonly IUnitOfWork _unitOfWork;

    public SomeHub (AccountManager accountManager, IUnitOfWork unitOfWork)
    {
        _accountManager = accountManager;
        _unitOfWork = unitOfWork;
    }

    public override Task OnConnectedAsync()
    {
        return base.OnConnectedAsync();
    }

    public async Task OnConnectSmth()
    {

    }

}
If you use authorize attribute like this all works fine, but if SomeHub used without AuthAccountType and OnConnectSmth with
[AuthAccountType(AccountType.Admin)]
public async Task OnConnectSmth()
{

}

It returns 401.
What can I do?
SignalR 1.0.4
.Net Core 2.1
The same issue if I use basic Authorize
[Authorize(AuthenticationSchemes = OAuthValidationDefaults.AuthenticationScheme)]

Or how can I made Anonymous connection in Authorize Hub?

A: DefaultScheme was not set in ConfigureServices(). And strange rules in Hub.
Fix:
services.AddAuthentication(options => { options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme; } );


text:
Q: What is the best approach to encapsulate multiple method calls? Is there some principle to follow in multiple method calls on Java?
I know about Facade, but in single methods, not service methods, sometimes we need to call other single methods that have a single responsibility, but doing this, I will break this in this method then make multiple calls. For example:
private void doSomethingA(){

}

private void doSomethingB(){

}

private void doSomethingC(){

}

//Am I breaking some rules here? What is the best approach?
private void processSomething(){
   doSomethingA();
   doSomethingB();
   doSomethingC();
}

A: What you're doing is perfectly acceptable, although your syntax is incorrect. Splitting large methods into smaller, more singly purposed, more readable, more testable methods and calling them from another method is good practice.

A: If there are a large number of processes or you use the same sequence often you could implement the processing as a sequence using an enum.
public enum Engine {

    A {

                @Override
                void doIt(Object to) {
                    // Do what you need to do.
                }
            },
    B {

                @Override
                void doIt(Object to) {
                    // Do what you need to do.
                }
            },
    C {

                @Override
                void doIt(Object to) {
                    // Do what you need to do.
                }
            };

    abstract void doIt(Object to);

    public void go(Object to) {
        for (Engine e : Engine.values()) {
            e.doIt(to);
        }
    }
}

This can be enhanced in many ways (which is why I like it). You can encode alternative orders of execution in an Iterable. You can add, remove and reorder the processes in just one place. The names of the enum can be greatly simplified. And many more.


text:
Q: What kind of switchable graphics technology does ATI/AMD have? AMD (formerly ATI) seems to have a lot different products (or names) for hybrid graphics technology. Which technologies does AMD have and what are the differences between those?
NVIDIA has just one such technology AFAIK: Optimus. This is a laptop with Intel + NVIDIA. On desktops it's called Synergy.
On the AMD side, there are combinations of Intel + AMD and AMD + AMD. Names that have been flying around:

*

*AMD Switchable Graphics Technology

*AMD Dynamic Switchable Graphics (PowerXPress 4.0 / BACON)
Which one refers to the AMD + AMD combination and which refers to the Intel + AMD one? Are there other differences?

A: Just from doing basic research, we can see that there are fundamental differences between the AMD Switchable and Dynamic Switchable technology.  In regards to which one is AMD+AMD or AMD+INTEL, the differences come down to the architecture on the actual computer:
AMD Switchable Available for the products mentioned in the first link you provided, mostly AMD+AMD build ups.  Enables the computer to decide to use the discrete graphics capability when plugged into AC power, or to use the mobile processor (degraded video capabilities) when on Battery power.
AMD Dynamic Switchable Available for both AMD and Intel based products, assuming you have the AMD A APU, or the Intel processor with a supported Radeon Discrete card.  The main difference here between the normal 'switchable' and the 'dynamic switchable' is that the dynamic makes it's determination not based on power consumption (persay), but on the actual application use of the A/GPU.
Meaning if you are using a video intensive application, it will be using the discrete card; if you are not using a video intensive application, it will be assigned to the integrated graphics.  This happens even if you are on battery or on AC power.
The benefits of the dynamic mode allow the graphics processor to decide on the mode to use, and using the Catalyst control center, the user can also force applications to run in either mode a well.  Which basically allows you to 'configure' or 'assign' applications to specific roles on the computer.
In Answer to your Question

*

*Which one is AMD+AMD:  Switchable.

*Which one is AMD+Intel:  Dynamic (which also includes AMD+AMD assuming you are using an AMD A series APU).


text:
Q: php compare two nested array and predict the difference How find difference of the two array
// ARRAY 1

$a1 = array(
    "a1" => 1,
    "a3" => array(
        "a31" => 31
    ),
    "a4" => array(
        "a41" => 41
    ),
    "a5" => array(
        "a51" => 51,
        "a52" => 52
    )
);

// ARRAY 2
$a2 = array(
    "a1" => 1,
    "a2" => 2,
    "a3" => array(
        "a31" => 31,
        "a32" => array(
            "a321" => 321,
            "a322" => 322
        )
    ),
    "a4" => array(
        "a41" => 42
    ),
    "a5" => array(
        "a51" => 51,
        "a52" => 52
    )
);

array_diff function returns ==> Array ( )
But there is a lot of difference exist in the above two array variables.
example:

*

*in ARRAY1 There is no key a2 but in ARRAY2 a2 is available.

*ARRAY2 a3 contain nested array (one nested level ) but in ARRAY 2 contain two nested sub level.

So here i want to compare two array n-level (ie. nested array)

A: $results = array_diff(array_map('serialize',$a2),array_map('serialize',$a1));
$results = array_map('unserialize',$results);

echo '<pre>';
print_r($results);


text:
Q: Phonegap plugin on ionic framework? I am trying to get ionic framework application started, and I want to use file system API in it.
I ran following:
$ionic plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git

which seems to have completed without an error. However, when I run the application using local chrome, I get an error on this line:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, ...

Inspecting the console, I see the error is:
ReferenceError: LocalFileSystem is not defined

My question is: what is the correct way to use the file system library in ionic project, and if it's even possible?

A: Plugins are only used when the app is compiled, not when runned locally from www folder. If you explore www folder on your project, you will not find any .js from any plugin. ionic prepare <platform> is in charge to copy the files from the plugin to the correct location in the native project, before building the final app package.
If you wish to debug a plugin, you can use ripple (a little bit tricky but achievable if you follow Apache Docs, do not try to install the chrome extension as it will probably not be working). Ripple just fakes the functionality of native plugins (does not emulate), so you can debug js layer but you can't test the native one.
Other better solutions would be to use eclipse + chrome remote debugger to debug android apps (have never tried) or xcode + safari to debug ios apps (works fine). Both require authorisation to developer tools on the phone. Also you could try weinre for both platforms but it is not as powerful as chrome/safari.
Weinre, chrome and safari all of them require to compile the app, install on the phone and connect the browser debugger to the running app via usb cable (local wifi network for weinre as it runs under a local server in your local network).


text:
Q: add html content to hidden form field Is it possible to pass a chunk of html content to a hidden field and how would I do this?
Thanks
Jonathan

A: You could do this with Javascript:
<input type="hidden" id="htmlCodes" />

document.getElementById("htmlCodes").value = "Hello World";

Just be sure that your values are properly-escaped when you pass them into the hidden form field.
Online Demo: http://jsbin.com/ubofu/edit

A: Yes - simply HTML encode the content (e.g. replace "<" with "&lt" etc...)
You didn't specify which language you'll use for poplulating the field value, so I can't help with details of how to encode.
Here's a reference of how to do it in jQuery.
Here's Java

A: You can also "spawn" a hidden textarea after processing the content inside.
This can be done easily with Jquery :
$('#your_form')
.append('<textarea name="content" class="hidden">' + your_content + '</textarea>');

Here we assuming that you've got a "hidden" class, Bootstrap's got one, but you can also use this :
CSS Code :
.hidden
{
  display: none !important ;
  visibility: hidden !important;
}


text:
Q: Toggling Map layers visibility from another component First of all, I am design student and I use Vue.js for prototyping my senior project. So this is not real working project. Just prototype of some diary app.
My issue is, I build a map component via Vue2Leaflet which has Tile Layer.
Over the Tile Layer I rendered a GeoJSON file which has two objects of coordinates.
I have also a datepicker component which emits values by an EventBus.
My aim is: when datepicker emits a specific value, turning off an <l-geo-json> and turn on the other <l-geo-json>.
<l-geo-json> has a parameter which is :visible to show or hide. :visible gets parameter from GeoJSON object. datepicker emits some boolean value for changing GeoJSON parameter. GeoJSON parameter changes but it does not render in map.
I think, it is because of not re-rendering map component.
My map component is like:
<template>

    location_searching
    <l-map :zoom="zoom" :options="{ zoomControl: false }" class="map" :center="center">
      <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
      <l-geo-json :visible="yesterday.day" :geojson="bus.geojson" :options="bus.options"></l-geo-json>
      <l-geo-json :visible="today.day" :geojson="today.geojson" :options="today.options"></l-geo-json>
    </l-map>

</template>

And also my geojson.js file is like
    import Vue from 'vue';
    export const EventBus2 = new Vue();
    export const data = {
      today: {
        "type": "FeatureCollection",
        "id": "0520",
        "visible": false,
        "features": [ // geojson features and coordinates ]
      },

      yesterday: {
        "type": "FeatureCollection",
        "id": "0520",
        "visible": false,
        "features": [ // geojson features and coordinates ]
      }
  }

As you can see, datepicker emit some value in MMDD format. Switch statement checks value in GeoJSON data by id. If it matches, change visible property. It is actually changed when datepicker emits.
But it is not render in map (the GeoJSON layers do not change visibility accordingly).
How can I do this? Should I use watch or something like that? If it is, how can I use that?

A: You should simply directly change your instance data.
For clarity I will do as if you imported from your geojson.js file as data2. Calling both the same might be a reason why you are confused.
import { data as data2, EventBus2 } from '../assets/geojson/sample-geojson.js';

The reason why your GeoJSON layers visibility does not dynamically change is because you properly initialize your instance data and day properties using information from your data2, but that does not dynamically bind them to future modifications in data2.
Therefore the easiest approach would be to toggle your instance data and day properties in your "mapDay" event listener, instead of the information in data2.
EventBus2.$on('mapDay', pickerValue => {
  switch (pickerValue) {
    case data2.today.id:
      this.yesterday.day = true;
      this.today.day = false;
    break;
    case data2.dun.id:
      this.yesterday.day = false;
      this.today.day = true;
    break;
  }
});

You could also toggle both your data and data2, in case you want data2 to also be synced, e.g. if you use it in another component. Note that such a strategy would be brittle, since changing data2 in that other component would have no effect here.
On the other hand, you could simplify your visibility toggling logic by simply storing your pickerValue in your instance data, and compare it to your geojson.id within :visible attribute binding expression: :visible="pickerValue === yesterday.geojson.id"
Code example:

Vue.component('map-view-2', {
  template: '#map-view-2',
  components: {
    'l-map': Vue2Leaflet.LMap,
    'l-tile-layer': Vue2Leaflet.LTileLayer,
    'l-geo-json': Vue2Leaflet.LGeoJson,
  },
  data() {
    return {
      pickerValue: '0520',
      url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      attribution: '© OpenStreetMap contributors',
      yesterday: {
        geojson: data2.yesterday,
      },
      today: {
        geojson: data2.today,
      },
    };
  },
  mounted() {
    this.$root.$on('mapDay', pickerValue => {
      this.pickerValue = pickerValue;
    });
  },
});

// Dummy DatePicker component for the sake of the demo.
Vue.component('date-picker', {
  template: '#datepicker',
  methods: {
    handleInputChange(event) {
      this.$root.$emit('mapDay', event.target.value);
    },
  },
});

const data2 = {
  today: {
    "type": "FeatureCollection",
    "id": "0520",
    "features": [{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.34, 48.86] // Left
      },
    }],
  },
  yesterday: {
    "type": "FeatureCollection",
    "id": "0519",
    "features": [{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.35, 48.86] // Right
      },
    }],
  },
};

new Vue({
  el: '#app',
});

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />

<template id="map-view-2">

    <l-map :zoom="11" style="height: 100px;" :center="[48.86, 2.35]">
      <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
      <l-geo-json :visible="pickerValue === yesterday.geojson.id" :geojson="yesterday.geojson"></l-geo-json>
      <l-geo-json :visible="pickerValue === today.geojson.id" :geojson="today.geojson"></l-geo-json>
    </l-map>

</template>

<template id="datepicker">
  <fieldset @change="handleInputChange">
    <legend>Choose a date</legend>
    <input type="radio" name="date" value="0520" id="today" checked />
    Today 0520
    <input type="radio" name="date" value="0519" id="yesterday" />
    Yesterday 0519
    <input type="radio" name="date" value="none" id="none" />
    None
  </fieldset>
</template>

  <map-view-2></map-view-2>
  <date-picker></date-picker>

A more modular approach would expose the pickerValue data as a prop, so that you modify it at the parent (e.g. App) level directly, instead of having to listen to your "mapDay" event:

Vue.component('map-view-2', {
  template: '#map-view-2',
  components: {
    'l-map': Vue2Leaflet.LMap,
    'l-tile-layer': Vue2Leaflet.LTileLayer,
    'l-geo-json': Vue2Leaflet.LGeoJson,
  },
  props: {
    // Receive the value directly from parent component / App.
    pickerValue: {
      type: String,
      default: '0520',
    },
  },
  data() {
    return {
      url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      attribution: '© OpenStreetMap contributors',
      yesterday: {
        geojson: data2.yesterday,
      },
      today: {
        geojson: data2.today,
      },
    };
  },
});

// Dummy DatePicker component for the sake of the demo.
Vue.component('date-picker', {
  template: '#datepicker',
  props: {
    value: {
      type: String,
      default: '0520',
    },
  },
  methods: {
    handleInputChange(event) {
      // https://vuejs.org/v2/guide/components-custom-events.html#Customizing-Component-v-model
      this.$emit('input', event.target.value);
    },
  },
});

const data2 = {
  today: {
    "type": "FeatureCollection",
    "id": "0520",
    "features": [{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.34, 48.86] // Left
      },
    }],
  },
  yesterday: {
    "type": "FeatureCollection",
    "id": "0519",
    "features": [{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [2.35, 48.86] // Right
      },
    }],
  },
};

new Vue({
  el: '#app',
  data() {
    return {
      pickerValue: '0519', // This value rules child components default value.
    };
  },
});

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" />

<template id="map-view-2">

    <l-map :zoom="11" style="height: 100px;" :center="[48.86, 2.35]">
      <l-tile-layer :url="url" :attribution="attribution"></l-tile-layer>
      <l-geo-json :visible="pickerValue === yesterday.geojson.id" :geojson="yesterday.geojson"></l-geo-json>
      <l-geo-json :visible="pickerValue === today.geojson.id" :geojson="today.geojson"></l-geo-json>
    </l-map>

</template>

<template id="datepicker">
  <fieldset @change="handleInputChange">
    <legend>Choose a date</legend>
    <input type="radio" name="date" value="0520" id="today" :checked="value === '0520'" />
    Today 0520
    <input type="radio" name="date" value="0519" id="yesterday" :checked="value === '0519'" />
    Yesterday 0519
    <input type="radio" name="date" value="none" id="none" :checked="value === 'none'" />
    None
  </fieldset>
</template>

  <map-view-2 :picker-value="pickerValue"></map-view-2>
  <date-picker v-model="pickerValue"></date-picker>

All that being said, if your work is only for a design prototype, not even showing off your programming skills, then even Vue, while already quite simple, might be overkill for your task.