text:
Q: algorithm challenge: merging date range I'm facing an interesting problem:

*

*I have several date ranges that can overlap

*each of them has a name

Is it possible to "des-overlap" theses ranges? That is, to generate:

*

*a new set of ranges where none overlaps the others

*each of this new range has a list of corresponding names

Maybe I can make this a bit more graphical. This is what I have first:
a   |------------------------------|
b                    |-------------------|
c          |-----------------|

This is what I would like to obtain:
    |------|---------|-------|-----|-----|
        a      a,c     a,b,c   a,b    b

I found a solution that kind of works, but which is not elegant:

*

*I transform each range (from, to) into a list of days (d1, d2, d3, etc.)

*I group names by day

*I aggregate groups that contain the same names to recreate ranges

Can you think of a better solution? I'm working with C# but any language independent idea would be much appreciated.  Thanks!

A: You may want to have look at Interval Trees.

A: I have code that does this. It relies on the input-set being ordered by from and then to (ie. if it was SQL, it would be ORDER BY from_value, to_value), but after that it is quite optimal.
My implementation basically does what @Justin L.'s answer describes, so if you just want a textual description, look at his answer for the algorithm.
The code is here: LVK.DataStructures, and the files you want to look at are:

*

*Range.cs

*RangeExtensions.cs, in particular the Slice method at line 206 and onwards.

To use it:
List<Range<DateTime>> ranges = ...
var slices = ranges.Slice();

This will give you one new range for each slice, and for each such range you would have a .Data property containing references back to the contributing ranges.
ie. for your original example, you would get exactly what you want, individual ranges, with the contributing ranges a, b, c etc. in the .Data property.
The classes might use other portions of my class library, which is all there. If you decide to use it, just copy out the portions you want to use.
If you're only interested in the implementation, it can be found in the RangeExtensions.cs file, line 447 and onwards, InternalSlice method.

A: I would

*

*Keep an unordered list of "open" ranges

*Start from day 1, and add the first range to the open ranges list.

*Move until the next range boundary (be it start or close).  Create your first "output" range: starting from day 1, ending on that day.  In it are the items in your open ranges list.

*If the range encountered is already in the open ranges list, remove it.  Otherwise, add it.

*Repeat 3 and 4, moving along the line.

I definitely did a bad job of explaining it.  I'll be writing some code for this soon.  But until then, here's what would happen in your solution:
a   |------------------------------|
b                    |-------------------|
c          |-----------------|

1.  Start at day 1, add A to open ranges list, which now contains [A]
2.  Move to the start of C.  First RESULT RANGE: A range from Day 1 to C's start,
      with a value A. (what is in your open ranges list)
3.  Add C to the open ranges list, which now contains [A,C]
4.  Move to the start of B.  Second RESULT RANGE: A range from C's start to B's
      start, with a value A,C. (what is in your open ranges list)
5.  Add B to the open ranges list, which now contains [A,C,B]
6.  Move to the end of C.  Third RESULT RANGE: A range from B's start to C's end,
      with a value of A,C,B.
7.  Remove C from the open ranges list, which now contains [A,B]
8.  Move to the end of A.  Fourth RESULT RANGE: A range from C's end to A's end,
      with a value of A,B
9.  Remove A from the open ranges list, which now contains [B]
10. Move to the end of A.  Fourth RESULT RANGE: A range from A's end to B's end,
      with a value of B

RESULT RANGES
1. from Day 1 to C's start: A
2. from C's start to B's start: A,C
3. from B's start to C's end: A,C,B
4. from C's end to A's end: A,B
5. from A's end to B's end: B

Alternative Method
You could do this:

*

*Keep a ordered list of "output ranges". This makes it easy to test if a point is within a range, and also what ranges follow eachother.

*Take a range from your input ranges.

*Check to see if it is completely before or completely after all output ranges, and handle accordingly.  Skip the next steps and go back to step 2, if so.

*Compare its start point to the output ranges

*If it is before any other output range, add a new output range from its start to the start of the first output range.

*If this is in between an already-existing output range, split that output range at that point.  The first part would hold the same "parents", and the second part would have the same parents + the new input range.

*Now, compare its end point to the output ranges.

*If it is after any other output range, add a new output range from the end of the last output range to its end.

*If this is in between an already-existing output range, split that output range at that point.  The second part would hold the same "parents", and the first part would have the same parents + the new input range

*Add the current input range as a part to all ranges in between the two "processed" ranges in steps 6 and 9, if any.

*Repeat 2-6 for all input ranges.

Here are the first few steps, using the sample data + another range D:
("processed" ranges indicated by **double stars**)
a   |------------------------------|
b                    |-------------------|
c          |-----------------|
d       |------------------------|

1.
   Process A
   Output ranges: |--------------A---------------|
2.
   Process B
     - Start of B is in **A**; split A in two:
                  |-------A-------|------AB------|
     - End of B is after any output range range;
         creating new output range at end
                  |-------A-------|------AB------|---B---|
    - Nothing was/is in between **A** and (nothing)
3.
   Process C
     - Start of C is in **A**; split A in two:
                  |---A----|--AC--|------AB------|---B---|
     - End of C is in **AB**; split AB in two:
                  |---A----|--AC--|--ABC--|--AB--|---B---|
     - There were/are no ranges between **A** and **AB**

4.
   Process D
     - Start of D is in **A**; split A in two:
                  |-A-|-AD-|--AC--|--ABC--|--AB--|---B---|
     - End of D is in **AB**; split AB in two:
                  |-A-|-AD-|--AC--|--ABC--|ABD|AB|---B---|
     - Ranges AC and ABC were/are in between **A** and **AB**
                  |-A-|-AD-|--ACD-|-ABCD--|ABD|AB|---B---|

Final output:     |-A-|-AD-|--ACD-|-ABCD--|ABD|AB|---B---|

A: You could:

*

*sort the list of all dates (combining the from and to dates)

*then running along this list, each new range would be from one date to the next start or end date that is different from the preceding.

For naming the new ranges, it would make sense to have the list of original range names that the current new range contains, and each time you hit an end date, remove the old range name from the list, and each tiem you hit a start date, add it's name to the list.

A: Do this:
Create an Event class.
class DateEvent : IComparable<DateEvent>
{
    public Date Date;
    public int DateRangeId;
    public bool IsBegin; // is this the start of a range?

    public int CompareTo(DateEvent other)
    {
        if (Date < other.Date) return -1;
        if (Date > other.Date) return +1;
        if (IsBegin && !other.IsBegin) return -1;
        if (!IsBegin && other.IsBegin) return +1;
        return 0;
    }
}

Define a List<DateEvent> events;
Add each range's start and end date into the list:
for (int i = 0; i < dateRanges.Length; ++i)
{
    DateRange r = dateRanges[i];
    events.Add(new DateEvent(r.BeginDate, i, true));
    events.Add(new DateEvent(r.EndDate, i, false));
}

Sort the events.
events.Sort();

Now set up an output class:
class OutputDateRange
{
    public Date BeginDate;
    public Date EndDate;
    public List<string> Names;
}

Finally, traverse the events, maintaining which ranges are present:
List<int> activeRanges;
List<OutputDateRange> output;
Date current = events[0].Date;
int i = 0;

while (i < events.Length;)
{
    OutputDateRange out = new OutputDateRange();
    out.BeginDate = current;

    // Find ending date for this sub-range.
    while (i < events.Length && events[i].Date == current)
    {
        out.EndDate = events[i].Date;
        if (events[i].IsBegin)
            activeRanges.Add(events[i].DateRangeId);
        else
            activeRanges.Remove(events[i].DateRangeId);
        ++i;
    }

    if (i < events.Length)
        current = events[i].Date;

    foreach (int j in activeRanges)
        out.Names.Add(dateRanges[j].Name);

    output.Add(out);
}

That should do the trick. Note that I've not made the constructors, and the code is a bit ugly, but hopefully that conveys the general idea.

A: *

*I have a list first, i don't know its length, but i got 3 chars

*check for one slot, if A there? add 'A', if B there? add 'B', if c there? add 'C'

*go to another slot, cycle like #2

*end when nothing added to another new slot

*I got the list

*flatten the list


text:
Q: How to handle multiple client using Indy 10 Currently I'm success fully make server and client using TIdTCPServer and TIdTCPClient Indy components, but I got a trouble when two client connect to the server at the same time. I have two networks 192.168.10.23 and localhost, when client connect using localhost it's fine and the second client try connect to 192.168.10.23 there still waiting for first client disconnect.
can anyone please give me advice how to handle multiple client using Indy10.
Added:
This my code:
void __fastcall TfrmServer::TCPServerConnect(TIdContext *AContext)
{
    TList *list = TCPServer->Contexts->LockList();
    try
    {
        for (int j=0; j < list->Count; j++)
        {
            TIdContext *myContext = static_cast<TIdContext*>(list->Items[j]);
            CLIENT_AUTH(myContext);

            INFO_CLIENT *br = ((INFO_CLIENT*)brb);
            br->ClientIP    = myContext->Binding()->IP;
            br->ClientPort  = myContext->Binding()->Port;
            br->peerIp      = myContext->Binding()->PeerIP;
            br->peerPort    = myContext->Binding()->PeerPort;

            if (myContext->Connection->Connected())
            {
                for (int i=0; i < list->Count; i++)
                {
                    ListIt = ListClient->Items->Add();
                    ListIt->Caption = String(i+1); // number
                    ListIt->SubItems->Add(br->UserName); // Name
                    ListIt->SubItems->Add(br->ClientIP); // Ip
                    ListIt->SubItems->Add(br->peerIp); // Peer Ip
                    ListIt->SubItems->Add(br->ClientPort); // port
                    ListIt->SubItems->Add(br->peerPort); // port
                    ListIt->SubItems->Add("Connected"); // Status
                }
            }
        }
    }
    __finally
    {
        TCPServer->Contexts->UnlockList();
    }
}

Did this code have supports for multiple client ?

A: TIdTCPServer supports multiple simultaneous connections on multiple networks and that works just fine.  If your clients are serializing with each other, then the problem has to be in your own code or networking setup.  Indy does not prevent multiple clients from connecting to the same server at the same time.
Update: try this:
class TAddToListSync : public TIdSync
{
protected:
    TIdContext *FContext;

    void __fastcall DoSynchronize()
    {
        TListItem *ListIt = frmServer->ListClient->Items->Add();
        ListIt->Caption = String(ListIt->Index+1); // number
        ListIt->SubItems->Add(...); // Name
        ListIt->SubItems->Add(FContext->Binding()->IP); // Ip
        ListIt->SubItems->Add(FContext->Binding()->PeerIP); // Peer Ip
        ListIt->SubItems->Add(FContext->Binding()->Port); // port
        ListIt->SubItems->Add(FContext->Binding()->PeerPort); // port
        ListIt->SubItems->Add("Connected"); // Status
    }

public:
    __fastcall TAddToListSync(TIdContext *AContext)
        : TIdSync(), FContext(AContext)
    {
    }

    static void Add(TIdContext *AContext)
    {
        TAddToListSync *sync = new TAddToListSync(AContext);
        sync->Synchronize();
        delete sync;
    }
};

void __fastcall TfrmServer::TCPServerConnect(TIdContext *AContext) {
{
    CLIENT_AUTH(AContext);
    TAddToListSync::Add(AContext);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: $this->input->request_headers() returns empty array I'm prototyping an app using CI 3.0 dev.  I have the following code in my Menu controller:
This code is returning nothing
 $myHeaders = $this->input->request_headers();
 log_message('info', "Headers..(option1) ", print_r($myHeaders, TRUE));

This code is returning the full array
 $headers = apache_request_headers();
 log_message('info', 'Headers.. (option2) '.print_r($headers, TRUE));

Yet, the input class is (eventually) calling the same apache_ function.  What dumb thing am I missing?
Here's the log:
INFO - 2015-02-22 14:45:56 --> Headers..(option1)
INFO - 2015-02-22 14:45:56 --> Headers.. (option2) Array
(
    [Host] => oap.local
    [Connection] => keep-alive
    [Content-Length] => 0
    [User-Agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
    [Origin] => chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
    [Content-Type] => application/x-www-form-urlencoded
    [Accept] => */*
    [Accept-Encoding] => gzip, deflate
    [Accept-Language] => en-US,en;q=0.8
)

Here's the entire controller:
defined('BASEPATH') OR exit('No direct script access allowed');

class Menu extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function getMenu($menuID)
    {
        log_message('info', __METHOD__ . "MenuID is ", $menuID);

        $myHeaders = $this->input->request_headers();
        log_message('info', "Headers..(option1) ", print_r($myHeaders, TRUE));

        $headers = apache_request_headers();
        log_message('info', 'Headers.. (option2) '.print_r($headers, TRUE));

        $deviceID = $this->input->post('device_reg_id', TRUE);
        log_message('info', "device=".$deviceID);
        $siteID = $this->input->post('site_id', TRUE);
        log_message('info', "device=".$siteID);

        $this->load->helper('zip');
        $this->load->helper('download');
        $filename = '';
        $rc = zipFile('./assets/menu/', $filename);
        $rc = false;
        if ($rc) {
            $data = file_get_contents($filename); // Read the file's contents
            $name = 'menu.zip';
            force_download($name, $data);
        } else {
            log_message('info', "returning 500");
            $this->output->set_status_header('500');
        }
    }
}

A: This might help you out. The log_message function (./system/core/Common.php) takes three parameters. The first being the level (error, debug, or info), the second being the message (string value) and the being a boolean.
In your controller on lines 12, and 15 you are sending menuID as the third parameter and print_r(myHeaders,TRUE). I think you meant to concatinate the values to your message.
Try changing your code to something like this:
log_message('info', __METHOD__ . "MenuID is ".$menuID);

$myHeaders = $this->input->request_headers();
log_message('info', "Headers..(option1) ".print_r($myHeaders, TRUE));


text:
Q: Find if element is included in array I have an array A = [1 2; 3 4; 5 6] and I want to check if a couple of values, let's say B = [1 2] is included in A. How would you do that?
I tried using C = ismember(B, A) but it gives as a result [1 1] both for [1 2] and [1 3].

A: Try it like this:
C = ismember(A,B,'rows');


text:
Q: Element-wise operations on real and imaginary data of fcomplex array? I have a array of type ILArray thats comes as an output from FFT function.
I want to further perform some math operations on the real and imaginary parts.
For example:
complexArray.realPart * 2 + complexArray.imaginaryPart * 4 ???

A: You have found the solution already. I'll put the answer here for sake of completeness.
Using ILMath.real() and ILMath.imag() gives access to the real and imaginary part of ILArray. If you are operating on the elements, using the properties .real and .imag of ILNumerics.fcomplex might be another option:
// create test array of complex elements
ILArray<fcomplex> C = ccomplex(ones<float>(1,10), -ones<float>(1,10));
// using real(), imag()
ILArray<float> a1 = 2 * real(C) + 4 * imag(C);
// using direct access to real / imag part of complex elements
foreach (var c in C) {
    float a2 = c.real * 2 + 4 * c.imag;
    // ...
}


text:
Q: how to insert row only once and make it updatable forever after I am working on source code where there is a table called tvseries (id = foreign key, tvs_id = primary key). what i want to achieve is that when user gets logged in for first time and submit a form related to tv series info it should insert a new row in table with related data but when again user submits that form it shouldn't create new row instead it should update the existing row.
Simply, only first time when user submits form it should insert details submitted and afterwards it should be updated whenever submitted.(i just want only one row to be inserted and latter updated with that form).
I have written a code which only inserts a new row with related data each time it is submitted
This is my code (Insertion part)
        $query = "INSERT INTO Tvseries SET Tvseries_fav=?, Tvseries_rank=?, Tvseries_rewatch=?,
        Tvseries_status=?, Tvseries_rec=?, id=?";

        $stmt = $conn->prepare($query);
        $stmt->bind_param('siissi', $tvsfav, $tvsrank, $tvsrewatched, $tvsstatus, $tvsrecommend, $id);
        $result = $stmt->execute();

        if ($result) {
            $tvs_id = $stmt->insert_id;
            $stmt->close();
            $_SESSION['message'] = 'Details have been submitted successfully!';
            $_SESSION['type'] = 'alert-success';
            header('location: Tvseriesinfo.php');
        } else {
            $_SESSION['error_msg'] = "Database error: Could not update details";
        }
    }

Extra info :
I have another table called users (where id = primary key),
Am using session variables.
How should i change my code so that i can achieve my objective which is mentioned in first two paragraphs.
I have searched stack overflow for related solution but haven't found satisfactory solution. Any help from you will be appreciated.
And one more thing my form contains only selcect boxes.
Thank you


text:
Q: Getdate() function shows different value When we are using
Select Getdate()

we get an output of:
'2017-08-21 09:31:50.660'

but the system time is
'2017-08-21 09:33'

A: GETDATE()

Function provides server machine's current date time but not local machine.


text:
Q: Tool to copy files of HDD with bad sectors I have an external hard drive that is starting to fail; it has some bad sectors. It's a 1 TB Fujitsu Siemens case with a Western Digital hard drive inside.
Eventually I will backup the whole drive with some backup/imaging software, but I don't have the free space to do that. At the moment I want to copy some video files, but I'm not able to because the drive hangs while copying a certain file, and disconnects. If I try to resume (using TeraCopy, great tool by the way) it hangs again and disconnects...
I don't seem to easily find a tool to copy that one file (and maybe others later), preferably freeware of course.
Another problem:
I have run chkdsk /r on that drive, and about 4 hours in it was at 1% (phase 1,2 and 3 were done in a few minutes, but phase 4 took hours to get from 0). At the moment I don't have access to a PC that can run long enough to get the job done in one sitting.
Is there a better tool out there so I could cut this job in pieces (or faster, but that seems unlikely)?

A: If you can handle Linux, ddrescue will do a block by block copy, recovering bad sectors, (like the dd command) to another hard drive.  I have used it successfully in the past to recover the contents of a hard drive Windows wouldn't mount.
It is included on the Linux System Rescue CD so you don't need to install Linux on a hard drive.

A: Roadkil's Unstoppable Copier recovers files from disks with physical damage and allows you to copy files from disks with problems such as bad sectors, scratches or that just give errors when reading data. The program will attempt to recover every readable piece of a file and put the pieces together. Using this method, most types of files can be made useable even if some parts of the file were not recoverable in the end.
Unstoppable Copier is freeware.
If that doesn't help, try fixing the drive with HDD Regenerator and salvage your files.
HDD Regenerator is shareware (US$39.95, money-back guarantee) and is try before you buy.
PS: I have pretty good experiences with this program, but of course success depends on the severity of the damage.

A: I wrote a simple PowerShell script here which allows better fine-tuning than Roadkil's Unstoppable Copier. Precision is up to the cluster size.
Currently I am trying to access the RAW disk/file with it, so that I am less limited and have more recovery options.

A: I've been given two drives from two separate machines that had bad sectors, and had to research this topic quite extensively. Some notes that may be useful:

*

*Roadkil was great for raw data copy. Unfortunately, I could only get it to work on Windows 8, not Windows 10. But hey, it's free!

*On Windows 10, Zinstall's Computer Rescue Kit worked fine. It also does migration, so you basically do recovery and redeployment in one shot. However, unlike Roadkil, it's not free (not even cheap, though worth the hassle in my view).

*On Windows 10, CHKDSK has been significantly dumbed down. The GUI CHKDSK practically does nothing. Have to do "CHKDSK /f /r /x" to get results.

*CHKDSK may kill a drive that's barely breathing - do it last!

A: You can try FileSaver. It will copy file in blocks. Even in case that some data cannot be read (after multiple retries) it will continue copy operation (with that data omitted of-course).


text:
Q: "Create App Service" Dialogue not retrieving info, Create button disabled I'm trying to create an empty ASP.NET 5 WepApplication, and hosting it to azure, there is a problem that I can't understand or resolve, the create app service dialogue doesn't seem to retrieve anything (It did some minutes ago) no Subscriptions, no Resource Group, no AppServicePlan, no nothing, and some of these fields are not even editable, making the Create Button always disabled hence no chance to create the Wep App in App Services.
Note that I got my credentials entered and connected with my Email that has a subscription to Azure and all.
Here are some screen shots that describe this :

The problem :

A: I was able to fix the issue in Visual Studio 2017 by logging out of my account in Visual Studio and then logging back in.
Visual Studio may be caching your account info from before you started the subscription. Logging out and back in would likely force a refresh of this data.


text:
Q: Unmarshal nested JSON with different structure but same keys I'm trying to unmarshal some nested JSON which looks like:
{
    "id": "aRandomId",
    "type": "aRandomType",
    "aRandomField": {
        "type": "someType",
        "createdAt": "2020-07-07T15:50:02",
        "object": "anObject",
        "modifiedAt": "2020-07-07T15:50:02"
    },
    "aParameter": {
        "type": "Property",
        "createdAt": "2020-07-07T15:50:02",
        "value": "myValue",
        "modifiedAt": "2020-07-07T15:50:02"
    },
    "location": {
        "type": "GeoProperty",
        "value": {
            "type": "Point",
            "coordinates": [
                7.0054,
                40.9999
            ]
        }
    },
     ... other things with type, value ...

    "createdAt": "2020-07-07T15:50:02",
    "modifiedAt": "2020-07-07T15:50:02",
}

I would like to get all keys and values which are: type, createdAt, Value (also if they are nested)
Actually, I have 2 structs:
type Attribute struct {
    Type       string `json:"type"`
    CreatedAt  string `json:"createdAt"`
    Value      string `json:"value"`
    ModifiedAt string `json:"modifiedAt"`
}

type Entity struct {
    Id        string `json:"id"`
    Type      string `json:"type"`
    CreatedAt string `json:"createdAt"`
    Attribute Attribute
}

in := []byte(buf.String())
    var entity Entity
    err := json.Unmarshal(in, &entity)
    if err != nil {
        panic(err)
    }

    frame.Fields = append(frame.Fields,
        data.NewField("key", nil, []string{"type : ", "createdAt : ", "name : "}),
    )
    frame.Fields = append(frame.Fields,
        data.NewField("value", nil, []string{entity.Type, entity.CreatedAt, entity.Attribute.Value}),
    )

The problem is there can be several different Attribute struct andIi can't provide them all.
I would like to display all key (only type, createdAt and Value) in one frame and all their value in another.
Maybe have something like that?
type Entity struct {
    attribute List<Attribute>
}
type Attribute struct{
    Type       string
    CreatedAt  string
    Value      string
    ModifiedAt string
}

A:
The problem is there can be several different Attribute struct andIi can't provide them all

It looks like your JSON data can have a set of keys with similar values (Attribute) and you can't know how many of them might be in the data.
For this case, you can use a map[string]json.RawMessage as the starting entity to unmarshal to
var e map[string]json.RawMessage
if err := json.Unmarshal([]byte(jsonData), &e); err != nil {
    panic(err)
}

You can then range over the values to see if you can unmarshal them into Attribute type
for k, v := range e {
    var a Attribute
    if err := json.Unmarshal(v, &a); err == nil {
        log.Printf("Got attribute %s: %s", k, string(v))
    }
}

Run it on playground


text:
Q: ASP.NET Core - getting a message from AuthenticateResult.Fail Can not get an error message in HTTP response.
            if (!string.IsNullOrWhiteSpace(checkTokenResponse.Error))
            {
                Logger.LogError(checkTokenResponse.Error);
                return AuthenticateResult.Fail(checkTokenResponse.Error);
            }

response

I suppose the error message should render into data response field
The same question ASP.NET Core - getting a message back from AuthenticationHandler
Update
code of custom Auth handler
public class AuthHandler : AuthenticationHandler<AuthOptions>
{
    private readonly IPrimeApiProxy _primeApiProxy;
    private readonly IPrimeProxy _primeProxy;
    private readonly int _adminGroupId;

    private static readonly string HeaderName = "Authorization";
    private static readonly string ApiAuthScheme = "oauth ";

    public AuthHandler(
        IOptionsMonitor<AuthOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock,
        IPrimeApiProxy primeApiProxy,
        IPrimeProxy primeProxy,
        ApplicationSettingsProvider settings)
        : base(options, logger, encoder, clock)
    {
        _primeApiProxy = primeApiProxy ?? throw new ArgumentNullException(nameof(primeApiProxy));
        _primeProxy = primeProxy ?? throw new ArgumentNullException(nameof(primeProxy));

        _adminGroupId = int.Parse((settings as dynamic).AdminGroupId as string);
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        Logger.LogTrace("HandleAuthenticateAsync");

        if (!Request.Headers.ContainsKey("Authorization"))
        {
            return AuthenticateResult.Fail("Missing Authorization Header");
        }

        try
        {
            var token = FetchToken(Request);

            if (string.IsNullOrWhiteSpace(token.token) && token.userId < 1)
            {
                Logger.LogError("Invalid token");
                return AuthenticateResult.Fail("Invalid token");
            }

            var checkTokenResponse = await _primeProxy.CheckToken(token.token);

            if (!string.IsNullOrWhiteSpace(checkTokenResponse.Error))
            {
                Logger.LogError(checkTokenResponse.Error);
                return AuthenticateResult.Fail(checkTokenResponse.Error);
            }

            var isValidInt = int.TryParse(checkTokenResponse.UserId, out var userId);

            if (!isValidInt)
            {
                return AuthenticateResult.Fail("User Id is invalid");
            }

            if (token.userId != userId)
            {
                return AuthenticateResult.Fail("The token belongs to another user");
            }

            bool isUserAdminAndCustomGroupMember = false;

            if (checkTokenResponse.UserRole == "admin")
            {
                isUserAdminAndCustomGroupMember = await _primeApiProxy.IsGroupMember(token.token, token.userId, _adminGroupId);
            }

            var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, token.userId.ToString()),
                new Claim(ClaimTypes.Role, isUserAdminAndCustomGroupMember ? "Admin" : "Learner")
            };

            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            return AuthenticateResult.Success(ticket);
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Auth exception");
            return AuthenticateResult.Fail("Invalid Authorization Header");
        }
    }

    private static (string token, int userId) FetchToken(HttpRequest request)
    {
        string authHeader = request.Headers[HeaderName];

        if (authHeader != null && authHeader.StartsWith(ApiAuthScheme, StringComparison.OrdinalIgnoreCase))
        {
            string token = authHeader.Substring(ApiAuthScheme.Length).Trim();
            string[] parts = token.Split(',', StringSplitOptions.RemoveEmptyEntries);

            if (int.TryParse(parts[1], out int userId))
            {
                return (parts[0], userId);
            }
        }

        return (null, 0);
    }
}


text:
Q: how to calculate duration with cloud functions i want to calculate duration for a given task/event. I am using cloud functions. I have four fields in flutter app;

*

*Start date

*Start time

*End date

*End time

how can i calculate the duration. Please help. i am using typescript for my cloud functions.
import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'

admin.initializeApp()

export const updateCharts =
functions.firestore.document('users/{UserId}/count/{uid}')
.onWrite(async(change, _) => await updateStats(change))

async function updateStats (change:
functions.Change<functions.firestore.DocumentSnapshot>){
const chartRating = change.after.ref.parent

let title = (await chartRating.where('Title', '==', 'Game').get()).size;
//duration

const restaurantRef = chartRating.parent!

console.log('{restaurantRef.path} now has ${Title}')
await restaurantRef.update({
Title: Title,

})

A: // place this code where you want to measure from.
var startTime = new Date().getTime();
...

// place this code where you want to get the difference
var diff = new Date().getTime() - startTime;

Use the getTime method to get the time in total milliseconds since 1970-01-01.


text:
Q: How to use SparkPost without a CC and/or BCC recipient? Here's my transmission object:

  if(req.body.bcc === ''){
    req.body.bcc = '';
  }
  if (req.body.cc === '') {
    req.body.cc = '';
  }
  if (req.body.subject === '') {
    req.body.subject = 'No subject';
  }
  if (req.body.source === '') {
    req.body.source = '<EMAIL OMITTED>';
  }
  if (req.body.messageBody === '') {
    req.body.messageBody = 'No body text has been entered';
  }
  var transmission = {
    recipients: [
      {
        address: {
          email: req.body.to,
          name: 'To recipient'
        },
        substitution_data: {
          recipient_type: 'Original'
        }
      }
    ],
    cc: [
      {
        address: {
          email: req.body.cc,
        },
        substitution_data: {
          recipient_type: 'CC'
        }
      }
    ],
    bcc: [
      {
        address: {
          email: req.body.bcc,
        },
        substitution_data: {
          recipient_type: 'BCC'
        }
      }
    ],
    content: {
      from: {
        name: req.body.source,
        email: req.body.source
      },
      subject: req.body.subject,
      text: req.body.messageBody,
      html: `<p></p>`
    }
  };

I have HTML input forms that send the entered data to req.body, but if there's no req.body.cc or req.body.bcc content, what happens is SparkPost throws an error saying Unaccessible entity and:

  name: 'SparkPostError',
  errors:
   [ { message: 'Invalid header',
       description: 'Error while validating header CC: Missing header content',
       code: '3002' } ],
  statusCode: 422 }

If I put a random number like 1 in the cc and bcc fields, then the message sends to the "to" user but sparkpost tells me that the message failed to send to 2 recepients. I feel like I'm missing something here because if there is no bcc or cc recipients then it should just send to the email in the "to" field and I shouldn't have to enter random gibberish in cc or bcc to get it to send an email. Has someone ran into this issue or have an idea how I could solve this problem?
Maybe I can do some check where if the field is blank, replace it with some default value that sparkpost will know that I'm not trying to send an email to anyone there, like a placeholder. But if there is such a thing, I haven't found it yet.

A: Here is an example of sending an email without CC or BCC. If you do not have any BCC or CC recipients than don't include their array objects.
{
    "options": {
        "open_tracking": true,
        "click_tracking": true
    },
  "campaign_id": "test",
  "recipients": [
    {
      "address": {
        "email": "to@example.com",
        "name": "To recipient"
      },
        "tags": [],
        "substitution_data": {"recipient_type": "Original"}
    }
  ],
  "content": {
    "from": {
      "email": "from@example.com",
      "name": "From address"
    },
    "subject": "My Sample Subject",
    "text": "{{recipient_type}}",
    "reply_to": "test@example.com",
    "html": "
{{recipient_type}}
"
  }
}

Here is the example as a curl command:
curl -X POST \
  https://api.sparkpost.com/api/v1/transmissions \
  -H 'authorization: YOUR_API_KEY_HERE' \
  -H 'cache-control: no-cache' \
  -d '{
    "options": {
        "open_tracking": true,
        "click_tracking": true
    },
  "campaign_id": "test",
  "recipients": [
    {
      "address": {
        "email": "to@example.com",
        "name": "To recipient"
      },
        "tags": [],
        "substitution_data": {"recipient_type": "Original"}
    }
  ],
  "content": {
    "from": {
      "email": "from@example.com",
      "name": "From address"
    },
    "subject": "My Sample Subject",
    "text": "{{recipient_type}}",
    "reply_to": "test@example.com",
    "html": "
{{recipient_type}}
"
  }
}

'

You will need to put your API key and replace the to/from addresses with ones appropriate for your test case.


text:
Q: What are the semantics of function pointers with empty parentheses in each C standard? Answers to this and this question say that function pointers of the form return-type (*pointer)() are pointers to a function which takes any number of arguments, though the latter says they obsolesced in C11.
On an i386 system with GCC, "extra" arguments passed in a call to an empty-parentheses-type'd function pointer are ignored, because of how stack frames work; e.g.,
/* test.c */
#include <stdio.h>

int foo(int arg) { return arg; }

int main(void)
{
    int (*fp)() = foo;
    printf("%d\n", fp(267239151, 42, (struct { int x, y, z; }){ 1, 2, 3 }));
    return 0;
}

$ gcc -o test test.c && ./test
267239151
$

In which C standards are empty-parentheses'd function pointers allowed? and wherever so, what are they specified to mean?

A: N1570 6.11.6:

The use of function declarators with empty parentheses (not
  prototype-format parameter type declarators) is an obsolescent
  feature.

This same wording appears in the 1990, 1999, and 2011 editions of the ISO C standard. There has been no change. The word obsolescent says that the feature may be removed in a future edition of the Standard, but so far the committee has not done so. (Function pointer declarations are just one of several contexts where function declarators can appear.)
The Introduction section of the C standard explains what obsolescent means:

Certain features are obsolescent, which means that they may be
  considered for withdrawal in future revisions of this International
  Standard. They are retained because of their widespread use, but their
  use in new implementations (for implementation features) or new
  programs (for language [6.11] or library features [7.31]) is
  discouraged.

A call to a function declared with an old-style declarator is still required to pass the correct number and type(s) of arguments (after promotion) as defined by the function's actual definition. A call with incorrect arguments has undefined behavior, which means that the compiler is not required to diagnose the error; the burden is entirely on the programmer.
This is why prototypes were introduced, so that the compiler could check correctness of arguments.

On an i386 system with GCC, "extra" arguments passed in a call to an
  empty-parentheses-type'd function pointer are ignored, because of how
  stack frames work ...

Yes, that's well within the bounds of undefined behavior. The worst symptom of undefined behavior is having the program work exactly as you expect it to. It means that you have a bug that hasn't exhibited itself yet, and it will be difficult to track it down.
You should not depend on that unless you have a very good reason to do so.
If you change
int (*fp)() = foo;

to
int (*fp)(int) = foo;

the compiler will diagnose the incorrect call.

A: Any function declarator can have empty parentheses (unless it's a function declaration where there is already a non-void prototype in scope).   This isn't deprecated, although it is "obsolescent".
In a function pointer, it means the pointer can point to a function with any argument list.
Note that when actually calling a function through the pointer, the arguments must be of correct type and number according to the function definition, otherwise the behaviour is undefined.

A: Although C allows you to declare a function (or pointer to function) with an empty parameter list, that does not change the fact that the function must be defined with a precise of parameters, each with a precise type. [Note 1]
If the parameter declaration is not visible at a call site, the compiler will obviously not be able to perform appropriate conversions to the provided arguments. It is, therefore, the programmer's responsibility to ensure that there are a correct number of arguments, all of them with the correct type. For some parameter types, this will not be possible because the compiler will apply the default argument promotions. [Note 2]
Calling a function with an incorrect number of arguments or with an argument whose type is not compatible with the corresponding parameter type is Undefined Behaviour.
The fact that the visible declaration has an empty parameter list does not change the way the function is called. It just puts more burden on the programmer to ensure that the call is well-defined.
This is equally true of pointer to function declarations.
In short, the sample code in the question is Undefined Behaviour. It happens to "work" on certain platforms, but it is neither portable nor is it guaranteed to keep working if you recompile. So the only possible advice is "Don't do that."
If you want to create a function which can accept extra arguments, use a varargs declaration. (See open for an example.) But be aware of the limitations: the called function must have some way of knowing the precise number and types of the provided arguments.

Notes

*

*With the the exception of varargs functions, whose prototypes end with .... But a declaration with an empty parameter list cannot be used to call a varargs function.

*Integer types narrower than int are converted to int and float values to double.


text:
Q: Set attribute to css file I have a CSS file with the name box.cs that contains the following code;
#box_overlay
{
  z-index: 10000;
  position: fixed;
  bottom: 5px;
  right: 5px;
}

#box_icon
{
  width: 100px;
  float: right;
}

I want to call this css file from a script;
     iframe.setAttribute("style", "/styles/box.cs"); but it's not letting me. Does anyone know what I'm doing wrong?


text:
Q: Can I detect a datagrid column being sorted in Silverlight? I need to be able to load a page of results into the grid from many tens of thousands of possible results. I want to get the data in pages of fifty from the server, using SQL Server to sort the data before returning it for binding to the datagrid. When the user sorts the dta in the datagrid by clicking a column header, I need to detect this and determine the new order before going back to the database.

A: I Don't think there is a way to ask the datagrid on what column it is sorted. However looking at http://blogs.msdn.com/scmorris/archive/2008/06/10/sorting-data-in-the-silverlight-datagrid.aspx I see that you can implement your own sorting when you implement ICollectionView on your items.
So you maybe you could implement ICollectionView on (a wrapper around) your results?
Datagrid does this internally if you set it's ItemSource to an IList, so maybe you can take a look at it's implementation to see how they did it? (see the Datagrids internal class ListCollectionView using reflector)
When you have a ICollectionView, you can use it's SortDescriptions to find out the current sorting.
I hope this helps you in the right direction?
Tjipke

A: You can by using a PagedCollectionView and casting the SortDescriptions property to an INotifyCollectionChanged. You then listen to the CollectionChanged event. Like this:
var collectionView = new PagedCollectionView(items);
(collectionView.SortDescriptions as INotifyCollectionChanged).CollectionChanged += (object sender, NotifyCollectionChangedEventArgs e) =>
{
  // This gets fired multiple times based on the previous sort and new sort
};
dataGrid.ItemsSource = collectionView;


text:
Q: I can't get the model from the view can somebody help me?
I have a model:
public class EditUserVM
{
    public string Role {get;set;}
    public IEnumerable<SelectListItem> AllRoles { get; set; }
}

I have a controller:
public class AdminController : Controller
    {
            // GET: Admin/Admin/EditUser/id
            [HttpGet]
            public ActionResult EditUser(string id)
            {
                ApplicationUser user = UserManager.FindById(id);
                EditUserVM model;
                //model initialization
                return View(model);
            }

            // POST: Admin/Admin/EditUser
            [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<ActionResult> EditUser(EditUserVM model)
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }
            //code
                return View(model);
            }
    }

And I have a view:
@model EditUserVM
@using (Html.BeginForm())
{

            @Html.LabelFor(model => model.Role, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownList("Role", Model.AllRoles, new { @class= "btn btn-light"})

                <input type="submit" value="Save" class="btn btn-success" />

}

But when I click on the save button, then in the post controller action I don't get model.AllRoles I mean, that model.AllRoles == null.
How can I get these values?

A: When the user submits the form (which then generates the callback to the [HttpPost]-variant of your EditUser method), the browser only submits the selected value of the drop down list, and not the entire list of possible selections. On the server side, an instance of the viewmodel is created and populated with what the browser sent. Since the browser hasn't sent the list of all possible options, that field is empty in your ViewModel.
This behavior makes sense. You're not interested in the list of possibilities (in fact, you already KNOW that list, because you sent it to the browser in the [HttpGet] method). You're only interested in the actual value that the user selected. If the ModelState is not valid, and you use that ViewModel to generate a new View, you need to repopulate AllRoles again.


text:
Q: Why do Python NumPy/SciPy numerical eigenvectors act incorrect compared to MATLAB when there is at least one eigenvalue degenerate point? For a physics problem, I numerically solve an eigenvalue equation with a square matrix (that is usually complex-valued, but is guaranteed to have real eigenvalues by construction). I have a 2D parameter space (x,y), over which I solve this equation at every point.
Then I take the dot product of an eigenvector and the discretized time derivative of another eigenvector along a trajectory in (x,y). For example, if my matrix is 4 x 4, and I get eigenvectors A, B, C, D with eigenvalues a, b, c, d, I am talking about (A).(dB/dt) (which is usually complex-valued). Then I calculate its complex argument/angle.
As long as my (x,y) points are sufficiently close enough (i.e. 'continuous'), and as long as I know that the eigenvalues of each eigenfunction considered are unique at every point along the trajectory (i.e. a =/= b at for all (x,y) making the trajectory), I can expect this angle to be a continuous quantity as well, without any sharp jumps (as in the first figure). However, when using Numpy/Scipy it seems as if this 'continuous' quality is ruined by a degenerate/repeating eigenvalue even if it is not on the trajectory. That is, if my trajectory comprises {(x1,y1),(x2,y2),(x3,y3),(x4,y4),(x5,y5)}, with unique eigenvalues at each point (i.e. a1 =/= b1, a2 =/= b2, ...), it seems as if that a9 = b9 at (x9, y9) causes trouble even if (x9, y9) is not on the trajectory considered.
I deduced this by changing my matrix so that the eigenvalues of each eigenfunction are unique at each point (i.e. I forced a9 =/= b9). Doing so gave me a 'continuous' angle. On the contrary, both cases are 'continuous' in MATLAB, as expected in theory.
It seems as if the issue is with the complex phases assigned to the numerical eigenfunctions. I used np.unwrap to delve into this more (last figure below), but it wasn't too fruitful.
I have spent weeks trying to understand why, to no avail. Any suggestions would be appreciated.
Expected behavior of complex argument along a trajectory without any repeating eigenvalues (both Python and MATLAB shows this when eigenvalues are unique everywhere):

Observed behavior when using numpy.linalg.eig or  scipy.linalg.eig:

Observed behavior when using numpy.linalg.eig AND np.unwrap - there aren't supposed to be jumps:


text:
Q: Is my voltage divider calculation OK? Can I use it to power an LED? I am planning on wiring 4 pin momentary push switch button that has a LED as well. The switch itself is fine with 20V, but the only problem is that the power source input is 20V and the LED requires 12V.How should I lower the voltage?
I was thinking of a voltage regulator, but I thought it is easier to work with color coded resistors, since I will be working on tight space. Now I salvaged the resistors and found 47Ohm and 33.4Ohm resistors.
When I did the simple math
$$
V_{DIV} = 20V * {47 \over (47+33.4)} = 11.6915V
$$
which is \$ 0.3V \$ lower than \$ 12V \$. Is this okay to be used?
Bear in mind I'm a newbie.

A: You can't use a voltage divider to power a load. That will almost never work.
You have two options:
 - Step down 20V to 12V using a LDO or switching regulator
 - Get your 12V out of the resistor network in an op-amp buffered with a NPN transistor
This describes accurately the problem with voltage dividers: http://www.learningaboutelectronics.com/Articles/Voltage-follower


text:
Q: Access the custom fields in joomla 3 In joomla 3 you can add custom fields. They are saved in the joomla mysql database under "_fields".
I´ve created a new custom field called "region". The users can add a value in their profile settings. So my question is now, how can i call the users value of this custom field via php?
I know how to call the users profile values for example:
jimport( 'joomla.user.helper' );
$user = JFactory::getUser();
$userId = $user->id;
$userProfile = JUserHelper::getProfile( $userId );
$usercity = $userProfile->profile['city'];

So how can I call the _field values?

A: When you add the custom field in the admin area (user fields)
You can view the full user profile in the default profile page
http://localhost/joomla/index.php?option=com_users&view=profile

Here's a screenshot

Then inspect the implementation. I came across accessing it this way.
$customFields = FieldsHelper::getFields('com_users.user', JFactory::getUser(), true);
// In my case there where only one additional field, so a took the 0-indexed value, you shall see in which index is the field you are searching for
$customFields[0]->value;

You can also try
    print_r($customFields);

Just to see whats in it.
Just so you know you can access it.

Hope this helps.

A: If you add new custom field from administration panel, number of object in $customFields array will change. And you access will poit to other field. You should access to field by it's name. You should add function for finding custom field by it's name.
$customFields = FieldsHelper::getFields('com_users.user', JFactory::getUser(), true);

public static function getValueByFieldName($fields, $field_name) {
    foreach ($fields as $field) {
        if ($field->name == $field_name){
            return $field->value;
            break;
        }
    }
}


text:
Q: Operand types are incompatible ("double*" and "int") Getting this error from my code. I had looked at similar questions on here but wasn't able to see why mine wasn't working (most answers involved chars and people using " instead of ', which wasn't really helpful to me). Not sure what I'm missing here. Edit: To be a little more specific it's the ">" sign in my if statement that is giving me trouble. My code is below:
    int main()
{
int numGrades = 0;
double *scores = nullptr;
double total = 0;
cout << fixed << setprecision(1);

cout << "How many grades would you like to enter? ";
cin >> numGrades;
if (numGrades < 0)
{
    cout << "Error, please enter positive values only: ";
    cin >> numGrades;
}
scores = new double[numGrades];
for (int x = 0; x <= numGrades; x++)
{
    cout << "Please enter student " << (x + 1) << "'s score: ";
    cin >> scores[numGrades];
    if (scores < 0 && scores > 100)     //ERROR IS HERE
    {
        cout << "Please enter a value between 0 and 100: ";
        cin >> scores[numGrades];
    }
}

A: cin >> scores[numGrades]; is assigning data outside of the allocated memory; anything after that is undefined behavior.
Did you mean cin >> scores[x];?

A: if (scores < 0 && scores > 100)     //ERROR IS HERE
{
    cout << "Please enter a value between 0 and 100: ";
    cin >> scores[numGrades];
}

That's what you wrote. However a number cannot be smaller than 0 and larger than 100 so this is how you should fix it.
if (scores < 0 || scores > 100)
{
    cout << "Please enter a value between 0 and 100: ";
    cin >> scores[numGrades];
}


text:
Q: Issue with parsing publication data from PubMed with Entrez I am trying to use Entrez to import publication data into a database. The search part works fine, but when I try to parse:
from Bio import Entrez

def create_publication(pmid):

    handle = Entrez.efetch("pubmed", id=pmid, retmode="xml")
    records = Entrez.parse(handle)
    item_data = records.next()
    handle.close()

... I get the following error:

File
  "/venv/lib/python2.7/site-packages/Bio/Entrez/Parser.py",
  line 296, in parse
      raise ValueError("The XML file does not represent a list. Please use Entrez.read instead of Entrez.parse") ValueError: The XML file
  does not represent a list. Please use Entrez.read instead of
  Entrez.parse

This code used to work until a few days ago. Any ideas what might be going wrong here?
Also, looking at the source code (http://biopython.org/DIST/docs/api/Bio.Entrez-pysrc.html) and trying to follow the listed example, gives the same error:
from Bio import Entrez
Entrez.email = "Your.Name.Here@example.org"
handle = Entrez.efetch("pubmed", id="19304878,14630660", retmode="xml")
records = Entrez.parse(handle)
for record in records:
    print(record['MedlineCitation']['Article']['ArticleTitle'])
handle.close()

A: The issue, as documented in other comments and the GitHub Issue, is caused by a deliberate change made by NCBI Entrez Utilities Developers. As documented in this issue by Jhird , you can change your code to the following:
from Bio import Entrez
Entrez.email = "Your.Name.Here@example.org"
handle = Entrez.efetch("pubmed", id="19304878,14630660", retmode="xml")

records = Entrez.read(handle)      # Difference here
records = records['PubmedArticle'] # New line here

for record in records:
    print(record['MedlineCitation']['Article']['ArticleTitle'])
handle.close()


text:
Q: Can't install Xcode Command Line Tools on Mountain Lion I try to install the most recent (july 25) version of Command Line Tools (xcode44cltools_10_76938107a.dm), downloaded from https://developer.apple.com/downloads/, but are stopped with the error message
"This package can only be installed on OS X 10.7
Install a version of the Command Line Tools that
supports OS X 10.8."
But I can't find any better version; if such exist why isn't it on the Developer site?

A: You can install the command line tools within XCode.
Open XCode and navigate to the preferences.

From here you have to go to the Downloads-Section. Here you can see
  the ability to install the command line tools:

EDIT: I can see the right command line tools on the download-page from Apple:

A: The best way to find developer tools for your version of XCode is to click on the XCode menu, scroll down to "Open Developer Tool" then select "More Developer Tools..." which will take you to a website displaying the latest developer tools.
See my screenshot:


text:
Q: VM - Append free space to Root partition do you please idea how can I append new free space for virtual Debian running on VM VirtualBox?
I have made my virtual HDD bigger but free space is not alocated next to boot partition where I have root folder. I cannot use any live partition disk as this is just virtual OS, right? Do you have any clues how to add some space to pripary dev/sda1 partition?
screen
Thakns!

A: DONE -

*

*I downloaded live cd of Gpart and mounted in VM VirtualBox manager

*live version started (not debian) - I have deleted SWAP between Root SDA and free space, extended space on disk and created new SWAP

Sorry for spam


text:
Q: How I obtain values from another row to place in the current row in a pandas dataframe? Consider the following dataframe:
df_test = pd.DataFrame(
    [
    ['TAVG',51,'2020-01-01'],
    ['TMAX',59,'2020-01-01'],
    ['TMIN',46,'2020-01-01'],
    ['TAVG',53,'2020-01-02'],
    ['TMAX',61,'2020-01-02'],
    ['TMIN',45,'2020-01-02'],
    ['TAVG',50,'2020-01-03'],
    ['TMAX',60,'2020-01-03'],
    ['TMIN',40,'2020-01-03']
    ],
    columns = ['datatype', 'value', 'date']
)

I would like to combine the values for each date in a single row like this:

I've made various attempts using loc but I failed.

A: Try pivot
out = df_test.pivot('date','datatype','value').reset_index()
Out[88]:
datatype    TAVG  TMAX  TMIN
date
2020-01-01    51    59    46
2020-01-02    53    61    45
2020-01-03    50    60    40

A: df_test.set_index(['date','datatype'])['value'].unstack().reset_index()

d
atatype        date  TAVG  TMAX  TMIN
0         2020-01-01    51    59    46
1         2020-01-02    53    61    45
2         2020-01-03    50    60    40


text:
Q: How do I compare 2 lists with different set of elements , in an adapter onBind()? I am currently using an adapter  to return the set of items in 2 lists, such that :
private List<ListResponse.Repo> mListResponseList;
private List<MyEvents.Event> mMyEventsList;

Now, MyListResponse.Repo and MyEvents.Event , get me json objects with complete list of events for the first one (ListResponse.Repo) and some select few events for the second one ( MyEvents.Event)
In my get item count for the adapter I return ListResponse.Repo size as follows:
 @Override
    public int getItemCount() {
        if (mListResponseList != null && mListResponseList.size() > 0 ) {
            return mListResponseList.size();
        } else {
            return 1;
        }
    }

Please note : mListResponseList.size() is list of all events, so it usually returns all the events in the list ( say 6) , and if I were to use mMyEventsList.size ,it is always less than or equal to the list of items in mListResponseList as its practically derived from there (as these are specific events from the main list that i am retrieving in another endpoint).
Now , I have an issue where I am trying to display only the events where the event title in mMyEventsList matches the event title returned from mListResponseList. The only issue is since the size of list returned by all events is larger than the size of the list returned by mMyEventsList, I usually get index out of bounds exception when I try to compare them. I tried using the following code:
if (position < mMyEventsList.size()){

if(mMyEventsList.get(position).getEventTitle().equals(repo.getTitle())
     {
                    cardView.setVisibility(View.VISIBLE);

      }
}

but it does not return the correct result, displays only one card (instead of 3 or so ,based on the matching titles)
The following hardcoded string works for the given test scenario( where first list has 8 items and second has 4,), but its still hardcoded(if the second list is to return more than 4 ,this wont work), I would like to introduce something dynamic(also by making sure the app doesnt crash if i compare the lists with different sizes with index out of bounds exception) ,for as the list items change, the content will change aswell.
Any idea how to make the following comparison dynamic, so it returns the expected result, where it compares items in list 1 with items in list 2 and  sets the cardview for that particular element as visible if the titles match, otherwise it sets the visibility to gone, if the titles do not match. here's the hardcoded code I am using as of now, just would like to make it more dynamic by introducing some kind of loop which would work for my case(didn't have any luck with it so far ).
    public void onBind(int position) {
                super.onBind(position);
 if(mMyEventsList.get(0).getEventTitle().equals(repo.getTitle()) && mMyEventsList.get(0).getIsAttending() ||
                        mMyEventsList.get(1).getEventTitle().equals(repo.getTitle()) && mMyEventsList.get(1).getIsAttending() ||
                        mMyEventsList.get(2).getEventTitle().equals(repo.getTitle()) && mMyEventsList.get(2).getIsAttending() ||
                        mMyEventsList.get(3).getEventTitle().equals(repo.getTitle()) && mMyEventsList.get(3).getIsAttending()){
                    cardView.setVisibility(View.VISIBLE);
                } else {
                    cardView.setVisibility(View.GONE);
                }

}

Thanks in advance!
 (p.s: sorry to make it so long, just wanted to explain what I basically need, which is a dynamic comparison loop, that outputs the result of items with matching titles (even if the lists are of different size based on different number of elements)

A: You compare item 1 from list 1 with item 1 from list 2. Item 2 with item 2 and so on, if the second list is a Derivate from the first one and it contains for example item 1,4 and 6. Item 1 of list 2 is item 1 of list 1, but item 2 is item 4 and they won't ever match again. You Need to compare each item of list 2 with every item of list 1. For example
public void onBind(int position) {
            super.onBind(position);
cardView.setVisibility(View.GONE);
for (int i = 0;i<mListResponseList;i++){
if (//Item from List 2 at Position 'Position' equals item on Position i of originallist){
cardView.setVisibility(View.VISIBLE);
break;
}

You basically iterate through your whole List 1 and check if any item equals your item in list 2 and if they are equal you set the cardview visible, otherwise it stays Gone as defined onBind.
Modification:
cardView.setVisibility(View.GONE);
            for (int i = 0;i<mMyEventsList.size();i++){
                if (mMyEventsList.get(i).getEventTitle().equals(repo.getTitle()) ) {
                    cardView.setVisibility(View.VISIBLE);
                    break;
                }
            }

A: code ArrayList results = new ArrayList<>(); // Loop arrayList2 items for (Person person2 : arrayList2) { // Loop arrayList1 items boolean found = false; for (Person person1 : arrayList1) { if (person2.id == person1.id) { found = true; } } if (!found) { results.add(person2.id); } }

A: @Angela Heely You should just update your adapted with the new list


text:
Q: How to add queries declaration in the manifest for using camera private fun clickPhoto(){
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            takePictureIntent.resolveActivity(requireActivity().packageManager)?.also {
                val photoFile: File? = try {
                    createFile(requireActivity(), Environment.DIRECTORY_PICTURES, "jpg")
                } catch (ex: IOException) {
                    Toast.makeText(requireActivity(), getString(R.string.create_file_Error, ex.message),
                        Toast.LENGTH_SHORT).show()
                    null
                }
                photoFile?.also {
                    selectedPhotoPath = it.absolutePath
                    val photoURI: Uri = FileProvider.getUriForFile(
                        requireActivity(),
                        BuildConfig.APPLICATION_ID + ".fileprovider",
                        it
                    )
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                    startActivityForResult(takePictureIntent, CAMERA_PHOTO_REQUEST)
                }
            }
        }
    }

This is my click photo function where resolveActivity() gives a warning Consider adding a <queries> declaration to your manifest when calling this method; see https://g.co/dev/packagevisibility for details.I know that since API 30 we need queries to access the information of other installed apps.
I also know that this can be resolved by not using resolveActivity() but i want to learn how to add queries to manifest.
This is my manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.akaalistudios.employeemanagement">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.EmployeeManagement">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    </application>

</manifest>

A: In order to access a broader list of installed apps, an app can specify information about apps they need to query and interact with directly. This can be done by adding a  element in the Android manifest.
For most common scenarios, including any implicit intents started with startActivity(), you won't have to change anything! For other scenarios, like opening a specific third party application directly from your UI, developers will have to explicitly list the application package names or intent filter signatures like this:
<manifest package="com.example.game">
  <queries>
    <!-- Specific apps you interact with, eg: -->
    <package android:name="com.example.store" />
    <package android:name="com.example.service" />
    <!--
         Specific intents you query for,
         eg: for a custom share UI
    -->
    <intent>
      <action android:name="android.intent.action.SEND" />
      <data android:mimeType="image/jpeg" />
    </intent>
  </queries>
  ...
</manifest>

For more details you must have to follow these links :
https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9
or
Android 11 (R) return empty list when querying intent for ACTION_IMAGE_CAPTURE
I hope it might help.


text:
Q: Large size image breaks template layout If I upload a large size image inn my wordpress, the image breaks my template width. I have seen some templates which scale the large image's width to the maximum width of the post div.
What CSS or code I need to change for that purpose? Thanks.

A: In your functions.php file, you need to define $content_width, which will cause WordPress to scale large-size images, and also embedded videos, accordingly.
e.g. if the width of your content area is 600px:
if ( ! isset( $content_width ) ) {
    $content_width = 600;
}

You will probably also want to add accompanying CSS, e.g.:
#content img {
    width: auto;
    max-width: 600px;
    height: auto;
}

That way, when the image is scaled, it will maintain its proportion;  rather than merely having its width reduced, the height will also be scaled proportionately.

A: You don't need any CSS, just go to Settings > Media and adjust the Large image size width to that of your post container. You may need to Regenerate Thumbnails after doing that.


text:
Q: Dynamically passing correct number of parameters to class constructor I do this here:
public function fetch($className)
{
   $rows = array();
   while($r = $this->result->fetch_object() {
      $rows[] = new $className($r);
   }
   return $rows;
}

Constructor
class User
{
   public $dbh;
   public $row;
   public function __construct($dbh, $row = null)
   {
      $this->dbh = $dbh;
      $this->row = $row;
   }
   public function getAll()
   {
      return $this->dbh->query('SELECT * FROM users')->fetchAll();
   }
   public function getFirstName()
   {
      return $this->row->first_name;
   }
}

This is all good and well if my class constructor only has ONE parameter.
How do I make this dynamic so that I can have other parameters in my constructor. Hope this makes sense.
Any help would be awesome :-)

A: It depends.
Well, it really does depend on what is your general code style. For example. I don't like using new near my SQL code. It seems to much of SRP violation.
What I tend to do looks kinda like this:
public function applyValues($instance, array $parameters)
{
    foreach ((array) $parameters as $key => $value) {
        $method = 'set' . str_replace('_', '', $key);
        if (method_exists($instance, $method)) {
            $instance->{$method}($value);
        }
    }
}

I personally think that it is a hack, but it works well with how rest of my code gets designed.

And if you are using PHP 5.6+, you can use variadics
That would look something like:
public function fetch($className)
{
   $rows = array();
   while($parameters = $this->result->fetch_object() {
      $rows[] = new $className(...$parameters);
   }
   return $rows;
}

But this approach will be really fragile and will require strict order in the $parameters array.

There is also third option: design your code in such a way, that you have something like populate() method in all of your domain entities. But that seems like a bad idea for  the same reason why entities should not contain their own factories.


text:
Q: Multiple Azure Antivirus installed VMs needs to be subscribed to Azure message queue using Peeklock model We have installed sophos in multiple Azure Linux VMs. Installed pip , azure service bus sdk and using the below code we are able to consume message when it arrives in queue.
from azure.servicebus import QueueClient, Message # Create the QueueClient
queue_client = QueueClient.from_connection_string("<connectionstring>", "taskqueue") # Receive the message from the queue with queue_client.get_receiver() as queue_receiver:
messages = queue_receiver.fetch_next(timeout=3)
for message in messages:
    print(message)
    message.complete()

How do we exactly subscribe multiple AV servers to the message queue using peek lock model. Peek lock ensures if first AV Linux VM picks up the message and initiates the scan, the message should stay locked with that particular VM only, no other VM should pick this up.

*

*Can we do event based polling using SDK. Is it advisable to do continuous polling.

*How do we set up the peek lock model- When a message arrives , any one AV scan VM should consume the message and lock it so that any other VM does not pick up.

*Although there are multiple AV scan VMs , only one should pick up the message. Should we use Service bus queue/topic.
End goal is: AV VMs should be subscribed to the Service bus

A: 1 - While Storage Queues don't yet support events, Service Bus supports Event Grid but currently just in the Premium Tier.
Also, in the case of Service Bus, the SDK uses AMQP by default which uses an full-duplex open connection.
2&3 -  For queue storage, when one receiver fetches a message, that message becomes invisible to other receivers until a specific timeout. Read more about concurrency in the queue service in the docs.
For service bus, you can use the peek-lock mode to achieve the same. In this case, you can also renew the lock for delayed processes.

A: Its working now:
How do we exactly subscribe multiple AV servers to the message queue using peek lock model. Peek lock ensures if first AV Linux VM picks up the message and initiates the scan, the message should stay locked with that particular VM only, no other VM should pick this up.
1.Can we do event based polling using SDK. Is it advisable to do continuous polling.-Yes we can do event based polling. We configured long polling.
2.How do we set up the peek lock model- When a message arrives , any one AV scan VM should consume the message and lock it so that any other VM does not pick up.-Its done using Azure service bus sdk. python code attached below.
Although there are multiple AV scan VMs , only one should pick up the message. Should we use Service bus queue/topic. End goal is: AV VMs should be subscribed to the Service bus- While multiple call to the services are made, the scripts in multiple VMs continues polling. Available VM takes up and completes the scanning.


text:
Q: Enabling IIS Failed Request Tracing at the root (not a particular site) I have some URL Rewrite rules at the root of IIS (i.e. not in a specific site).  They are at the root because they Route to Server Farm, and apparently that has to be done at the root (I don't see the option for "Route to a Server Farm" when I create a URL Rewrite rule on a site.)
I would like to enable Failed Request Tracing so I can see what's going on with this particular rule, but I don't see a way to enable it at the root, only on a site-by site basis.  How do I enable Failed Request Tracing at the root?

A: Add the Failed Request Tracing rule to the web site for which its bindings match the URL being used. The explanation for this is that ARR is still running on a worker process. The only purpose of global URL Rewrite rules is to make them global to all web sites.


text:
Q: Validating Form How to validate form fields on submit button using jquery?

A: jQuery.validate plugin is the best solution I've found.
All you have to do is give the inputs the class "required" and then call .validate() on the form in your document.ready call e.g.
$(function() {
    $('#idofyourform').validate();
});

You can also do email and other types of validation using the same method. The plugin is also extensible for your own rules.
Remember you will also need to validate any data server side.
Edit: Response to comment
To validate only when the form is submitted add the following option:
$("#idofyourform").validate({
   onsubmit: true,
   onkeyup: false,
   onfocusout: false,
   onclick: false
})

Have a read of the options for more detail.


text:
Q: print break line after n number of iterations The goal is to "break line" after each split.
I have two arrays:
$split = [4, 2, 4];
$courses = ['HTML', 'JS', 'CSS', 'VueJS', 'ReactJs', 'PHP', 'Ruby', 'Python', 'Java', 'C#'];

As you can see I have the first array called split, and the second array called courses, I want to add
   after each split
I want to loop over $courses and after the 4 items I print
. Also after 2 items I print another

Note: I can have more values in my $split array, that's why I don't want to use
foreach($courses as $key => $value){
   echo $value;
   if ($key == 4 OR $key == 2){
      echo '
';
   }
}

My code is not working fine because I can't use a lot of OR with if statements, because I can have a lot of split in my $split array
Is there any clean and best way to loop over $courses and print
 after 4 loop and after 2 and after 4 and so on, it depends on how many split I have in my $split

A: This will get the job done, bear in mind that arrays start at 0, not 1. so it would break on the 3rd and 5th item not 2nd and 4th.
More on in_array()
<?php

$split = [4, 2, 4];
$courses = ['HTML', 'JS', 'CSS', 'VueJS', 'ReactJs', 'PHP', 'Ruby', 'Python', 'Java', 'C#'];
foreach($courses as $key => $value){
    echo $value;
    if (in_array($key, $split)) {
        echo '
';
    }
 }
 ?>

A: You need to track next items order after found it.
<?php

$split = [4, 2, 3];
$courses = ['HTML', 'JS', 'CSS', 'VueJS', 'ReactJs', 'PHP', 'Ruby', 'Python', 'Java', 'C#'];

$split_position = $reIndexValue = 0;
$elements = [];

foreach($courses as $index => $name) {
    $reIndexValue++;

    if(is_int($split_position) && $reIndexValue == $split[$split_position]) {

        $name = $name.'
';
        $split_position = isset($split[$split_position + 1])? ++ $split_position : false;
        $reIndexValue = 0;

    }

    $elements[] = $name;
}

echo implode (' ',$elements);

A: The following code will first echo a line break after 4 iterations, then it will echo a line break after 2 more iterations, and then it will echo another line break after 4 more iterations. (The code will continue for any specified sequence in the $split array)
<?php

$split = [4, 2, 4];
$courses = ['HTML', 'JS', 'CSS', 'VueJS', 'ReactJs', 'PHP', 'Ruby', 'Python', 'Java', 'C#', 'Pascal', "Fortran"];

$count = 0; //Counting the times we looped using a seperate variable
foreach($courses as $key => $value){
    echo $value." ";
    $count += 1; //Increase count
    if ($split[0]==$count) { //If the $count is similar to the first variable in $split array,
        echo '
';
        $count=0; //Reset $count back to 0
        array_shift($split); //Remove the already performed first variable from array
    }

    //without the following block, code will give you an "Undefined offset" notice
    if (count($split)==0){
        array_push($split, -1);//Add a dummy variable (-1) that will never be tested.
    }
 }

?>

I added 2 other variables "Pascal" and "Fortran" into the $courses array to test the behavior


text:
Q: Access modules and module variables at runtime from python via String In my Python programm I want to dynamically load modules and access variables of the module by converting a string parameter into a variable name.
Use Case
I have different Fonts on SD Card which are python files, and a display function which loads the font when needed to display the caracters.
Examples for my font file:
# arial14.py
# ch_(ASCII) = (widht), (height), [bitmask]
ch_33 = 3, 16, [0,0,0,0,0,0,0,0,0,1,1,1,1,1 ........
ch_34 = 5, 16, [0,0,0,0,0,0,0,0,0,0,0,0,0,0 ........
....

# arial20.py
ch_33 = 4, 22, [0,0,0,0,0,0,0,0,0,1,1,1,1,1 ........
ch_34 = 8, 22, [0,0,0,0,0,0,0,0,0,0,0,0,0,0 ........

Further, there is a Writer class which renders the fonts to the display:
class Writer(object):
    def __init__(self):
       try:
           global arial14
           import arial14
           self.current_module = "arial14"
           self.imported_fonts = []
           self.imported_fonds.append(self.current_module)
      except ImportError:
           print("Error loading Font")
   def setfont(self, fontname, fontsize):
           modname = fontname+str(fontsize)
           if modname not in self.importedfonts:
               try:
                    exec("global" + modname)
                    exec("import" + modname)      #import the font (works)
                    self.importedfonts.append(modname)
               except ImportError:
                    print("Error loading Font")
                    return
           else:
               print(modname+" was already imported")
           self.current_module = modname
           print("Font is set now to: "+ self.current_module

## HERE COMES THE NON WORKING PART:
    def putc_ascii(self, ch, xpos, ypos):

           execline = "width, height, bitmap = "+ self.cur_mod+".ch_"+str(ch)
           print(execline)
           #this example.: width, height,bitmap = arial14.ch_55

           width, height,bitmap = arial14.ch_32
           print(width, height, bitmap) # values of arial14.ch_32 -> correct

           exec (execline)
           print(width, height, bitmap) # values of arial14.ch_32
                                        # BUT VALUES OF arial14.ch_55 EXPECTED

Has anybody an idea how can I accomplish to save the correct values of the queried character of the correct font into the variables width, height and bitmap?
I want to load the Fonts dynamically only if needed, and offer the possibility to add new fonts by putting new .py font files into the folder.
Thanks in advance.

A: EDIT
The OP is actually using micropython, which doesn't implement importlib...
Possible (untested) solution (yes, using exec - if someone knows a better solution please chime in).
def import_module(name):
    name = name.strip().split(
    statement = "import {}"
    exec(statement, globals())
    return sys.modules[name]

class Writer(object):
    def __init__(self):
       # reference to the current module
       # WARNING : this is the `module` object itself,
       # not it's name
       self.current_module = None

       # {name:module} mapping
       # not sure it's still useful since we
       # now have a reference to the module itself
       # and `sys.modules` already caches imported
       # modules...
       self.imported_fonts = {}

       # set default font
       self.setfont("arial", "14")

    def setfont(self, fontname, fontsize):
        self.current_module = self._loadfont(fontname, fontsize)

    def _loadfont(self, fontname, fontsize):
        name = fontname+str(fontsize)
        if name not in self.imported_fonts:
            self.imported_fonts[name] = load_module(name)
        return self.imported_font[name]

    def putc_ascii(self, ch, xpos, ypos):
        width, height, bitmap = self._get_char(ch)
        print("{}.{}: {} - {} - {}".format(
            self.current_module, ch, width, height, bitmap
            )

    def _get_char(self, chrnum):
        # assume the font modules have been rewritten
        # using dicts (cf lower) and all chars are defined
        # in all fonts modules
        return self.current_module[ch]

        # alternate implementation using the current
        # fonts definitions
        # return getattr(self.current_module, "ch_{}".format(ch))

TL:DR :
You want importlib.import_module and eventually getattr(). But you should still read the longer answer, really, it will save you a lot of time and frustration.
Longer answer:
First point about your "font" files format - this:
ch_33 = 3, 16, [0,0,0,0,0,0,0,0,0,1,1,1,1,1 ........
ch_34 = 5, 16, [0,0,0,0,0,0,0,0,0,0,0,0,0,0 ........

is a huge design smell. You want lists or dicts instead (or possibly an ordered dict), ie:
characters = {
    33: (3, 16,  [0,0,0,0,0,0,0,0,0,1,1,1,1,1...]),
    34: (5, 16,  [0,0,0,0,0,0,0,0,0,0,0,0,0,0...]),
    # etc
    }

As a general rule, when you start having some "var1", "var2", "var3" etc pattern then you know you want some kind of container instead.
Second  point - your error handling, ie:
 try:
       global arial14
       import arial14
       self.current_module = "arial14"
       self.imported_fonts = []
       self.imported_fonds.append(self.current_module)
  except ImportError:
       print("Error loading Font")

is worse than useless, it's actually harmful. First because it doesn't stop program execution in the case of an unrecoverable error (you dont want your program to continue when something totally wrong happened), then because it replaces all the incredibly useful informations you'd either get from the error message and traceback with a plain useless "An error happened" message.
Only catch exceptions that you can properly manage one way or another, let everything else propagate (maybe someone upper in the call stack - usually in the UI part - might be able to handle it properly).
Third point: do not use globals. I mean: do not mutate nor rebind globals (read-only (pseudo-constant) globals are ok of course). Which means you really never have to use the "global" keyword in your code.
When you need to share state between a group a functions, use a class, store the state as attributes and make your functions methods. That's what objects are for (well, not only but that's part of there raison d'être).
EDIT : this part is still true for complete Python implementation and probably still partly true for micropython, except for parts that are not implemented in micropython (like importlib - I don't know what else is missing)
And finally: never ever use exec nor eval. You don't need them, whatever you're trying to do there's a better, safer specific solution.
In your case, to import a module by it's name, you have importlib.import_module, and to get an object's attribute by it's name you have getattr() (but if you use a proper container, cf first point, you don't even need getattr here).


text:
Q: Javascript: event duplication I can not figure out what is wrong with my code.
I have a couple of global variables which I change every time some certain button is pressed,there is also a couple of custom functions that perform ajax calls that returns a chunk of html code with a pagination below, that works like this:
    $('#foot #pagination a.page').live('click', function(){
        window.mode = 'partial';
        window.key = $('input#search').val();
        window.page = $(this).parent().find('input').val();
        setTimeout('getData();', 0);
    });

sometimes when moving to another page event doubles and I got the doubled html.
when caling getData(); from a browser console - everything works fine, like it has to work.
What can cause this?

A: You should execute this function only once after document.ready.
Or do something like this:
$('#foot').off('click', '#pagination a.page', navigation) // remove event
          .on('click', '#pagination a.page', navigation); // add event

function navigation(e) {
   window.mode = 'partial';
   window.key = $('input#search').val();
   window.page = $(e.currentTarget).parent().find('input').val();
   setTimeout('getData();', 0);
});

A: The problem was that jQuery .live() pushes some data to jQuery stack on document ready, but after ajax response comes from the server and document ready event is called again - in this case .live() pushes the same data again to a jQuery stack, which then causes multiple event body calls.
I used .die() before .live() and everything now works fine.


text:
Q: How to store a Dictionary in a MySQL database? Can some one demonstrate how I can save the values of a dictionary into a MySQL database?
public void Update()
{
           Dictionary<string,int> t = new Dictionary<string,int>();
for(int i = 0; i < t.Count;i++)
{
//What comes Here?
}
}

A: First fix your iteration loop, second it is up to you to decide, eg:
MySqlConnection conDataBase = new MySqlConnection(constring);
conDataBase.Open();
        foreach (KeyValuePair<string, string> entry in)
        {
            string constring = "..........";
            string Query = "insert into Tablename  values(@par1,@par2)";
            MySqlCommand cmd = new MySqlCommand(Query, conDataBase);
            cmd.Parameters.AddWithValue( "@par1",entry.Key)
            cmd.Parameters.AddWithValue("@par2",entry.Value)

           //Execute command
           cmd.ExecuteNonQuery();
        }


text:
Q: Group Dataframe using values of a column to group rows So I have a Dataset of Patients that would look like this (I'm using toy values here for simplicity).

I wanted to sort the data frame by the discharge values and then group it according to Patients. Everything else in my preprocessing happens perfectly, and my it groups the way it is supposed to (gives me clusters of each patient, sorted (descending) by the value of P). However, my code returns a groupedby object and I need a data frame to do analysis on. How can I convert it? I've tried a few online samples, but none of them work. Is there a better way?
The End Result would be this. The ordering of the clusters doesn't matter (PT 1 can be after 7 etc etc.)

def preProcessing(df):
    """
    The preprocessing done on the Dataset for efficient use.
    @returns- The new and improved dataset
    We're using the following steps-
    Sort Data by P
    Group by PID

    """
    dateTimeCols=['P']
    df= df.sort_values(by=dateTimeCols, ascending=False)
    df= df.groupby('PT_ID')
    print(df)
    # for name,group in df:
        # print (name)
        # print (group)
    return df

A:
I wanted to sort the data frame by the discharge values and then group it according to Patients.

It doesn't sound like grouping will solve your problem. Usually grouping is used to get an average of each group, or reduce the amount of data. I think what you should do is sorting.
You could use sort_values() to accomplish both steps. This line of code both puts each patient's records together, and sorts that group of records by discharge.
df = df.sort_values(by=['PT_ID', 'P'], ascending=[True, False])

Here is the full code, including the data I tested it on:
import pandas as pd
df = pd.DataFrame({
    'ENC_ID': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6},
    'PT_ID': {0: 1, 1: 1, 2: 7, 3: 2, 4: 2, 5: 1},
    'P': {0: 2, 1: 3, 2: 1, 3: 2, 4: 4, 5: 1}
})
df = df.sort_values(by=['PT_ID', 'P'], ascending=[True, False])

Some notes:

*

*When given multiple keys to sort by, sort_values() will sort by the first one, then if there are any ties, it will sort by the second one, and so on.

*I'm sorting PT_ID in ascending order, but P in descending order. That's the purpose of ascending=[True, False].


text:
Q: SQL Output if row exists, insert and output if it does not exist I basically want to insert something and use the OUTPUT function to get some values out of the inserted line. That's easy.
But I also want my query to get these values even if there has nothing been inserted because the primary already exists.
DECLARE @existingId bigint;
IF EXISTS(SELECT @existingId = Id FROM MyTable WHERE Name = @Name)
    OUTPUT @existingId;
    RETURN;
INSERT INTO MyTable (Name) OUTPUT INSERTED.Id VALUES (@Name);

This just always gives me Incorrect syntax near '='.
Any ideas how to achieve this behavior?

A: I believe you are missing  A opening and closing parenthesis, try:
DECLARE @existingId bigint;
IF EXISTS(SELECT @existingId =( Id FROM MyTable WHERE Name = @Name))
    OUTPUT @existingId;
    RETURN;
INSERT INTO MyTable (Name) OUTPUT INSERTED.Id VALUES (@Name);

A: output takes a table, not a value.  So the code you are striving to write should look more like this:
DECLARE @out table (existingid bigint);

INSERT INTO @out(existingid)
    SELECT Id FROM MyTable WHERE Name = @Name;

IF EXISTS (SELECT * FROM @out)
    RETURN;

INSERT INTO MyTable (Name)
    OUTPUT INSERTED.Id INTO @out
    VALUES (@Name);

This code, however, has race conditions.  Because someone could insert Name between the check for the existence and the insert.  To really fix this, you should use try/catch and have a unique index on name. Here is an example of the code:
DECLARE @out table (existingid bigint);

BEGIN TRY
    INSERT INTO MyTable (Name)
        OUTPUT INSERTED.Id INTO @out
        VALUES (@Name);

    RETURN
END TRY
BEGIN CATCH -- assume there is a duplicate although there could be other problems
    INSERT INTO @out(existingid)
        SELECT Id FROM MyTable WHERE Name = @Name;
END CATCH;

The following code creates the unique index:
create unique index idx_mytable_name on mytable(name);


text:
Q: Getting a range of objects after an object and hide/show them accordingly I have a list group that has seperated groups, meaning there are rows in the list group which seperate/group them by assigning title rows in the list by class. I'm trying to hide only the list inside inside the group, I don't want to hide all the list objects like this code does. Does anyone know how to only hide the groups individually so when you click the title of the group it only hides the list inside that group (Without modifying any tags in the HTML code). Specifically when referring to the code example below, If someone clicks on 'Title 2', then only the
 which are after that and before 'Title 3' disappear/reappear.  Please see the code below:
HTML:

Title 1

Title 2

Title 3

jQuery / Js:
$("ul li.title").click(function(){
  $("ul li").not(".title").toggle();
});

You can find the fiddle here: http://jsfiddle.net/QNNgE/

A: I think you're after something like this:-
$(this).nextUntil('li.title').toggle();
So when clicking a title, toggle the visibility of all elements after the clicked title, up until the next one.
Here's a fiddle

A: ok try this approach:
HTML:

Title 1

Title 2

Title 3

jquery:
$("ul li.title").click(function(){
    $(this).nextAll().toggle();
});

hope this helps.
jsFiddle

A: This is aweful, but works as requested without modifying the HTML:
EDIT: Ah, I see I've misunderstood the question.
In any case this does a similar thing (something like an accordian) without modifying the HTML.
$("ul li.title").click(function(){
    var title = $(this);
    var inGroup = false;
    title.parent().children().each(function(){
        var li = $(this);
        if (li.hasClass('title')) {
            inGroup = li.get(0) == title.get(0);
        } else {
            if (inGroup) {
                li.show();
            } else {
                li.hide();
            }
        }
    });
});
$("ul li.title").eq(0).click();


text:
Q: Manga/webtoon where a girl's eyes changes color with her emotions It's the story of these 3 royal princes that have the unique ability to change the color of their eyes due to their emotions.
In the beginning of the story they are a looking for a young girl who is supposed to be their sister. They found her working as a young child slave with a young boy who became her friend; both of them are named after days of the week, one of them is named Wednesday I think. They bring her back home and the boy, he decides he wants to become a knight to protect her. The brothers are very protective of her.
She maybe had blonde hair, but I'm not sure.
Also one of the princes work at the magical tower, a tower that pops out of nowhere.

A: My Three Tyrant Brothers

All members of the Ascania imperial family are cursed to die at the hands of a loved one, a curse only broken by the birth of a girl into the bloodline. So when a young slave girl with the telltale, color-changing Ascania eyes is discovered, she's declared Princess Chloe, the little sister of the three princes. She's excited to finally have a family, but her new brothers seem a bit strange… They've always had to be cold and unfeeling for their own protection, but will Chloe's arrival plant the seed of change in their hearts?

Looking at the reviews, indeed, Chloe was named Wednesday as a slave.
Found with search terms of manga "three princes" sister slave wednesday


text:
Q: undefined local variable or method `clientid' for #I am new to factory_girl gem. My Ruby gem have static clientid, session & host.
My Factory code is like
FactoryGirl.define  do
 factory :session do |f|
        f.clientid "clientid string"
        f.secret " secret string"
        f.host "host string"
    end
end

My Spec code is like
describe '#new' do
    it 'works' do
      result = FactoryGirl.build(clientid, secret, host)
      expect(result).not_to be_nil
    end
end

My spec_helper file is
require 'rspec'
require 'factory_girl'
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'mydemogem'

I am trying to create one factory for that. But it gives me following error:
undefined local variable or method `clientid' for #<RSpec::ExampleGroups::

A: Here is some explanation:
You have defined
factory :session

File, containing this factory usually called sessions_factory.rb, so it is being used to produce sessions. You can build one with:
FactoryGirl.build(:session)

which will call:
Session.new(clientid: 'clientid string', secret: 'secret string', host: 'host string')

You can also modify some of the attributes like this:
FactoryGirl.build(:session, clientid: 'other id string')

now, the object returned will be equal to:
Session.new(clientid: 'other id string', secret: 'secret string', host: 'host string')

This is how you work with objects factory.

A: Your spec has
result = FactoryGirl.build(clientid, secret, host)

but you aren't defining clientid, secret, and host. You can't access variables that aren't defined


text:
Q: Fazer Upload e visulizar PDF's Django admin Queria tirar uma dúvida, estou tentando fazer um upload de um arquivo PDF, no django, e eu queria saber se te como eu visualizar este pdf, tenho o seguinte código:
models.py
class Edital(models.Model):
    # ...

class DataFile(models.Model):
    Arquivo = models.FileField()

    def chage_view(self):
        return self.Arquivo

class Meta:
    verbose_name_plural = 'Editais'

Numero = models.CharField(primary_key=True, max_length= 15)
pro_reitoria = models.ForeignKey('Pro_reitoria', default="")
Arquivo = models.FileField(upload_to= "", default="")

def __str__(self):
    return self.Numero

settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

no meu admin fica assim o arquivo

Quando eu clico no arquivo carregado aparece Page not Found(404)

Como eu faço pra eu conseguir visualizar o PDF??
Agradeço quem puder me ajudar!

A: Creio que o único detalhe que esteja faltando, seja você habilitar o Django a servir os arquivos estáticos e de media, coisa que ele não faz por padrão. Para fazer isso, só fazer isso no seu urls.py do projeto:
from django.conf.urls.static import static

# depois das suas definições de urls

if settings.DEBUG:
urlpatterns += static(
    settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(
    settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


text:
Q: How do I extend IdentityUser class in DbFirst approach? I have a table named User in my database. I also have a .net core project where authentication is built-in. I want to connect to my database and after scaffolding reveals my User class, I want it to inherit from IdentityUser.
After scaffolding went well, I tried to inherit from IdentityUser.
public partial class User :IdentityUser<int>
{
    public int Id { get; set; }
    public string Country { get; set; }
    public string PersonalId { get; set; }
    public string MobilePhone { get; set; }
    public string Email { get; set; }
    public DateTime BirthDate { get; set; }
    public string Password { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public byte[] Idimage { get; set; }
    public bool? EmailConfirmed { get; set; }
    public bool? Smsconfirmed { get; set; }
}

I can not see Identity Fields like PasswordHash, PhoneNumberConfirmed and so on, in my database. Specifically, in User table.


text:
Q: group by date, confirm, pending im trying to build chart for users for each day with total confirmed user and total pending users for that each day and i need data like following:
date         |   confirmed    |  pending
2010-01-05   |   5            |  2
2010-01-06   |   10           |  3

following is the structure of the table:
user_id
username
confirm     enum(0,1)
date        date

A: SELECT Date, SUM(CASE Confirm WHEN 1 THEN 1 ELSE 0 END) Confirmed,
  SUM(CASE Confirm WHEN 0 THEN 1 ELSE 0 END) Pending,
 FROM Table
GROUP BY Date


text:
Q: Redirect URLs to other domain with .htaccess So I am getting rid of my blog on my main site and want to direct everybody to my other domain where I will continue. I have already cross posted my most popular articles, but I want people to be directed there automatically.
How can I use .htaccess to redirect specific URLs to the new URLs?
IE
http://domain.com/blog/2015/jan/responsive-doesn-t-mean-mobile-first
Thanks in advance!

A: You can use RedirectMatch to redirect your rule to a new location .
Try in htaccess :
RedirectMatch ^/blog/2015/jan/responsive-doesn-t-mean-mobile-first$ http://newdomain.com


text:
Q: JimFS: how to get File from Path I started using google jimfs and I can't understand how I can get file from path. In source code I see that Path.toFile throws UnsupportedOperationException. But how then can I use it without files? For example if my application need to know if some path is folder or file.

A: The JSR 203 API has all the tools you need for that; and in this case, the Files class.
In spite of its name, it handles everything Path. For instance, you can use:
Files.isDirectory(thePath)

to test whether a file is a directory. But there are also other ways to test for the same thing.