text:
Q: Collect unique and the newest objects with Sets in Java Suppose I have a class (response model)
TransactionResult {
    private List<Transaction> transactions;
}

Transaction {
    private OffsetDateTime date;
    private String account;
}

and I want to have unique transactions by account and should be the newest by date. So, I have mapped dto
TransactionResultDto {
    private Set<TransactionDto> transactions;
}

TransactionDto implements Comparable<TransactionDto> {
    private OffsetDateTime date;
    private String account;

    //equals and hashcode only using account
    //compareTo using date
}

Firstly, I collect into a TreeSet to sort the transactions (newest are first) and then I build a HashSet to have unique transactions by account.
Set<TransactionDto> transactions = new HashSet<>(
                transactionResult.getTransactions().stream()
                        .map(transaction -> mapToTransactionDto(transaction))
                        .collect(Collectors.toCollection(TreeSet::new)));

So, the questions are:

*

*Is this the right way to collect the newest and unique by account transactions?

*Do you have any improvements or other ideas?

A: 1. No, it is incorrect to use TreeSet for this case.
Suppose we have transactions:
{"account": "A", "date": "2022-01-01"},
{"account": "B", "date": "2022-01-01"}(omit time for simplicity).
They are considered the same object if you put them in TreeSet as you only compare date.(i.e. only 1 objects remain if you put both in TreeSet).
What you may face is some account records may disappear when the date collides with another account. It may be extremely rare but it will cost you days to debug if it really occurs.
2. Let's fix it and make it more descriptive
Your method can also be fixed by using sort, and then put it to HashSet. However, this approach has some drawbacks:

*

*The logic is not straightforward, as the reader needs time to figure out what it is trying to achieve.

*Override hashcode and equals to consider account only may cause trouble when other users expect both account and date should be considered.

As what you really want is

*

*groupBy account

*select transaction with max date in each group.

We can use Collectors#groupingBy and then select Collectors#maxBy for downstream, as shown below:
Set<TransactionDto> transactions = transactionResult.getTransactions().stream().map(TransactionDto::new)
       .collect(
               groupingBy(TransactionDto::getAccount,
                       collectingAndThen(
                               maxBy(Comparator.comparing(TransactionDto::getDate)),
                               Optional::get)
               )
       ).values().stream()
       .collect(toSet());

A: I would probably just loop over them in one pass. You can use a HashMap to store the newest for each account and then build a set from the HashMap's values.
You asked for other tips so I would:

*

*Have a method that just finds the transactions you want. Converting to DTO or anything else can be handled elsewhere.

*Have equals and hash use all the fields, otherwise it won't be useful for other use cases. For example, I wrote some unit tests for my method below and having equals and hash using all fields was very useful.

*I would personally not implement comparator here for this task. You can imagine other useful ways of ordering these for different tasks and I don't think this object really has an intrinsic order. You can always implement as many custom comparators as you like but I personally wouldn't wouldn't do this either for this task.

*Without knowing much about the architecture of your system, I would expect DTOs to be for transferring data and domain objects to have functionality, so I would move logic to those classes. Your architecture might be different.

To build a collection of the newest transactions, I would probably do something like this:
private Collection<Transaction> findNewestForEachAccount(Collection<Transaction> transactions) {
    HashMap<String, Transaction> result = new HashMap<>();
    for (Transaction t : transactions) {
        if (isNewestForAccountSoFar(result, t)) {
            result.put(t.getAccount(), t);
        }
    }
    return result.values();
}

private boolean isNewestForAccountSoFar(HashMap<String, Transaction> result, Transaction t) {
    return !result.containsKey(t.getAccount())
        || isNewer(t, result.get(t.getAccount()));
}

private boolean isNewer(Transaction candidate, Transaction incumbent) {
    return candidate.getDate().isAfter(incumbent.getDate());
}

You could then build your DTOs like this:
    List<Transaction> transactions = transactionResult.getTransactions();
    Set<TransactionDto> selectedTransactionDTOs = findNewestForEachAccount(transactions)
        .stream()
        .map(t -> mapToTransactionDto(t))
        .collect(Collectors.toSet());

One option would be to move the logic for finding the newest transactions to your TransactionResult class. This would mean you wouldn't have to expose the getter for the entire list. This depends on your architecture though so your mileage may vary.


text:
Q: Issue with centre alignment of text in flexbox and headings Currently the text headings which are inside a flexbox (the three divs) are not aligning with the main headings on the rest of the page.
See Image Here
The issue appears to only take place with the character length of the text headings inside the flexbox of three divs are not the same.
See Image of Alignment when character length is the same
I've unsuccessfully tried css alignments, but they do not appear to have an effect. My desired outcome for the three divs is something like this:
See successful reference alignment example
The code is here:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  max-width: 100vw;
  list-style: none;
  scroll-behavior: smooth;

}
body {
  height: 100%;
  margin: 0;
  background-color: white;
  font-family: Poppins;
  min-height: 100vh;
}

a {
  color: black;
}

/* ----------------------------------------------------------Landing Page -------------------------------------*/
.full-height-grow {
  height: 100%;
  display: flex;
  flex-direction: column;
}

section {
  display: flex;
  height: 100vh;
  width: auto;
  max-width: 80vw;
  min-width: 75vw;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

.about-container {
  padding-top: 100px;
  height: 100vh;
  width: 90vw;
  max-width: 90vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;

}

.about-img {
    border-radius: 50%;
    height: calc(80px + 40%);
    width: auto;
}
.about-h1 {
    font-family: 'Poppins', sans-serif;
    color: rgb(255, 42, 95);
    margin-top: 30px;
    margin-right: -30px;
    margin-left: -30px;
    font-size:calc(12px + 0.8vw) ;
}

.about-h2 {
    font-family: 'Poppins', sans-serif;
    color: rgb(17, 17, 17);
    margin-right: -30px;
    margin-left: -30px;
    font-size:calc(15px + 2vw) ;
    font-weight: 500;
    opacity: 0.9;
}

.about-desc {
    font-family: Lora;
    font-size:calc(10px + 1.2vw);
    line-height: 1.8;
    color: #888888;
    text-align: center;
    margin-left: 25vw;
    margin-right: 25vw;
   overflow:hidden;
   z-index: 2;
   width: auto;

}
.about-tasks-container {
    align-self: center;
   background-color: blanchedalmond;
    max-width: 80vw;
    width: 80vw;
    display: flex;
    justify-content: space-evenly;
    text-align: center;
    flex-direction: row;
    flex-grow: 1;

}

.about-task-heading {

    font-size: 80px;

}

.about-tasks-resources {

}

.about-tasks-learning {

}

 ABOUT

More About Me

Example

Exampler

Examplers

(JSFiddle : https://jsfiddle.net/2cL5h4m6/9/)

A: Try this code
Idk if this is what you wanted but you can try it and you can see if it was the thing you looked for
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  max-width: 100vw;
  list-style: none;
  scroll-behavior: smooth;

}
body {
  height: 100%;
  margin: 0;
  background-color: white;
  font-family: Poppins;
  min-height: 100vh;
}

a {
  color: black;
}

/* ----------------------------------------------------------Landing Page -------------------------------------*/
.full-height-grow {
  height: 100%;
  display: flex;
  flex-direction: column;
}

section {
  display: flex;
  height: 100vh;
  width: auto;
  max-width: 80vw;
  min-width: 75vw;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

.about-container {
  padding-top: 100px;
  height: 100vh;
  width: 90vw;
  max-width: 90vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;

}

.about-img {
    border-radius: 50%;
    height: calc(80px + 40%);
    width: auto;
}
.about-h1 {
    font-family: 'Poppins', sans-serif;
    color: rgb(255, 42, 95);
    margin-top: 30px;
    margin-right: -30px;
    margin-left: -30px;
    font-size:calc(12px + 0.8vw) ;
}

.about-h2 {
    font-family: 'Poppins', sans-serif;
    color: rgb(17, 17, 17);
    margin-right: -30px;
    margin-left: -30px;
    font-size:calc(15px + 2vw) ;
    font-weight: 500;
    opacity: 0.9;
}

.about-desc {
    font-family: Lora;
    font-size:calc(10px + 1.2vw);
    line-height: 1.8;
    color: #888888;
    text-align: center;
    margin-left: 25vw;
    margin-right: 25vw;
   overflow:hidden;
   z-index: 2;
   width: auto;

}
.about-tasks-container {
    align-self: center;
   background-color: blanchedalmond;
    max-width: 100vw;
    width: 100vw;
    display: flex;
    justify-content: space-evenly;
    text-align: center;
    flex-direction: row;
    flex-grow: 0;

}

.about-task-heading {
 font-size: 30px;

}

.about-tasks-resources {

}

.about-tasks-learning {

}```

redpajama_set_name: RedPajamaStackExchange


text:
Q: EmberJs 1.5.x change log url Where can i find ember v1.5.x changelog, there was an update on the 23/04/2014, that is causing some strange behaviour in my application
I have visited http://emberjs.com/blog/ and found nothing,
I also know that it is a minor change to 1.5 1.6 isnt scheduled for release.

A: The changelog is located here, you can generally find it on the release page.

A: Maybe here:
https://github.com/emberjs/ember.js/blob/master/CHANGELOG.md
or you can see all commits, comments, versions related to the changelog file
https://github.com/emberjs/ember.js/commits/master/CHANGELOG.md


text:
Q: Join several strings I have for example 3(or n) strings like this, with always the same length :
"abc                            "
"         xy                    "
"         xy   ----             "
"              ----             "
"              ----     xcv     "

What's the best way to combine these strings to :
"abc      xy   ----     xcv     "

A: Using Array#reduce and Array#forEach you can do something like this

var a = "abc                            ",
  b = "         xy                    ",
  c = "         xy   ----             ",
  d = "              ----             ",
  e = "              ----     xcv     ";

var res = [
  a.split(''), // split intosingle character array
  b.split(''),
  c.split(''),
  d.split(''),
  e.split('')
].reduce(function(arr, v) { // iterate and generate character array
  // iterate each array element and set arr value if non space character found
  v.forEach(function(v1, i) {
    if (v1.trim().length)
      arr[i] = v1;
  })
  // return updated array
  return arr;
// set initial value as an array of string size  and fill it with ' '(space)
}, new Array(a.length).fill(' ')).join(''); // join the result array to generate the string

console.log(res);


text:
Q: moderncv - How do I put the date column on the right rather than on the left The career advisor at my university suggests putting the title of the position on the left, and dates on the right side of the resume.
I'm wondering how to I do that in moderncv themes?
Edit: My apologies for not closing this question. I totally forgot it.
The comment by xavier is the answer i was looking for but I'll accept the post as the correct answer for the credit.

A: You can right-align dates by doing something like this:
Store Clerk \hfill 2008-2012

It might be wiser to create your own commands for positions and dates, such that you can format them differently later without having to retype anything.
Here is an example of what I mean:
\newcommand{\rdate}[1]{\textsc{#1}}
\newcommand{\position}{\par\noindent\hspace*{0pt}\ignorespaces}
\newcommand{\details}{\par\noindent\hspace*{30pt}\ignorespaces}

You could then write \position{Store Clerk}followed by \hfillfollowed by \rdate{Aug 2008-Sep 2012}
Why would you consider putting the dates or other information into custom environments? You might realize later that some of your lines are too long. Perhaps the left-aligned information overlaps the date. This would be no problem, because you could just make the text smaller, for example \newcommand{\details}[1]{\par\noindent\hspace*{30pt}\ignorespaces{\tiny #1}

Two Youtube Videos might help you (although they use the article class)

*

*CV Part One

*CV Part Two


text:
Q: LINQ groupby and json output my task is to group the data from a list of Subscription object which has the following structure:
public class Subscription
{
    public string ApplicationId { get; private set; }
    public string UserCode { get; private set; }
    public string SubscriptionId { get; private set; }
    public string SubscriptionCode { get; private set; }
    public DateTime? StartDate { get; private set; }
    public DateTime? EndDate { get; private set; }
}

The code return a list of subscription, so List. In my case I've several items with same ApplicationId but different StartDate and EndDate. Basically I have to group these items
in order to create a json structure like this:
"applicationId" : {
    "subscriptions" : [
        {
            "startdate"  : ...,
            "enddate"  : ...,
        },
        {
            "startdate"  : ...,
            "enddate"  : ...,
        },
    ]
}

Can I achieve this using LINQ?

A: Try this:
subscriptions.GroupBy(item => item.SubscriptionCode)
.Select(group => new { Subscription = group.Key, Items = group.Select(item => new { StartDate = item.StartDate, EndDate = item.EndDate}) })

Not sure if it will work but it reads like it will.
subscriptions is just a list of your object.


text:
Q: PHP Compare result to high score database returns duplicate values I have a jQuery function that send the result time variable to a php file that compares the result to the database and returns 1 if it is a new highscore.. but for some reason it is returning 111
Here is the PHP:
require_once('db.php');

$sql = "SELECT score FROM highscores ORDER BY score ASC LIMIT 10";
$result = mysqli_query($con, $sql);
$score = $_POST['time'];

while($row = mysqli_fetch_array($result)) {
    if($row['score'] > $score) {
        echo 1;
    }
}

and then the jquery function:
jQuery.ajax({
    url:'model/highscore.php',
    type:'POST',
    data: {time:totalTime},
    success:function(result){
        highScore = result;
    }
});

Any Help Greatly Appreciated.

A: Why don't you modify your SQL Query to your needs?
You are fetching the 10 highest scores, and loop through all of them, to check, how many scores are actually higher than yours. But you actually don't check, if your score is higher than the highest.
If you want to check, if your score is the highest, count all scores that are higher than yours. If there is none (count = 0), you know you got the highest.
Edit:
Here is the complete script:
$score = $_POST['time']; // Format "00:00:02.95";
$sql = "SELECT Count(score) as c FROM highscores WHERE score > '".mysqli_real_escape_string($score)."'";
$result = mysqli_query($con, $sql);
$count = mysqli_fetch_object($result)->c;
if(!is_null($count) && $count < 1 )
    echo 1;
}

Adding the escaping function is mandatory to protect against SQL injection!
You should also find a better data-type for your score, because varchar is not the best respresentation for a timestamp.
I am out now.
Edit: Check if $count is not null

A: Without seeing the database itself this is mostly a guess, but I'm guessing it's returning 3 separate scores from your database. You need to limit your query to 1.

A: This is happening because you are looping through 10 highscores record and it found 3 higher result so it printed three time 1, like it was
echo 1;
echo 1;
echo 1;

that outputs
111

You can just put a break after your echo 1
echo 1;
break;


text:
Q: Parsing Web Page Using Python 3.x and Beautiful Soup I'm trying to parse this web-page by the categories of the headers (Searchable By, Special Summoned from Hand by, etc) I've looked around for a good parser for 3.3 but all I could find was BeautifulSoup (which I can't install because it's still coded in 2.x) and lxml which I can't understand. I try reading the HTML itself and searching the code for the headers but to no avail. Can anyone help me?

A: Actually you could use Beautiful Soup for Python 3.x. Beautiful Soup homepage says:
Beautiful Soup 4 works on both Python 2 (2.6+) and Python 3.

Beautiful Soup is licensed under the MIT license, so you can also download the
tarball, drop the bs4/ directory into almost any Python application (or into
your library path) and start using it immediately. (If you want to do this under
Python 3, you will need to manually convert the code using 2to3.)

If you need help on how to manually convert Python 2 code to Python 3, refer to Converting BeautifulSoup 4 for Python 3 for instructions. HTH.


text:
Q: How to get *my* ip from udp endpoint Boost.Asio's udp::endpoint has a member that is remote address. Because I'm listening on multiple interfaces (like this):
udp_socket(io_service, udp::endpoint(udp::v4(), port))

In my handler, I do not know which network interface received the packet.
Without iterating over network interfaces and looking for a similarity between the endpoint address and my IP on each interface, can I get my IP for the interface that I got message from?

A: No.  Boost.Asio does not expose the ability to identify the datagram's destination address.
The socket::aync_receive_from() and socket::receive_from() operations perform the native socket operations within boost::asio::detail::socket_ops::recvfrom().  On Windows, WSARecvFrom() provides no way to extract lower layer information from the protocol stack.  On Linux, the IP_PKTINFO socket option can provided to datagram oriented sockets enabling recvfrom() to populate the msghdr.msg_control buffer with ancillary information, such as the interface index on which the packet was received and the destination address in the packet header.  However, the Boost.Asio implementation does not use themsg_control field:
msghdr msg = msghdr();
init_msghdr_msg_name(msg.msg_name, addr);
msg.msg_namelen = static_cast<int>(*addrlen);
msg.msg_iov = bufs;
msg.msg_iovlen = static_cast<int>(count);
signed_size_type result = error_wrapper(::recvmsg(s, &msg, flags), ec);

As suggested in this answer, one can:

*

*Use lower-level system calls. (i.e. IP_PKTINFO and recvfrom())

*Explicitly bind a socket to each interface rather than INADDR_ANY, causing the socket::local_endpoint() to return a specific interface.  The completion handlers will need some way to obtain the local endpoint on the socket for which the operation was invoked, such as passing a reference to the socket or its local endpoint via boost::bind().

A: As far as I understand you have different boost::asio::ip::udp::sockets. And in case one of them recieves a message you want to know the local ip address of that socket/the interface that socket uses.
So if socket is the socket that recives the msg you should be able to get the ip in the handler by
socket.local_endpoint().address()

See local_endpoint() and address() in the boost manual.

A: i think you should explicit specify the address rather than simply a protocol
udp_socket(io_service, udp::endpoint(boost::asio::ip::address::from_string(""), port))

so that you can use udp_socket.local_endpoint().address() to get the ip.


text:
Q: Como medir los fps Tengo una función Render que se repite infinitamente gracias a la función RequestAnimationFrame necesito una manera de medir los fps para comprobar las estabilidad de mi juego
function Render(){
  window.requestAnimationFrame(Render)
}

A: requestAnimationFrame recibe una timestamp como argumento, que son los milisegundo transcurridos
Un FPS es 1/T, con T en segundos, o 1000/T con T en milisegundos
Yo tenía un ejemplo de una bola rebotando, lo adecué para mostrar cómo se puede  medir los FPS. En el código deje enmarcado una pequeña porción que es lo que tu buscas

const sizeSVG = document.getElementsByTagName("svg")[0].getBoundingClientRect();
let FPS=50;
//Esto no es relevante
window.onload = () =>{
       bola1.incX = GetRandomVelocidad();
       bola1.incY = GetRandomVelocidad();
       bola1.dirX = 1;
       bola1.dirY = 1;
       bola1.radio = Number(bola1.getAttribute("r"));
       bola1.posXActual= Number(bola1.getAttribute("cx"));
       bola1.posYActual= Number(bola1.getAttribute("cy"));
       window.requestAnimationFrame(animar);
}

function GetRandomVelocidad(){
  return Math.floor(Math.random() * 100) + 1;
}

// Esto es lo que te interesa------------
let lastTimestamp = 0;
function animar(timestamp) {

    FPS = 1000 / (timestamp - lastTimestamp);
    lastTimestamp = timestamp;
    FPS_DIV.innerText= FPS.toFixed(0);
    //console.log(FPS);
//hasta aqui-----------------------------

    bola1.posXActual += bola1.dirX * bola1.incX / FPS;
    bola1.posYActual += bola1.dirY *  bola1.incY / FPS;

    if ((bola1.posXActual-bola1.radio)<=0 || (bola1.posXActual+bola1.radio)>=sizeSVG.width)
    {
      bola1.dirX*=-1;
    }
    if ((bola1.posYActual-bola1.radio)<=0 || (bola1.posYActual+bola1.radio)>=sizeSVG.height)
    {
      bola1.dirY*=-1;
    }

    bola1.setAttribute("cx",bola1.posXActual);
    bola1.setAttribute("cy",bola1.posYActual);

    window.requestAnimationFrame(animar);
}
FPS:

<svg width="100%" height="100vh">
  <circle id="bola1"  cx="80" cy="20" r="20" stroke="green" stroke-width="4" fill="yellow"/>
</svg>

Nota: El máximo FPS de requestAnimationFrame, según la documentación es de 60


text: Q: Setting a PrintJob name Is it possible to set the name for a PrintJob when printing a MovieClip? At the moment the PrintJob is just called "Flash" and when i try to save it as a PDF it is named "Flash.pdf".


text:
Q: CGEventPostToPSN not working for cgkeycode (56) I am trying to send keyboard event to a process. Seding keys like 'a', 'v' 't' ... works fine but keys such as space, command, control doesn't work. Here's what I am doing:
CGEventRef e1 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)55, YES);
CGEventRef e4 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)0, YES);

CGEventPostToPSN(&spotPSN, e1);
CGEventPostToPSN(&spotPSN, e4);

e4 works, but e1 doesn't. My purpose here is to send command+a for select all.
Thanks.

A: You need to set the command key as a flag of the keyboard event for letter 'a' instead of posting another event for the command key:
// virtual key code for letter 'a'
CGKeyCode keycode = 0;

// keyboard event for letter 'a'
CGEventRef event = CGEventCreateKeyboardEvent(NULL, keycode, true);

// modify keyboard event so that it becomes 'command-a'
CGEventSetFlags(event, kCGEventFlagMaskCommand);

For a list of possible event flags, see the Quartz Event Services Reference.


text:
Q: What is the difference between passport-google-oauth and passport-google-token? I am trying to validate my node app using google. But I found these two modules being used in different tutorials. Could you please tell what the difference is between these two.
passport-google-token

On the npmjs.com page of both, i found the desc as  Passport strategy
  for authenticating with Google access tokens using the OAuth 2.0 API.
  This module lets you authenticate using Google in your Node.js
  applications. By plugging into Passport, Google authentication can be
  easily and unobtrusively integrated into any application or framework
  that supports Connect-style middleware, including Express.

passport-google-oauth

Passport strategies for authenticating with Google using OAuth 2.0.
Lead Maintainer: David Pate
This module lets you authenticate using Google in your Node.js
  applications. By plugging into Passport, Google authentication can be
  easily and unobtrusively integrated into any application or framework
  that supports Connect-style middleware, including Express.

A: passport-google-oauth was made for express apps, so you can configure permissions, callback uri and request user data, all in the same place.
passport-google-token is made for REST APIs, so you handle authentication logic in front-end and then, you send google token to the back-end (node server) and there you can request user data using google token and grant access to your app using your own authentication mechanism (JWT, Bearer Token, etc.).


text:
Q: Simple while loop, that appends user input into a list ; not working I'm trying to write a simple code that takes a user input and appends whatever number user typed in into a list. Lastly when the user types "done", the loop stops.
a = []
user_input = input("Please enter a number: ")
while user_input:
    if user_input == "done":
        break
    int(user_input)
    a.append(user_input)
print(a)

But for some reason when I type done, the loop doesn't stop and the list does not get printed.

A: Put the input() inside the loop like so:
a = []
while True:
    user_input = input("Please enter a number: ")
    if user_input == "done":
        break
    user_input = int(user_input)
    a.append(user_input)
print(a)

A: I would suggest checking the indentation then and make sure that everything is indented correctly.
I just  copied your code here : https://www.programiz.com/python-programming/online-compiler/
and it printed out the list .
The print statement needs to have the same "level of indentation" as the "while true " statement

A: The user_input never changes inside the loop, so it will never terminate. You need to put the input call inside the loop.
If the list still doesn't get printed (as you seemed to indicate on another answer), the problem is somewhere else. It could possibly be a problem with the interpreter/terminal, since from your question it seems you are able to input more data even though the loop should prevent you from doing that.


text:
Q: Create transitions on data change d3.js I'm trying to create a chart which basically has a number of horizontal lines on it. The data for the lines is taken from the function that generates random arrays of objects like this:
{
    "process": 2,
    "time": 5
}

And also there is a setInterval function that redraws the chart every 3s. How can I make it change not that abruptly, but with easing and transitions?
Here is my code below:
html:

Operating System Processes Model

Enter the number of processes:

    <input type="number" min="0" max="30" id="input">

<svg id="visualisation" width="1000" height="500"></svg>

utils.js:
// Renders grid in the system of axes
function renderGrid() {
    // Vertical lines
    for(var i = 5; i <= 50; i+=5) {
        vis.append('svg:path')
            .attr('d', lineGen(
                [
                    {
                        "process": "0",
                        "time": + i
                    },
                    {
                        "process": "50",
                        "time": + i
                    },
                ]
            ))
            .attr('stroke', '#777')
            .attr('stroke-dasharray', "5,5")
            .attr('stroke-width', 1)
            .attr('fill', 'none');
        // Horizontal lines
        vis.append('svg:path')
            .attr('d', lineGen(
                [
                    {
                        "process": i,
                        "time": "0"
                    },
                    {
                        "process": i,
                        "time": "50"
                    },
                ]
            ))
            .attr('stroke', '#777')
            .attr('stroke-dasharray', "5,5")
            .attr('stroke-width', 1)
            .attr('fill', 'none');
    };
}

// Generate single line
var lineGen = d3.svg.line()
                    .x(function(d) {
                        return xScale(d.time);
                    })
                    .y(function(d) {
                        return yScale(d.process);
                    })
                    .interpolate("basis");

// Generate random color
function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

// Generate random data array
function getDataArray(count) {
    var array = [];
    for(var i = 0; i < count; ++i) {

        var proc = Math.round(Math.random() * (50 - 1)) + 1;
        var time1 = Math.round(Math.random() * (50 - 1)) + 1;
        var time2 = Math.round(Math.random() * (50 - 1)) + 1;

        var data = [
            {
                "process": proc,
                "time": Math.max(time1, time2)
            },
            {
                "process": proc,
                "time": Math.min(time1, time2)
            },
        ];

        array.push(data);

    }
    return array;
}

// Generate random data
function renderProcesses() {

    vis.selectAll('.line-process').remove();

    // var processCount = Math.round(Math.random() * (50 - 1)) + 1;
    var processCount = document.getElementById('input').value;

    var arr = getDataArray(processCount);

    for(var i = 0; i < processCount; ++i) {

        var processLength = Math.round(Math.random() * (50 - 1)) + 1;

        var color = getRandomColor();

        vis.append('svg:path')
            .attr('class', 'line-process')
            .attr('d', lineGen(arr[i]))
            .attr('stroke', color)
            .attr('stroke-width', 5)
            .attr('stroke-linecap', 'round')
            .attr('fill', 'none')

            .on("mouseover", function() {
                d3.select(this)
                    .attr('stroke', "#1abc9c");
            })
            .on("mouseout", function() {
                d3.select(this)
                    .attr('stroke', color)
            });
    }
}

axis.js:
// Draw the axis

var vis = d3.select("#visualisation"),
    width = 1000,
    height = 500,
    margins = {
        top: 20,
        right: 20,
        bottom: 20,
        left: 50
    },
    xScale = d3.scale.linear().range([margins.left, width - margins.right]).domain([0,50]),
    yScale = d3.scale.linear().range([height - margins.top, margins.bottom]).domain([0,50]),
    xAxis = d3.svg.axis()
                .scale(xScale),
    yAxis = d3.svg.axis()
                .scale(yScale)
                .orient('left');

vis.append("svg:g")
    .transition()
    .attr("transform", "translate(0," + (height - margins.bottom) + ")")
    .attr("class", "axis")
    .call(xAxis);

vis.append("svg:g")
    .transition()
    .attr("transform", "translate(" + (margins.left) + ",0)")
    .attr("class", "axis")
    .call(yAxis);

styles for the axises:
.axis {

    path {
        fill: none;
        stroke: #777;
        shape-rendering: crispEdges;
    }

    text {
        font-family: Lato;
        font-size: 12px;
    }
}

and finally, main.js:
renderGrid();
setInterval(renderProcesses, 3000);

Here is the screenshot:

So, Could you help me with those transitions?
And, another question, as you can see on the screenshot, some lines can be drown on each other. How can I avoid it?


text:
Q: UIDatePicker and Two Buttons from different time Start app.

Choice of hour and secondButton. I want different hour.

I have two buttons and one DatePicker. set datePickerMode = .time.
I need to set two different hours on different buttons.
Unfortunately, I could not find solutions for this.
This is my code:
class ViewController: UIViewController  {
    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(firstButton)
        firstButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 100).isActive = true
        firstButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
        firstButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true
        firstButton.heightAnchor.constraint(equalToConstant: 100).isActive = true

        view.addSubview(secondButton)
        secondButton.topAnchor.constraint(equalTo: firstButton.bottomAnchor, constant: 10).isActive = true
        secondButton.leftAnchor.constraint(equalTo: firstButton.leftAnchor).isActive = true
        secondButton.rightAnchor.constraint(equalTo: firstButton.rightAnchor).isActive = true

        view.addSubview(myDatePicker)
        myDatePicker.topAnchor.constraint(equalTo: secondButton.bottomAnchor, constant: 10).isActive = true
        myDatePicker.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10).isActive = true
        myDatePicker.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10).isActive = true
    }

    // MyFirstButton
    let firstButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("First", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.tintColor = .white
        button.tag = 0
        button.addTarget(self, action: #selector(handleButton), for: .touchUpInside)
        return button
    }()

    // MySecondButton
    let secondButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Second", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.tintColor = .white
        button.tag = 1
        button.addTarget(self, action: #selector(handleButton), for: .touchUpInside)
        return button
    }()

    // Target First and Second Button
    @objc func handleButton() {
        view.layoutIfNeeded()
        UIView.animate(withDuration: 0.25, animations: {
            self.view.layoutIfNeeded()
        }) { (completed) in
            UIView.animate(withDuration: 0.25, animations: {
                self.myDatePicker.alpha = 1
                self.view.layoutIfNeeded()
            })
        }
    }

    // DataPicker
    let myDatePicker: UIDatePicker = {
        let pv = UIDatePicker()
        pv.timeZone = .current
        pv.datePickerMode = .time
        pv.backgroundColor = .white
        pv.translatesAutoresizingMaskIntoConstraints = false
        pv.addTarget(self, action: #selector(handleMyDatePicker), for: .valueChanged)
        return pv
    }()

    // Target
    @objc func handleMyDatePicker(sender: UIDatePicker) {
        let formatter = DateFormatter()
        formatter.timeStyle = .short
        let selectedTime = formatter.string(from: sender.date)

        firstButton.setTitle(selectedTime, for: .normal)

        // here is the problem
        secondButton.setTitle(selectedTime, for: .normal)

        myDatePicker.alpha = 0
    }

How to achieve this effect?

A: Set your myDatePicker tag to same with button, that you touched
@objc func handleButton(button: UIButton) {
    view.layoutIfNeeded()
    UIView.animate(withDuration: 0.25, animations: {
        self.view.layoutIfNeeded()
    }) { (completed) in
        UIView.animate(withDuration: 0.25, animations: {
            self.myDatePicker.alpha = 1

            self.myDatePicker.tag = button.tag
            self.view.layoutIfNeeded()
        })
    }
}

@objc func handleMyDatePicker(sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.timeStyle = .short
    let selectedTime = formatter.string(from: sender.date)
    let button = self.view.viewWithTag(sender.tag) as? UIButton
    button?.setTitle(selectedTime, for: .normal)
    myDatePicker.alpha = 0
}

and small change in your addTarget code
button.addTarget(self, action: #selector(handleButton(button:)), for: .touchUpInside)


text:
Q: Connect Power BI Desktop to .odc file I have an .odc file that connects to a cube. It opens a pivot table.
It seems it's not possible to connect Power BI to this file directly as seen here, but how do I retrive the server name, database name, user id and password from this file?

A: .odc files are actually a text file. Open it with any text editor and it should tell you the data source type and connection details.


text:
Q: Calling a single method from a list of methods of an interface Can someone explain why getStartScreen() is the only method in the interface Game that gets added as an unimplemented method in MrNomGame class?
public class MrNomGame extends AndroidGame
{
     public Screen getStartScreen()
     {
        return new LoadingScreen(this); // Instantiate class
     }
}

public abstract class AndroidGame extends Activity implements Game
{
     AndroidFastRenderView renderView;
     Graphics graphics;
     Audio audio;
     Input input;
     FileIO fileIO;
     Screen screen;
     WakeLock wakeLock;

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    boolean isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
    int frameBufferWidth = isLandscape ? 480 : 320;
    int frameBufferHeight = isLandscape ? 320 : 480;
    Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
            frameBufferHeight, Config.RGB_565);

    float scaleX = (float) frameBufferWidth
            / getWindowManager().getDefaultDisplay().getWidth();
    float scaleY = (float) frameBufferHeight
            / getWindowManager().getDefaultDisplay().getHeight();

    renderView = new AndroidFastRenderView(this, frameBuffer);
    graphics = new AndroidGraphics(getAssets(), frameBuffer);
    fileIO = new AndroidFileIO(this);
    audio = new AndroidAudio(this);
    input = new AndroidInput(this, renderView, scaleX, scaleY);
    screen = getStartScreen();  //unimplemented method from MrNomGame
    setContentView(renderView);

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "GLGame");
}

@Override
public void onResume() {
    super.onResume();
    wakeLock.acquire();
    screen.resume();
    renderView.resume();
}

@Override
public void onPause() {
    super.onPause();
    wakeLock.release();
    renderView.pause();
    screen.pause();

    if (isFinishing())
        screen.dispose();
}

public Input getInput() {
    return input;
}

public FileIO getFileIO() {
    return fileIO;
}

public Graphics getGraphics() {
    return graphics;
}

public Audio getAudio() {
    return audio;
}

public void setScreen(Screen screen) {
    if (screen == null)
        throw new IllegalArgumentException("Screen must not be null");

    this.screen.pause();
    this.screen.dispose();
    screen.resume();
    screen.update(0);
    this.screen = screen;
}

public Screen getCurrentScreen() {
    return screen;
}

}

public interface Game
{
    public Input getInput();
    public FileIO getFileIO();
    public Graphics getGraphics();
    public Audio getAudio();
    public void setScreen(Screen screen);
    public Screen getCurrentScreen();
    public Screen getStartScreen();
}

A: MrNomGame class extends an abstract class AndroidGame. As MrNomGame is a concrete class, it must implement all abstract methods of its parent. Abstract class AndroidGame has no implementation of getStartScreen() method and because of this, it gets added as an unimplemented method in MrNomGame class.


text:
Q: how to make a day from date in LibreOffice? I want to convert date into a Day
I am using LibreOffice
I used some of its syntax weekday and text but it returns  nothing
WEEKDAY("30-04-2019"; 1) is there any way to do that?
in google sheet i used =TEXT(C7758,"dddd") but it didn't work
how can I do that?
thanks in advance

A: Try the combination of functions WEEKDAY and DATE:
=WEEKDAY(DATE(2019;4;30))

The specific example will return 3 which is Tuesday (see all days and other options at https://wiki.openoffice.org/wiki/Documentation/How_Tos/Calc:_WEEKDAY_function)
Hope that helps.


text:
Q: How to write Tables in SQL with a Disjoint Connection So I have three tables which I want to create with a disjoint Connection. These are person, Tenant and employee.
So every person must either be a Tenant or an employee, never both.
I create a Person table with the PersonID primary key, and tenant and Employee as two separate tables whose Primary Keys are both Foreign Keys linking back to the Person(PersonID).
How do i create a Disjoint here where every Person can only be either a Tenant or an Employee? Thanks

A: You can try this, which will pick out every person who is EITHER a person OR an employee:
SELECT *
FROM (SELECT person.*,
             CASE WHEN employee.id IS NULL THEN 0 ELSE 1 END AS is_employee,
             CASE WHEN tenant.id   IS NULL THEN 0 ELSE 1 END AS is_tenant
      FROM person LEFT JOIN employee on person.id = employee.id
                  LEFT JOIN tenant on person.id = tenant.id) AS tA
WHERE tA.is_employee <> tA.is_person

Make sure that the id columns are all indexed.


text:
Q: Parse.com login using email or username android I have been trying to get this code to work, but I had no success.
All I want is to be able to login using either Email or username. I have already tried some methods but they did not work.
Here is the code I am using:
private EditText mUsernameEmailEtxt;
private EditText mPasswordEtxt;
private Button mSignupBtn;
private Button mSigninBtn;

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

    // Get view references
    mPasswordEtxt = (EditText) findViewById(R.id.password);
    mUsernameEmailEtxt = (EditText) findViewById(R.id.username);
    mSigninBtn = (Button) findViewById(R.id.btn_sign_in);
    mSignupBtn = (Button) findViewById(R.id.btn_sign_up);

    // Setup button click listeners
    mSigninBtn.setOnClickListener(new SignInOnClickListener());
    mSignupBtn.setOnClickListener(new SignUpOnClickListener());
}

// Input validation
private boolean isFormInputValid(String username, String password) {
    mUsernameEmailEtxt.setError(null);
    mPasswordEtxt.setError(null);

    // validate the username or email
    if (username == null || username.isEmpty()) {
        mUsernameEmailEtxt.setError(getString(R.string.error_username));
        mUsernameEmailEtxt.requestFocus();
        return false;
    }
    // validate the password
    if (password == null || password.isEmpty()) {
        mPasswordEtxt.setError(getString(R.string.error_password));
        mPasswordEtxt.requestFocus();
        return false;
    }
    return true;
}

// OnClickListener Implementations
private class SignUpOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        // Get the username and password from the view
        String username = mUsernameEmailEtxt.getText().toString().toLowerCase();
        String password = mPasswordEtxt.getText().toString();
        if (isFormInputValid(username, password)) {
            Intent intent = new Intent(AuthenticationActivity.this, RegistrationActivity.class);
            intent.putExtra("ue", username);
            intent.putExtra("pw", password);
            startActivity(intent);
        } else {
        }
    }
};

private class SignInOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        // Get the username and password from the view
        final String username = mUsernameEmailEtxt.getText().toString().toLowerCase();
        final String password = mPasswordEtxt.getText().toString();
        if (isFormInputValid(username, password)) {
            if (!username.matches("@")) {
                String email = mUsernameEmailEtxt.getText().toString();
                ParseQuery<ParseUser> query = ParseUser.getQuery();
                query.whereEqualTo(email, username);
                query.getFirstInBackground(new GetCallback<ParseObject>() {
                    public void done(ParseObject object, ParseException e) {
                        ParseUser.logInInBackground(username, password, new LogInCallback() {
                            public void done(ParseUser user, ParseException e) {
                                if (user != null) {
                                    // Hooray! The user is logged in.
                                    Intent intent = new Intent(getBaseContext(), MainActivity.class)
                                            .addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                                                    Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    ParseUser.logInInBackground(username, password, new LogInCallback() {
                                        public void done(ParseUser user, ParseException e) {
                                            if (user != null) {
                                                // Hooray! The user is logged in.
                                                Intent intent = new Intent(getBaseContext(), MainActivity.class)
                                                        .addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                                                                Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                                startActivity(intent);
                                                finish();

                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }

@maxib7
Ive tried your method. But i want a way to login with my Email or my Username. But this doesn't work either,
private class SignInOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        // Get the username and password from the view
        final String username = mUsernameEmailEtxt.getText().toString().toUpperCase();
        final String password = mPasswordEtxt.getText().toString();
        if (isFormInputValid(username, password)) {
            if (!username.matches("@")) {
                String email = mUsernameEmailEtxt.getText().toString();
                ParseUser.logInInBackground(email, password, new LogInCallback() {
                            public void done(ParseUser user, ParseException e) {
                                if (user != null) {
                                    // Hooray! The user is logged in.
                                    Intent intent = new Intent(getBaseContext(), MainActivity.class)
                                            .addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                                                    Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    ParseUser.logInInBackground(username, password, new LogInCallback() {
                                        public void done(ParseUser user, ParseException e) {
                                            if (user != null) {
                                                // Hooray! The user is logged in.
                                                Intent intent = new Intent(getBaseContext(), MainActivity.class)
                                                        .addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                                                                Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                                startActivity(intent);
                                                finish();
                                            }
                                        }
                                    });
                                    ;
                                }
                            }
                        }
                );
            }
        }
    }
}

A: UPDATE: I found out a way to achieve this some time ago, but forgot to post it here. Here's the final code,
private class SignInOnClickListener implements View.OnClickListener {

    public void onClick(View v) {
        // Get the username and password from the view
        final String username_email = mUsernameEmailEtxt.getText().toString().toLowerCase().trim();
        final String password = mPasswordEtxt.getText().toString().trim();
        if (isFormInputValid(username_email, password)) {
            if (username_email.indexOf('@') != -1) {
                ParseQuery<ParseUser> query = ParseUser.getQuery();
                query.whereEqualTo("email", username_email);
                query.getFirstInBackground(new GetCallback<ParseUser>() {
                    public void done(ParseUser object, ParseException e) {
                        if (object == null) {
                            TextView error = (TextView) findViewById(R.id.info);
                            error.setVisibility(View.VISIBLE);
                            error.setText(getString(R.string.error_sign_in));
                            Log.d("error", "The getFirst request failed. Probably because no associated account found");
                        } else {
                            String actualUsername = (String) object.get("username");
                            ParseUser.logInInBackground(actualUsername, password, new LogInCallback() {
                                public void done(ParseUser user, ParseException e) {
                                    if (user != null) {
                                        // Hooray! The user is logged in.
                                        Intent intent = new Intent(getBaseContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                        startActivity(intent);
                                        finish();
                                    } else {
                                        TextView error = (TextView) findViewById(R.id.info);
                                        error.setVisibility(View.VISIBLE);
                                        error.setText(getString(R.string.error_sign_in));

                                        Log.d("error", "email or password  invalid");
                                    }
                                }
                            });
                        }
                    }
                });

            } else {
                Log.d("detector", "username_email detected as username:" + username_email);
                ParseUser.logInInBackground(username_email, password, new LogInCallback() {
                    public void done(ParseUser user, ParseException e) {
                        if (user != null) {
                            // Hooray! The user is logged in.
                            Intent intent = new Intent(getBaseContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                            finish();
                        } else {
                            TextView error = (TextView) findViewById(R.id.info);
                            error.setVisibility(View.VISIBLE);
                            error.setText(getString(R.string.error_sign_in));

                            Log.d("error", "username or password invalid");
                        }

                    }
                });
            }
        }
    }
}

A: Here's how I do it when I use parse to log in
/*
* Log user in
*/
public void setLoginButtonListener()
{
    Button LoginButton = (Button) rootView.findViewById(R.id.button_login);

    // listen for click to login button
    LoginButton.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v)
        {
            // views for login form
            final EditText emailView = (EditText) rootView.findViewById(R.id.login_email);
            final EditText passwordView = (EditText) rootView.findViewById(R.id.login_password);

            // Get the values of all the form fields
            final String email = emailView.getText().toString().trim();
            final String password = passwordView.getText().toString().trim();

            //Simple validation: if any field is empty then don't let the form submit
            if (email.isEmpty() || password.isEmpty())
            {
                // show an alert dialog with error message
                Dialog.Builder newBuilder = new SimpleDialog.Builder(R.style.SimpleDialogLight);
                ((SimpleDialog.Builder) newBuilder).message("Please make sure you entered all the fields correctly.")
                        .title("Oops!")
                        .positiveAction("OK");

                DialogFragment fragment = DialogFragment.newInstance(newBuilder);
                fragment.show(getFragmentManager(), null);
            }

            // log user in
            ParseUser.logInInBackground(email, password, new LogInCallback()
            {
                @Override
                public void done(ParseUser parseUser, com.parse.ParseException e)
                {
                    if (parseUser != null)
                    {
                        // parse login was successful
                        // TODO do what you want here
                    }
                    else
                    {
                        // Sign in failed. Look at the ParseException to see what happened
                        Dialog.Builder newBuilder = new SimpleDialog.Builder(R.style.SimpleDialogLight);
                        ((SimpleDialog.Builder) newBuilder).message(e.getMessage())
                                .title("Oops!")
                                .positiveAction("OK");

                        DialogFragment fragment = DialogFragment.newInstance(newBuilder);
                        fragment.show(getFragmentManager(), null);
                    }
                }
            });
        }

    });
}


text:
Q: Circular dependency problem "Single item in a set depends on the whole set. Set depends on that item."
I'm creating a compiler (https://github.com/SuperJMN/Plotty). In the last stage, the Intermediate Code is converted to Machine Instructions. I have them represented with the IntermediateCode and MachineCode classes.
To do it, I'm using the Visitor Pattern, that visits each of the elements of the list of Intermediate Codes. Each Intermediate Code can emit one or more MachineCodes.
It's working perfectly, but I have a big problem: one of the instructions that must be generated is dependent on the whole result! Concretely, there is an instruction that needs to know the index (ordinal) of another instruction has not been generated yet.
In other words, I have to emit an instruction that means "push the address of label X", when label X hasn't been emitted yet. The address of that label will only be known when all the instructions have been emitted.
The illustrate the problem better, this is similar to the creation of table of contents in a document. If you want to be able to create the TOC, where you want to specify the page number of a given section, first you have to generate the all the document, so you can then know the page of a given section.
Can you please tell me an algoritmo or a pattern to solve my problem? I don't know how to emit those pending-fix instructions.
Big thanks!

A: You can do a two pass compilation.
In the first pass emit the machine instructions as you do now.  When you encounter a label record its address in a symbol table.  When you encounter a reference to a label, check the symbl table.  If it has no entry for the label, create an entry for the label but leave its address blank and emit a placeholder in the stream of machine instructions.
In the second pass fill in the label references that you didn't know during the first pass.
By introducing the extra concepts symbol table, label and address you break the circular dependencies.


text:
Q: Variable changes its format on printing I am trying to store a variable with Key Value data in a file using Python, but when I try printing it, it comes up in a different format.
I want the result to be printed like this-
data={"name":'name',"description": "This is my offering","icon":"/csa/api/blobstore/Magic_RGB_blue_NT.png?tag=library","version": "1.0.0",
                  "design": {
                    "@self": "@self"
                    }
                }

This is the output I get while printing the data-
{'icon': '/csa/api/blobstore/Magic_RGB_blue_NT.png?tag=library', 'design': {'@self': '@self'}, 'name': 'name', 'version': '1.0.0', 'description': 'This is my offering'}

A: You haven't stated what is important to you when printing, nor how you are currently attempting to print.
There is no formatting within a dictionary.  Any formatting in your code is merely to make the code look human readable and is not actually stored within your data dictionary (only formatting within each string element is retained, ie, between a pair of quotes).
If it is merely the format (multiple lines and indents) that you are concerned about, the easiest way to resolve that is to use either the Pretty Print module or the JSON module - either should do the job, depending on your preferences for how you want the data to look and how much control you want to have over the printed output format.  In particular, the JSON output occupies more vertical screen space, but some people may think that it is marginally more human readable.
PrettyPrint pprint:
import pprint
data={"name":'name',"description": "This is my offering","icon":"/csa/api/blobstore/Magic_RGB_blue_NT.png?tag=library","version": "1.0.0","design": {"@self": "@self"}}
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(data)
>>>
{   'description': 'This is my offering',
    'design': {   '@self': '@self'},
    'icon': '/csa/api/blobstore/Magic_RGB_blue_NT.png?tag=library',
    'name': 'name',
    'version': '1.0.0'}
>>>

JSON dumps:
import json
data={"name":'name',"description": "This is my offering","icon":"/csa/api/blobstore/Magic_RGB_blue_NT.png?tag=library","version": "1.0.0","design": {"@self": "@self"}}
print(json.dumps(data, indent=4))
>>>
{
    "icon": "/csa/api/blobstore/Magic_RGB_blue_NT.png?tag=library",
    "design": {
        "@self": "@self"
    },
    "name": "name",
    "version": "1.0.0",
    "description": "This is my offering"
}
>>>

If you are concerned about the the order in which the items are printed, then you'll need to have an array that stores the keys in their preferred order (dictionaries don't have any inherant ordering), and then iterate through your keys and print the dictionary items out manually one by one (perhaps using a list comprehension on your keys array).

A: Python doesn't respect the indention or newlines you use to define your data structure, and ignores any format you had when print()ing it. You don't have very many options here, but perhaps you can use the json.dumps() function to format your code. The format does not match your expected output exactly, but it comes fairly close:
>>> data = {"name":'name',"description": "This is my offering","icon":"/csa/api/blobstore/Magic_RGB_blue_NT.png?tag=library","version": "1.0.0",
                  "design": {
                    "@self": "@self"
                    }
                }
>>> import json
>>> print(json.dumps(data, indent=2))
{
  "description": "This is my offering",
  "version": "1.0.0",
  "icon": "/csa/api/blobstore/Magic_RGB_blue_NT.png?tag=library",
  "name": "name",
  "design": {
    "@self": "@self"
  }
}
>>>

A: Note that a variable doesn't contain any formatting to be changed. The python interpreter reads text from the REPL or a file and turns them into  instructions for the CPU of your machine. None of this involves formatting until you call print(). By default, print() calls str() which then provides some very basic formatting. For dictionaries, this includes the curly braces, colons, and commas. If you want anything more than this, you will need to do it yourself. Alternatively, you can find a Python module that helps reduce some of the tedium.


text:
Q: Read data from firestore is undefined I'm trying to read data from firestore document specific vield but it is turn undefined. i dont know why, this is my code:
const [alluser, setAllUser] = useState([])
console.log(alluser.fullname)

useEffect(() => {
   db.collection('users').get().then((querySnapshot) => {
      const listUser = []
      querySnapshot.forEach((user) => {
          listUser.push(user.data())
      })
      setAllUser(listUser)
   })
}, [])

in my console log say "undefined". I don't know what's wrong... any suggestion?? please help


text:
Q: How to get name from another table when using a key in SELECT? I know this may be an easy question, but I've been stumped on this for the past hour and am not sure what terms to lookup that accurately describe what I am trying to do.
I have a MySQL database with two tables. Countries and Regions. The Regions table has two columns, id and name. An example of a row would be 1, north-america.
In the Countries table, there's a column named RegionID that would have a 1 if the country's region is north-america.
How can I grab the "north-america" in my query instead of printing out "1"?
Here's my SELECT that I am stumped on:
SELECT A.name, A.regionID FROM countries A, regions B ORDER BY A.name ASC

A: SELECT A.name, A.regionID, b.Name
FROM countries A
   Join regions B
      on B.id = A.RegionId
ORDER BY A.name ASC

A: Try this
    SELECT A.name, A.regionID
FROM countries A, regions B
WHERE a.RegionID =  b.id
AND b.id = 1
ORDER BY A.name ASC

A: Try this
SELECT A.name, A.regionID
FROM countries A JOIN regions B
ON A.regionID  = B.ID
ORDER BY A.name

A: select  c.name as country, r.name as region
from countries c
inner join regions r
on r.id=c.regionid


text:
Q: Calculating vegetation indices NDRE AND RECI using Sentinel 2 I am trying to calculate NDRE and RECI using Sentinel imagery ON ArcGIS software . For RECI( RED EDGE CHLOROPHYLL INDEX) the formula is (NIR/RED-1).
Can you tell me which band to use in order to calculate this, like for NIR do I have to use band 8 or 8A and for red band which band do I have to use band 4 which is red band or 5,6,7 which are red edge band?
When I use formula as float(band8/band5 -1)  my result appears completely black.
And for NDRE (Normalized difference red edge index) I was calculating it like float(nir - red edge)/float (nir + red edge) I was using band 8 as nir and band 5 as red edge.
Do I have to use band 8A instead of band 8 for this and if I am using band 5 correctly for red edge or do I have to use some other band instead of band 5?


text:
Q: How to change formatting of google spreadsheet columns and rows? How can I alter/change/set the:

*

*text color

*background color

*width

*text wrapping

of a specific cell range, or whole rows and columns in a google spreadsheet from NodeJs?
I'm currently using the googleapis npm package, but happy to use a different one.
A direct REST call is also fine - if there's an API?

A: Things you've mentioned can be found in Sheets API Basic Formatting:

The Sheets API allows you to update the formatting of cells and ranges
  within spreadsheets. The examples on this page illustrate how some
  common formatting operations can be achieved with the API. In
  addition, you may find addition examples using conditional formatting
  in the Conditional
  Formatting
  recipe page.


text:
Q: Code run but answer not correct ( python) player_number=name_to_number(name)
player_number=int ()

# compute random guess for comp_number using random.randrange()
comp_number=random.randrange (0,4)

# compute difference of player_number and comp_number modulo five
rpsls_match = (player_number-comp_number)%5

 # use if/elif/else to determine winner
if rpsls_match == 1 or 2:
    rpsls_winner = 'Player wins!'
elif rpsls_match == 3 or 4:
    rpsls_winner = 'Computer wins!'
else:
    rpsls_winner = 'Player and computer tie!'

    #print "Player chooses " + name

   # convert comp_number to name using number_to_name
print 'Computer chooses ', number_to_name(comp_number),comp_number
print 'player chooses ' , name, player_number
return rpsls_winner

Code run correctly but i did not get answer what i want,, it give me answer like
Computer chooses  paper 2
player chooses  rock 0
Player wins!

Computer chooses  lizard 3
player chooses  paper 0
Player wins!

Computer chooses  spock 1
player chooses  scissors 0
Player wins!

Computer chooses  paper 2
player chooses  lizard 0
Player wins!

incorrect input
Computer chooses  lizard 3
player chooses  Spock 0
Player wins!

but I want like
Player chooses rock
Computer chooses scissors
Player wins!

Player chooses Spock
Computer chooses lizard
Computer wins!

Player chooses paper
Computer chooses lizard
Computer wins!

Player chooses lizard
Computer chooses scissors
Computer wins!

Player chooses scissors
Computer chooses Spock
Computer wins!

A: rpsls_match == 1 or 2 should be
rpsls_match in (1, 2) or
rpsls_match == 1 or rpsls_match == 2.
Try evaluating 1 or 2 at the REPL. The answer is 1 because or returns the first non-false-evaluating operand.

A: The line
player_number=int ()

Will always set player_number to the default value for int, which is zero. You should remove that line to keep the value set in the previous line.


text:
Q: DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER error My package consists of dynamic db connections. When i run my package it is throwing error like  DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.The AcquireConnection method call to the connection manager "conn" failed with error code 0xC0202009.
I tried setting delay validation property to true at package level.
I tried to change Package Protection Level property to EncryptSensitiveWithpassword. Still am facing with same error.
Am able to run the package manually.
How to get rid of this.

A: This can be solved in 2 ways
First, i have changed my delay validation property at package level to True from false.
Change ProtectionLevel to EncryptSensitiveWithUserKey.
Second, Remove the old connection manager and create new one.
Most of the time first way solves the problem.

A: Convert the package to Package deployment model
Please create a Package configuration file for the Connection String. Save the password here.
When you deploy the package to a separate environment, copy the package along with the configuration file. Make sure the path in local and new environment is the same.
This solved my problem

A: I had this error keep reappearing because I forgot my connection string was created on the fly using variables and an expression (see image).  Once I edited the connection string there then this error went away.

A: I have added port number along with the DB name and added Provider as SQLNCLI11 in dts(config file) and added port number along with the IP address in the dtsx file(SSIS package) and it worked for me.

A: In my case, I forgot to assign/grant the user that's executing the package the required privileges to act on the databases used in the packages.


text:
Q: Creating multidimensional array from dynamic form in JQuery I'm trying to capture values from inputs and put them in JQuery object instead of having to deal with PHP indexing.
This is the form
<form name="second_form" id="second_form" action="#" method="POST">
    Add Champion

        <input id="obj" type="hidden" name="obj">
        <input type="submit" name="submit">
    </form>

My script that I'm trying to use to recreate the array:
$("#second_form").submit(function(event) {
    var object = [];
    $('.Champion').each(function() {
        var champion = {
            'name': $(this).find(".ChampionInput").val(),
            'change': $(this).find("input:radio:checked").val(),
            'General_Description': [],
            'General_Change':[]
        };
        $(this).find('.GeneralChange').each(function() {            champion.General_Description.push($(this).children(".GeneralChangeDescription").val());
            champion.General_Change.push($(this).children(".General_Change").val());
        });
        object.push(champion);
    });
    object = JSON.stringify(object);
    $('#obj').val(object); //Sending object to hidden input
});

And here is the way I used to create this PHP array which messes up indexing when I delete some inputs when creating the form
 foreach($_POST['champion'] as $champion){
                if(isset($_POST['Release'][$ChampionNumber])){
                    $_POST['Release'][$ChampionNumber]=='New' ? $champions[$champion]['New']=1 : $champions[$champion]['New']=0;

                    $_POST['Release'][$ChampionNumber]=='Rework' ? $champions[$champion]['Rework']=1 : $champions[$champion]['Rework']=0;

                }
                if(!empty($_POST['GeneralChangeDescription'][$ChampionNumber])){
                    foreach($_POST['GeneralChangeDescription'][$ChampionNumber] as $indexGeneral=>$GeneralChangeDescription){
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] =ucfirst(trim($GeneralChangeDescription));
                    if(substr($GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1], -1)!='.'){
                        $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1].'.';
                    }
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace('/\s\/\s/','/',$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/(\.?\d\/?%?)+/', '$0', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
                    $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/\b\w+\.(jpg|png|gif)/', '', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
                    $champions[$champion]['General']['Change'][] =  $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1];
                    $champions[$champion]['General']['Type'][] = $_POST['GeneralChange'][$ChampionNumber][$indexGeneral];

                    }
                }

                $ChampionNumber++;
            }

Removing champions
$('div#ChampionInput').on('click', 'a.Remove',function(){
    var champion = $(this).closest('.Champion');
    var id = champion.data("id");
    var nextChampion = champion;

    while((nextChampion = nextChampion.next()).length != 0){

        nextChampion.attr("data-id",id++);
        nextChampion.children('.ChampionInput').attr('placeholder','Champion '+ id);

    }
    championNumber=id+1;
    championNumberArray=id;
    champion.remove();
});

Removing changes
$('div#ChampionInput').on('click', 'a.RemoveGeneralChange',function(){
        $(this).closest('.GeneralChange').remove();
    });

Here is how my array looks like in PHP: http://i.imgur.com/rURnNTG.png and I want to get array looking like that after sending JQuery object through hidden input in form and obtaining it in PHP. Here is how my JQuery object looks like right now http://imgur.com/2r9iyKN which is not even close.
Here is also JSfiddle of form creation: jsfiddle.net/g50zd384/

A: If you really need that array, so create it in PHP after sending the form:
$array;
for($i = 1; $i <= count($_POST['champion']); $i++) {
    $champion = $_POST['champion'][$i];
    $array[$champion]['General'] = $_POST['GeneralChangeDescription'][$i];
    $array[$champion]['Type'] = $_POST['GeneralChange'][$i];
    $array[$champion]['Release'] = $_POST['Release'][$i];
}

Your form should be created with this names:
championNumber = 1;
    championNumberArray = 0;
    $('a#AddChampion').on('click',function(){
        $('div#ChampionInput').append(
        '
\

\
             <input type="text" class="ChampionInput" name="champion['+championNumber+']" placeholder="Champion '+championNumber+'">\
             <datalist id="champions"></datalist>\
             <input type="radio" name="Release['+championNumber+']" value="New">New\
             <input type="radio" name="Release['+championNumber+']" value="Rework">Rework\
             <input type="radio" name="Release['+championNumber+']" value="None" checked>None\
             Add General Change\

\

\

\

');
        championNumber++;
    });
    $('div#ChampionInput').on('click','a.AddGeneralChange', function(){
        var id = $(this).data('id');
        $(this).siblings('.GeneralChanges').append(
           '
\
                <textarea type="text" size="20" rows="3" cols="50" maxlength="500" class="GeneralChangeDescription" name="GeneralChangeDescription['+id+'][]" placeholder="Enter General Change Description"></textarea>\
                <select class="General_Change" name="GeneralChange['+id+'][]">\
                   <option value="buff">Buff</option>\
                   <option value="nerf">Nerf</option>\
                   <option value="new">New</option>\
                   <option value="change">Change</option>\
                   <option value="bugfix">Bugfix</option>\
                </select>\

');
    });

It is important, that you name your inputs in this way!
..not the best way, but better than sending json data in a hidden input form. I hope this could help you.


text:
Q: Order of Full Outer Joins Yields Different Number of Result Rows..Why? I'm working with two tables A and B. Table A identifies equity securities and Table B has a number of details on the security.
For example, when B.Item = 5301, the row specifies price for a given security. When B.Item = 9999, the row specifies dividends for a given security. I am trying to get both price and dividends in the same row. In order to achieve this, I FULL JOINed table B twice to table A.
SELECT *
FROM   a a
       FULL JOIN (SELECT *
                  FROM   b) b
              ON b.code = a.code
                 AND b.item = 3501
       FULL JOIN (SELECT *
                  FROM   b) b2
              ON b2.code = a.code
                 AND b.item = 9999
                 AND b2.year_ = b.year_
                 AND b.freq = b2.freq
                 AND b2.seq = b.seq
WHERE  a.code IN ( 122514 )

The remaining fields in the join clause like Year_, Freq, and Seq just make sure the dates of the price and dividends match. A.Code simply identifies a single security.
My issue is that when I flip the order of the full joins I get a different number of results. So if b.Item = 9999 comes before b.Item 2501, I get one result. The other way around I get 2 results. I realized the table B has zero entries for security 122514 for dividend, but has two entries for price.
When price is specified first, I get both prices and dividend fields are null. However, when dividend is specified first, I get NULLs for the dividend fields and also nulls for the prices fields.
Why aren't the two price entries showing up? I would expect them to do so in a FULL JOIN

A: It's because your second FULL OUTER JOIN refers to your first FULL OUTER JOIN.  This means changing the order of them is making a fundamental change to the query.
Here is some pseudo-SQL that demonstrates how this works:
DECLARE @a TABLE (Id INT, Name VARCHAR(50));
INSERT INTO @a VALUES (1, 'Dog Trades');
INSERT INTO @a VALUES (2, 'Cat Trades');
DECLARE @b TABLE (Id INT, ItemCode VARCHAR(1), PriceDate DATE, Price INT, DividendDate DATE, Dividend INT);
INSERT INTO @b VALUES (1, 'p', '20141001', 100, '20140101', 1000);
INSERT INTO @b VALUES (1, 'p', '20141002', 50, NULL, NULL);
INSERT INTO @b VALUES (2, 'c', '20141001', 10, '20141001', 500);
INSERT INTO @b VALUES (2, 'c', NULL, NULL, '20141002', 300);

--Same results
SELECT a.*, b1.*, b2.* FROM @a a FULL OUTER JOIN @b b1 ON b1.Id = a.Id AND b1.ItemCode = 'p' FULL OUTER JOIN @b b2 ON b2.Id = a.Id AND b2.ItemCode = 'c';
SELECT a.*, b2.*, b1.* FROM @a a FULL OUTER JOIN @b b1 ON b1.Id = a.Id AND b1.ItemCode = 'c' FULL OUTER JOIN @b b2 ON b2.Id = a.Id AND b2.ItemCode = 'p';

--Different results
SELECT a.*, b1.*, b2.* FROM @a a FULL OUTER JOIN @b b1 ON b1.Id = a.Id AND b1.ItemCode = 'p' FULL OUTER JOIN @b b2 ON b2.Id = a.Id AND b2.ItemCode = 'c' AND b2.DividendDate = b1.PriceDate;
SELECT a.*, b2.*, b1.* FROM @a a FULL OUTER JOIN @b b1 ON b1.Id = a.Id AND b1.ItemCode = 'c' FULL OUTER JOIN @b b2 ON b2.Id = a.Id AND b2.ItemCode = 'p' AND b2.DividendDate = b1.PriceDate;


text:
Q: Grades of each quiz in Moodle I'm trying to get grades of each question, I have a query but it only return final grade of whole exam, but i want grade of each question, how to get it?
Here is query that i have:
SELECT mdl_grade_items.id AS ItemID,
   mdl_course.shortname AS CourseShortname,
   mdl_grade_items.itemname AS ItemName,
   mdl_grade_items.grademax AS ItemGradeMax,
   mdl_grade_items.aggregationcoef AS ItemAggregation,
   mdl_grade_grades.finalgrade AS FinalGrade,
   mdl_user.username AS StudentID,
   mdl_user.id
FROM mdl_grade_items
INNER JOIN mdl_grade_grades
ON mdl_grade_items.id = mdl_grade_grades.itemid
INNER JOIN mdl_role_assignments
ON mdl_grade_grades.userid = mdl_role_assignments.userid
AND mdl_grade_items.courseid = mdl_role_assignments.mdlcourseid
INNER JOIN mdl_course
ON mdl_course.id = mdl_grade_items.courseid
INNER JOIN mdl_user
ON mdl_user.id = mdl_role_assignments.userid

A: Ok, i found it
SELECT mqa.id,meqi.grade * (select fraction from mdl_question_attempt_steps where
questionattemptid = mqas.questionattemptid and state like 'mangr%' order by id desc limit
1 ) finalgrade,me.course , mqas.userid,u.firstname, u.lastname, mqa.questionsummary,
mqa.responsesummary , meqi.grade
FROM mdl_question_attempts mqa
left JOIN mdl_question_attempt_steps mqas ON mqa.id = mqas.questionattemptid
left JOIN mdl_user u ON mqas.userid = u.id
left JOIN mdl_examm_question_instances meqi ON meqi.question = mqa.questionid
left JOIN mdl_examm me ON meqi.examm = me.id
WHERE  me.course= $courseID and userid = $userID


text:
Q: How can I join 3 columns on one table with 1 columns from another table? I have a table (Table1) with 5 columns, each result shows an ID for a timezone (TZID). In a seperate table (Table2) is a list of these IDs, with the corresponding name for them. I need to join them so as that for each column result, it shows the corresponding name for them. But I can only seem to figure out how to join for the result of 1 column. For example:
Table1 joined with Table2

Here I have joined Column3 with TZID from table 2. But if Column3 is equal to zero, and Column 1 or 2 is not, I need TZID from table2 to return that corresponding name from Table2.
Currently I have the following:

SELECT
      Column1
     ,Column2
  ,Column3
  ,Table2.TZID as 'TZID from Table2'
  ,Table2.[DESCRIPT] as 'Name from Table2'

  FROM Table1
  left outer join Table2 on Table2.TZID=Table1.Column3

I have tried using REPLACE, is it possible to replace with the reult from another table? Something like
REPLACE(Column1, Table2.TZID, Table2.[DESCRIPT]) AS 'Column1 Mask'
Is there any way to actually do this?

A: I think you want to join with priorities, first join with Column3 if it is not 0. If Column3 is 0 then join with Column1. And if column 1 is also 0 then join with Column2, right?
If this is correct, then you need a sql query like this:
SELECT
      Column1
     ,Column2
     ,Column3
     ,Table2.TZID as 'TZID from Table2'
     ,Table2.NAME as 'Name from Table2'

  FROM Table1
  LEFT OUTER join Table2 on Table2.TZID =
  CASE
    WHEN Table1.Column3 <> 0
       THEN  Table1.Column3
    WHEN Table1.Column1 <> 0
       THEN Table1.Column1
    WHEN Table1.Column2 <> 0
       THEN Table1.Column2
  END

A: If you need to join all tree columns in one query, you can join one table multiple times and rename it.
> SELECT
>       Column1
>      ,Column2
>      ,Column3
>      ,t2c1.TZID as 'TZID Column1'
>      ,t2c1.NAME as 'Name Column1'
>      ,t2c2.TZID as 'TZID Column2'
>      ,t2c2.NAME as 'Name Column2'
>      ,t2c3.TZID as 'TZID Column3'
>      ,t2c3.NAME as 'Name Column3'
>
> FROM Table1   LEFT OUTER join Table2 t2c1 on t2c1.TZID = Table1.Column1
>               LEFT OUTER join Table2 t2c2 on t2c2.TZID = Table1.Column2
>               LEFT OUTER join Table2 t2c3 on t2c3.TZID = Table1.Column3


text:
Q: EF Core 2.x date subtraction/difference in Npgsql I am using Npgsql provider version 4.0.x and ef core 2.x. I have the following entities with navigation properties:
public class Entity : ...
{
   .....
   public ICollection<OtherEntity> OtherEntities { get; set; }
}

public class OtherEntity : ...
{
   ...
   public int Order { get; set; }
   public DateTimeOffset Date { get; set; }
}

I am trying to perform the following query:
var query = provider.Query<Entity>()
     .Select(x => new
     {
         Difference = (x.OtherEntities.OrderBy(y => y.Order).FirstOrDefault().Date
- x.OtherEntities.OrderByDescending(y => y.Order).FirstOrDefault().Date).TotalDays
     })
     .FirstOrDefault();

But it does not work :( No warnings or whatever, simply skips my Select query.
I found out that there are default DbFunctions hidden in EF.Functions.DateDiff* layer, but these are working only if using SQL Server provider. Is there any way to perform this in Npgsql?
I tried to implement custom database user function named DATE_PART (which is a Postgres feature), but it calculates only days/hours/month, and I can't combine these. I need format of TimeSpan.TotalDays (the first part is a num of days and the fraction contains day hours).


text:
Q: Plugin isn't found in visual studio Environment:

*

*VS2015 with cordova tools.

*Win8.1.

*Practise project is WinJS ToDo sample app from web.

Maybe this is just SUE (Stupid User Error) but when I'm adding barcodereader plugin (config editor ui -> using git address) all goes fine and new plugin comes to plugin folder in project tree.
Problem is that I can't seem to find way to use that new plugin at all. I can add <script src=""> tag for plugin's .js-file and it compiles, but when I try actually do something with plugin from code, it isn't recognized at all.
My new love with VS is suffering now...

A: The problem is that you need a definition for the plugin in order to consume it in a TypeScript project. The usual place to find definitions (commonly defined in d.ts files) is on www.definitelytyped.org. However in this case, the plugin author probably has not defined a TypeScript definition so you won't find it there.
That means you'll need to write one yourself. Think of a d.ts file like a header file in c++. It defines the interfaces and contracts in the library you're consuming. It's really not too hard to write these once you've learned how to do it. Here's one link that might be useful:
https://typescript.codeplex.com/wikipage?title=Writing%20Definition%20%28.d.ts%29%20Files
Hope that helps.


text:
Q: Nokogiri XML file output is located where? I need to generate an XML file with Ruby and/or Rails and have Nokogiri installed.

*

*In what file does the Ruby code go that will generate the XML file?

*How do I tell Nokogiri to generate the XML and put it into a file?

*Where is the XML output located?

Here is my code from my controller file:
class MonkeyTalkController < ApplicationController

require 'rubygems'
require 'nokogiri'

  def edit

  end

  def update
#debugger
    render :text => MonkeyTalk.new(params).build_xml

    builder = Nokogiri::XML::Builder.new(:encoding => 'utf-8') do |xml|
      xml.root {
  xml.products{
         xml.widget {
          xml.id_ "10"
          xml.name "Awesome widget"
          }
        }
      }

      doc = Nokogiri::XML.parse(params)
      File.open('xml.out', 'w') do |fo|
      fo.print doc.to_s
      end
    end
    puts builder.to_xml

  end

end

I need a basic understanding of the structure of Ruby and Rails applications and how Nokogiri works.

A: To generate an xml file you do not need Rails. Ruby (and Nokogiri or some oder builder) will suffice.
First, you have to build your xml:
builder = Nokogiri::XML::Builder.new(:encoding => 'utf-8') do |xml|
  xml.root do
    xml.products do
      xml.widget do
        xml.id_ "10"
        xml.name "Awesome widget"
      end
    end
  end
end

You can get an xml string from this builder using builder.to_xml:
xml_string = builder.to_xml # => "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n  <products>\n    <widget>\n      <id>10</id>\n      <name>Awesome widget</name>\n    </widget>\n  </products>\n</root>\n"

To save this string into a file, you use File.open and File#write:
# open a file instance with path '/path/to/file.xml' in write mode (-> 'w')
File.open('/path/to/file.xml', 'w') do |file|
  # write the xml string generated above to the file
  file.write xml_string
end

An important note: you always have to make sure that you close all files that you opened if you no longer need them. File.open with a block (as used in my snipped above) will automatically close the file for you after the code in the block is executed...

A: Your file was written to xml.out. Where is this file? It depends on what the working directory was when you started your application, and whether your code or any library ever called Dir.chdir to change the working directory.
You can output Dir.pwd or File.expand_path('xml.out') to see where this file was written.


text:
Q: Target specific Enterprise CA for auto-enrollment? We have two intermediate Enterprise CAs (Windows AD CS) in our AD domain. Both CAs only have the Certification Authority role enabled.
CA1 is responsible for issuing certificates to workstations and users and has a template Workstation Auth.
CA2 is responsible for issuing certificates to servers and has a template Server Auth.
Auto-Enrollment is enabled on all Workstations and servers in our domain and working.
Problem:
Workstations should only target CA1 for auto-enrollment
and servers should only target CA2 for auto-enrollment.
I want to achieve this using group policies.
I know that I can allow auto-enrollment on a template only for members of security groups, and that would work.
However, I prefer a solution using group policies, because we organise workstations and servers in different OUs. I can target both groups with group policies on OUs. The security group solution would require us to manage two new security groups on top of that.
Is it possible to configure a workstation or server to only auto-enroll from a particular Enterprise CA? I'm open to alternatives, if they can be achieved using group policies.

A:
I'm open to alternatives, if they can be achieved using group policies.

I think you went in wrong direction. The solution is chosen based on a problem, not opposite. Your requirement (GPO only) isn't justified by a problem.
Let's focus on a problem:

*

*Workstations should only target CA1 for auto-enrollment

*and servers should only target CA2 for auto-enrollment

this task is solved by permissions. Put workstations in a security group (let's say "Workstations") and grant Read, Enroll and Autoenroll permissions to "Workstation Authentication" certificate template. Assign this template only to CA1.
Put servers in a security group (let's say "Servers") and grant Read, Enroll and Autoenroll permissions to "Server Authentication" certificate template. Assign this template only to CA2.
Single autoenrollment GPO can be applied to top-level OU or even at domain level. It is a good practice to have autoenrollment GPO applied at domain level and exact autoenrollment settings (who and what templates can use for autoenrollment) are controlled by certificate template permissions and template assignment to corresponding CAs.


text:
Q: wpf MVVM ObservableCollection My model has a couple properties one is a string and the other is an observablecolletion.  When the model is created it fires off a backgroundworker thread to basically poll a .dll for data.  Based on the data it receives it will either set the string and/or add and item to observable collection.  My string property seems to fire its Onproperty change just fine and the view updates.  However, my observable Collection throws a cross thread exception.  I have tried moving code where i set the ObesrvableCollection to the worker.ReportProgress and get the same error.  I have moved the logic into the view model and still get the same threading error.  I'm unsure why my string property works for one.  I have read about Dispatcher.Invoke, but i'm pretty sure that my model should not be aware of this.  Can anyone explain the correct way to go about this please.
Just fyi - my view is not tied directly to my model.  I have a property for my model in my viewModel and the model gets passed through constructor injection.  Just want to put that out there before anyone thinks my model is talking directly to the the view.

A: Hard to give specifics without code. However, WPF automatically marshals property change notifications for scalar properties but not collections. Hence, you must be modifying the collection from a non-UI thread.
There is no reason why your VM can't use Dispatcher, or perhaps the more generic SynchronizationContext if you prefer. It can make things more tricky to test, however.
If you post code there may be a way you can simplify things.

A: As Kent said, if you're not on the UI you need to use the Dispatcher to update your collection:
Application.Current.Dispatcher.Invoke(new Action(() =>
{
    // update your ObservableCollection here
}));


text:
Q: Multiple sheets and time periods for vlookup and if formula I have a multi page spreadsheet and want to achieve the following.
On the summary page I want it to look up the values that are deducted from the other sheets and reported. That part to me seems like a simple vlookup but where I confuse myself is when I do this.
Let's say sheets 2 and 3 are identical (they represent two different locations) so they both have deductions at the same time. On the summary page I want to add those deductions together to report one total.
Now say sheets 4 and 5 all started 10 and 20 periods after sheet 1 I want to add the deductions together that occurred at the same time. This is where I thought an IF formula would be needed but my messy solution is an extra column that represents the original period. Say sheet 1 is 1-50 but sheet 4 started at period 10 then it's behind 10 so if had an extra column that was original 1-50 the deductions would only need to look at the original period column.
If I do this the long way it is a bloom up for each sheet and I have 50 sheets so I'm trying to find a neater solution. In my mind that is clear and I hope someone can give me just the long way around solution

A: Thanks for all the assistance.
Answer was to create a shorter list, and then a number of other formulas


text:
Q: Increasing invoke spawn speed using enumerator I'm trying to increase the spawn time of an invoke function, I'm using an IEnumerator but it's not working.
It looks like the system reads the starting spawnSpeed value and not changing it reading the IE function.
I'm not aware if there is another way to make this work.
Plz, help.
this is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObstaclesController : MonoBehaviour
{
    public GameObject obstacle;
    private GameObject obstacleClone;
    public Transform ObstacleMarker;
    private float CloneLifeTime = 4f;
    float spawnSpeed;
    float spawnInterval = 3;
    float minSpawn = -4;
    float maxSpawn = 0;

    void Start()
    {
        spawnSpeed = 2f;
        StartCoroutine("IncreaseSpeedWithInterval");
        InvokeRepeating("AddingObstacle", spawnSpeed, spawnSpeed);
    }

    IEnumerator IncreaseSpeedWithInterval()
    {
        while (true)
        {
            yield return new WaitForSeconds(spawnInterval);

            spawnSpeed *= 1.5f;
        }
    }

    private void AddingObstacle()
    {
        float randomLocation = Random.Range(minSpawn, maxSpawn);

        obstacleClone = Instantiate(obstacle, ObstacleMarker.position, ObstacleMarker.rotation);
        obstacleClone.transform.position = new Vector3(ObstacleMarker.transform.position.x, randomLocation, ObstacleMarker.transform.position.z);

        Destroy(obstacleClone, CloneLifeTime);
    }

    private void Update()
    {
        Debug.Log(spawnSpeed);
    }
}

A: After the call to
InvokeRepeating("AddingObstacle", spawnSpeed, spawnSpeed);

any later change on spawnSpeed has no effect whatsoever .. a float is passed by value and there is no connection between the passed one and the one you later adjust!

You can instead wrap it into another Coroutine like
private IEnumerator AddingObstacleRoutine()
{
    while(true)
    {
        yield return new WaitForSeconds (spawnSpeed);

        AddingObstacle();
    }
}

And instead start this routine as well using
StartCoroutine(IncreaseSpeedWithInterval());
StartCoroutine(AddingObstacleRoutine());


text:
Q: Is there a way to find a file in an inverse recursive search? So say I'm in a directory that is deep within a file structure, such as
/home/cory/projects/foo/bar/bash/baz

I know that in either the current folder baz or one of the folders above me (such as home, cory, projects, foo, bar, or bash) there is a file named happy.  How can I find that file without searching a lot of extra folders?

A: #!/bin/bash

function upsearch () {
    test / == "$PWD" && return || test -e "$1" && echo "found: " "$PWD" && return || cd .. && upsearch "$1"
}

This function will walk up from the current dir. Note, that it is a function, and will change the directory, while traversing. It will stop in the directory, where it finds the file, and will walk up to the root / if not.
You might want to change it to a script instead of a function, and maybe jump back, if the file isn't found in the root directory.
If you never want to cd to the dir:
upsearch () {
  local slashes=${PWD//[^\/]/}
  local directory="$PWD"
  for (( n=${#slashes}; n>0; --n ))
  do
    test -e "$directory/$1" && echo "$directory/$1" && return
    directory="$directory/.."
  done
}

This will lead to results like /home/cory/a/b/c/../../../happy if the file is in /home/cory/. If you need a cleaned path, you could do some
cd "$directory"
echo "$PWD"
cd -

on success.
To restrict the search to regular files and excludes directories, symbolic links and the like, you can change the tests to -f instead of -e.

A: Take a look at the -mindepth and -maxdepth options to find.
find won't traverse directories in a backwards direction, but you can approach it in the regular direction and limit the depth of the search.
For example:
find /home /home/cory /home/cory/projects /home/cory/projects/foo /home/cory/projects/foo/bar /home/cory/projects/foo/bar/bash -maxdepth 0 -name happy -print

A: I improved on @user-unknown's solution a bit by saving the current dir, performing an arbitrary test, then restoring the original dir before returning with response.  It's more flexible because you can test for anything.
I also provide for an optional second argument that says how high to go.
https://gist.github.com/1577473
#!/bin/bash

# Use this script instead of ~/.rvm/bin/rvm-prompt
# and the output of rvm-prompt will show up in your command prompt
# only if you are in a Ruby project directory.

# see http://stackoverflow.com/a/4264351/270511
# and http://unix.stackexchange.com/questions/13464/is-there-a-way-to-find-a-file-in-an-inverse-recursive-search

upsearch () {
  the_test=$1
  up_to=$2
  curdir=`pwd`
  result=1

  while [[ "`pwd`" != "$up_to" && "`pwd`" != '/' ]]; do
    if eval "[[ $the_test ]]"; then
      result=0
      break
    fi
    cd ..
  done
  cd $curdir
  return $result
}

if upsearch '-e Gemfile || ! -z "$(shopt -s nullglob; echo *.gemspec *.rb)"' ; then
  ~/.rvm/bin/rvm-prompt
fi


text:
Q: basic chart + title using vba for ppt I am new to vba.
I want to generate a ppt with chart and title in it. I am using following code, but having problems. Please suggest.
Set pptobj = CreateObject("PowerPoint.Application")
pptobj.Visible = TRUE
Set presentn= pptobj.Presentations.Add
Dim dirtemp
dirtemp= CreateObject("WScript.Shell").ExpandEnvironmentStrings("%Temp%")
Dim tempImg
tempImg = dirtemp+"\test.gif"
Dim cnt
ind = 1
'my chart is in chartobj
if Not IsNull ( chartobj) then
    presentn.Slides.Add ind, 8
    chartobj.ExportPicture tempImg, "gif"
    presentn.Slides(ind).Shapes(1).TextFrame.TextRange.Text = "some title"
    presentn.Slides(ind).Shapes(2).AddPicture tempImg, false, true, 50, 50
ind = ind + 1
end if

I am using ppLayoutChart (value 8).
However if I use layout = 12 (ppLayoutBlank), I am able to generate the chart successfuly, however there is no way I can add title then :(

A: On a blank layout slide, there will be no shapes, so .Shapes(1) will not return anything (it's throwing an error when you refer to it, yes?)
If you need to add a title to a blank slide, you'll have to add a text shape, set its text and format it to taste.
It might be simpler to add a dummy ppLayoutChart slide, set its title text, copy/paste that onto your real slide, then delete the dummy slide.  That will ensure that the "pseudo-title" is formatted as it should be.
Or simpler yet, don't add a blank, add a title only layout slide.


text:
Q: Difference between Android Studio different views I have recently started using Android studio and observed the different views available at top left corner with options like (Project, Packages, Android, Scratches) .
I was searching for it but didn't get significance of each and difference between them.
Can anyone help me for this?

Thanks

A: From this, it says:
The Project view structure appears different than you may be used to in Eclipse but considered as traditional.
The Android project view shows a hierarchy that helps you work with Android projects by providing a flattened structure that highlights the most commonly used files while developing Android applications. However, the project structure on disk differs from this representation.
To sum up:

*

*Project view: traditional

*Android view: Most commonly used files (flattened version of your project's structure that provides quick access to the key source files)

*Package: View as package list

*Problem: links to the source files containing any recognized coding and syntax errors

*Project files: focus on files (provide project-wide files and settings that apply across all modules in the project)

Figure 1: The traditional project view (left) and the Android project view (right).