text:
Q: Please assist in the creation of a pure css slide in panel on click instead of hover I have this example.  I need this to not be on hover but on click.  I've read about the checkbox hack but when I try to apply it to this fiddle it breaks it.
I tried to add a checkbox to the page and then check if it was checked with
#checky:checked
instead of the :hover bit.
Here i tried on hover:

#slideout {
    position: fixed;
    top: 40px;
    left: 0;
    width: 35px;
    padding: 12px 0;
    text-align: center;
    background: #6DAD53;
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    -webkit-border-radius: 0 5px 5px 0;
    -moz-border-radius: 0 5px 5px 0;
    border-radius: 0 5px 5px 0;
}
#slideout_inner {
    position: fixed;
    top: 40px;
    left: -250px;
    background: #6DAD53;
    width: 200px;
    padding: 25px;
    height: 130px;
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    text-align: left;
    -webkit-border-radius: 0 0 5px 0;
    -moz-border-radius: 0 0 5px 0;
    border-radius: 0 0 5px 0;
}
#slideout_inner textarea {
    width: 190px;
    height: 100px;
    margin-bottom: 6px;
}
#slideout:hover {
    left: 250px;
}
#slideout:hover #slideout_inner {
    left: 0;
}

        <form>
            <textarea></textarea>
            <input type="submit" value="Post feedback"></input>
        </form>

Can someone out there explain how the checkbox hack works and apply it to this example?

A: If you want yo use Jquery you can try like this -

$(document).ready(function(){
    $('#slideout img').click(function(){
        $('#slideout').animate({
        'left' : $('#slideout').css('left') == '0px' ? '250px' : '0px'
        }, 200);
        $('#slideout_inner').animate({
        'left' : $('#slideout_inner').css('left') == '-250px' ? '0px' : '-250px'
        }, 200);
    });
});
#slideout {
    position: fixed;
    top: 40px;
    left: 0;
    width: 35px;
    padding: 12px 0;
    text-align: center;
    background: #6DAD53;
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    -webkit-border-radius: 0 5px 5px 0;
    -moz-border-radius: 0 5px 5px 0;
    border-radius: 0 5px 5px 0;
}
#slideout img{
  cursor:pointer
}

#slideout_inner {
    position: fixed;
    top: 40px;
    left: -250px;
    background: #6DAD53;
    width: 200px;
    padding: 25px;
    height: 130px;
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    text-align: left;
    -webkit-border-radius: 0 0 5px 0;
    -moz-border-radius: 0 0 5px 0;
    border-radius: 0 0 5px 0;
}
#slideout_inner textarea {
    width: 190px;
    height: 100px;
    margin-bottom: 6px;
}

        <form>
            <textarea></textarea>
            <input type="submit" value="Post feedback"/>
        </form>

A: You may want to use javascript or jquery for this..here is a javascript solution (Note...Clicking on the feedback image will cause the toggle)

function toggle(e){
 if(this.parentNode.style.left!='250px'){

    this.parentNode.style.left='250px'
 this.nextElementSibling.style.left='0px';
 }
  else{
    this.parentNode.style.left='0px'
    this.nextElementSibling.style.left='-250px';
  }
}
document.querySelector('#slideout img').addEventListener('click',toggle,false)
#slideout {
    position: fixed;
    top: 40px;
    left: 0;
    width: 35px;
    padding: 12px 0;
    text-align: center;
    background: #6DAD53;
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    -webkit-border-radius: 0 5px 5px 0;
    -moz-border-radius: 0 5px 5px 0;
    border-radius: 0 5px 5px 0;
}
#slideout_inner {
    position: fixed;
    top: 40px;
    left: -250px;
    background: #6DAD53;
    width: 200px;
    padding: 25px;
    height: 130px;
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    text-align: left;
    -webkit-border-radius: 0 0 5px 0;
    -moz-border-radius: 0 0 5px 0;
    border-radius: 0 0 5px 0;
}
#slideout_inner textarea {
    width: 190px;
    height: 100px;
    margin-bottom: 6px;
}
/*#slideout:hover {
    left: 250px;
} */
/*#slideout:hover #slideout_inner {
    left: 0;
}*/

        <form>
            <textarea></textarea>
            <input type="submit" value="Post feedback"></input>
        </form>

A: Here you can do with only css following way.
Use checkbox for that. And When checkbox checked slideout the div.

.main{
  position:fixed;
  top:40px;
  left:0;
}
#slideout {
    position: fixed;
    top: 40px;
    left: 0;
    width: 35px;
    padding: 12px 0;
    text-align: center;
    background: #6DAD53;
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    -webkit-border-radius: 0 5px 5px 0;
    -moz-border-radius: 0 5px 5px 0;
    border-radius: 0 5px 5px 0;
}
#slideout_inner {
    position: fixed;
    top: 40px;
    left: -250px;
    background: #6DAD53;
    width: 200px;
    padding: 25px;
    height: 130px;
    -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    text-align: left;
    -webkit-border-radius: 0 0 5px 0;
    -moz-border-radius: 0 0 5px 0;
    border-radius: 0 0 5px 0;
}
#slideout_inner textarea {
    width: 190px;
    height: 100px;
    margin-bottom: 6px;
}

#feedbackswitch:checked ~ #feedbackimg #slideout {
    left: 250px;
}

#feedbackswitch:checked ~ #feedbackimg #slideout_inner {
    left: 0;
}

<input type="checkbox" name="feedbackswitch" class="feedback-checkbox" id="feedbackswitch"  />

        <form>
            <textarea></textarea>
            <input type="submit" value="Post feedback" />
        </form>


text:
Q: Setting up a connection in Rstudio to a Oracle DB Below is my code to connect to a Oracle database
connection <- DBI::dbConnect(jdbcDriver,"jdbc:oracle:thin:@//aaaaa1111.bb.com:PORT_NUM/SID",user = 'user', password = 'password')
and i got this error
rror in .jcall(drv@jdrv, "Ljava/sql/Connection;", "connect", as.character(url)[1],  :
  java.sql.SQLRecoverableException: Listener refused the connection with the following error:
ORA-12514, TNS:listener does not currently know of service requested in connect descriptor
Any feedback would be appreciated!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Placing two figures (each having subfigures) next two each other I would like to place two figures, where each figure has subfigures next to each other.
I tried with minipage, but tex does not like the \subfigure as Not in outer par mode.
Is there any way to place figures with subfigures next to each other?
\begin{figure*}[htbp]

\begin{minipage}[hbt]{0,49\textwidth}

\begin{figure}
\subfigure[Subfigure 1.1]{
\label{fig:subfig1_1}
\includegraphics[scale=0.42]{graphs/sub_1_1.pdf}
}

\subfigure[Sub 1.2] {
\label{fig:subfig1_2}
\includegraphics[scale=0.42]{graphs/sub_1_2.pdf}
}
}
\label{fig:subfigure1}
\caption{Subfigure 1}
\end{figure}
\end{minipage}

\begin{minipage}[hbt]{0,49\textwidth}
%... as above
\end{minipage}
\end{figure*}

A: You can't put a floating object inside a minipage, but you can place minipages inside a floating object. I notice that you are using the obsolete subfigure package; you should use subfig or subcaption instead.
Below there are two approaches; the first one using the subfig package, and the other one using the subcaption package:
\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{caption}
\usepackage{subfig} % Needs subfig for this example.

\begin{document}

\begin{figure}
\begin{minipage}{.48\textwidth}
\centering
\subfloat[]{\includegraphics[width=.4\linewidth]{fig1}}\quad
\subfloat[]{\includegraphics[width=.4\linewidth]{fig2}}
\caption{First figure with two subfigures}
\label{fig:testa}
\end{minipage}\hfill
\begin{minipage}{.48\textwidth}
\centering
\subfloat[]{\includegraphics[width=.4\linewidth]{fig3}}\quad
\subfloat[]{\includegraphics[width=.4\linewidth]{fig4}}
\caption{Second figure with two subfigures}
\label{fig:testb}
\end{minipage}
\end{figure}

\end{document}

\documentclass{article}
\usepackage[demo]{graphicx}
\usepackage{caption}
\usepackage{subcaption}

\begin{document}

\begin{figure}
\begin{minipage}{.48\textwidth}
\centering
\subcaptionbox{}{\includegraphics[width=.4\linewidth]{fig1}}\quad
\subcaptionbox{}{\includegraphics[width=.4\linewidth]{fig2}}
\caption{First figure with two subfigures}
\label{fig:testa}
\end{minipage}\hfill
\begin{minipage}{.48\textwidth}
\centering
\subcaptionbox{}{\includegraphics[width=.4\linewidth]{fig3}}\quad
\subcaptionbox{}{\includegraphics[width=.4\linewidth]{fig4}}
\caption{Second figure with two subfigures}
\label{fig:testb}
\end{minipage}
\end{figure}

\end{document}

The demo option for graphicx simply replaces actual figures with black rectangles; do not use that option in your actual document.

A: Since figure is a floating object and minipages are not, you can't use figures inside minipages. One method is to avoid using figure and use the captionof from caption/subcation (or capt-of) package.
Code:
\documentclass[a4paper]{article}
\usepackage{graphicx}
\usepackage{subcaption}

\begin{document}
\noindent
\begin{minipage}[t]{0.49\linewidth}%
\begin{minipage}[t]{0.49\textwidth}%
\includegraphics[width=\textwidth]{example-image-a}%
\captionof{subfigure}{sub figure - 1}
\end{minipage}%
\hfill
\begin{minipage}[t]{0.49\textwidth}%
\includegraphics[width=\linewidth]{example-image-b}
\captionof{subfigure}{sub figure - 2}
\end{minipage}
\captionof{figure}{figure one}
\end{minipage}%
\setcounter{subfigure}{0}
\hfill
\begin{minipage}[t]{0.49\linewidth}%
\begin{minipage}[t]{0.49\textwidth}%
\includegraphics[width=\textwidth]{example-image-c}%
\captionof{subfigure}{sub figure - 1}
\end{minipage}%
\hfill
\begin{minipage}[t]{0.49\textwidth}%
\includegraphics[width=\linewidth]{example-image}
\captionof{subfigure}{sub figure - 2}
\end{minipage}
\captionof{figure}{figure two}
\end{minipage}%

\end{document}


text:
Q: for each not updating variables When using the AS3 for each construct I find that I can't update the members of the array that im iterating.
for each( obj:Object in array ){
    obj = new Object();
}

when I loop over the array again they will still have the same values as before the loop.
Am I stuck with using tradition for-loops in this situation or is there a way to make the updates stick.

A: As Daniel indicated, you are instantiating a new object to the obj reference instead of the array element.  Instead, access the array by ordinal:
var array:Array = [{}, {}, {}];

for (var i:uint = 0; i < array.length; i++)
{
    array[i] = {};
}


text:
Q: avoid redundant conditional statements Using the following code, assume I have 5 different types that I might receive in the variable type. Instead of writing 5 conditional statements, is there a way to write one and use the variable "type" to dictate what the model is, in this case "CommentVote?" Or is this more a deficiency in the way I've designed the data model with each of those 5 things having a "vote" model?
 if (type == "comment")
 {
      CommentVote voteObj = db.CommentVotes
           .Where(x => x.UserID == UserID && x.CommentID == id)
           .SingleOrDefault();
      if (voteObj != null)
      {
          voteObj.Vote = vote;
          db.SaveChanges();
      }
      else
      {
          CommentVote c = new CommentVote {
               CommentID = id, UserID = UserID, Vote = vote, DateCreated = DateTime.Now
          };
          db.CommentVotes.Add(c);
          db.SaveChanges();
      }

      count = (db.CommentVotes.Count(x => x.CommentID == id && x.Vote == true) - db.CommentVotes.Count(x => x.CommentID == id && x.Vote == false));
 }

Magic Code: The stuff I would love to be able to do.
 var modelName = "";
 var modelOtherName = "";
 if (type == "comment") {
      modelName = CommentVote;
      modelOtherName = CommentVotes;
 }

      modelName voteObj = db.modelOtherName
           .Where(x => x.UserID == UserID && x.CommentID == id)
           .SingleOrDefault();

Update: I'm beginning to think my model may be crap based on some of the reading referenced bellow. So I am including some of that as a reference. Let me know if that's the problem I should be trying to solve.
 public class CommentVote
 {
    public int CommentVoteID { get; set; }
    public bool Vote { get; set; }
    public DateTime DateCreated { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; }

    public int CommentID { get; set; }  //This row changes from model to model
    public virtual Comment Comment { get; set; }  //This row changes from model to model
 }

I have a handful of models that are almost identical.

A: As I understand you question, it more database architecture-related.
If those kind of votes are not very different from each other (in terms of properties) I woldn't use different tables for them. Instead create one Vote table with Type column and (as in the example you provided) nullable column for CommentID.
Then you can use class inheritance to reflect your votes (Vote base class and CommentedVote child class).
Table Per Hierarchy Inheritance in Entity Framework
Update:
Best is not to repeat the same propertieses in all classes. You just use inharitence like this:
 public abstract class Vote
 {
    public int VoteID { get; set; }
    public bool isVote { get; set; }
    public DateTime DateCreated { get; set; }
    public int UserID { get; set; }
    public virtual User User { get; set; }

    public int VoteType { get; set;} //this property specifies type of vote (e.g. VoteType=1 for CommentedVote )
 }
 public class CommentVote : Vote
 {
    public int CommentID { get; set; }
    public virtual Comment Comment { get; set; }
 }
 public class OtherVote : Vote
 {
    public int OtherID { get; set; }
    public virtual Other Other { get; set; }
 }

In this very good blog post you can find all possible approches. The one I'm writing about is called Table per Hierarchy (TPH).

A: You can absolutely reduce the code to a single statement assuming that you perform the same actions and set the same data. In this case, you should have an interface that contains the common actions and data and an object factory to instantiate the correct object based on the type.

A: You could do it if you implement the Factory pattern with reflection, a very basic example is shown here.
In a nutshell what you do is this: Since you have 5 different types that it could be, you would make 5 different classes that each implement a specific interface. You then create the factory class to use reflection to grab the class that is the most appropriate for your situation (be it with a straight-up class name, like in the example, or with an Attribute over the class, such as here). The factory returns an instance of that interface, which you would then just invoke the exposed method from the interface to do all of this for you.
The best part of this is that if you ever need to make another type, all you'd have to do is add another class with that attribute/name that you would be searching for in the factory. None of your other code would need to be affected, thus making you compliant with the Open/Closed Principle.


text:
Q: Is it possible to get the Hwnd of a WPF Popup control? I need to apply an Aero background blur to only part of a custom-shaped WPF window. The problem is that to apply the blur with DWM, I need to provide a window handle to the DwmEnableBlurBehindWindow function.
I have been told that the WPF popup control is actually a separate window. That is good. Can I get a popup's handle to apply blur to it? If so, how?

A: Try this:
<Popup Name="MyPop" IsOpen="True" Height="50" Width="50">
    <!--or other control-->
    <Rectangle/>
</Popup>

// only after MyPop.IsOpen is true
IntPtr handle =  ((HwndSource)PresentationSource.FromVisual(MyPop.Child)).Handle;

A: Try this
HwndSource source = (HwndSource)HwndSource.FromVisual(myPopup)

or this but this one only works for actual Windows, but might help for future references.
IntPtr handle = new WindowInteropHelper(myWindow).Handle;

A: Does it have a custom class name? If so, you can Find the window handle via class name (FindWindow).
I'm a bit of a hacker-type when it comes to this stuff in Windows, so that's what I usually try first, rather than trying to discover a "proper" method. All old stuff for me, though, I don't do much of this anymore - see blackbeltvb.com
Two other ways I've done this is 1) to hook the windows creation messages, watch for that pop up window, then do something to it (SetWindowsHookEx) and 2) enumerate all the window handles being used, then watch for the new one.


text:
Q: How to add mnesia node to existing cluster I have mnesia installed on a node a.
I have already defined a schema and a table.
Now i do not know how can i add another node b so that mnesia now can run distributed.
By distributed i mean :

*

*issue a insert of a record in mnesia from node a

*be able to fetch the record when querying mnesia of node b
What i have tried:

*

*Start node a and start mnesia

*create_schema and create_table on node a

*dirty_insert in node a
Then

*

*Start node b

*connect node b to node a

*from node a issue : mnesia:change_config(extra_db_nodes,[nodes()]). // doesnt matter if i issue this command from node a or node b i get the following error :

(a@DESKTOP-GOMS8S8)7> mnesia:change_config(extra_db_nodes,[nodes()]).
=ERROR REPORT==== 3-Jul-2021::13:33:16.147000 === Error in process <0.138.0> on node 'a@DESKTOP-GOMS8S8' with exit value:
{function_clause,
[{gen_server,do_abcast,
[[['b@DESKTOP-GOMS8S8']],
mnesia_controller,
{'$gen_cast',{merging_schema,'a@DESKTOP-GOMS8S8'}}],
[{file,"gen_server.erl"},{line,263}]},
{mnesia_controller,connect_nodes2,3,
[{file,"mnesia_controller.erl"},{line,486}]}]}
** exception exit: function_clause
in function  gen_server:do_abcast/3
called as gen_server:do_abcast([['b@DESKTOP-GOMS8S8']],
mnesia_controller,
{'$gen_cast',
{merging_schema,'a@DESKTOP-GOMS8S8'}})
in call from mnesia_controller:connect_nodes2/3 (mnesia_controller.erl, line 486)

I just want any operation i do upon mnesia of a given node to be reflected on the others

A: nodes() already returns a list, so there is no need to wrap the return value in a list.  Try this:
mnesia:change_config(extra_db_nodes,nodes()).


text:
Q: mocha js with react js I am trying to write test scripts using mocha js for my react code. The test helper file is like this
browser.js
var baseDOM = '<!DOCTYPE html><meta charset="utf-8">';
var jsdom = require('jsdom').jsdom;
global.document = jsdom(baseDOM);
global.window   = document.defaultView;
if ( global.self != null) {
  console.log(' global.self >>>>> ' + global.self);
} else {
  global.self = global.this;
}
global.navigator = {
  userAgent: 'node.js'
};

The test script is like this (component.specs.js)
'use strict';
import ReactDOM from 'react-dom';
import React from 'react';
import { expect } from 'chai';
import { mount, shallow, render } from 'enzyme';
import { App } from '../../js/app.js';
import sinon from 'sinon';
var dispatch = function() {
`enter code here`   console.log('>>>>>>>> Mocking dispatch ');
};

describe('App', function () {
it('App calls check', () => {
     sinon.spy(App.prototype, 'check');
     const enzymeWrapper = mount(<App {...props} />);
     expect(App.prototype.check.calledOnce).to.equal(true);
   });

So, when I run npm test, I get the error as 'jsdom is not a function'. What is wrong with the code?

A: I'm not familiar with jsdom but based on the examples I don't think you're using it correctly. jsdom's example code:
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);

What this means for you is that var jsdom = require('jsdom').jsdom; should be var jsdom = require('jsdom').JSDOM;. The example also uses new.
That said, you may want to check out jest for testing node/react - it's very easy to setup and works well.


text:
Q: What format do I use with moment to give me same string as `new Date()`? I'm using moment() and want to know if there's a shortcut to give me the same date string as new Date() would give me.
I have to do some timezone conversions so using moment.js makes that easier, but I need the same date format: Thu Oct 06 2016 23:08:53 GMT-0700 (PDT) as the native Date object would give me.
I would assume there is a shortcut for this, but I can't find it.
moment.tz('America/New_York').format('???')

A: I could not find a shortcut however this gives the string I need:
moment.tz('America/New_York').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ (z)')

from the docs: http://momentjs.com/docs/#/displaying/
Returns: Fri Oct 07 2016 02:25:17 GMT-0400 (EDT)

A: if you have no idea which timezone the browser is currently in, you can try moment.tz.guess(), it isn't 100% correct for timezone offset that has multiple names though:
var d = moment()._d;
d.toString().replace(/\([\w ]+\)$/, moment.tz(d, moment.tz.guess()).format('(z)'));

A: The date format you're referring to, depends on the culture/language of your browser. That aside, if you want the same format as the standard new Date().toString() returns, you just use the toString() method on the moment object, without any arguments:
moment().toString();

Source: http://momentjs.com/docs/#/displaying/as-string/


text:
Q: register custom Windows 10 callto: uri handler I'm trying to register a custom callto: uri handler in Windows 10.
I've followed this instructions:
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\callto]
@="URL:callto"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\callto\shell]

[HKEY_CLASSES_ROOT\callto\shell\open]

[HKEY_CLASSES_ROOT\callto\shell\open\command]
@="\"C:\\Users\\Michael\\AppData\\Roaming\\someFolder\\some.exe\" \"%1%\""

It works like a charm under Windows 7, but refuses to work under Window 10.
If I click a callto link in any browser, Windows asks me to choose an application to open the link.
Any hints are welcome.
peggel


text:
Q: Why python script loop is not fetching updated data from DB? I've two Python script. Both of them uses PYMYSQL to read / write data on a table of MySQL DB.
Script 1: It runs in a infinite while loop and fetches data from outside API in every second and updates the same to the table of MySQL DB via UPDATE SQL Query. It's working completely fine. I can see on DB level that data is getting updated every second.
Script 2: It runs in a infinite while loop and fetches data from above mentioned table of MySQL DB and prints it via SELECT SQL Query. While I run it first time, it fetches correct / updated / latest data from DB, but after that when it iterates on the while loop, it fetches the same data which it fetched at the first time of starting and does not fetch the updated data. But it should fetch the updated data as Script 1 is continuously updating the data on DB every second. But if I stop the script and restarts then it shows the updated data.
I just want to know the reason or fix for same. It seems that when DB connection is getting restarted for Script 2 when I restart the script, it fetches the latest data.
Kindly help on same.

A: I have found the fix. Any of below can be applied.

*

*Adding autocommit=True into the connect() parameters.

*Calling conn.commit() after the cursor.execute() command.

It's repeatable read as mentioned here: https://dev.mysql.com/doc/refman/8.0/en/glossary.html#glos_consistent_read


text:
Q: NullReferenceException on code that should work I have the following controller Action:
public ActionResult Details(int id)
        {
            Seguimiento seguimiento = repo.GetSeguimiento(id);

            if (seguimiento == null)
            {
                return View("NotFound");
            }
            else
            {
                return View("Details", seguimiento);
            }
        }

And in the details view:
<fieldset>
        <legend>Informacion General</legend>

ID: <%: Model.ID %>

Materia: <%: Model.Materia.Nombre %>

Docente: <%: Model.Materia.Docente.Nombre %>

    </fieldset>

    <fieldset>
        <legend>Informacion Tiempo</legend>

Fecha: <%: String.Format("{0:g}", Model.Dia) %>

Hora: <%: String.Format("{0:g}", Model.Hora) %>

Evaluador: <%: Model.Evaluador.Nombre %>

    </fieldset>

    <fieldset>
        <legend>Desarrollo</legend>

Objetivo: <%: Model.Desarrollo.Dominio %> |

Objetivo: <%: Model.Desarrollo.Contenido %> |

Objetivo: <%: Model.Desarrollo.Organizacion %> |

    </fieldset>

The first two fieldsets work; the last one doesn't.
Dominio, Contenido, Organizacion are bit type is the database, so maybe that's a factor?

A: It is probably the case that Model.Desarrollo (or Model.Materia or Model.Evaluador) is null, not Dominio etc.

A: This should be pretty easy to figure out.  Put a break point in the method and check if the property Desarollo is null.  If so, you'll need to modify your view code to account for this (or fix the reason why it is null when it shouldn't be).


text:
Q: Concating two arrays into one I am looking to combine these two arrays into a single one.  I want any id information that is the same to be filtered so that it only appears once, making it a simple list of name, age, occupation, and address.
I have tried simply concating the info, using splice, using filter... but I just cant seem to get the right answer.
var a = [{
  id: 'aBcDeFgH',
  firstName: 'Juan',
  lastName: 'Doe',
  age: 32
 },
{
  id: 'zYxWvUt',
  firstName: 'Alex',
  lastName: 'Smith',
  age: 24
}]

var b = [{
  id: 'aBcDeFgH',
  occupation: 'architect',
  address: {
    street: '123 Main St',
    city: 'CityTown',
    Country: 'USA'
  }
},
{
  id: 'zYxWvUt',
  occupation: 'receptionist',
  address: {
    street: '555 Ocean Ave',
    city: 'Beach City',
    Country: 'USA'
  }
}]

I always end up with a single list after the concat, but I cant find out how to filter the same info.

A: You can make an object from first array a whole keys will be id of each object. Then use map() on b and return object having all props.

var a = [{
  id: 'aBcDeFgH',
  firstName: 'Juan',
  lastName: 'Doe',
  age: 32
 },
{
  id: 'zYxWvUt',
  firstName: 'Alex',
  lastName: 'Smith',
  age: 24
}]

var b = [{
  id: 'aBcDeFgH',
  occupation: 'architect',
  address: {
    street: '123 Main St',
    city: 'CityTown',
    Country: 'USA'
  }
},
{
  id: 'zYxWvUt',
  occupation: 'receptionist',
  address: {
    street: '555 Ocean Ave',
    city: 'Beach City',
    Country: 'USA'
  }
}]

let obj = a.reduce((ac,a) => (ac[a.id] = a,ac),{});
let res = b.map(x => ({...x,...obj[x.id]}));
console.log(res)

A: Sounds like you need to merge each item of each array together - and that they're both in the same order, in which case you could do:
const newList = []

a.forEach((item, index) => {
  newList.push({
    ...item,
    ...b[index]
  })
})

console.log(newList)

A: The following will reconstruct the array in the same order as a but the function doesn't depend on b being in the same order.

var a = [{id:"aBcDeFgH",firstName:"Juan",lastName:"Doe",age:32},{id:"zYxWvUt",firstName:"Alex",lastName:"Smith",age:24}],
    b = [{id:"aBcDeFgH",occupation:"architect",address:{street:"123 Main St",city:"CityTown",Country:"USA"}},{id:"zYxWvUt",occupation:"receptionist",address:{street:"555 Ocean Ave",city:"Beach City",Country:"USA"}}];

let res = a.reduce((a,c) => {a.push({...c, ...b.find(v => v.id == c.id)}); return a;},[])

console.log(res)

And as a more performant solution, that instead of using find for every look-up uses a map-like object for our second array so we just have to insert from it for our result via O(1) look-ups.
So instead of O(n²) we now have O(n):

var a = [{id:"aBcDeFgH",firstName:"Juan",lastName:"Doe",age:32},{id:"zYxWvUt",firstName:"Alex",lastName:"Smith",age:24}],
    b = [{id:"aBcDeFgH",occupation:"architect",address:{street:"123 Main St",city:"CityTown",Country:"USA"}},{id:"zYxWvUt",occupation:"receptionist",address:{street:"555 Ocean Ave",city:"Beach City",Country:"USA"}}];

let tmp = b.reduce((a,c) => {a[c.id] = c; return a},{}),
    res = a.reduce((a,c) => {a.push({...c, ...tmp[c.id]}); return a;},[]);

console.log(res)

A: If the id is the key to compare,
const concatListById = (base, target) => base.reduce((acc, c) => {
    const matched = target.find(e => e.id === c.id);
    let el = c;
    if (matched) el = { ...matched, ...c };
    acc.push(el);
    return acc;
}, []);

console.log(concatListById(a, b));

If there is an assumption that id sequence of each array is the same,
const justMergeArray = (base, target) =>
  base.map((e, idx) => ({ ...e, ...target[idx] }));

console.log(justMergeArray(a, b));

A: You can use reduce and compare if id match just push into same object and add this to an array

var a = [{
    id: 'aBcDeFgH',
    firstName: 'Juan',
    lastName: 'Doe',
    age: 32
  },
  {
    id: 'zYxWvUt',
    firstName: 'Alex',
    lastName: 'Smith',
    age: 24
  }
]

var b = [{
    id: 'aBcDeFgH',
    occupation: 'architect',
    address: {
      street: '123 Main St',
      city: 'CityTown',
      Country: 'USA'
    }
  },
  {
    id: 'zYxWvUt',
    occupation: 'receptionist',
    address: {
      street: '555 Ocean Ave',
      city: 'Beach City',
      Country: 'USA'
    }
  }
]

const res = a.reduce((all, acc, index) => {
  if (acc.id === b[index].id) {
    all.push({
      ...acc,
      ...b[index]
    });
  }
  return all;
}, []);

console.log(res);

A: Try this:

 var a = [{
  id: 'aBcDeFgH',
  firstName: 'Juan',
  lastName: 'Doe',
  age: 32
 },
{
  id: 'zYxWvUt',
  firstName: 'Alex',
  lastName: 'Smith',
  age: 24
}]

var b = [{
  id: 'aBcDeFgH',
  occupation: 'architect',
  address: {
    street: '123 Main St',
    city: 'CityTown',
    Country: 'USA'
  }
},
{
  id: 'zYxWvUt',
  occupation: 'receptionist',
  address: {
    street: '555 Ocean Ave',
    city: 'Beach City',
    Country: 'USA'
  }
}];

const newA =   a.reduce((acc, ele) => (acc[ele.id] = ele, ele),{});
const result  = b.map(ele=> ({...newA[ele.id],...ele}));

console.log(result);


text:
Q: netbeans gradle, deploy to Wildfly quite a simple question, but i cannot find a solution:
I imported a gradle Project into netbeans from eclipse, which worked seamlessly, even though i had to fight eclipse itself to barely be able to build it there.
The sole Problem left, keeping me from moving on to netbeans is, i want to be able to deploy the resulting .ear to a wildfly-applicationserver and be able to debug the application.
As netbeans does see the project as a gradle project, it does not offer me the options in the contextmenus to deploy to the configured wildfly, that i can already run and stop from netbeans.
In eclipse i could deploy the ear to a local wildfly in debug-mode and attach the sources off all subprojects (ejb.jar, ...) for eclipse to find while debugging.
How can i configure netbeans to do this?


text:
Q: iFrame Best Practices I have a large, hi-def JavaScript-intensive image banner for a site I'm designing.  What is everyone's opinion of using iframes so that you incur the load time only once?  Is there a CSS alternative to the iframe?
Feel free to preview the site.
It is very much a work in progress.

A:
I should also have mentioned that I would like the banner rotation to keep moving. When the visitor clicks on a link, the banner rotation starts over. It would be nice if the "animation" kept rotating, regardless of the page the user visits.Blockquote

Well, in that case I would strongly recommend not doing that. The only real way of achieving that is to have the actual website content in the iframe, which means that you suddenly have lots of negative sides to the site: not being able to bookmark urls easily due to the address bar not changing; accessibility concerns; etc
I think you'll find that most people won't care that it reloads again. Once a visitor lands on your website, they'll marvel at the wonderful banner immediately, and then will continue to ignore it while they browse your site - until an image they haven't seen appears and distracts them away from your content.
Keep the rotation random enough, and with enough images, and people will stop to look at it from whatever page they're on.

A: I find the main challenge with iFrame headers is resizing.  Since the font in your header is of static size, I don't see a problem with using an iFrame.  Although I'm not sure if it's really intensive enough to be worth it.

A: Well, the browser appears to cache all seven banner images upon the first load, and runs them out from the cache (for each subsequent page) thereafter. I don't think you have a problem :D
Try it out with Firebug's Net monitoring tool in Firefox.

A: While using IFrames as a sort of master page/template for your pages might be a good thing, IFrames have a known negative impact to searchability/SEO.
It might also be unnecessary in the first place because once your images are loaded the first time (and with the large high-def images you have on your site, that would be slow no matter what you do) the images are cached by browsers and will not be reloaded until the user clears their cache or does a Ctrl+F5.

A: This may work without CSS also, but if you use CSS to load the background and your server is configured correctly, the image should already only be downloaded once.
Usually the browser will request a resource by asking for it only if it has not been modified since the last time it was downloaded. In this case, the only things sent back and forth are the HTTP headers, no content.
If you want to ensure the image is only downloaded once, add an .htacces or an apache2.conf rule to make the image expire a few days into the future so that users will only request it again if their cache is cleared or the content expiration date passes. An .htaccess file is probably too excessive to use in your case, though results may vary.

A: You could have it load the main page once, then asynchronously load the other elements when needed (ajax).  If you did that, an iFrame would not be necessary.  Here is an example of loading only the new material.


text:
Q: Cannot find an answer to fix issue with Websocket connection closing Struggling with one issue on a simple Websockets example using node
I originally used this Websocket/node tutorial as a starting-point. This is my first attempt, so I knew almost nothing when I started.
"Connection closed before… handshake" is a very common issue, to which there seems to be no definitive answer. From the many SO questions I've spent a day trying answers and suggested code, to no effect, including checking my proxy and allowing localhost (no joy).
Here's my code, including an (incomplete) front-end (I used npm install websocket in my local dir, not using socket.io, and although I'm willing to try I'd rather get this working first):
server.js
"use strict";

let http = require('http');
let fs = require('fs');

let server = http.createServer(function(request, response) {});
const PORT=8080;

fs.readFile('client/index.html', function (err, html) {
  if (err) throw err;
  http.createServer(function(request, response) {
    response.writeHeader(200, {"Content-Type": "text/html"});
    response.write(html);
    response.end();
    console.log(`${(new Date())} Server is listening on port ${PORT}`);
  }).listen(PORT);
});

let WebSocketServer = require('websocket').server;

let wsServer = new WebSocketServer({
  httpServer: server
});

wsServer.on('request', function(r){
  // runs on connection
  let connection = r.accept('echo-protocol', r.origin);
  let count = 0;
  let clients = {};
  // Specific id for this client & increment count
  let id = count++;
  // Stores the connection method for looping through & contacting all clients
  clients[id] = connection;

  console.log(`${(new Date())} Connection accepted [${id}]`);
  connection.on('message', function(message) {

    // The string message sent to us
    let msgString = message.utf8Data;

    // Loops through all clients
    for(let i in clients){
      // Sends a message to the client with the message
      clients[i].sendUTF(msgString);
    }
  });
  connection.on('close', function(reasonCode, description) {
    delete clients[id];
    console.log(`${(new Date())} Peer ${connection.remoteAddress} disconnected.`);
  });
});

index.html

Hello Web Sockets

  <input type="text" id="message">
  <input type="button" value="Send" onclick="sendMessage()">


text:
Q: How to detect universal reference parameter type with std::is_same Have a look at these lines:
template <typename T>
void f(T&& param) {
    if (std::is_same<T, int>::value) {
        cout << "param is an int" << endl;
    } else {
        cout << "param is not an int" << endl;
    }
    if (std::is_same<T, int&>::value) {
        cout << "param is an lvalue reference to int" << endl;
    }
    if (std::is_same<T, int&&>::value) {
        cout << "param is an rvalue reference to int" << endl;
    }
}
int main() {
    int i = 0;
    f(i);
    f(std::move(i));
    return 0;
}

The first function call f(i) yields:
param is not an int

param is an lvalue reference to int

which is what I expected, because as per the template argument deduction rules, T resolves to T&, resulting in T&& & which yields T& because of reference collapsing.
The second funtion call f(std::move(i)) yields
param is an int

which is not what I expected. I'd have expected

param is an rvalue reference to int

or at least

param is not an int

Can someone explain why my expectations regarding the second function call are not met  ?

A: try this one:
#include <iostream>
#include <utility>
using namespace std;

template <typename T>
void f(T&& param) {
    using raw_type = std::remove_reference_t<T>;
    if (std::is_same<decltype(param), raw_type>::value) {
        cout << "param is an int" << endl;
    }
    else {
        cout << "param is not an int" << endl;
    }
    if (std::is_same<decltype(param), raw_type&>::value) {
        cout << "param is an lvalue reference to int" << endl;
    }
    if (std::is_same<decltype(param), raw_type&&>::value) {
        cout << "param is an rvalue reference to int" << endl;
    }
}
int main() {
    int i = 0;
    f(i);
    f(std::move(i));
    return 0;
}


text:
Q: Combine legends on a map when data is specified in a geom I am using ggplot2 to plot a map and points on top of it. This consists of plotting a map and then using geom_point() to place the points on. Furthermore these points vary in size based on another variable. When I plot this it results in multiple legends.
ggplot(mapdata, aes(x=long, y=lat)) +
geom_map(map=mapdata, aes(map_id=region),  fill="#ffffff", color="black", size=0.15) +
xlim(4, 15) +
ylim(47, 55) +
geom_point(data = dat, aes(long, lat, size = feature, alpha = 0.2, colour = "#007f3f")) +
scale_colour_manual(values = "#007f3f")

As explained in this question (and also this one) this can usually be achieved by using identical name and labels values for both scales however I am unsure how to apply this when the data is not being specified in the primary ggplot call (i.e. not in a geom) and with size as the legend. I have tried many iterations of this:
ggplot(mapdata, aes(x=long, y=lat)) +
  geom_map(map=mapdata, aes(map_id=region),  fill="#ffffff", color="black", size=0.15) +
  xlim(4, 15) + ylim(47, 55) +
  geom_point(data = dat, aes(long, lat, size = feature, alpha = 0.2, colour = "#007f3f")) +
  scale_color_manual(name = "feature", values = "#007f3f", labels=c("1.0", "1.5", "2.0", "2.5", "3.0")) +
  scale_size_manual(name = "feature", values = c(1.0, 1.5, 2.0, 2.5, 3.0), labels=c("1.0", "1.5", "2.0", "2.5", "3.0"))

How can I combine the legends?

A: You get multiple legends because you have multiple arguments inside aes. In your example the only aesthetic that varies based on a variable is the size, the rest (color and alpha) do not need to be mapped.
This:
ggplot(mapdata, aes(long, lat)) +
    geom_map(map = mapdata,
             aes(map_id = region),
             fill="#ffffff",
             color="black",
             size=0.15) +
    geom_point(data = dat,
               aes(long, lat, size = feature),
               alpha = 0.2,
               colour = "#007f3f")+
    xlim(4, 15) +
    ylim(47, 55)

Will give you a single legend, already combined.


text:
Q: Browse through nodes in XmlNodeList (vb.net) I can't find in the documentation how to "browse" through the nodes that I already have in XmlNodeList.
Given this XML:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE tmx SYSTEM "tmx14.dtd">
<tmx version="1.4">
  <tu changedate="20180509T145123Z" creationdate="20180509T145123Z" >
    <prop type="aligned">no</prop>
    <prop type="x-context">320920</prop>
    <tuv xml:lang="en-gb">
      <seg>Hello1</seg>
    </tuv>
    <tuv xml:lang="es">
      <seg>Hola1</seg>
    </tuv>
  </tu>
  <tu changedate="20180509T145216Z" creationdate="20180509T145216Z" >
    <prop type="aligned">no</prop>
    <prop type="x-context">325152</prop>
    <tuv xml:lang="en-gb">
      <seg>Hello2</seg>
    </tuv>
    <tuv xml:lang="es">
      <seg>Hola2</seg>
    </tuv>
  </tu>
</tmx>

I am trying to run through the different nodes in each /tu to load that to a DB. Should be simple but I am struggling with the syntax.
So far I have this:
Dim tmxfile As String = "d:\Documents\Desktop\myxml.xml"
        Dim xmldoc As New XmlDocument
        xmldoc.Load(tmxfile)

        Dim nodes As XmlNodeList = xmldoc.DocumentElement.SelectNodes("//tu")

        For node = 0 To nodes.Count - 1
            Dim x = nodes.Item(node).SelectNodes("/seg")

            MsgBox(x.ToString)
        Next
    End Sub

What I am trying to achieve is to show each /seg in //tu. The first part of the code is fine as if I loop through node with innerxml or innertext I see the actual elements of XML, but I am struggling to get the specified elements on those nodes.
Any guidance?
Thanks in advance!

A: If you'd use XDocument instead of XmlDocument, you could use unique VB's feature - XML Literals:
Sub Main()

    Dim xml =
<?xml version="1.0" encoding="utf-8"?>
<tmx version="1.4">
    <tu changedate="20180509T145123Z" creationdate="20180509T145123Z">
        <prop type="aligned">no</prop>
        <prop type="x-context">320920</prop>
        <tuv xml:lang="en-gb">
            <seg>Hello1</seg>
        </tuv>
        <tuv xml:lang="es">
            <seg>Hola1</seg>
        </tuv>
    </tu>
    <tu changedate="20180509T145216Z" creationdate="20180509T145216Z">
        <prop type="aligned">no</prop>
        <prop type="x-context">325152</prop>
        <tuv xml:lang="en-gb">
            <seg>Hello2</seg>
        </tuv>
        <tuv xml:lang="es">
            <seg>Hola2</seg>
        </tuv>
    </tu>
</tmx>

    xml.AddFirst(New XDocumentType("tmx", "SYSTEM", "tmx14.dtd", ""))

    ' All <tu> elements
    Dim tus = xml.<tmx>.<tu>

    For Each tu In tus
        Dim seg = tu.<tuv>.<seg>
        Console.WriteLine(seg.Value)
    Next

    Console.ReadKey(True)

End Sub


text:
Q: Authorize and AllowAnonymous attribute MVC I've the following class
[Authorize]
public class LoginController : Controller
{
    [AllowAnonymous]
    public ActionResult GetUsersList()
    {
    }
}

Config
<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" name=".AppUser" timeout="2000"/>
</authentication>

Though I've added AllowAnonymous for GetUsersList() Action, it still redirects to Login page. The GetUsersList is called through ajax
I do not have any custom authorization.


text:
Q: SQL Server: update on single record only updated half the varchar content update table1
set comments = @comments
where id = @id

In a web application, I had a single record update query for a varchar(MAX) column that only updated 40K characters of the 80K characters I was sending. So it chopped off the last 40K or so.
I don't see how a column can part-update like that. Does it stream large values? ie. if the connection broke half way, and only half was transferred across? But surely it would wait for the full command and parameters to load in a buffer before executing?
What if the table was busy with many users, and locks occurred and it was a victim of a deadlock? Once it started, I assume it would be all or nothing. But any possibility it could part-update the column?
Edit: it's definitely not in the database because the customer complained about the missing data, which I verified is in fact missing.
Edit: save would come via Javascript call to .NET web service to an EF save function. so could any of those truncate the data on a transmission/thread interruption type event?
Note this is a one off event. But severely disrupting to the customer. So I really need to audit a cause. Many times this has worked fine over a long period of time. I am assuming it's some infrequent occurrence due to thread or internet interrupt somewhere on the pipe.

A:
but any possibility it could part-update the column?

No.  No possibility that that would happen other than a bug somewhere, perhaps in your controller code.
One possibility is that there's a 0x00 character in the middle.  SQL Server can handle that, but many, many client programs will refuse to display anything after a 0x00 code point, thinking it's a null-terminated string.
EG
create table #x(data varchar(max))

insert into #x(data) values (cast(0x414141410041414141 as varchar(max)))

select data, DATALENGTH(data)
from #x

will display in the SSMS data grid output like this:

but in text output like this:
data
---------
AAAA AAAA

A: I agree with David Browne.
You could try something like this in SSMS to "see" what is in the column easier:
select comments, '(' + comments  + ')' as comments2, CAST(comments as varbinary(max)) as CommentsAsBytes,
 LEN(comments) as CommentsLength, DATALENGTH(CAST(comments as varbinary(max))) as CommentsNumBytes
 from table1 where id = @id

What does it return? Do CommentsLength and CommentsNumBytes look right?


text:
Q: How can I ignore an argument? I made some code (attached below). It is meant to make a list of random numbers that is not divisible by some value k.
I wish to be able to not enter a value k, and have the code run regardless. It would simply make a list of random numbers with no regards for divisibility.
mylist[n_, r_, k_] := Module[{list, rain, appe},
  list = {};
  While[Length[list] < n, rain = RandomInteger[{r[[1]], r[[2]]}];
   appe = If[Mod[rain, k] == 0, , AppendTo[list, rain]]];
  list
 ]

Below are examples of inputs and outputs:
mylist[20, {1, 100}, 2]
Output: {69, 3, 47, 47, 69, 59, 95, 99, 61, 57, 69, 75, 63, 43, 93, 97, 87, 75, 65, 85}

mylist[20, {1, 50}]
Output:{32, 45, 33, 4, 19, 31, 45, 14, 29, 38, 4, 34, 8, 17, 5, 49, 24, 1, 43, 38}

A: While you didn't ask for advice, you could do this without the explicit While looping:
mylist[n_, r_, k_] := RandomChoice[Select[Range @@ r, Not[Divisible[#, k]] &], n]

A: Use Reap and Sow instead of AppendTo.
Also you can do away with the list and appe. I've added a test argument, so you can pass in any test to accept numbers. And you can use Divisible instead of Mod:
mylist[n_, r_, test_] := Module[{rain, i = 0},
   Reap[While[i < n,
      rain = RandomInteger[r];
      If[test[rain], Sow[rain]; ++i]];
    ]][[2, 1]]
mylist[n_, r_] := mylist[n, r, Function[{x}, True]]

mylist[20, {1, 100}, Not[Divisible[#, 2]] &]
(* {33, 81, 57, 93, 83, 3, 21, 19, 57, 21, 97, 45, 11, 43, 21, 63, 97, 51, 7, 53} *)

mylist[20, {1, 100}]
(* {67, 78, 89, 23, 36, 72, 14, 97, 72, 64, 73, 100, 37, 70, 27, 5, 27, 85, 24, 67} *)

A: You can make the default value random:
mylist[n_, r_, k_ : RandomInteger[10]] :=
 Module[{list, rain, appe}, list = {};
  While[Length[list] < n, rain = RandomInteger[{r[[1]], r[[2]]}];
  appe = If[Mod[rain, k] == 0, , AppendTo[list, rain]]];
  list]
mylist[20, {1, 50}]

{17, 1, 35, 45, 37, 31, 21, 19, 30, 27, 10, 17, 46, 45, 50, 22, 30, 21, 17, 38}

A: Using a default argument of 1:
Clear[mylist]
SeedRandom[1];
mylist[n_, r_, k_ : 1] := Module[{list, rain, appe}, list = {};
  While[Length[list] < n, rain = RandomInteger[{r[[1]], r[[2]]}];
   appe = If[k > 1 && Mod[rain, k] == 0, , AppendTo[list, rain]]
   ];
  list]

Usage:
mylist[10, {1, 100}, 2]

{81, 15, 1, 69, 75, 25, 5, 91, 71, 31}

mylist[10, {1, 100}]

{49, 26, 45, 74, 70, 57, 48, 29, 69, 27}

A: Probably the easiest and clearest way would be to just overload mylist with another definition:
mylist[n_, r_, k_] := <...what you already have...>;
mylist[n_, r_] := RandomInteger[r, n]


text:
Q: File upload gets cancel when opening the camera I'm trying to upload a file to the server. Once the user take the photo with the app and accept it, the photo its uploaded. But if the use choose to take another photo while the previous photo is being still uploading, the uploading process gets cancel and throws a AggregateException. I need to upload more than one to avoid that kind of scenario.
Here the code that i use to upload the file:
  private async Task<T> ExecuteHttpPost<T>(string url, HttpContent content) where T : BaseServerResponseModel
        {

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    HttpStatusCode statusCode = HttpStatusCode.OK;

                    if (BeforeRequestPerformListener != null)
                    {
                        if (!BeforeRequestPerformListener(this, new BeforeRequestEventArgs(url, null)))
                        {
                            return null;
                        }
                    }

                    var response = await client.PostAsync(url, content);

                    if (ResponseRecivedListener != null)
                    {
                        ResponseRecivedListener(this, response);
                    }

                    statusCode = response.StatusCode;
                    response.EnsureSuccessStatusCode();

                    var entityResponse = await response.GetJsonResponse<T>();

                    entityResponse.ThrowIfNoSuccess();

                    return entityResponse;
                }
            }
            catch (Exception e)
            {

                throw;
            }

            return null;
        }

I also tried to wrap the whole code into a Task.Run but still throwing the same exception.
Anything that I'm missing?
Side note: the photo indeed gets uploaded to the server if I wait for it to finish. Its only when I open the camera while uploading that the exception occur

A: There are multiple scenarios where such file uploads can be canceled. In fact, taking another picture is just one. You should also consider lifecycle events such as spontaneous suspension and termination of your app.
To create a more robust environment for these sensitive server communications you should consider delegating your file upload to a background task. A background task will continue running, even if your app is terminated (*) or - like in your case - the user decides to do something different.
The most simple approach would be using a background transfer.
Overview: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh452975(v=win.10).aspx
Upload sample code: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj152727.aspx
This should do the trick for you. However if you need a more sophisticated solution you could write yourself a background task that processes your upload queue and notifies the foreground app on status updates such as progress and completion.
Quickstart: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx
How to monitor progress and completion: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977054.aspx
(*) There are performance restrictions for background tasks as well.


text:
Q: Write multiple TXT files to Excel in R I have over 100 txt files that were the output of a SQL scrape across 100 different schemas and tables. The files as tabular data, pipe delimited.
All of the column names in each text file are different.
Once I loaded the files into a directory I created 3 different symbols to separate the files based upon their name. E.g., x.files <- list.files(pattern="_X.txt") so I can separate my "X" files from my other files.
After that I used lapply to loop through those files and "read.csv" them into variable: x.read <- lapply(x.files, read.csv, sep = "|", header = TRUE).
What I need to do now is to write all of those dataframes (stored in a list) back to an XLSX file with a sheet for each dataframe. The preference would be that these TXT files would represent a worksheet for [i] text files within a single workbook (XLSX file).
I'm having some issues doing this using the 'xlsx' and 'XLConnect' packages. They both caused JVM to run out of memory even when I allocate java.parameters to -Xmx4000m.
I've tried using 'openxlsx' but I'm having a difficult time figuring out how to get it to create a sheet based upon the index of the list/df. So, index [1] would be "Sheet 1" and so forth. Or, it would also be fine if the sheet name was the name of the actual file name (SOME_DATA_STORE_SYS_NAME) minus .TXT as the file names are(SOME_DATA_STORE_SYS_NAME.X.txt or .P1.txt, etc).

A: This is a very simple version of an Excel write out function I use frequently. Note, your list names must be unique or this will write over sheets. This may not be a tenable solution if your data frames are very large.
Solution 1 uses the xlsx package to build an Excel workbook into your computer's memory and then write all of the sheets simultaneously.
require(xlsx)
eg <- list("one" = data.frame(one = rep(1, 100)),
           "two" = data.frame(two = rep(2, 200)))
wb <- createWorkbook()
for (i in seq_along(eg)) {
  sheet <- createSheet(wb, names(eg)[i])
  addDataFrame(eg[i], sheet)
}
saveWorkbook(wb, "eg.xlsx")

Solution 2 uses the XLConnect package and will write data frames into an Excel worksheet one at a time (with less onerous requirements on your computer's memory).
require(XLConnect)
eg <- list("one" = data.frame(one = rep(1, 100)),
           "two" = data.frame(two = rep(2, 200)))
for (i in seq_along(eg)) {
  writeWorksheetToFile(file = "eg.xlsx", data = eg[i], sheet = names(eg)[i])
}


text:
Q: How can i get the li-first child of this code?

                <img src="<?php the_post_thumbnail_url(); ?>" class="grid-img">

<?php the_title();?>

i used this code to get the initial info
initList($('#playlist li:first-child'));

but since the client decided to make it grid list
i dont know how to revised it when it is inside a div

A: Your problem is that the li is not the first child of #playlist. You want :first instead.


text:
Q: Functional analysis, fixed point theory In the theory of Riesz spaces, I am unable to understand a point.
If $aRb$ and $cRd$ then it is necessarily true that $a+cRb+d$, where $R$ shows partial order relation. If this is not true, please provide a counterexample.
Thanks in advance

A: I will replace the order $R$ by a simple $\le$ sign. Then $a\le b$ and $c\le d$ are equivalent to
$a-b\le 0$ and $0\le d-c$, hence $a-b\le d-c$ or $a +c \le b+d$.
Nothing special is going on here when comparing to the standard ordering on the reals.


text:
Q: Let $\{a_n\} ,\{b_n\}$ be given bounded sequences of positive real numbers. Let $\{a_n\} ,\{b_n\}$ be given bounded sequences of positive real numbers. Then (Here $ a_n\uparrow a$ means $a_n$ increase to a n goes to $\infty$, similarly, $b_n\downarrow b$ means $b_n$ decreases to b as n goes to $\infty$)
A. If $ a_n\uparrow a$, then $sup_{n\geq1}\; (a_nb_n)\leq a(sup_{n\geq1}\;b_n)$
B. If $ b_n\downarrow b$, then $inf_{n\geq1}\;(a_nb_n)\geq(inf_{n\geq1}\;a_n)b$

A: For a counter-example to A, let $a_1=0$ and $a_n=1-2^{-n}$ for $n>1$, let $b_1=2$ and $b_n=0$ for $n>1$. Then  $a=1$ so $a\sup_nb_n=\sup_nb_n=2$ while $\sup_na_nb_n=0$. Counters to B are similar .

A: A.
Since $a_n$ increases to $a$, $a_n\leq a$ for all $n$
Also by definition, $b_n\leq sup (b_n)$. Therefore by using the product rule for inequalities $a_nb_n\leq a(sup(b_n)) \forall n$. The answer follows from this result.
B can be answered similarly to how how A is answered


text:
Q: Serializing an extended form object I've been reading up on this whole subject, but I never came across this specific problem. I already understand that the whole idea of serializing an entire form is a horrible idea and just doesn't work. But, I am encountering a bit of a different problem. I have a class that inherits the "button" form object, that I call DataButton.
Now for my problem. I want to be able to serialize this class, but I don't need any of the information from the actual button class. Is there any way to bypass the fact that I can't set the button form object to Serializable() and notify VB that when serialization is to occur, it should simply skip over that information? Theoretically, if such a procedure were possible, I'd be able to do the entire serialization without a hitch.
I came up with the idea earlier of removing the "inherits" feature from the class, and having simply a button within the class, but that makes my program really difficult to work with as I am constantly changing the location, size, backgroundImage, text, and whatnot. Thus, immediate updates would be much tougher to work with.
Any help would be greatly appreciated.

A: You mention the Serializable attribute, so I assume that you are talking about binary serialization. In this case, have your DataButton implement ISerializable and you will take complete control of serialization.
Look ISerializable up. It has only one method for serialization and assumes a specific constructor for deserialization (as constructor cannot part of an interface).


text:
Q: How do you create a subset of the given list? Here's the problem I'm stuck on:  Subset the data to include only Chicken Bowl orders and assign it to a new variable called chipo_chicken_df
Here is the dataset: https://raw.githubusercontent.com/ahsen1402/badm211/main/data/chipotle.csv
I've tried:
chipo_chicken_df = chipo_df['item_name': 'Chicken Bowl']
chipo_chicken_df = chipo_df['Chicken Bowl']
chipo_chicken_df = chipo_df[['Chicken Bowl']]
chipo_chicken_df = chipo_df[['item_name','Chicken Bowl']]
chipo_chicken_df = chipo_df[['item_name': 'Chicken Bowl']]


text:
Q: Mouse and Keyboard don't work from Shutdown, do work from Restart I have a Lenovo Twist. The Touchpad doesn't work if I start from a cold shutdown. It does work if I restart (I can restart using the touchscreen, which always works). from dmesg the differences in the 2 boots are these files are not loaded off a cold start:
[   21.221813]  serio1: synaptics: Touchpad model: 1, fw: 8.1, id: 0x1e2b1, caps: 0xd002a3/0x940300/0x126c00, board id: 2253, fw id: 1192539
[   21.288391] input: SynPS/2 Synaptics TouchPad as /devices/platform/i8042/serio1/input/input5
[   25.907455] psmouse serio2: alps: Unknown ALPS touchpad: E7=10 00 64, EC=10 00 64
[   21.221827] psmouse serio1: synaptics: serio: Synaptics pass-through port at isa0060/serio1/input0
[   21.288391] input: SynPS/2 Synaptics TouchPad as /devices/platform/i8042/serio1/input/input5
[   21.360391] inputs:
[   28.169132] input: TPPS/2 IBM TrackPoint as /devices/platform/i8042/serio1/serio2/input/input13

Also the psmouse module not loaded. Loading it manually does not fix the problem.  I tried to ssh into the laptop and load the module after a cold start.
In the input devices the Synaptics TouchPad is not there after a cold shutdown.
I am booting from UEFI, not secure boot.

A: i set "Enabled" the option LaunCMS, then i changed the boot to Legacy only(old-fashion way), and re-install Ubuntu.
This last its because the ubuntu installation under UEFI boot disappeared from boot list, when i choose the Legacy Bios option


text:
Q: Hosts file resetting on Windows 7 Recently I've noticed my hosts file resetting itself.
 D:\Windows\System32\drivers\etc  (OS installed on D drive)

First time it reset it to the default, and now for the first time its completely disappeared after installing a whole bunch of updates.
I don't have any virus protection other than Microsoft's Security Essentials.
What's going on???

A: A quick Google shows that MSE does in fact play around with your hosts file:link
Maybe try disabling/uninstalling it and see if it persists.


text:
Q: Unzip and access folder with powershell I have a powershell script the downloads a zip file with a folder with files within it to the %TEMP% folder and I'm trying to understand how it can be unziped and acessed an exe file within it?
I have made searches both here and on google but I didn't found anything and have no clue how can that be done or evn where to start.

A: Try Extract-ZipFile cmdlet. Then access the exe where you have extracted the zip file.

A: Try expand-archive to unzip files. Power shell v5 has it


text:
Q: Why is the Voltage only 1.4 for reset input when in high impedance? I attempted to make myself a 2-in-1 programmer so I can program both AT89Cx051 and AT89S52 on the same board without having to do so much plugging/unplugging of the port.

The main issue is the strobe pin aka reset (RST in circuit). (pin 1 of the DB25 connector). I tested it with a PC and got no results.
What seems to somewhat work is if I connected RST to VCC via a 1K resistor. It somewhat works because even though the output is only at 3.8V instead of 5 (which VCC is also at), it puts the AT89S52 in reset mode as expected, but I'm not getting 12V at pin 1 of the small AT89Cx051 socket.
If I don't make the manual connection, then I get 1.4V measured at RST, even after I added a 10K resistor between VCC and RST. Without RST being forced to ground, I should get 5V but I'm not.
I have also tested the transistors manually from leg to leg using the diode setting on the multimeter and they turned out fine. The resistors going to the base of the transistors are 2.2K and I used 1K resistors in place of the diodes. All other resistors are 10K. The resistor going into the buffer (74HC125) is 0 ohm.
All capacitors are 0.1uF.
Why would I be getting such awkward voltages for reset pin?
Am I using too weak of resistors or something?
UPDATE
So I ended up making myself an ms-dos 6.22 bootdisk and booted my machine into that with qbasic to test the parallel port (with port at address 278-27AH ) in general with simple circuitry and that seems to work decently.
When I teted only the parallel port on the pc with only a voltmeter with anode lead connected to the strobe pin, I get the following results:
Qbasic code           Result
OUT &H27A, 0          4V output from strobe
OUT &H27A, 1          0V output from strobe

When I plugged my circuit into the port, the voltage dropped:
Qbasic code           Result
OUT &H27A, 0          1.56V output from strobe
OUT &H27A, 1          0V output from strobe

How is it possible I'm only getting 1.56V from that pin?
update 2
I disconnected the 12V line from the circuit and the voltages on the reset line are now 1.52V and 0V

A: *

*You are missing a 10 K pull-up resistor in series with a 1N4148 diode at the reset pin of the MPU itself. You show CRESET as being there for programming the IC, but no 3.3 volt pull up which MUST be there. Your reset transistor needs a current on its collector at all times or the IC may stay in reset state.

*The diode is to prevent 12 volts from going back into the Vcc 3.3 volt line during programing.

*Pin 1 of your DB25 connector should have a 10 K resistor to ground so the reset transistor does not turn ON due to leakage currents.

*To reset the IC you need to ground its RESET pin or connect pin1 of the DB25 connector to Vcc. At least that should be your goal.

*I am not sure where or why you get 1.4 volts on the reset pin. First of all your are not defining which reset pin. The IC or the DB25 pin 1. Plus you are missing important pull-up and pull-down resistors so by my standards the 1.4 volts is just leakage current.

*I am sure you will see the 1.4 volt reading change and be more sensible once you install the resistors and diode I mentioned.

*You missed a couple of important steps that should get it working correctly, at least the RESET function anyways.

*In all honesty your diagram is a bit confusing. I am only looking at the left schematic with the DB25 connector, which you have pin1 as RESET if it is high. It cannot be open collector unless it is a PNP transistor because T1 must have its base pulled low or it will reset the MPU.

*You are sooo close to having it right. Yes the diode is forward biased from a 3.3 or 5 volt line, through the 10 K resistor. This insures that the MPU RESET pin is held high, yet can still act as a programming pin. The 3 pin connector should NOT be used unless you are programming the MPU.


text:
Q: Passing as a variable the individual columns of individual matrices in a list of matrices I want to pass columns in various matrices to a for loop.
If my two matrices had the same number of columns, I might do something like this:
mat1 = matrix(rep(1:25), 5,5)
mat2 = matrix(rep(26:50), 5,5)
array.mat = array(c(mat1,mat2), dim=c(5,5,2))
mat1.ncol = ncol(mat1)
mat2.ncol = ncol(mat2)
mat.ncol = c(mat1.ncol, mat2.ncol)
mat.ncol
array.mat
for (dimi in 1:2){
  dim.col = mat.ncol[dimi]
    for (coli in 1:dim.col){
      st = shapiro.test(array.mat[,coli,dimi])$p.value
        if(st > .001){
          array.mat[,coli,dimi] = log(array.mat[,coli,dimi])
}}}

But, my data don't have the same number of columns, so I'd like to use a list of matrices instead.
mat1 = matrix(rep(1:10), 5,2)
mat2 = matrix(rep(26:50), 5,5)
list.mat=list(a=mat1, b=mat2)
list.mat

But I can't figure out how I'd pass the columns of the matrices?
list.mat$a[1:5]

gives the first column of the first matrix, but how would you pass $a and [startindex:endindex] in a loop? All the other answers I see tend to pass the ith element (e.g., column) of both matrices. I need to keep the two matrices (a and b) separate for later computations, but I want them together (the list of the two matrices) for these types of loops.
Once again, I'm probably just thinking about this incorrectly. Thanks for any thoughts.

A: Can you use numeric indices? e.g., matrix 1, column 1: list.mat[[1]][,1]
In a loop:
for (m in 1:2) {
  for (i in 1:ncol(list.mat[[m]])) {
    cat('Here is matrix', m, ', columnn', i, '\n')
    print(list.mat[[m]][,i])
  }
}

result:
Here is matrix 1 , columnn 1
[1] 1 2 3 4 5
Here is matrix 1 , columnn 2
[1]  6  7  8  9 10
Here is matrix 2 , columnn 1
[1] 26 27 28 29 30
Here is matrix 2 , columnn 2
[1] 31 32 33 34 35
Here is matrix 2 , columnn 3
[1] 36 37 38 39 40
Here is matrix 2 , columnn 4
[1] 41 42 43 44 45
Here is matrix 2 , columnn 5
[1] 46 47 48 49 50


text:
Q: Google application engine, maximum number of static files? I am developing an application in google application engine which would have a user profiles kind of feature. I was going through the Google App's online tutorial where I found that the maximum number of static files (app files and static files) should not exceed 3000. I am afraid whether the user's would be able to upload their images when the number of users increase. Is this limitation for the Free Quota only or its even after billing. In the document, its mentioned as the additional limit than the Free Quota.
Please suggest.
Thanks in advance.

A: Welcome to Stack Overflow!
One of the limitations in App Engine is that you cannot write directly to the filesystem from your app. Static files would be things like HTML, CSS, javascript and images that are global to your application, and get uploaded manually when you deploy. They are uploaded to and served from different servers than the ones that handle dynamic content.
Since you can't write to the filesystem from your app, files uploaded by users must be saved to the datastore as blobs. These are not considered static files. As others have mentioned, you can use S3 or the Blobstore API, however both of these require billing. With the free quotas, each entity can be up to 1MB, and each HTTP request and response can be up to 10MB. Using standard entities with a BlobProperty, you can easily store and serve dynamically uploaded files up to 1MB, or 10MB if you want to get fancy and store your blob in slices across multiple entities.

A: There is a new service called the BlobStore that let's you store binary data in the database. Also you may want to look into Amazon S3 as storage for the data. If user's are uploading images they cannot be stored as static files.  Static files are files included in your GAE project like html and png/jpg/gif files.

A: As others have mentioned, for more dynamic content such as user-uploaded files, those should go into the datastore as blobs, or if they're larger, as Blobstore objects (max size 2GB).
3000 static files is somewhat reasonable unless you have a lot of static assets (such as images, HTML, CSS, and JS files). for Python source however, you have another workaround, and that is to throw all your .py files into a single ZIP so they don't hit that count so badly. here's an article that describes how to do this:
Using Django 1.0 on App Engine with Zipimport
Just be aware that this article talks about how to bundle Django's source with App Engine; however, that's unnecessary unless you're doing 1.3 or are using a fork. App Engine systems already have 0.96 or 1.2.5 available to you for free.
UPDATE (Mar 2011): In SDK 1.4.3, the App Engine team has released the Files API which allows you to read/write files/data programmatically with Blobstore. This applies to both Python and Java. More info can be found in the corresponding blogpost. In addition to Blobstore, the public roadmap shows a future feature integrating in Google Storage access.
UPDATE (Sep 2011): In SDK 1.5.4, the App Engine team removed the Blobstore filesize limitation from 2GB to allow files of unlimited size. You pay per GB of storage however.
UPDATE (Oct 2011): In SDK 1.5.5, the App Engine team extended the maximum number of files from 3000 to 10000, which is a great boost for users. Furthermore, the maximum individual filesize was bumped up from 10MB to 32MB. Another storage related improvement is that users can now write to Google's Cloud Storage directly from their App Engine app.


text:
Q: SAS: Spliting data groups into its own rows I'm new to SAS and found myself having to use it for my new job. So this is a basic question.
I have a table which looks like this:
COMPANY | Employee
--------|----------
COMP1   | @,@,@,@
COMP2   | @
COMP3   | @,@
...

Every @ is an email adress - divided by commas - of an employee in the company in the first row.
Now I want to use Data step to give every email its own row. Each with the corresponding company name in the first row. Like this:
COMPANY | Employee
--------|----------
COMP1   | @
COMP1   | @
COMP1   | @
COMP1   | @
COMP2   | @
COMP2   | @
...

I hope this is enough to go on.
Thank you in advance
Jan

A: Code below should solve your problem. Please note that I used 50 symbols to store the email, if you think that you might encounter longer emails increase the length in the second data step. First data step is just an example which I used for testing.
data tmp1;
    length COMP EMAIL $50.;

    comp="CMP1";
    email="ABC@cmp1.com, DEF@cmp1.com, GHI@comp1.com";
    output;

    comp="CMP2";
    email="ABC@cmp2.com, DEF@cmp2.com";
    output;
run;

data tmp2;
    set tmp1;
    i=1;
    length new_email $50;

    do while(scan(email, i, ",") ne "");
        new_email = strip(scan(email, i, ","));
        i+1;
        output;
    end;
    drop email i;
run;


text:
Q: Unable to open Atom I am unable to open my Atom Editor. It was working fine until yesterday, but don't know why it won't open today. No windows update or anything on my computer. I tried deleting the 'Storage' folder as mentioned in some online forums, doesn't help. Any suggestions? I am using Atom version 1.19.6.0.

A: I experienced this issue when my Atom windows all suddenly resized to be so small I could not see or find them anywhere (some weird glitch with opening it from a full-screen window on an external display). I resolved it by command-tabbing (I think it's ctrl-tab on Windows, I forget) to my open atom application to bring up the application's menu bar, and then selecting Window > Zoom from the menu.

A: If you're using MAC OS and have similar problem, try this:
Open Window tab

and then click Zoom.

A: Atom will sometime fail to open because of a bad configuration-file.
To better diagnose this on Windows (10), try running atom from a CMD window:

*

*Open the task-manager and kill any instance of Atom that is listed there

*Open a Command-window -
Ctrl+Esc > (type "command") > Enter

*Go to where Atom is installed -
cd %USERPROFILE%/AppData/Local/atom/app-*

*Run Atom -
atom.exe
If you see an error message at this point, it should help identify the problem.
If still not clear, you can try moving the main configuration-file,
which is in a different folder:

*

*cd %USERPROFILE%/.atom/

*rename config.cson config.SAVE.cson

*Go to where Atom is installed (again) -
cd %USERPROFILE%/AppData/Local/atom/app-*

*Run Atom -
atom.exe
Based on this answer on the Atom forum:
https://discuss.atom.io/t/atom-will-not-open-windows/47489

A: I am using Atom on Windows 10 64-bit, and had similar problems of installation and not running later.
You can do the following:

*

*Empty Trash, and Temp and Prefetch folders.

*Change the security and read only properties of the temp folder.

*IMP > Disable antivirus and run atom it will work, later add the Atom app to exclusion list of your antivirus.

A: *

*Open the task-manager and kill any instance of Atom that is listed there

*Got to where Atom installed : Mine:> C:\Users\%userprofile%\AppData\Local\atom

See this Image
Go to Folder indicated in the picture and find atom.exe by scrolling through the folder and open it and make a shortcut to desktop and it will work.

A: I found that mv command is not builtin Windows cmd as suggested by Gonen. So following the idea of Gonen, a working solution can also be like:

*

*In windows explorer type %USERPROFILE%/.atom/, or manually go to the path
(in my case): C:\Users\hussainazhar.atom. Of course, go to your drive path accordingly. Close Atom application if already opened.

*Simply rename the config.cson to config.SAVE.cson

*Open up the Atom and now you can go to the settings :)

A: All you simply need to do is go the main directly where the file is located and open the FIRST folder.
After opening it, there you will see atom file, double click on it and it will be opened successfully.

A: The atom Window is just minimized, it gives the impression of not openning, but it is actually opening, again is just minimized.
I was able to see the atom interface, by maximizing the window using the keyboard:
on windows, it normally is Alt+SpaceBar+x.


text:
Q: DrEdit Java App of Google App Engine gives 500 Server while deploying I am trying to bring up DrEdit Java App. I followed all the instructions provided in the following link https://github.com/googledrive/dredit/tree/master/java to bring it up.
From eclipse, once I start "Deploy the app", eclipse says building and deployed the app successfully but on the browser end, it asks for authentication, once I tell accept I am
getting 500 server error
Error: Server Error
The server encountered an error and could not complete your request.
If the problem persists, please report your problem and mention this error message and the query that caused it.
Can somebody suggest where I have gone wrong, and how to solve this problem.
Thanks
lakshmi


text:
Q: Read file attributes with java I'm trying to read some basic file attributes, i.e. is file readable, writeable etc...
I've been baning my head reading the java tutorial. Seems fairly easy only my eclipse doesn't recognize any of the interfaces/methods that are in the tutorial.
Also I found this
Files class that also doesn't work.
I am using ubuntu but wasn't able to tell what version of JDK I am using.
Also I didn't see anywhere in the documentation that those methods are new.
Any ideas about why can't I use them?

A: If you just want to read basic attributes and you're using Java 6 (or above) just use canRead(), canWrite() and canExecute(). All are on the basic File class.
The doc you link to there is for JDK7 which isn't yet released (due late July this year.) So you probably don't want to be looking at that unless you're specifically developing for it in advance!
UPDATE: Java 7 is of course now released.

A: For your version at the command line try java -version otherwise I'd go with berry's suggestion of using the java.io.* stuff. If you're really hard up you can execute a bash command(http://ubuntuforums.org/archive/index.php/t-319735.html) and parse the output but then you are seriously platform dependent.


text:
Q: PostgreSQL: get advisory lock unless more than n transactions are waiting for it I've a resource that gets acquired from distributed clients. This resource is protected by a transaction level lock:

SELECT pg_advisory_xact_lock(123456)

I know I can use pg_try_advisory_xact_lock if I don't want to wait for it to be free. If I got it - the call would return true, otherwise false.
What I would like to achieve is the behaviour of pg_advisory_xact_lock with queue-size. If less than 4 transactions are waiting from the lock join them in waiting, otherwise return false pg_try_advisory_xact_lock otherwise. If you managed to get the lock - return true.
Can I achieve this without writing a plv8 extension? Any ideas?
I'm using PostgreSQL 10.

A: Cycle through "pg_try_advisory_xact_lock(...)" on 5 different lock ids (say 123457 to 123461) (1 real lock holder and 4 more non-holding waiters = 5).  Getting one of those then grants you the right to wait on the "real" lock id.  Failing to get any of the 5 results in failure.  This does mean you have to reserve/coordinate 6 magic constants, rather than 1.


text:
Q: How to reinstall Windows MBR with no Windows listed? There is nice article how to reinstall windows MBR:
http://support.microsoft.com/kb/927392
however there is a catch. I have Windows system, but when I go with repair mode it is not shown and as the effect I cannot repair it.
The repair software indicates that I would need the drivers I used when installing it, but I don't recall I had any disk with drivers.
Computer: MacBookPro, systems: openSUSE 12.3, Windows 7. Loader: GRUB.
Clarification: GRUB works, Windows works, I would like to remove GRUB and install Windows mbr instead (that's all). The problem is, according to Windows install DVD (repair program) I don't have Windows installed, Windows is NOT listed (actually there is no system detected at all).

A: If you are booting from a rescue usb/disk, there should be a repair mode.
If your recovery partition is ok, you can also try to boot from there:
How to Boot into a Recovery Partition in Windows


text:
Q: How to use setCurrentTab method in an activity of tab? I've been having this problem for 1 week.
I have a MainActivity extends TabActivity and A, B two activities in each tab.
Now I want to press a button in activity A to set the current page to the tab of activity B
But I can't use setCurrentTab method except in MainActivity.
How can I make this function work?

public class MainActivity extends TabActivity
public TabHost tabHost;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Resources res = getResources();
    tabHost = getTabHost();
    TabHost.TabSpec spec;
    Intent intent;
    intent = new Intent().setClass(this, StartActivity.class);
    spec = tabHost.newTabSpec("tab1").setIndicator("A",res.getDrawable(R.drawable.start))
                  .setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, WeatherActivity.class);
    spec = tabHost.newTabSpec("tab2").setIndicator("B",res.getDrawable(R.drawable.weather))
                  .setContent(intent);
    tabHost.addTab(spec);

    tabHost.setCurrentTab(0);

}

public class AActivity extends Activity{

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_layout);
        Button b = (button)findViewById(R.id.bt);
        b.setOnClickListener(this);
    }
    public void onClick(View v) {
        tabHost.setCurrentTab(1);
        //Can't work here
    }
}

A: Try making the following changes :
In Main activity :

*

*Make the tabHost variable Static.
private static TabHost tabHost;

*Add a new function to fetch the current tabhost.
public static TabHost getCurrentTabHost(){
return tabHost;
}

*In AActivity, Use like this :
MainActivity.getCurrentTabHost().setCurrentTab(1);
If required, you can go for a null check.


text:
Q: How to reduce the Font of a LWUIT Button text I've created 3 LWUIT buttons like below:
b1.setText("Tab1");
b1.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
b2 = new Button();
b2.setText("Tab2");
b2.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
b3 = new Button();
b3.setText("Tab3");
b3.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM,                  Font.STYLE_PLAIN, Font.SIZE_SMALL));

tabs.addTab(b1, tab1List);
tabs.addTab(b2, tab2List);
tabs.addTab(b3, tab3List);
form1.addComponent(BorderLayout.CENTER, tabs);

My Requirement is to reduce the Font of a Button Text(Tab1,Tab2,Tab3),If i use my above code I'm not able to reduce the font,Can any one any help me?

A: Do you know that you can use the LWUIT Resource Editor to do this kind of things?
The Resource Editor will be helpful to customize the style of everything in your interfaces. Take a look on this tutorials:
Resoruce editor tutorial


text:
Q: Meteor breadcrumb How do I implement a reactive breadcrumb with Meteor and iron-router?
Now I'm looking for the current path, triggered by a reactive session variable and then adding each link that corresponds to that route inside the DOM with jQuery.

A: You can call Router.current().path inside a helper function and it will return the current path. Then split the path on / and return the array to your breadcrumbs template. The function is reactive, so updates will propagate:
Template.breadcrumbs.path = function() {
  return Router.current().path.split( "/" );
}

A: With Meteor 1.0 and Iron.Router it would be:
Template.breadcrumbs.helpers({
  path: function() {
    return Router.current().route.path(this).split( "/" );
  }
});

Note that the way of adding methods to the template engine Template.breadcrumbs.path = function() {} is deprecated.


text:
Q: Authenticating a Xamarin.Forms-Client at a ASP.NET MVC Server with SignalR? I have created a new ASP.NET MVC project and by default it appears to use a .mdf-databasefile for authentification.
I would like to authenticate my Xamarin (Xamarin.Forms) client. The reason for this is that I would like to use the [Authorize] attribute later on in my SignalR hub.
What I would like to know now:
What exactly do I have to do to authenticate my client?
Do I have to do it in one of my hubs methods? And what classes do I have to access / call using my name & password for this purpose?
Or are my thoughts completely wrong and I have to do it in a completely different way?
Thanks in advance!

A: I wouldn't authenticate directly in your hubs. I would first authenticate and then allow the hubs to be reached. To do this securely, I'd do something like this:

*

*Create a Web API service to authenticate against a database, for example.

*Make the client pre-hash the password.

*Send a HtppRequest to the Web API login service, sending username and pre-hashed password.

*Make the login method finish the hashing of the password using information from the database and authenticate the user.

*Assign some secure token to that user, and send that back to the client (through HTTPS, if possible)

*Make a custom authorize attribute, so you can check against the security token.

*Mark the hub classes with your new [Authorize].

This is at least an idea of how you can get this done securely. For the double hashing of the password, we use a combination of SHA512CryptoServiceProvider, RNGCryptoServiceProvider and Rfc2898DeriveBytes.


text:
Q: how to collaborate multiple pacman agents in a maze without ghosts to eat all food pellets in a time-constrained environment? The problem is actually of a minicontest from the course CS188(intro to AI), UC,berkeley for fall 2018.Here is the link to the minicontest1.
(https://inst.eecs.berkeley.edu/~cs188/fa18/minicontest1.html/)
In this mini-contest, we have to apply the search algorithms and problems implemented in Project 1(A*,ucs,bfs,dfs) to handle more difficult scenarios that include controlling multiple pacman agents and planning under time constraints(and without ghosts) to eat all foods in the maze before score dropping to 0.There are also penalties for decision time taken,and score boosts up for eating food pellets and more for completing all pellets.
I tried some ways to solve the problem.

*

*Agents which always go towards the closest dot computed by bfs.

*Agents which always turns left whenever there is a chance.

*Agents which keep track of locations they have been to in last 7 chances and don't repeat.(using fixed size queue) and randomly choose an action from the legal actions possible.
But these agents are not efficient enough as it(last one) gives wins in only 11 or 12 mazes out of 71 mazes with a average score of around 262 on autograder provided for the contest.

I am somehow not able to make these pacman agents collaborate for fast retrieval of all food pellets.
I want some ideas on how to go ahead with this assignment.

A: https://courses.cs.washington.edu/courses/cse473/14au/slides/03-hsearch.pdf
https://www.hackerrank.com/challenges/pacman-ucs
https://github.com/jeknov/aiAlgorithmsWithPacman
https://github.com/aahuja9/Pacman-AI
these links talk about these algorithms with reference to pacman


text:
Q: Angular $document append not working when start call is from jQuery I got some code that I got from this article and it works nicely when called from an ng-click directive but doesn't when the initial call comes from jQuery, I'm trying to show the modal popup after a draggable is dropped.
var popupTemplate = document.createElement("div");
popupTemplate.setAttribute("ng-include", "'myTemplate.html'");
var popupScope = $rootScope.$new();
popupScope.bucket = bckt;
var popupLinker = $compile(popupTemplate);
var popupElement = popupLinker(popupScope);
$document.find('body').append(popupElement);

First scenario where the code is working perfectly, I have a function in a Service that displays the modal popup when the user does ng-click on an element inside an ng-repeat. This works, just fine. the way I show the pop up is using $document.find('body').append(popupElement);
ng-repeat -> ng-click -> function in scope -> call to service -> create pop-up from template and append to body √
However when I try to perform the same action from jQuery the append doesn't happen, I debugged everything to the point where I'm sure that popupElement
has the new element to inject and everything is ready by $document.find('body').append(popupElement); doesn't work, the popupElement doesn't get appended to body
jQuery event -> callback to Angular through angular.element('#controller').scope().someFunction() -> call to Service ->  create pop-up from template and append to body X
Do you have any idea on why this later append call could not be working?
Thank in advance for any advice

A: I found the solution to my problem, I was making DOM modifications but they were not being shown until the DOM was rendered by angular, to kick in the DOM Render I just had to call
$rootScope.$apply();

That is the reason why when I started the login from jQuery the element was not showing, because there was no natural cycle of angular, therefore the $apply cycle was not kicking in on it's own.


text:
Q: Detect iPhone disconnected from WatchOS app in background I'd like to know if there's a way to detect if the iPhone is unreachable while the WatchOS app is in background. I tried to connect each other with CoreBluetooth but if WatchOS app is in background won't call didDisconnected method.
So I tried the trick of update locations to get alive the app in the background, but everytime the Apple Watch screen awakes the WatchOS app is in foreground and the notification won't works.
I implemented the
sessionReachabilityDidChange but neither this is called in background.
Can somebody give me a hint?
Or can tell me how to prevent the WatchOS app to be in foreground while update locations is running?


text:
Q: Shell or AWK assistance, how can I substitute a specific text from one file to another file? File 1 - list of CSV files
Run_100000_data.csv
Run_101001_data.csv
Run_102002_data.csv
...
...

(Please note that the list above could grow and files are always in this structure Run_6digit#_data.csv.)
File 2
LINEMAP [1]
NAME = '&M#&'
LINEMAP [2]
NAME = '&M#&'
LINEMAP [3]
NAME = '&M#&'

I would like to write a shell script that substitutes the 1st line of File 1 with the first instance of &M#& found in File 2. This would repeat for the second and third line or as many lines as are in the file.
Output:
LINEMAP [1]
NAME = 'Run_100000'
LINEMAP [2]
NAME = 'Run_101001'
LINEMAP [3]
NAME = 'Run_102002'

Please note I'm not using the full name from File 1, ('_data.csv' is not used). If the run number can be substituted then that would be acceptable too. I would like to leave this open ended to allow for any creative ideas. Any help would be much appreciated!!

A: awk '
BEGIN { str = "&M#&" }
NR==FNR { sub(/_[^_]+$/,""); a[NR] = $0; next }
s = index($0,str) { $0 = substr($0,1,s-1) a[++c] substr($0,s+length(str)) }
{ print }
' file1 file2

A: This works in my tests with gnu awk:
echo "$a"
Run_100000_data.csv
Run_101001_data.csv
Run_102002_data.csv

echo "$b"
LINEMAP [1]
NAME = '&M#&'
LINEMAP [2]
NAME = '&M#&'
LINEMAP [3]
NAME = '&M#&'

awk -F"_" 'NR==FNR{f[FNR]=$1FS$2;next}FNR%2!=0{print $1;print "NAME = \x27"f[++c]"\x27"}' <(echo "$a") <(echo "$b")
LINEMAP [1]
NAME = 'Run_100000'
LINEMAP [2]
NAME = 'Run_101001'
LINEMAP [3]
NAME = 'Run_102002'

In above test i use two variables. In your case you can use
awk -F"_" 'NR==FNR{f[FNR]=$1FS$2;next}FNR%2!=0{print $1;print "NAME = \x27"f[++c]"\x27"}' file1 file2

A: Here is a Bash script that does it:
#!/bin/bash

macro='&M#&'

while IFS= read -r line; do
    if [[ $line == *${macro}* ]]; then
        # Read replacement from fd 3 / file1
        read -r -u 3 rpl
        # Compose output line with parameter substitutions
        printf '%s%s%s\n' "${line%"$macro"*}" "${rpl%_data.csv}" "${line#*"$macro"}"
    else
        printf '%s\n' "$line"
    fi
# Read from file2, redirect fd 3 to read from file1, redirect output to outfile
done < file2 3< file1 > outfile

This redirects file1 to file descriptor 3 so we can read from there when we want during the loop. The rest is pattern matching and parameter expansions.

If file2 has the lines with the string to be replaced on every second line, we can use paste and sed as follows:
paste -d ' ' file2 <(paste -d '\n' /dev/null file1) |
    sed 's/&M#&\(.*\) \([^[:blank:]]*\)_data\.csv$/\2\1/'

Explanation:

*

*paste -d '\n' /dev/null file1 interleaves file1 with empty lines, resulting in

Run_100000_data.csv

Run_101001_data.csv

Run_102002_data.csv

*paste -d ' ' file2 <(paste -d '\n' /dev/null file1) pastes that together with file2, space separated:
LINEMAP [1]
NAME = '&M#&' Run_100000_data.csv
LINEMAP [2]
NAME = '&M#&' Run_101001_data.csv
LINEMAP [3]
NAME = '&M#&' Run_102002_data.csv

*sed 's/&M#&\(.*\) \([^[:blank:]]*\)_data\.csv$/\2\1/' checks for the string to be replaced, captures everything up to the last blank on the line and the part of the replacement we want and rearranges it, resulting in
LINEMAP [1]
NAME = 'Run_100000'
LINEMAP [2]
NAME = 'Run_101001'
LINEMAP [3]
NAME = 'Run_102002'


text:
Q: Unable to install a python package on zsh but successful on bash I want to install papermill[s3] using pip.
The command indicated in the traceback is: pip install papermill[s3]. However, when I run the command: pip3 install papermill[s3], I get a following traceback:
zsh: no matches found: papermill[s3]

I tried going through the documentation but they state the exact same syntax.
Source: https://github.com/nteract/papermill
Update:
I am able to install the same when I enter bash and not zsh terminal.

A: Square brackets in zsh have special meanings but in MOST circumstances maybe you just have to escape them by putting (backslash) before them. See this
So with next which do escape string, it works:
pip3 install papermill\[s3\]


text:
Q: OS X Photos removes 5 photos when converting to iCloud Photos When I try to convert my local Photos.app library to iCloud, the amount of photos in the library decreases from 686 to 681. I have tried to convert my local library multiple times but the problem keeps happening. I have found one of those 5 photos, but the file doesn't seem to be damaged.

The library was created in OS X 10.10.3 and I am currently running 10.10.4. Is this a bug in the app? What can I do to prevent these photos from getting deleted while enabling iCloud Photos?

A: After contacting AppleCare, it seemed I had a database error. The problem was forwarded to the iCloud engineers and has now been fixed.


text:
Q: Fixed header scroll to tag issue I am having issues making the links in my header scroll to the tag. Because it is a fixed header it scrolls past the area and the content is behind the header. How can I fix it to where it goes to the bottom of the header? I am also using box-sizing: border-box; if that has anything to do with it. Thanks for the help.
here is the jquery:
$(".scrolltotag").click(function(event){
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 600);
});

all the links in the nav have a class of scrolltotag and an href="#tag"

A: I was able to fix it by adding - $('header').outerHeight() after $('html,body').animate({scrollTop:$(this.hash).offset().top thanks though!

A: // Get the height of the header
var headerHeight = $(".header").height();
// Attach the click event
$('a[href*=#]').bind("click", function(e) { e.preventDefault();
var target = $(this).attr("href");
var scrollToPosition = $(target).offset().top - headerHeight;
$('html').animate({ 'scrollTop': scrollToPosition }, 600, function(){
window.location.hash = "" + target;
$('html').animate({ 'scrollTop': scrollToPosition }, 0); });
});


text:
Q: Unknown Circuit Symbol What are these circuit symbols (circled in red) in these diagrams?

I am studying high school introductory physics, and this image is from a problem on circuitry in my online course. The problem is unrelated to the meaning of these particular symbols, but I am curious and would like to know.

A: DC generator (x 4) and DC motor (x 1).

A: The bottom symbol in B is a fairly common symbol for a motor.
The other one seems to be an uncommon symbol for a generator. This page identifies it as a DC generator:
http://avstop.com/ac/apgeneral/basiccircuit.html
But this page says it's "AC power":
http://www.electronic-symbols.com/electric-electronic-symbols/electric-generator-symbols.htm
Both pages are missing the + and - signs. The presence of + and - signs and the overall context suggest it's meant as a DC generator, or (less likely) a generic voltage source.
Unfortunately, as my links show, there's not a lot of consistency in these kinds of symbols.

A: Adam Hauns answer is mostly right, but both references say dc generator, ac generators does not have +-, while dc does.

A: It appears that the circuits are given as possible answers to a problem.  If this is the case, (A) is not a valid answer. If (B) is correct, you have a DC generator and a DC motor connected in series.  If (C) is correct, you have a DC generator acting like a DC motor because it is connected to a battery.  If (D) is correct, you have a DC generator connected to a lamp, and its current is being measured.


text:
Q: Socket.IO -- Additional Attributes and Socket Data are not restored after reconnect (NodeJs) I'm using React and working on a chat app.
The initial connect is fine, and then after the socket is established my app emits a joinChat event to place itself in a room, which works. In addition to being placed in a room, I set a chatId value on the socket via
if (socketCanAccessRoom(someRoom)) { socket.chatId = SOME_VALUE; }
after verifying that the user has access to that room.
However, when the socket disconnects and then reconnects, the chatId attribute of the socket instance is lost. Am I doing something wrong here?
I was expecting the arbitrary attributes to be restored on reconnection. I have tried both doing it like this and using the socket's data object, per the docs. Neither seem to work.
I COULD do a fallback and have the instance re-authenticate the user each time it reconnects, I guess, but it seems unnecessary if the socket can recall its data like I think it should.
If I'm just totally off-base and this isn't possible, no worries! I just thought it would be but am having a hard time searching for this behavior.
The closest stack overflow I can find is about a 'client store expiration' option, but I can't find that in the docs, and I don't believe these disconnects are longer than the indicated 15 second timeout, either.


text:
Q: How to get a function's return value after the :e command in Vim I wrote a function to get the full path of the current file under the cursor
nmap <F12> :echo GetFullPath()<cr>
function! GetFullPath()
    let currentFile=expand("<cfile>")
    let afterChangeSlash=substitute(currentFile,"/","\\","g")
    let fullPath="e:\\Test\\".afterChangeSlash
    return fullPath
endfunction

When I call the function after the :echo command, I get the expected result,like:
:echo GetFullPath()

e:\Test\test.h
However,When I call it after the :e(edit) command:
:e GetFullPath()

Vim just create a new file named GetFullPath()
Why the command :e  will treat a function call literally while the command :echo won't?

A: You can use :execute to build your ex command string and execute it:
:exe "e ".GetFullPath()

Or use the `=` syntax to expand a Vim expression:
:e `=GetFullPath()`

If you check the help for :edit and :echo, you'll notice that the former expects its argument to be the file name (literally), while :echo expects an expression which will be evaluated.

A: Some ex commands expect to be given an expression, while some others expect to be given a string. For your case to make it work use exec:
nmap <F12> :exec 'e ' . GetFullPath()