text:
Q: Submitting Select value with ajax.beginform on mvc4 It seems that my view isn't reaching my controller, I'm populating a select looping a model in the view and then I try to call an partial view with new info
My HomeController.cs has this method:
[HttpPost]
public ActionResult BusquedaDeSensores(int id)
{
    ViewBag.Message = "text...";
    retail2Entities cl = new retail2Entities();
    List<GetSensorByClient_Result> sensores = cl.GetSensorByClient(id,0).ToList();
    return PartialView("_BusquedaDeSensores",sensores);
}

This is what I have on my index page preloading some data and trying to send the selected value to my controller.

@using (Ajax.BeginForm("BusquedaDeSensores", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "Post", UpdateTargetId = "busquedaDeSensores" }))
{
<select id="Cientes" name="Clientes">
   @foreach (var item in Model)
   {
   <option value="@item.idClient">@item.name</option>
   }
    </select>
   <input type="submit" value="submit" />
}

lel

This would be my partial view _BusquedaDeSensores:
@model IEnumerable< Recnons.Models.GetSensorByClient_Result>

@using (Ajax.BeginForm("EntradaSalida", "Home", new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "Post", LoadingElementId = "ajax-loader", UpdateTargetId = "entradaSalida" }))
{
<select id="Sensores" name="Sensores">
   @foreach (var item in Model)
   {
   <option value="@item.Id">@item.Id</option>
   }
    </select>
   <input type="submit" value="submit" />


text:
Q: How can I check if a Point Intersect A Moving Sphere? My problem is that I can't find all the points that intersect the sphere during its linear motion. What I did was to check starting with the starting point, from point to point until the final point, if the point is in the sphere. Then I checked the points that are between the 2 moments of the sphere, considering a cylinder that the sphere forms when it moves. There I used the distance from a point to a line (formed by the points f(t) and f(t+deltaT)).
the requirement of the problem
Visualization
bool checkPoint(geo::Point3D point, const double sphereRadius, const geo::Curve& curve,
const double deltaT)
{
int iterations = round(1 / deltaT);

for (int i = 1; i <=iterations; i++)
{

    geo::Point3D currentPoint = curve.Evaluate((i-1) * deltaT);
    geo::Point3D nextPoint = curve.Evaluate(i * deltaT);

    //check if point is in sphere at current point or nextPoint
    if (point.IsTolerant(currentPoint, sphereRadius) || point.IsTolerant(nextPoint, sphereRadius))
        return true;

    //Check if the point is inside the cylinder
    /*if (checkPointInCylinder(point, sphereRadius, currentPoint, nextPoint))
        return true;*/

    geo::Point3D dirVector = (nextPoint - currentPoint);

    double projectionAP = ((point - currentPoint) * dirVector);
    double projectionBP = (point - nextPoint) * dirVector;
    double distance = (((point - currentPoint) % dirVector).Length2())/dirVector.Length2();

    int flag = 0;
    if (point.x() == 86.0f && point.y() == 86.0f && point.z() == 32.0f)
        flag = 1;

    if (projectionAP >= 0 && projectionBP <= 0 && distance <= sphereRadius*sphereRadius)
        return true;

}
return false;

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: XPath Query With Multiple Arrays I have the following XML structure:
<xml>
    <header>
        (Tags goes here)
    </header>
    <listItem>
        <id></id>
        ...
        (Sort of data)
        ...
        <arrayType1>
            <id></id>
            <parentId></parentId>
            <!-- Key: Data to lookup and get the entire structure (listItem) with XPath-->
            <key></key>
        </arrayType1>
        <arrayType2>
            <id></id>
            <parentId></parentId>
            <!-- Key: Data to lookup and get the entire structure (listItem) with XPath-->
            <key></key>
        </arrayType2>
    </listItem>
    <listItem>
        (Exactly same structure with different data as above)
    </listItem>
</xml>

Tag <parentId> has the same data of <listItem><id> tag (not to be confused with <id> of each arrayType).
I need a XPath expression that returns the <parentId> or <listItem><id> only having the  data (or, by default, return the entire arrayTypeX and process later in another XSLT transformation).
I need this for a transformation in a XSLT Map in IBM Integration Designer (Websphere ESB), but i'm very confused about the XPath expression, but, the point is merely in build that XPath Expression.
I've tried with this expression:
/listItem[arrayType1[key = 'value']]/parentID
But i don't know if XPath supports that kind of syntax (array inside array looking for a specific value). That expression always return the first ID of the list.
The Cardinality for each item is:
header: [0..1]
listItem: [0..*]
arrayType1: [0..*]
arrayType2: [0..*]

Can you shed some light about this?
Thanks
EDIT: This is an example:
<xml>
    <header>
        (Tags goes here)
    </header>
    <listItem>
        <id>1</id>
        <arrayType1>
            <id>1000</id>
            <parentId>1</parentId>
            <key>abc</key>
        </arrayType1>
        <arrayType1>
            <id>1500</id>
            <parentId>1</parentId>
            <key>mno</key>
        </arrayType1>
        <arrayType2>
            <id>2000</id>
            <parentId>1</parentId>
            <key>def</key>
        </arrayType2>
    </listItem>
    <listItem>
        <id>2</id>
        <arrayType1>
            <id>3000</id>
            <parentId>2</parentId>
            <key>ghi</key>
        </arrayType1>
        <arrayType2>
            <id>4000</id>
            <parentId>2</parentId>
            <key>jkl</key>
        </arrayType2>
    </listItem>
</xml>

Only having the <key> (for example, "ghi"), i expect to get the <id> or <parentId> "2", with an XPath expression.

A: if the order of <parentId> and <key> is maintained, i.e. <parent> appears before <key> in each <arrayTypeX> then this will work:
//key[text()="value"]/preceding-sibling::parentId[1]

for eg:
for key = "jkl" the return will be 2.
though, it must be mentioned here that, if required, it can be tweaked to account for multiple matches for <key> as well as no particular order for <parent> and <key>.


text:
Q: Get data from array with several object i would like to get the "-lists" data from an array with several objects:
[{...},{...},{...},{"-name": "Test", "-lists": [123, 456, 789]},{...}]

i tried with a filter function but it doesnt works :-(
this is the query where i would like to change the result to the value/array of "-lists"
             .findOne({ _id: serviceID }, function (err, result) {
                if (err) {
                    res.json(err);
                } else {
                    try{
                        res.json(result.service.modules)
                        console.log(result.service.modules)
                    }catch(error){
                        console.log(error)
                    }

                }
            })

Have someone an idea for me?
Best regrads & stay healthy

A: You can try the map function of the array.

const data = [
  {"-name": "Test", "-lists": [123, 456, 789]},
  {"-name": "Test", "-lists": [222, 333, 444]}
 ];

 const result = data.map((x) => x['-lists']);

 console.log(result);

This will return an array of the lists data which is an array in itself.

A: This is an example of one of the approaches you can use to extract the value of an array nested in an object which is inside an array.

const arr = [{ someValue: 1 }, { "-lists": [1, 2, 3] }];
const result = [];

arr.filter((val) => {
  if (val["-lists"]) {
    result.push(...val["-lists"]);
  }
});

console.log(result);


text:
Q: MySQL case when using JOIN/GROUP BY I have a posts table. I am joining it with votes table via:
SELECT posts.*,
       (CASE
            WHEN vs.user_id = 1 THEN 0
            ELSE 1
        END) AS voted_by_me
FROM `posts`
LEFT OUTER JOIN votes AS vs ON vs.post_id = posts.id
GROUP BY posts.id

Basically I want know if the joined value vs.user_id = 1. This obviously doesn't work because it will just use a random returned value in CASE WHEN condition . I am wondering if there's a way to find out if the join values group by contains a specific value.
To clarify:
I want to get all posts, and also for each post have a column called voted_by_me where if posts was voted by user with id 1, then make it value 0, otherwise 1.

A: Is that what you want?
SELECT posts.id,
       sum(vs.user_id = 1 AND vs.option = 0) > 0 AS downvoted_by_me,
       sum(vs.user_id = 1 AND vs.option = 1) > 0 AS upvoted_by_me
FROM `posts`
LEFT OUTER JOIN votes AS vs ON vs.post_id = posts.id
GROUP BY posts.id

A: SELECT posts.id,
       ifnull(vs.isvoted, 0) AS voted_by_me
FROM `posts`
LEFT OUTER JOIN (select distinct postid , 1 as isvoted from votes where user_id=1) AS vs
ON vs.post_id = posts.id


text:
Q: Bulk uploading markers from Excel with custom info boxes I'm trying to upload an Excel Spreadsheet containing student names their geolocations, and their "top skills" from an online class into the Google Javascript API.
Eventually, I want each location to have a popup box associated with it, displaying the student name and their top skills.
From what I can tell according to the API, I have to use Data Arrays like this to plot the markers:
var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

Then I could add these locations like this:
for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });
    }

A couple of questions:

*

*Is there a speedier way of uploading the Excel Spreadsheet Data into a Javascript format without manually writing each location?

*How do I associate those specific locations with a student name and list of skills?

A: You could use a json to do this.  If you save an excel file as a .csv there are online converters that can change it to a json.  In the past I've done this on a project:
http://burdsgis.coffeecup.com/BluePlaques/bpWords.html
The json for the above looks like this:
var dec_markers = [

{
    "NewNumber": "1",
    "Title": "97",
    "Location": "Unknown",
    "Unveiler": "Unknown",
    "Date": "Unknown",
    "Sponsor": "Unknown",
    "TomEast": "-1.55167",
    "TomNorth": "53.7917",
    "Title2": "97",
    "TomURL": "http://farm1.staticflickr.com/76/198148805_85d6ff5b44_m.jpg",
    "TomLink": "http://www.flickr.com/photos/44067831@N00/198148805/in/set-1439239/"
},

etc...
You can then call the json in your map.js:
        //For loop to run through marker data
    for (id in dec_markers) {

        var photo = '';

        var info =  '

' + dec_markers[id].Title + '

Date Unveiled: '  + dec_markers[id].Date + "
Sponsor: " + dec_markers[id].Sponsor + '
' + photo + '
';

        var latlng = new google.maps.LatLng(dec_markers[id].TomNorth,dec_markers[id].TomEast);

        addMarker(latlng,dec_markers[id].Title,info);

        mc.addMarker(marker);
        }

I was scraping images from a Flickr album to populate the pop up boxes (using the Flickr API).
Google csv to json for a converter.
I'd also suggest using infobubble rather than infowindow as the former is more versatile.
For the clustering effect you can use MarkerClustererPlus for Google Maps V3

A: You can load information directly from Excel data file with Alasql and XLSX.js libraries.
For example, if you have Excel file with four columns with the following headers in row number 1 and all data in next rows:

*

*Student

*Latitude

*Longitude

*Mark

You can load it and process to Google Maps with the following code:


text:
Q: Java Regex - Trying to use regex to get an array of "function" arguments I have a bunch of strings representing mathematical functions (which could be nested and have any number of arguments), and I want to be able to use regex to return an array of strings, each string being an argument of the outer-most function. Here's an example:
"f1(f2(x),f3(f4(f5(x,y,z))),f(f(1)))"

I would want a regex pattern that I could use to somehow get an array of all the arguments of f1, which in this case are the strings "f2(x)", "f3(f4(f5(x,y,z)))", and "f(f(1))". There will be no spaces in the input string.
Thank you very much to anyone who can help.

A: I don't think this can be done with regexes alone.
This would probably require being able to identify balanced parentheses -- for example, once we've parsed f1(f2(x), the next character could either be a ) or a , -- and that's a canonical example of something that can't be done with regexes, but requires a more sophisticated parser.


text:
Q: Core Data - Savings and sharing images via iCloud I have an app that allows a user to either take photo or point to a photo on from their camera roll. This record must be peristed locally. A record consists of text and an image. Savings this data on a single device seems simple, as I can persist the link to the image or store the image locally in the file system if taken via camera.
Problem is how to share this record via iCloud to make record available to all instances of the app on multiple devices. I.e iPhone creates a record with an image, which is then available to view on iPad or Apple TV.
Is it efficient to store a UIImage in a Core Data record and make this available via iCloud? Many people saying not for local storage
My concern is this could potentially be some large quantities of data?
Does anyone have any thoughts on how to solve this issue?

A: I´m working on a similar app, for me working with http://Parse.com is a solution.
If your user have an internet connection and can wait to upload the images/text files you can save it directly using Parse (with a fancy progress Bar!) But if you want to make it network-less proof, you might work as whatsapp. I mean using Core Data to save your files locally, then try to upload the imagens whenever there is internet available.
There are some others clouds DB you can use, but I´m familiar with this one.

A: You can upload  to iCloud using NSFileManager.
There is a complete walkthrough on how to do that.


text:
Q: Infinite sequence of coin tosses, $\Bbb{P}(\limsup_{n\to \infty} A_n) = 1$ Let $(\Omega, \mathcal{A}, \Bbb{P}) = \otimes_{j=1}^{\infty} ( \{0,1\}, \mathcal{P}(\{0,1\}), \Bbb{P}_j)$ with $\Bbb{P}_j(1)=1/2=\Bbb{P}_j(0)$, i.e. the model for an independent infinite sequence of coin tosses. Fix $r\in \Bbb{N}$ and $(a_1,…,a_r)\in \{0,1\}^r$, and let $A_k = \{ \omega=(\omega_1,\omega_2,…)\in \Omega : \omega_{k+l-1} = a_l, 1\leq l \leq r \}$.
Then $\Bbb{P}(\limsup_{n\to \infty} A_n) = 1$.
My attempt:
The set $\limsup_{n\to \infty} A_n$ consists of those $\omega = (\omega_1, \omega_2,…)$ that are contained in infinitely many $A_k$'s, i.e. they contain the sequence $(a_1,…,a_r)$ infinitely often.
At first glance, it looks like we might be able to apply Borel-Cantelli, but the $A_k$'s are not independent, so we cannot apply the Lemma.
The statement itself seems intuitively clear, but I haven't been able to formalize it.
Since $( \limsup_{n\to \infty} A_n )^c= \liminf_{n\to \infty} A_n^c$, it would also suffice to show that $\Bbb{P}( \liminf_{n\to \infty} A_n^c) = 0$.
I appreciate any help.

A: Hints:

*

*Show that the sets $A_r, A_{2r},\ldots$ are independent.

*Deduce from $$\sum_{k \in \mathbb{N}} \mathbb{P}(A_{k \cdot r}) = \infty$$ and  the Borel-Cantelli lemma that $\mathbb{P}\left( \limsup_{k \to \infty} A_{k \cdot r} \right) = 1$.

*Conclude that $$\mathbb{P} \left( \limsup_{n \to \infty} A_n \right)=1.$$


text:
Q: How to get user information for records created in Common Data Service entity table by Created by column? The User() function only gets currently logged on user's information.
Is there a way to find out the user information, i.e. user name, email address etc. via the created by id in the table?
Thanks,
Jack


text:
Q: How to resolve broadcasted variable issues in parloop? I have made for loop parralel in matlab, but I get warning that some of my arrays are broadcasted which lead to unnecessary communication overhead. I'm new in matlab and don't know how to solve this issue. Would someone help me with this?
A and Y is broadcasted in this code
parfor k=1:length(gamma)

    Lambda=gamma(k);
    tmp=zeros(nfolds,Num_Tasks);

    for p=1:length(omega)

        OmegA= omega(p)
        for Fold=1:size(Fold_indices,2)
            % Creat train and test fold
            A_Train=A(logical(Fold_indices(:,Fold)),1:end);  # A is broadcasted
            %size(A_Train)
            Y_Train=Y(logical(Fold_indices(:,Fold)),1:Num_Tasks); # Y is broadcated

            A_Test=A(~logical(Fold_indices(:,Fold)),1:end);
            Y_Test=Y(~logical(Fold_indices(:,Fold)),1:Num_Tasks);
            coff=Estimate_x(Y_Train,A_Train,Lambda,OmegA,Binding_matrix)  ;

            % Do the prediction on Kth f;old and compute the error
            % coff
            %sum((A_Test*coff-Y_Test).^2) ./ size(A_Test,1)
            tmp(Fold,1:end)=sum((A_Test*coff-Y_Test).^2) ./ size(A_Test,1);
            tmp;
            %Coefficents{:,Fold}=coff;
            coff
        end
        In_Fold_Error{1,p}=tmp;
        %In_Fold_Error{2,k}= Lambda;

        Coefficents{:,p}=coff;
    end
    CVErr_twoparam{1,k}=In_Fold_Error;
    Coefficents_twoparam=Coefficents;

end

A: Unless you can compute A_Train and Y_Train directly in the parfor loop, as opposed to using subscripting in order to get their values from A and Y, there's nothing you can do. Your source of information is unique, so these values will be broadcasted.
If you have enough memory, maybe it would be a better idea to compute A_Train and Y_Train as cell arrays of matrices in a normal for, and then use these sequentially pre-computed values inside the parfor. Like this you don't send the entire matrices A and Y to workers.


text:
Q: Replcae inner space in Python Iam new to Python, And I need to remove space between string and a digit only not between two strings.
eg:
Input : Paragraph 25 is in documents and paragraph number in another file.
Output : Paragraph25 is in documents and paragraph number in another file.
How this can be done in Python ? I tried regex
re.sub("paragraph\s[a-z]", "paragraph[a-z]", Input)

But its not working.

A:  >>> re.sub(r'\s+(\d+)', r'\1', 'Program 25 is fun')
'Program25 is fun'

That might work in a pinch. I'm not the most familiar with regexes, so hopefully someone who is can chime in with something more robust.
Basically we match on whitespace succeeded by numbers and remove it.


text:
Q: Cross ratio: two different views There are I think at least two views on the cross ratio of 4 points even https://en.wikipedia.org/wiki/Cross-ratio gives two definitions
And I was wondering what is the relation between the two
The Geometrical view:
The cross ratio of 4 points A,B;X,Y is
$$ CR_g =\frac{d(A,Y) d(B,X)}{d(A,X) d(B,Y)}$$
Where d(I,J) is the distance between I and J.
The Algebraic view:
The cross ratio of four (complex) numbers a,b,x,y is:
$$ CR_a=\frac{(y-a) (x-b)}{(x-a)(y-b)}$$
Wondering / Questions
Points in a plane can be represented by complex numbers  and this made me  wonder:
What is the relationship between the two cross ratio views  if $A,B,X,Y$ and $a,b,x,y $ represent the same points.
And I also would like to see a proof of that relation.
Explorations:
When the points A,B,X,Y are on a line then the cross ratio's are equal
When the points are on a circle $CR_a$ is a real number (see reference in comments)


text:
Q: kde login screen only on 1 monitor I'd like my kde login screen to be ONLY on 1 monitor. The other one is not always ON, and in that case I'm missing cursor and it's just inconvenient to use.
I learned, that kde uses sddm, learned about file /usr/share/sddm/scripts/Xsetup, and put there:
xrandr --output HDMI-1 --off --output DVI-D-1 --mode 1920x1200 --rate 59.95

which is command, that works after login. If I have both screens on, this will shutdown hdmi output, and keep only dvi. I cannot find any issue regarding xrandr in journalctl
Can anyone suggest what can be wrong? Is it possible that indices of HDMI are different while sddm is invoked? Or what can be the issue?


text:
Q: Week Number when week starts on Friday I am trying to write SQL to populate a customer calendar table in which the business week for the customer is Friday to Thursday.  I will need to populate for several customers that each have a different business week defined.  I am trying to populate the following fields:
WeekBeginDate
WeekEndDate
WeekNo
WeekYear

This is an example of the result set:
Date      WeekBeginDate  WeekEndDate    DayofWeek   WeekNo   WeekYear
01/03/13  12/28/12       01/03/2013     Thursday    52       2012
01/04/13  01/04/13       01/10/2013     Friday  1    2013

A: I'm going to assume you have a Dates table with the date range you need to avoid looping.  Then, you can take advantage of SET DATEFIRST to vary the first day of the week:  http://msdn.microsoft.com/en-us/library/ms181598(v=sql.105).aspx
Then, the following should return the correct results.  The following is using your Friday example.  I also included a "CustomerID" in the list, just in case you need to vary by customer.
--Set the first day of the week as Friday.  For other customers with different week start days, vary this setting
set datefirst 5

select
    1 AS CustomerID,  --or whatever you use as a customerid
    CalendarDate,
    dateadd(dd, (-1 * datepart(dw, calendardate)) + 1, calendardate) as WeekBeginDate,
    dateadd(dd, (7 - datepart(dw, calendardate)), calendardate) as WeekEndDate,
    datename(dw, calendardate) as DayofWeek,
    datepart(wk, dateadd(dd, (-1 * datepart(dw, calendardate)) + 1, calendardate)) - 1 as Week No,
    datepart(yyyy, dateadd(dd, (-1 * datepart(dw, calendardate)) + 1, calendardate)) as WeekYear
FROM
    dates  --my dates table
where
    calendardate between '12/28/12' and '1/5/14'

A: To get all the dates for seeding, you can use something like this:
Select DateAdd (D, ROW_NUMBER() Over (Order By C1.Ordinal_Position), '12/31/1999') DateValue
From INFORMATION_SCHEMA.COLUMNS C1, INFORMATION_SCHEMA.COLUMNS C2

If you run the above query in a database with too few columns, then change the FROM to be.  Cartesian product FTW
From INFORMATION_SCHEMA.COLUMNS C1, INFORMATION_SCHEMA.COLUMNS C2,
     INFORMATION_SCHEMA.COLUMNS C3, INFORMATION_SCHEMA.COLUMNS C4

Now, you need a different day of the week to be the first day.  So read up on SET DATEFIRST.  This lets you set the first day of week for a particular session to TSQL.
Then you can then use DATEPART to get the other columns that you require.
Combine the three to get your answer.  I am going to give you a sample of how you can make this work - you can use DATEADD to the query to get Start-Of-Week and End-Of-Week values, and DATEPART to get Week-Of-Year and YearN-umber
SET DATEFIRST 3 -- put your corresponding day here

;With AllDates AS
(
Select
    DateAdd (D, ROW_NUMBER() Over (Order By C1.Ordinal_Position), '12/31/1999') DateValue
From INFORMATION_SCHEMA.COLUMNS C1
),
AllDatesWithWeekDayNumber AS
(
Select
    DateValue,
    DatePart (weekday, DateValue) WeekDayNumber
From AllDates
)
Select * From AllDatesWithWeekDayNumber


text:
Q: Need Help Translating SQL Server UNION Syntax to LINQ I have the below SQL which works just fine:
SELECT     Message, CreateDate, AccountId, AlertTypeId
FROM       dbo.Alerts
UNION
SELECT     TOP (100) PERCENT Status, CreateDate, AccountId,
                          (SELECT     10 AS Expr1) AS AlertTypeId
FROM         dbo.StatusUpdates
WHERE AccountId = PassedInParameter
ORDER BY CreateDate DESC

I am trying to convert it to LINQ, which doesn't work just fine :) Obviously, there is a lot wrong here - it is just a rough start. It does not account for the above temp column or the order by condition and the generics / return type ambiguity is my attempt to make sense of the two different return types:
public List<T> GetSomething<T>(Int32 accountId)
{
   List<T> result;

   using (DataContext dc = _conn.GetContext())
   {
      IEnumerable<Alert> alerts = (from a in dc.Alerts
                                   where a.AccountId == accountId
                                   select a);
      IEnumerable<StatusUpdate> updates = (from s in dc.StatusUpdates
                                           where s.AccountId == accountId
                                           select s);

      IEnumerable<T> obj = alerts.Union(updates);

      result = obj.ToList();
   }

   return result;
}

The problems I am having are:
1) I am dealing with two different types (Alerts and StatusUpdate) in my selects and
I am not sure how to combine them (or what type to return). I am guessing this might
be solved with generics?
2) In my SQL, I have this code: (SELECT 10 AS Expr1) AS AlertTypeId which adds the value ten to the temp column AlertTypeId (allowing the union to match it to Alert's real column AlertTypeId). How are temp columns such as this accomplished in LINQ / how do I do this?
Thanks for your help.
EDIT---------------------------------EDIT------------------------------------------EDIT
OK, I am a little further along. Below is what I have currently. You will notice I added some logic to return the updates for friend relations. I also made this a generic method of type IList given that alerts and updates have to be generic to agree. I pass in StatusUpdate in the calling method (further down below).
public IList GetUpdatesByAccountId<T>(Int32 accountId)
{
    List<Friend> friends = _friendRepository.GetFriendsByAccountId(accountId);

    using (DataContext dc = _conn.GetContext())
    {
        // Get all the account ids related to this user
        var friendAccountIds =
            friends.Select(friend => friend.MyFriendsAccountId).Distinct();
            friendAccountIds = friendAccountIds.Concat(new[] { accountId });

        var updates =
            dc.StatusUpdates.Where(s => s.AccountId.HasValue && friendAccountIds.Contains(s.AccountId.Value)).Select(
                s => new { Alert = (Alert)null, StatusUpdate = s});

        var alerts =
            dc.Alerts.Where(a => a.AccountId == accountId).Select(
                a => new {Alert = a, StatusUpdate = (StatusUpdate) null});

        var obj = updates.Union(alerts).Take(100);

        return obj.OrderByDescending(su => su.StatusUpdate.CreateDate).ToList();

    }

}

And, the calling method:
protected void LoadStatus()
{

    repStatusUpdates.DataSource = _statusRepository
        .GetUpdatesByAccountId<StatusUpdate>(_userSession.CurrentUser.AccountId);

    repStatusUpdates.DataBind();

}

AND here are the interfaces to the repositories I am using to access my Alert and StatusUpdate tables via LINQ:
public interface IAlertRepository
    {
        List<Alert> GetAlertsByAccountId(Int32 accountId);
        void SaveAlert(Alert alert);
        void DeleteAlert(Alert alert);
    }

public interface IStatusUpdateRepository
    {
        StatusUpdate GetStatusUpdateById(Int32 statusUpdateId);
        List<StatusUpdate> GetStatusUpdatesByAccountId(Int32 accountId);
        List<StatusUpdate> GetFriendStatusUpdatesByAccountId(Int32 accountId, Boolean addPassedInAccount);
        void SaveStatusUpdate(StatusUpdate statusUpdate);
        List<StatusUpdate> GetTopNStatusUpdatesByAccountId(Int32 accountId, Int32 number);
        List<StatusUpdate> GetTopNFriendStatusUpdatesByAccountId(Int32 accountId, Int32 number, Boolean addPassedInAccount);
    }

Current Problems:
1) When I compile this code, I get this strange error:

Unable to cast object of type
  'System.Data.Linq.SqlClient.SqlNew' to
  type
  'System.Data.Linq.SqlClient.SqlValue'.

The only reading I can find on it is this link although there isn't a clear solution there (at least that I can tell). However, if the above LINQ code does not look good to you, maybe whatever you suggest will cause this error to disappear.
2) The above code is still not accounting for this line from the original SQL:
(SELECT 10 AS Expr1) AS AlertTypeId

but this is minor.
Thanks again for the help.

A: Try this (i converted the StatusUpdate to an alert, if this isn't acceptable, you're going to have to either convert the Alert to a StatusUpdate, or create a new class):
var alerts = (from a in dc.Alerts
              where a.AccountId == accountId
              select a);
var updates = (from s in dc.StatusUpdates
               where s.AccountId == accountId
               select s)
              .OrderByDescending( x => x.CreateDate)
              .Take(100)
              .Select( x => new Alert
                {
                   Message = x.Percent.ToString(),
                   CreateDate = x.CreateDate,
                   AccountId = x.AccountId,
                   AlertTypeId = 10 // Is this right?
                 }
               );

 var obj = alerts.Union(updates);

 result = obj.ToList();

The reason I do the Select last is so that you don't have to construct a new alert for all the results your are not using.
This will give you a list of Alerts.
Using a generic in this situation is sort of hard to pull off. For instance, you can't do this:
IQueryable alerts = (from a in _alerts
                        where a.AccountId == accountId
                        select a);
Because that implicitly converts a to type T. Even if you try to limit what T implements or inherits from:
public List<T> GetSomething<T>(Int32 accountId) where T : IAlert// Interface that both StatusUpdates and IAlert implement
public List<T> GetSomething<T>(Int32 accountId) where T : Alert
public List<T> GetSomething<T>(Int32 accountId) where T : AlertBase // Base class for both Status and Alert

You'll still run into problems because there is no way to statically know exactly what type T is, so you cannot know if it can be converted from Alert and StatusUpdate.
An alternative is to explicitly use IAlert as your return type:
public List<IAlert> GetSomething(Int32 accountId)

With IAlert:
public interface IAlert
{
    int AccountId { get; set; }
    int AlertTypeId { get; set; }
    DateTime CreateDate { get; set; }
    string Message { get; set; }
}

If you have have both Alert and StatusUpdate implement IAlert, you could rewrite it as so:
IQueryable<IAlert> alerts = (from a in dc.Alerts
              where a.AccountId == accountId
              select a);
IQueryable<IAlert> updates = (from s in dc.StatusUpdates
               where s.AccountId == accountId
               select s)
              .OrderByDescending( x => x.CreateDate)
              .Take(100);

 var obj = alerts.Union(updates);

 result = obj.ToList();

This is the route I would take instead of passing in some unknown type and trying to limit what it implements or inherits, because casting to that type might still be  invalid.

A: You can only take unions of sequences of equal types.  You need to convert alerts and updates to sequences of a common type, then take the union.  You can do so using anonymous types.  Especially useful if the types don't have anything in common.
//this is a hack and probably not what you would want to use.
var alerts =
        from a in dc.Alerts
        where a.AccountId == accountId
        select new { Alert = a, StatusUpdate = (StatusUpdate)null };
var updates =
        from s in dc.StatusUpdates
        where s.AccountId == accountId
        select new { Alert = (Alert)null, StatusUpdate = s };

//both are sequences of anonymous type with properties:
//    Alert (of type Alert)
//    StatusUpdate (of type StatusUpdate)
var obj = alerts.Union(updates);

If you have fields in common, you'd still use anonymous types except you'd include the known fields.
var alerts =
        from a in dc.Alerts
        where a.AccountId == accountId
        select new
        {
            a.Message, //assuming is a string
            Status = (string)null,
            a.CreateDate,
            a.AccountId,
            a.AlertTypeId //assuming is an int
        };
var updates =
        (from s in dc.StatusUpdates
        where s.AccountId == accountId
        select new
        {
            Message = (string)null,
            s.Status, //assuming is a string
            s.CreateDate,
            s.AccountId,
            AlertTypeId = 10 //this should handle the "10 AS AlertTypeId" part
        }).OrderByDescending(s => s.CreateDate);

var obj = alerts.Union(updates);

The key is that both anonymous types has the same exact properties of the same exact types.  Then you can take the union between them both.


text:
Q: Conditional summing of columns in pandas I have the following database in Pandas:
Student-ID   Last-name   First-name  HW1  HW2  HW3  HW4  HW5  M1   M2  Final
59118211           Alf        Brian   96   90   88   93   96  78   60   59.0
59260567      Anderson         Jill   73   83   96   80   84  80   52   42.5
59402923     Archangel      Michael   99   80   60   94   98  41   56    0.0
59545279         Astor         John   93   88   97  100   55  53   53   88.9
59687635        Attach         Zach   69   75   61   65   91  90   63   69.0

I want to add only those columns which have "HW" in them. Any suggestions on how I can do that?
Note: The number of columns containing HW may differ. So I can't reference them directly.

A: You could all df.filter(regex='HW') to return column names like 'HW' and then apply sum row-wise via sum(axis-1)
In [23]: df
Out[23]:
   StudentID   Lastname Firstname  HW1  HW2  HW3  HW4  HW5  HW6  HW7   M1
0   59118211        Alf     Brian   96   90   88   93   96   97   88   10
1   59260567   Anderson      Jill   73   83   96   80   84   99   80  100
2   59402923  Archangel   Michael   99   80   60   94   98   73   97   50
3   59545279      Astor      John   93   88   97  100   55   96   86   60
4   59687635     Attach      Zach   69   75   61   65   91   89   82   55
5   59829991       Bake      Jake   56    0   77   78    0   79    0   10

In [24]: df.filter(regex='HW').sum(axis=1)
Out[24]:
0    648
1    595
2    601
3    615
4    532
5    290
dtype: int64

A: John's solution - using df.filter() - is more elegant, but you could also consider a list comprehension ...
df[[x for x in df.columns if 'HW' in x]].sum(axis=1)


text:
Q: Win32/.NET applications and browsers (but not CURL) suddenly unable to make HTTP requests on AWS VM Environment: AWS / Microsoft Windows Server 2019 VM
A few .NET applications are running on a VM (as windows services), which make various HTTP requests. One of these is also using MQTT (via MQTTnet) to relay events from an external service to a different HTTP API.
Everything will work as expected for a few days, until finally HTTP requests from the applications start timing out.
Windows Event Viewer shows the following error every few minutes: "The WinHTTP Web Proxy Auto-Discovery Service service terminated with the following service-specific error: The endpoint mapper database entry could not be created."
At this point, seemingly any Win32/.NET application will fail to execute an HTTP request, including IE, etc -- but not CURL. Likewise, other network connectivity and protocols seem fine. I'm assuming this would be due to an issue with WinHttp (or other low level Win32 HTTP services)? I've spent some time researching the Web Proxy Auto-Discovery service and trying to understand why it would suddenly start failing (and if it's the cause or just an effect), but I haven't found anything online.
I haven't found corrective action (restarting services, resetting things with netsh, etc) that will fix this condition. Only a full restart of windows seems to solve it. At which point the WinHTTP Web Proxy Auto-Discovery Service is happy again, http requests work again, etc.
I'm struggling to even find where to begin to troubleshoot this.

A: I had the same problem. I had disabled the services "WinHttpAutoProxySvc" and "iphlpsvc" in the instances that I had the problem .  The service "iphlpsvc" depends on "WinHttpAutoProxySvc" and provides connectivity IPv6 over IPv4 (6to4). I haven't detected any problem with this action since last month and up to now.


text:
Q: Discord.py Cooldown in Seconds Well, I have a command with a cooldown. It shows the cooldown in seconds, but I want it to be in
hours:minutes:seconds.
Since I'm still very new to Python. I need a little help.
This is my Code:
@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send("User existiert nicht!")
    if isinstance(error, commands.CommandOnCooldown):
        msg = f'**Du bist in einem Cooldown** Versuch es in {round(error.retry_after)} Sekunden erneut.'
        await ctx.send(msg)

A: Suggested related question which very much applies to this
But, adapted to your use case with just a little bit of math (no extra imports):
msg = f'**Du bist in einem Cooldown** Versuch es in {error.retry_after // (60 * 60):02d}:{(error.retry_after // 60) % 60:02d}:{error.retry_after % 60:02d} erneut.'

Would result in
"**Du bist in einem Cooldown** Versuch es in 34:17:36 erneut."

with error.retry_after == 123456.
Assuming error.retry_after is an integer. If it's not, cast it to an integer first and store it in another variable that is then used for the math.


text:
Q: Cannot access map object with []. operator [] is not defined I am working on a mobile application using Flutter 1.7.8.
I collected data from the server in a form of a nested json object, e.g.
class Obj {
  final String obj_to_access;
  const Obj({this.obj_to_access});
  factory Obj.fromJson(Map<String, dynamic> json) {
    return Obj(
      obj_to_access: json['item']
    );
  }

some_obj =
{
  "id": some_id,
  "nested_obj": Obj.fromJson(json["obj_to_access"])
}

However, I can't seem to access the nested Obj with '[]' and it always give me this error: The operator '[]' isn't defined for the class 'Obj'. Try defining the operator.
I saw that I should try defining the '[]' but I am not sure how. Please help thanks

A: The reason for the error is that you're passing a dynamic value to Obj.fromJson() instead of a Map - which it expects. To solve this issue, you can add cast as <Map<String, dynamic>> to the value to let the compiler know that it's a Map.


text:
Q: C# combobox adding multiple items text and values from database dynamically I am trying to list multiple companies in a combobox. These companies populate from database table tbl_companies. Combobox value should be id of table(Which is primary key of the table). Text should be the name of company.
Like id=1 and name = "XYZ".
Code is
      string connStr = "My Connection string";
        SqlConnection conn = new SqlConnection(connStr);

        string strQuery = "SELECT * FROM tbl_Companies ORDER BY id ASC";
        SqlCommand cmd = new SqlCommand(strQuery, conn);

        conn.Open();

        SqlDataReader companyRead = cmd.ExecuteReader();

        if (companyRead.HasRows)
        {
            while (companyRead.Read())
            {
                int cId = (Convert.ToInt16(companyRead["id"].ToString()));
                cmbCompany.Items.Insert(cId, companyRead["name"].ToString());
            }
        }
        conn.Close();

When I am executing the code, getting the following error.
System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '1' is not valid for 'index'.
Parameter name: index'
For reference, I am also sharing the [enter image description here]screenshot of code with error1
I need guidance, how to fix the problem.

A: You are inserting at a specific index, and when the list is empty at the start, an index of '1' is considered out of range.
Try:
cmbCompany.Items.Add(companyRead["name"].ToString());
instead.

A: Your error is in the Item.Insert method where the first parameter should be the position in the already existing items collection where you want to insert the new value and not the Item's value.
Instead of using this manual loop you could simply set the combo datasource to a DataTable and set the DisplayMember and ValueMember properties
string connStr = "My Connection string";
using(SqlConnection conn = new SqlConnection(connStr))
{
    string strQuery = "SELECT * FROM tbl_Companies ORDER BY id ASC";
    SqlCommand cmd = new SqlCommand(strQuery, conn);
    conn.Open();
    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader())
    cmbCompany.DisplayMember = "name";
    cmbCompany.ValueMember = "id";
    cmbCompany.DataSource = dt;
}

Consider also that once you set the Datasource property in this way you shouldn't manually insert new items, instead you add elements to the underlying DataTable and refresh the combo datasource binding


text:
Q: File Management for Large Quantity of Files Before I begin, I would like to express my appreciation for all of the insight I've gained on stackoverflow and everyone who contributes. I have a general question about managing large numbers of files. I'm trying to determine my options, if any. Here it goes.
Currently, I have a large number of files and I'm on Windows 7. What I've been doing is categorizing the files by copying them into folders based on what needs to be processed together. So, I have one set that contains the files by date (for long term storage) and another that contains the copies by category (for processing and calculations). Of course this doubles my data each time. Now I'm having to create more than one set of categories; 3 copies to be exact. This is quadrupling my data.
For the processing side of things, the data ends up in excel. Originally, all the data was brough into excel. Then all organization and filtering was performed in excel. This was time consuming and not easily maintainable over the long term. Later the work load was shifted to the file system itself, which lightened the work in excel.
The long and short of it is that this is an extremely inefficient use of disk space. What would be a better way of handling this?
Things that have come to mind:

*

*Overlapping Folders

*

*Is there a way to create a folder that only holds the addresses of a file, rather than copying the file. This way I could have two folders reference the same file.

*To my understanding, a folder is a file listing the memory addresses of the files inside of it, but on Windows a file can only be contained in one folder.

*Microsoft SQL Server

*

*Not sure what could be done here.

*Symbolic Links

*

*I'm not an administrator, so I cannot execute the mklink command.

*Also, I'm uncertain about any performance issues with this.

*A Junction

*

*Apparently not allowed for individual files, only folders in windows.

*Search folders (*.search-ms)

*

*Maybe I'm missing something, but to my knowledge there is no way to specify individual files to be listed.

*Hashing the files

*

*Creating hash tags for all the files, would allow for the files to be stored once. But then I have no idea how I would handle the hash tags.

*XML

*

*Maybe I could use xml files to attach meta data to the files and somehow search using them.

*Database File System

*

*I recently came across this concept in my search. Not sure how it would apply Windows.

A: I have found a partial solution. First, I discovered that the laptop I'm using is actually logged in as Administrator. As an alternative to options 3 and 4, I have decided to use hard-links, which are part of the NTFS file system. However, due to the large number of files, this is unmanageable using the following command from an elevated command prompt:
mklink /h <source\file> <target\file>

Luckily, Hermann Schinagl has created the Link Shell Extension application for Windows Explorer and a very insightful reading of how Junctions, Symbolic Links, and Hard Links work. The only reason that this is currently a partial solution, is due to a separate problem with Windows Explorer, which I intend to post as a separate question. Thank you Hermann.


text:
Q: How to make inverse switch with bc547? I want to make a circuit where the power to mcu switches from mains transformer to dc battery when when mains power is not available.
The basic concept is to use a transistor to stay open circuit to keep the battery from supplying the mcu while the mains transformer is active.
Once mains power goes out it should make the transistor conductive and close the circuit with battery.
In a nutshell when mains power is on transistor is off and vice versa
A complimentary congiguration with pnp would have been ideal but I'm limited to using bc548 atm
Please guide me to the right direction

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. (a) The diode version. (b) The BC548 version, if that's all you've got.
Either of these solutions should work if if \$ DC_{MAINS+} > V_{BAT} \$.


text:
Q: I have a problem with adding elements to my page after click - "Undefined", what I need to do? I am learning JS and I don't know what to do with this problem.
A function must return something? If yes, what does it need to return?
It is a part of my js:
const workExamplesAdding = (htmlFirstText, htmlSecondText) => {
htmlFirstText += '

';
htmlSecondText += '

';

document.getElementById("work-examples__item--afterClick").innerHTML = htmlFirstText;
document.getElementById("work-examples__item--afterClick2").innerHTML = htmlSecondText;
document.getElementById("work-examples__item--afterClick3").innerHTML = htmlFirstText;
document.getElementById("work-examples__item--afterClick4").innerHTML = htmlSecondText;
document.getElementById("work-examples__item--afterClick5").innerHTML = htmlFirstText;
document.getElementById("work-examples__item--afterClick6").innerHTML = htmlSecondText;
document.getElementById("work-examples__item--afterClick7").innerHTML = htmlFirstText;
document.getElementById("work-examples__item--afterClick8").innerHTML = htmlSecondText;};

It is must look like this (without undefined):

But it looks awful with undefined:

I can not give you html code, because Stack Overflow is warning that there is too much code.
Calling function:
const btnClick = (elementIsClicked, element) => {
  elementIsClicked = false;

  function clickHandler() {
    if (elementIsClicked = true) {
      showText();
      workExamplesAdding();
    } else {
      alert("Error");
    };
  };

  // grab a reference to your element
  element = document.getElementById('load-work-examples-btn');
  // associate the function above with the click event
  element.addEventListener('click', clickHandler);
}

A: Wow, problem was just in "htmlFirstText += ..." I did "htmlFirstText = ..." and it works!


text:
Q: Creating a New Variable for Each Unique Group I am working in R.
I have the following 5 data sets (data_1, data_2, data_3, data_4, data_5):
v1 <- c("2010-2011","2011-2012", "2012-2013", "2013-2014", "2014-2015")
v2 <- c("A", "B", "C", "D", "E")

data_1 = data.frame(var_1 = rnorm(871, 10,10), var_2 = rnorm(871, 5,5))

data_1$dates <- as.factor(sample(v1, 871, replace=TRUE, prob=c(0.5, 0.2, 0.1, 0.1, 0.1)))

data_1$types <- as.factor(sample(v2, 871, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))

data_2 = data.frame(var_1 = rnorm(412, 10,10), var_2 = rnorm(412, 5,5))

data_2$dates <- as.factor(sample(v1, 412, replace=TRUE, prob=c(0.5, 0.2, 0.1, 0.1, 0.1)))

data_2$types <- as.factor(sample(v2, 412, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))

data_3 = data.frame(var_1 = rnorm(332, 10,10), var_2 = rnorm(332, 5,5))

data_3$dates <- as.factor(sample(v1, 332, replace=TRUE, prob=c(0.5, 0.2, 0.1, 0.1, 0.1)))

data_3$types <- as.factor(sample(v2, 332, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))

data_4 = data.frame(var_1 = rnorm(611, 10,10), var_2 = rnorm(611, 5,5))

data_4$dates <- as.factor(sample(v1, 611, replace=TRUE, prob=c(0.5, 0.2, 0.1, 0.1, 0.1)))

data_4$types <- as.factor(sample(v2, 611, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))

data_5 = data.frame(var_1 = rnorm(789, 10,10), var_2 = rnorm(789, 5,5))

data_5$dates <- as.factor(sample(v1, 789, replace=TRUE, prob=c(0.5, 0.2, 0.1, 0.1, 0.1)))

data_5$types <- as.factor(sample(v2, 789, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))

# sample of one of the files

head(data_1)
      var_1     var_2     dates types
1  8.523382  4.945344 2010-2011     E
2 14.137515  3.223525 2012-2013     A
3 19.610770  7.762698 2011-2012     D
4 11.334196 10.879946 2012-2013     E
5 -1.406475  2.498347 2011-2012     E
6 11.116458  9.988073 2011-2012     E

Based on the above data, I made a table that provides summaries:
summary_table = data.frame(names = c("data_1", "data_2", "data_3", "data_4", "data_5"),
 counts = c(nrow(data_1), nrow(data_2), nrow(data_3), nrow(data_4), nrow(data_5) ),
mean_var_1 = c(mean(data_1$var_1), mean(data_2$var_1), mean(data_3$var_1), mean(data_4$var_1), mean(data_5$var_1)),
mean_var_2 = c(mean(data_2$var_1), mean(data_2$var_2), mean(data_3$var_2), mean(data_4$var_2), mean(data_5$var_2))

)

   names counts mean_var_1 mean_var_2
1 data_1    871   9.426475   9.853399
2 data_2    412   9.853399   4.680188
3 data_3    332  10.275049   5.256084
4 data_4    611  10.094421   5.323108
5 data_5    789   9.960050   4.946458

I would like to add 5 new columns to the above tables that contain the counts per year . This would look something like this (this an empty template):
df <- data.frame(matrix(ncol = 7, nrow = 0))
x <- c("names", "counts", "counts 2010-2011", "counts 2011-2012", "counts 2012-2013", "counts 2013-2014", "counts 2014-2015")
colnames(df) <- x

I know how to do this manually, but it would take a long time:
    library(dplyr)

     summary_1 = data.frame( data_1 %>%  group_by(dates) %>% summarise(my_counts = n()) )
     summary_2 = data.frame( data_2 %>%  group_by(dates) %>% summarise(my_counts = n()) )
     summary_3 = data.frame( data_3 %>%  group_by(dates) %>% summarise(my_counts = n()) )
     summary_4 = data.frame( data_4 %>%  group_by(dates) %>% summarise(my_counts = n()) )
     summary_5 = data.frame( data_5 %>%  group_by(dates) %>% summarise(my_counts = n()) )

#view sample of output
summary_1

      dates my_counts
1 2010-2011       407
2 2011-2012       189
3 2012-2013        79
4 2013-2014       101
5 2014-2015        95

But I would then have to manually create 5 new columns and manually copy these 25 counts ( 5 x 5 = 25).
Can someone please show me a faster way to do this?
Thanks!
Example of Desired Output

A: Perhaps you could consider to use set.seed() next time when using random values, so someone who is answering might use the exact same sampled data. Also, you could consider to use _  instead - signs when defining V1 to avoid the backticks in the resulting dataframe, which are added since R does not like minus-signs in column names.
You could use a named list to have values like data_1, data_2 etc in the data_nr column instead of 1, 2 etc.
library(tidyverse)

list(data_1, data_2, data_3, data_4, data_5) %>%
  set_names(paste0("data_", 1:length(.))) %>%
  bind_rows(.id = "data_nr") %>%
  count(data_nr, dates, name = "my_counts") %>%
  pivot_wider(names_from = dates, values_from = my_counts, names_prefix = "counts_")

       data_nr `counts_2010-2011` `counts_2011-2012` `counts_2012-2013` `counts_2013-2014` `counts_2014-2015`
  <chr>                <int>              <int>              <int>              <int>              <int>
1 data_1                 437                161                 93                 88                 92
2 data_2                 218                 68                 40                 36                 50
3 data_3                 170                 58                 35                 34                 35
4 data_4                 331                114                 65                 54                 47
5 data_5                 398                146                 89                 78                 78


text:
Q: I am trying to set the profile image and name in the navigation header but the code is not working The following code is used to to set the profile image and name, but it is not working and does not show any error on the logcat.  I want to add the image and name in header of navigation drawer. Kindly help.
 public class Admin_Dashboard_Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

        private AppBarConfiguration mAppBarConfiguration;
        private ActivityAdminDashboardBinding binding;

        CircleImageView profile_imageView;
        TextView profile_Name;
        RecyclerView mRecyclerView;
        List<FoodData> myFoodList;
        String profileImageUrl, userName;
        FoodData mFoodData;
        private ValueEventListener eventListener;

        DrawerLayout drawer;
        NavigationView navigationView;
        //
        DatabaseReference databaseReference;
        FirebaseAuth mAuth;
        FirebaseUser mUser;
        ///

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

            binding = ActivityAdminDashboardBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());

            //
            mAuth = FirebaseAuth.getInstance();
            mUser = mAuth.getCurrentUser();
            databaseReference = FirebaseDatabase.getInstance().getReference().child("Profile_Credentials");
            ///

            setSupportActionBar(binding.appBarAdminDashboard.toolbar);
            binding.appBarAdminDashboard.fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(Admin_Dashboard_Activity.this, Upload_Recipe.class);
                    startActivity(intent);
                }
            });

            drawer = findViewById(R.id.drawer_layout);
            navigationView = findViewById(R.id.nav_view);

           // View view = navigationView.inflateHeaderView(R.layout.nav_header_admin_dashboard);
            profile_imageView = navigationView.getHeaderView(0).findViewById(R.id.profile_imageView);
            profile_Name = navigationView.getHeaderView(0).findViewById(R.id.profile_Name);

            databaseReference.child(mUser.getUid()).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (snapshot.exists()){
                        profileImageUrl = snapshot.child("itemImage").getValue().toString();
                        userName = snapshot.child("itemName").getValue().toString();
                        Glide.with(getApplicationContext()).load(profileImageUrl).into(profile_imageView);
                     //   Picasso.get().load(profileImageUrl).into(profile_imageView);
                        profile_Name.setText(userName);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Toast.makeText(Admin_Dashboard_Activity.this, "Sorry!!", Toast.LENGTH_SHORT).show();
                }
            });

I think I used the correct method for retriving, but still don't show any result.


text:
Q: Send PHP mail with AngularJS I want to send an email when submitting a form in my AngularJS app.
My email.php file looks like this:
<?php
 $receiver = $_REQUEST['to'];
 $subject = "The subject";
 $message .= 'Hello';
 $header = "MIME-Version: 1.0" . "\r\n";
 $header .= "Content-type:text/html;charset=utf-8" . "\r\n";
 $header .= "From: mail@mail.com" . "\r\n";

 mail($receiver, $subject, $message, $header);
?>

On my form, I have ng-submit="submit()", and this function looks like this:
var data = "to=" + $('.user-email').val();
  $scope.url = "/email.php";
  var transform = function(data) {
    return $.param(data);
  }
  $http({
    type: "POST",
    url: $scope.url,
    data: data,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: transform
  }).success(function(responseData) {
    Console.log('Hurray')
  }).error(function(responseData) {
    console.log('error');
  });

However, when I push the submit button, I get the following error: http://cl.ly/image/1k0E2O0Q3c0B
What am I doing wrong?

A: So... The following works:
.ajax({
   type: "POST",
   url: "email.php",
   data: data,
   success: function() {
      console.log('yessør');
   }
 });

But if I use the $http.post angular method, it doesn't work - I only get this: http://cl.ly/image/2n0Z0o231l0v  --- a Request Method of 'undefined'. Why is that?

A: Is it possible that you have a typo? Angular's $http expects a method key instead of a type key.
You also have the shortcut methods ($http.post, for instance) that could prevent you from making this kind of error.


text:
Q: How do you suppress errors to a method call in C#? I'm looking for an "elegant" way to suppress exceptions when calling a method.
I think the following code is way too verbose:
try
{ CallToMethodThatMayFail(3); }
catch {}

Is there some syntactic sugar I can use to say "I don't really care if this method fails"? I want to call the method and continue execution regardless of what happens with the method.

A: Nope this is it.
And it's a good thing it's verbose. If you're suppressing a possible exception you better have a very good reason. The verbosity will help you or the next person who looks at the code in a few months.

A: Using Castle, you could do something like this:
public class ExceptionSuppressionInterceptor : Castle.Core.Interceptor.IInterceptor
{
   public void Intercept(IInvocation invocation)
   {
       try {
           invocation.Proceed();
       }
       catch (Exception ex) {
            // Suppressed!
       }
   }
}

And decorate the class you want to suppress exceptions for like this:
[Interceptor(typeof(ExceptionSuppressionInterceptor))]
public class GoodPracticeBreaker {

}

But you really probably shouldn't.

A: It is rarely a good idea to ignore/swallow errors...
To allow re-use, the only option you have is something like a method that takes an Action:
 static void IgnoreErrors(Action action) {try {action();} catch {}}

But you haven't exactly saved much by the time you've done:
SomeHelper.IgnoreErrors(() => CallToMethodThatMayFail(3));

I'd just leave the try/catch in place...

Re the question in the comment:
static void IgnoreErrors<T>(Action action) where T : Exception
{
    try { action(); } catch (T) {}
}

SomeHelper.IgnoreErrors<ParseException>(() => CallToMethodThatMayFail(3));

but I would still find it clearer to have the try/catch locally...

A: I don't know of anything more terse.  I suppose you could do some AOP or similar for something more fancy.

A: The .Net convention is that classes implement a TryCallMayFail() method and a CallMayFail() method and the caller chooses which one to uses but the TryCallMayFail() method would include exactly what you have there.

A: No, there's no better way to do this, and there's a good reason for it. The exception you see may mean more than "the method failed". It may mean, "the system is failing".
You probably should at least log the fact of the failure, in case it turned out to be important after all.

A: Why do you say this is too verbose?  If you are trying to save keystrokes, you can just use a code snippet.  If you are concerned about readability, then I think that an AOP method would be less clear to another maintainer (at least initially) and for me, this outweighs the verbosity.


text:
Q: In Matlab, How to divide multivariate Gaussian distributions to separate Gaussians? I have an image with multivariate Gaussian distribution in histogram. I want to segment the image to two regions so that they both can follow the normal distribution like the red and blue curves shows in histogram. I know Gaussian mixture model potentially works for that. I tried to use fitgmdist function and then clustering the two parts but still not work well. Any suggestion will be appreciated.

Below is the Matlab code for my appraoch.
% Read Image
I = imread('demo.png');
I = rgb2gray(I);
data = I(:);

% Fit a gaussian mixture model
obj = fitgmdist(data,2);
idx = cluster(obj,data);
cluster1 = data(idx == 1,:);
cluster2 = data(idx == 2,:);

% Display Histogram
histogram(cluster1)
histogram(cluster2)

A: Your solution is correct
The way you are displaying your histogram poorly represents the detected distributions.

*

*Normalize the bin sizes because histogram is a frequency count

*Make the axes limits consistent (or plot on same axis)

These two small changes show that you're actually getting a pretty good distribution fit.
histogram(cluster1,0:.01:1); hold on;
histogram(cluster2,0:.01:1);

Re-fit a gaussian-curve to each cluster
Once you have your clusters if you treat them as independent distributions, you can smooth the tails where the two distributions merge.
gcluster1 = fitdist(cluster1,'Normal');
gcluster2 = fitdist(cluster2,'Normal');

x_values = 0:.01:1;
y1 = pdf(gcluster1,x_values);
y2 = pdf(gcluster2,x_values);
plot(x_values,y1);hold on;
plot(x_values,y2);

A: How are you trying to use this 'model'? If the data is constant, then why dont you measure, the mean/variances for the two gaussians seperately?
And if you are trying to generate new values from this mixed distribution, then you can look into a mixture model with weights given to each of the above distributions.


text:
Q: How to connect to Amazon MQ Broker with Mosquitto MQTT Client I created a single instance broker with Amazon MQ, and were able to subscribe to the broker with just username and password using Eclipse Paho MQTT Client.
The code:
//sample endpoint from Amazon MQ
final String WIRE_LEVEL_ENDPOINT = "ssl://b-1234a5b6-78cd-901e-2fgh-3i45j6k178l9-1.mq.us-east-2.amazonaws.com:8883";
final String ACTIVE_MQ_USERNAME = "user";
final String ACTIVE_MQ_PASSWORD = "password";

// Specify the topic name and the message text.
final String topic = "whatever";
final String text = "Hello from Amazon MQ!";

// Create the MQTT client and specify the connection options.
final String clientId = "abc123";
final MqttClient client = new MqttClient(WIRE_LEVEL_ENDPOINT, clientId);
final MqttConnectOptions connOpts = new MqttConnectOptions();

// Pass the username and password.
connOpts.setUserName(ACTIVE_MQ_USERNAME);
connOpts.setPassword(ACTIVE_MQ_PASSWORD.toCharArray());

// Create a session and subscribe to a topic filter.
client.connect(connOpts);
client.setCallback(this);
client.subscribe(topic);

// Create a message.
final MqttMessage message = new MqttMessage(text.getBytes());

// Publish the message to a topic.
client.publish(topic, message);
System.out.println("Published message.");

// Wait for the message to be received.
Thread.sleep(3000L);

// Clean up the connection.
client.disconnect();

Running the code above shows that I am able to subscribe to the topic and also receive the message that I've sent.
However, doing the same with mosquitto_sub client, it gives me protocol error:
mosquitto_sub -h host -p 8883 -u user -P password -t whatever -i abc123

error:

Error: A network protocol error occurred when communicating with the
  broker.

And I searched on how to make connection to MQTT Broker with SSL. I found out that I need to set a certificate for the client.

But how come in java it worked without any certificate set???

A: Because to enable SSL support with mosquitto_sub you have to pass either --cafile or --capath. Without them the app will not even try to create a secure connection.
It works in java because it has access to the list of public CA certs to check the brokers cert against. mosquitto_sub doesn't have that list so you need to pass it a cert to validate against.


text:
Q: Add the ability to reply to a chat message directly from the transcript Notifications of new messages in chat land in the global inbox and the links take you to the chat transcript. This is fine, but a lot of my chat communication involves asking other moderators questions, so I often get replies long after I'm gone from chat.
I usually want to respond to what they told me or answer one of their questions and there isn't a way to easily do that from the transcript since responding to a specific message involves looking up its ID in the permalink, clicking the "join this room" button and then pasting the chat message ID in the text box.
I think this could be simplified by adding the reply arrow to transcript messages. Clicking it would make the user join the chat room and prepopulate the chat message ID they're replying to in the chat box, as if the arrow had been clicked from within the room.

A: This makes a lot of sense, so to prevent more people from spending precious meta rep on bounties here, it's now implemented. The transcript doesn't have the "quick action" icons on messages, so you'll have to go through the popup menu:

– but other than that, it does exactly what you suggested.

A: I have no way of influencing this request whatsoever, so here you go:


text:
Q: How to find a number of integral solutions (all $x$) If $A$ is between $[1..9000]$
$$A*X = 1 \pmod{9000}$$
All parameters are integers.
I have found some solutions:
$$A = 6907, X = 43,$$
$$A = 7111, X = 991$$
But I don't know how to find all $x$.
I want to know how many of them exist.

A: By Euler`s Theorem, if $\gcd(X, A) = 1$, $X \equiv A^{\phi(9000) - 1} \pmod {9000}$, then $XA \equiv 1 \pmod {9000}$, were $\phi(n)$ is the Euler Totient Function.
Therefore the answer is as long as $A$ is coprime to $9000$, $X$ exists. Therefore there are $\phi(9000)$ number of $A$, or $2400$ of them.
Not the best answer, but it is short.


text:
Q: Не работают медиа запросы без !important Использую отдельный файл media.sass для написания медиа-запросов. Но ничего не работает без !important. Как только его прописываю для каждого параметра, всё начинает работать чётко, по разрешениям. Без него — пусто, основные стили перебиваются. В чём проблема?
@media only screen and (max-width: 1200px)
.call
    ul
        li
            span
                font-size: em(15px)
        li:last-child
            padding-left: 10px
            padding-top: 14px
.prem
    h3
        font-size: em(15px)

A: В том, что ты не в том порядке подключаешь файлы. Надо сначала обычный, а потом media.


text:
Q: Parameter is not valid when draw text in label with custom font I have label with custom font and timer which change value in label. My app start minimzed. When I displaying the app sometimes exception is displayed and insted of text in label is red cross.
here I try call async method for label text change
private void timer1_Tick(object sender, EventArgs e)
    {
        // create a delegate of MethodInvoker poiting to showTime function.
        MethodInvoker simpleDelegate = new MethodInvoker(showTime);
        // Calling showTime Async
        simpleDelegate.BeginInvoke(null, null);
    }

font loading
public Form1()
    {
        InitializeComponent();

        SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //event handler for windows lock

        File.WriteAllBytes(appPath + "\\font.ttf", Resources.font); //copy font from resources

        try
        {
            PrivateFontCollection pfc = new PrivateFontCollection();
            pfc.AddFontFile(appPath + @"/font.ttf");
            label1.Font = new Font(pfc.Families[0], 11, FontStyle.Bold);
        }
        catch
        {
            MessageBox.Show("Failed to load nice font." + "\r\n" + "Using standart font instead.", "Time app", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

    }

here is method for label tet change
private void showTime()
    {
        label1.Text = time.ToString();
    }

***** Exception Text *******
System.ArgumentException: Parameter is not valid.
at System.Drawing.FontFamily.GetName(Int32 language)
at System.Drawing.FontFamily.get_Name()
at System.Windows.Forms.Internal.WindowsFont.FromFont(Font font, WindowsFontQuality fontQuality)
at System.Windows.Forms.Internal.WindowsGraphicsCacheManager.GetWindowsFont(Font font, WindowsFontQuality fontQuality)
at System.Windows.Forms.TextRenderer.MeasureText(String text, Font font, Size proposedSize, TextFormatFlags flags)
at System.Windows.Forms.Layout.LayoutUtils.MeasureTextCache.GetUnconstrainedSize(String text, Font font, TextFormatFlags flags)
at System.Windows.Forms.Layout.LayoutUtils.MeasureTextCache.TextRequiresWordBreak(String text, Font font, Size size, TextFormatFlags flags)
at System.Windows.Forms.Label.CreateTextFormatFlags(Size constrainingSize)
at System.Windows.Forms.Label.CreateTextFormatFlags()
at System.Windows.Forms.Label.OnPaint(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Label.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Question: how get rid of this exception when Im using custom font?

A: The problem is that the PrivateFontCollection instance in the pfc variable goes out of scope, and sometimes gets collected before the control is drawn for the first time (which seems to acquire a strong reference to the instance afterwards).
Move the instance outside the method to prevent GC from collecting it:
class Form1 : Form
{
    readonly PrivateFontCollection _pfc = new PrivateFontCollection();
    public Form1()
    {
        ...

        _pfc.AddFontFile(appPath + @"/font.ttf");

        ...
    }
}

A: Here is an example that was used in another question on here. It shows what you need. https://web.archive.org/web/20141224204810/http://bobpowell.net/embedfonts.aspx


text:
Q: Pipeline design chain of responsibility pattern I'm designing a pipeline, in its simplest form: a customer applies for a loan, the request goes to the credit score service, after the credit score is calculated, it goes to the credit service with the credit score and the approval or rejection of the loan is calculated there. In this system, would the Chain of Responsibility design pattern be appropriate?The working logic of the system
I'm confused little bit

A: No. you have one Handler here only which is Credit service that decide based on score calculated from Score Service whether Customer is eligible for the loan or not.in fact i mean the Score Service is not Handler here and it just support the Credit Service (which is handler) with information to handle. But let say there are multiple Credit Services (or credit service with 3 types of loan objects which handle the request)  that may handle the loan request base on variety of the score calculated for customer. for example the bank has 3 plans of Loans

PlanA_Loan require score > 10 for $100000 PlanB_Loan require score > 7
for $20000PlanC_Loan require score > 5 for $10000

and now you have 3 handlers of A,B,C.
now we have customer who wants to know the maximum loan he can get. so the credit score service calculates the score let say 8 and call credit service and this scenario happens

*

*Plan A is not satisfied with the score and call the next

*Plan B is satisfied with the score and accept and the chain stops here.


text:
Q: Почему повторяется фон для tr внутри td? Есть такой код

            Дата
            IP адрес
            Город

           02.06.2016 11:07
           127.0.0.1

tbody > tr {
    //ширина картинки 360 пикселей на 32
    background: url(../images/bg_last_auth.png) no-repeat;
    height: 32px;
}

Вот как работает в FireFox

А вот так, работает в хроме - каждый td начинает фон с начала

Как исправить, чтобы в хроме отображалось так же, как и в FireFox?
Для td стилей особо нет, только цвета меняет...
https://jsfiddle.net/ktjzcshx/1/


text:
Q: LARAVEL 5.2 -- Integrity constraint violation: 1452 Cannot add or update a child row: -- Problema relacionar tablas Estoy intentando llenar unas tablas con la libreria faker, hasta ahora no he tenido ningún problema, puesto que eran miniproyectos y las tablas no estaban relacionadas, pero ahora, me estoy iniciando con las relaciones en laravel y me da un error que no consigo resolver.
Hay tres tables, libros users, y categoria
Este es el error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails (`laraveleloquentbasico`.`libros`, CONSTRAINT `libros_id_categoria_foreign` FOREIGN KEY (`id_categoria`) R
EFERENCES `categoria` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: ins
ert into `libros` (`titulo`, `descripcion`, `id_categoria`) values (Animi.,
 Voluptate illo ut recusandae adipisci iure atque quasi. In hic dolorum tem
pora. Quos quidem et cumque non., 1))

[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails (`laraveleloquentbasico`.`libro
s`, CONSTRAINT `libros_id_categoria_foreign` FOREIGN KEY (`id_categoria`) R
EFERENCES `categoria` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

Despues de mucho investigar sé que es culpa del campo id_categoria que tiene la clave foranea, ya que intento rellenar ese campo manualmente, y me salta ese error, lo que no sé es lo que estoy haciendo mal.
La migracion la hace bien, el problema es al usar el db:seed, siempre sale ese error.
He intentado hacer ese campo fillable en el modelo, y entonces si que no puedo rellenar ningun campo del modelo, por lo que lo he quitado.
Aqui los codigos.
Migracion para crear libros
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreandoTablaLibros extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
         Schema::create('libros',function(Blueprint $table){
           $table->increments('id');
           $table->string('titulo')->nullable();
           $table->text('descripcion')->nullable();
           $table->integer('id_categoria')->unsigned()->nullable();

           $table->SoftDeletes(); //update at
           $table->timestamps();//create at, update at

           //RELACIONES

           $table->foreign('id_categoria')
                      ->references('id')
                      ->on('categoria')
                      ->onDelete('cascade')
                      ->onUpdate('cascade');

       });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
          Schema::drop('Libros');
    }
}

MIGRACION PARA CREAR CATEGORIAS
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreandoTablaCategoria extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
       Schema::create('categoria',function(Blueprint $table){
            $table->increments('id');
            $table->string('nombrecategoria');
            $table->timestamps();

       });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('categoria');
    }
}

MIGRACION PARA CREAR USUARIOS
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nombre');
            $table->string('correo')->unique();
            $table->string('password');
            $table->enum('genero', array('f','m'));
            $table->string('bio');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

SEEDER PARA CREAR LIBROS Y USUARIOS
use Illuminate\Database\Seeder;
use Faker\Factory;

class generaDatos extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for ($i=1; $i <5 ; $i++)
        {
        \DB::table('users')->insert(
                         array(
            'nombre' => $faker->name,
            'correo' => $faker->email,
            'password' => bcrypt('1'),
            'genero' => $faker->randomElement(array('m','f')),
            'bio' => $faker->text(255),

                            ));

         \DB::table('libros')->insert(
                         array(
            'titulo' => $faker->sentence(rand(1,5)),
            'descripcion' => $faker->text(rand(6,200)),
             'id_categoria' => $faker->randomElement(array('1','2','3')),

                            ));

        }

    }

}

SEEDER PARA CATEGORIA
use Illuminate\Database\Seeder;

class CategoriaSeeder extends Seeder
{

   /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
         \DB::table('categoria')->insert(
                         array(
            'nombrecategoria' => 'PHP',
                       ));
              \DB::table('categoria')->insert(
                         array(
            'nombrecategoria' => 'HTML',
                       ));
                 \DB::table('categoria')->insert(
                         array(
            'nombrecategoria' => 'JAVASCRIPT',
                       ));
                    \DB::table('categoria')->insert(
                         array(
            'nombrecategoria' => 'CSS',
                       ));
    }
}

No pongo los modelos por que no tienen practicamente nada, pero si los necesitais los pondre
¿Alguna idea?

A: Debes ejecutar el seeder de Categorias antes de los otros dos.
El error ocurre porque intentas asignar un valor a categoria_id sin que existan dichos id en la tabla de categoría, por lo cual la relación no se puede establecer.

A: Para hacerlo todo relacionado y al mismo tiempo de la creación, puedes hacer:
Los users antes o después, no están relacionados, esos aparte cuando quieras.
Y las categorias y los libros en el mismo seeder, algo así como:
$id = DB::table('categoria')->insertGetId([...

Con esto va guardando el id al mismo tiempo que inserta, y en el mismo seeder cuando cierres categoria, abajo abres
DB::table('libros')->insert([<br>
           'id_categoria' => $id, ...

Así puedes crear en el mismo bucle "for" 100 categorias y 100 libros asociados a la vez
Espero que te sirva, no es 100% tu caso , pero sirve genial para usuarios y sus perfiles de usuarios por ejemplo.


text:
Q: file_get_contents api link two connections with session I have two api pages, api1.php and api2.php. On 1 there is set an session and on 2 this session needs to be returned.
Ofcourse there will be additional functions but my goal of this is to link those two api connections to one and eachother by using a session.
api1.php:
session_start();

$api_key = 'dfdsakdsfjdskfjdskfdsjfdfewfifjjsd';

$_SESSION['api_key'] = $api_key;
setcookie('api_key', $api_key);

api2.php:
session_start();

echo $_SESSION['api_key'];
echo $_COOKIE['api_key'];

test.php:
$url = 'http://example.com/api1.php';
$content1 = file_get_contents($url);

$url2 = 'http://example.com/api2.php';
$content2 = file_get_contents($url2);
echo $content2;

As you may have noticed, i'm visiting the page test.php to obtain a result.
But no result is being returned.
Can somebody tell me why this is not working and what may be an additional way of making all of this happen?
(Notice: the example.com are both the same site (mine))

A: You're code "links" correctly.  The problem is actually in test.php!  Instead of executing the code contained in both files, it retrieves the entire file.  If you view source you will note the PHP tags and your code. A better solution to check if this is working is to go to api1.php and api2.php separately.  With some code adjustments you could also just use the include() or require() functions.  Which would look like this:
api2.php
echo $_SESSION['api_key'] . "\n<br/>\n";
echo $_COOKIE['api_key'];

test.php
include('api1.php');
include('api2.php');

It's worth noting the using the include and require functions executes the code in api1.php and api2.php as if that code were a part of test.php.


text:
Q: Download failed at VideoColorizerColab.ipynb-Coloaboratory Here's the message I get with deatils about the fail.
Download failed
Could not fetch resource at https://colab.research.google.com/tun/m/gpu-p100-s-1nsim9mlahjyh/files/content/DeOldify/video/result/video.mp4?authuser=5: 504
FetchError: Could not fetch resource at https://colab.research.google.com/tun/m/gpu-p100-s-1nsim9mlahjyh/files/content/DeOldify/video/result/video.mp4?authuser=5: 504
    at Lz.Kz [as constructor] (https://colab.research.google.com/v2/external/external_polymer_binary.js?vrz=colab-20191219-082400-RC00_286397102:911:76)
    at new Lz (https://colab.research.google.com/v2/external/external_polymer_binary.js?vrz=colab-20191219-082400-RC00_286397102:911:293)

Since 2 days this web can only communicate with the google drive, if I make a copy of the video and share that one.  After the colorization process finished, as usual the connect with the runtime breakes and a few moments later it connects back and I can find the mp4 result in the deoldify folder. Now it all gets disappeared, so the whole session gets lost. I tried with 2 minutes video segment. Strangely also pops up a messge that failed to runtime, but after it reconnects the session will be found. What happeded, can't I use 7 or 8 minutes video segments anymore or the servers are too busy these days?  Please help me about my problem!

A: i had the same problem and after few researches i found a solution that may help.
if you're using Firefox, try to use google chrome instead.
If you're using google chrome, go in the settings, then search for "reset" (there's a search bar above), and reset google chrome.
it worked for me.