text:
Q: XML: Get only some child nodes of a node I want to traverse the two sessions in the below xml as two seperate nodes:
abc.xml:
<?xml version="1.0" encoding="UTF-8"?>
<resource>
<session>
     <parameter name="QWS" value="N1"/>
     <parameter name="AQC" value="Y2"/>
     <parameter name="VDF" value="301"/>
     <parameter name="VTT" value="X2"/>
     <parameter name="HRR" value="Y2"/>
 </session>
 <session>
    <parameter name="ABC" value="N"/>
     <parameter name="XYZ" value="Y"/>
     <parameter name="GHI" value="30"/>
     <parameter name="DEF" value="X"/>
     <parameter name="QQW" value="Y"/>
    </session>
</resource>

However when i run this code, it traverses through both sessions both times:
#!/usr/bin/perl
use warnings;
use strict;
use XML::LibXML;

my $filename = 'E:/perl_files/abc.xml';
my $dom = XML::LibXML->load_xml(location => $filename);

foreach my $session ($dom->findnodes('//session'))
{
    print "In SESSION \n";
    foreach my $parameter ($session->findnodes('//parameter')) {
        my $name= $parameter->getAttribute('name');
        my $value= $parameter->getAttribute('value');
        print "Tag in session is $name with value $value\n";
    }
    print "END OF SESSION\n";
}

Leaving me with this output:
In SESSION
Tag in session is QWS with value N1
Tag in session is AQC with value Y2
Tag in session is VDF with value 301
Tag in session is VTT with value X2
Tag in session is HRR with value Y2
Tag in session is ABC with value N
Tag in session is XYZ with value Y
Tag in session is GHI with value 30
Tag in session is DEF with value X
Tag in session is QQW with value Y
END OF SESSION
In SESSION
Tag in session is QWS with value N1
Tag in session is AQC with value Y2
Tag in session is VDF with value 301
Tag in session is VTT with value X2
Tag in session is HRR with value Y2
Tag in session is ABC with value N
Tag in session is XYZ with value Y
Tag in session is GHI with value 30
Tag in session is DEF with value X
Tag in session is QQW with value Y
END OF SESSION

I would like the output to be
In SESSION
Tag in session is QWS with value N1
Tag in session is AQC with value Y2
Tag in session is VDF with value 301
Tag in session is VTT with value X2
Tag in session is HRR with value Y2
END OF SESSION
In SESSION
Tag in session is ABC with value N
Tag in session is XYZ with value Y
Tag in session is GHI with value 30
Tag in session is DEF with value X
Tag in session is QQW with value Y
END OF SESSION

I am using XML::LibXML.
What changes could I make to get the child nodes of only one session every time?
I saw answers using childNodes(), but that would return a list and I do not want to use grep to find a particular node.

A: //parameter searches for parameter everywhere, you only need to search under session, i.e. under the current node:
    foreach my $parameter ($session->findnodes('.//parameter')) {

A: //parameter

is short for
/descendant::parameter

which means a descendant of the root node (/) named parameter, but you want to get descendants of the context node. For that, you want
descendant::parameter

which can also be written as
.//parameter

The thing is, parameter is a child of sessions, so what you really want is just
child::parameter

which can also be written as
parameter

Final code:
#!/usr/bin/perl
use warnings;
use strict;
use XML::LibXML;

my $filename = 'E:/perl_files/abc.xml';
my $dom = XML::LibXML->load_xml(location => $filename);

foreach my $session ($dom->findnodes('/resource/session'))         # <---
{
    print "In SESSION \n";
    foreach my $parameter ($session->findnodes('parameter')) {     # <---
        my $name= $parameter->getAttribute('name');
        my $value= $parameter->getAttribute('value');
        print "Tag in session is $name with value $value\n";
    }
    print "END OF SESSION\n";
}


text:
Q: Rails gem Ratyrate showings stars only after refresh and not saving (Saw many posts with these problems and got it working, so I will upload solution)
I'm using Ratyrate without Devise and the stars only appear after a web refresh and they do not save the previously assigned rate.

A: Fixed this issue with:

*

*Specifying version in each Rating Migration (currently using ActiveRecord::Migration[5.1])

*Changing Rate Controller "create" method, replacing "if user_signed_in?" with "if current_user"

*Adding "post '/rate' => 'rater#create', :as => 'rate'" to routes.rb (gem should do this for you)

*Adding
  <%= javascript_include_tag 'ratyrate.js', "data-turbolinks-track": false %> at the bottom of show.html.erb (the view of the model you want to rate)

Hope this helps !

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to hide all of ExoPlayer2? I'm trying to replace an ExoPlayer2 view with an ImageView if the video media file isn't available.
    if(stepVideo != null) {
        mPlaceHolderIv.setVisibility(View.GONE);
        exoPlayerView.setVisibility(View.VISIBLE);
        initializePlayer(Uri.parse(stepVideo));
        //initialize MediaSession
        initializeMediaSession();
    } else if(stepThumbUrl != null) {
        mPlaceHolderIv.setVisibility(View.GONE);
        exoPlayerView.setVisibility(View.VISIBLE);
        initializePlayer(Uri.parse(stepThumbUrl));
        //initialize MediaSession
        initializeMediaSession();
    } else {
        exoPlayerView.setVisibility(View.GONE);
        releasePlayer();
        mPlaceHolderIv.setVisibility(View.VISIBLE);
        Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(mPlaceHolderIv);
    }

I know the else is being called because the placeholder image is being shown; however, the playback controls are still visible. I've tried all the answers here and still the control view (play, pause, etc.) are shown. Any ideas?
Note: I've overwritten the custom controls with a file labled as exo_playback_control_view.xml.
Edit: Fixed the problem for showing the controls when view was GONE, but new question is why does the xml for SimpleExoPlayerView need to have a app:use_controller="false" and then set it to true in java when initialized and false again when released? Why doesn't the control view disappear with the rest of the SimpleExoPlayerView?

A: Not sure if this can help, but if you just want to replace a view with another, why not use ViewSwitcher or ViewAnimator?
The 2 child views (the placeholder and the player view/layout) would be those that you switch between, and you call showNext to switch to the other view.
You can also use these nice helper functions:
fun ViewAnimator.setViewToSwitchTo(viewToSwitchTo: View, animate: Boolean = true): Boolean {
    if (currentView === viewToSwitchTo)
        return false
    for (i in 0 until childCount) {
        if (getChildAt(i) !== viewToSwitchTo)
            continue
        if (animate)
            displayedChild = i
        else {
            val outAnimation = this.outAnimation
            val inAnimation = this.inAnimation
            this.inAnimation = null
            this.outAnimation = null
            displayedChild = i
            this.inAnimation = inAnimation
            this.outAnimation = outAnimation
        }
        return true
    }
    return false
}

fun ViewAnimator.setViewToSwitchTo(@IdRes viewIdToSwitchTo: Int, animate: Boolean = true): Boolean {
    if (currentView.id == viewIdToSwitchTo)
        return false
    for (i in 0 until childCount) {
        if (getChildAt(i).id != viewIdToSwitchTo)
            continue
        if (animate)
            displayedChild = i
        else {
            val outAnimation = this.outAnimation
            val inAnimation = this.inAnimation
            this.inAnimation = null
            this.outAnimation = null
            displayedChild = i
            this.inAnimation = inAnimation
            this.outAnimation = outAnimation
        }
        return true
    }
    return false
}


text:
Q: ReactJS and a backend I am new to React. I created a simple login form and sign up form.
I am a little confused about using a backend. I've Googled it (lol) and I've seen a large variety of answers from using AWS to creating another project with NodeJS/Express.
For a beginner, what is the best approach? What confuses me is that I am handling all the routing in my React app. The tutorials that I've seen appear to handle routing in the NodeJS/Express portion.

A: Like Chris mentioned your question is to broad to answer, but I'll try to propose some general directions which may help you to pursue building a back-end.
There is not really a best approach. I suggest you look into several courses and tutorials on what web technologies suits best for the type of application you want to build. Start first by selecting which framework would provide the most productive and scale-able workflow for you. This is depended on various factors of your envisioned application and your current skill-set. Then follow along tutorials and read documentation of each separate technology first to get a good understanding of each building block. When grasping how everything functions individually, looked in complete full stack tutorials to see how everything works together and how you connect your front-end to your back-end.
I chose for a Nodejs RESTfull API myself using the MERN stack (MongoDB, Express, Reactjs and Nodejs), but you can also look into python (django, flask) or PHP back-ends as well.
Some good Youtubers to get you started:
https://www.youtube.com/academind
https://www.youtube.com/traversymedia
They provide many up to date tutorials for different web-technologies so you can make an informed decision yourself of what you want to adapt to.
Keep in mind there is a lot to work with when you just getting started, but at some point things will become familiar after using it over and over again and it becomes less overwhelming.


text:
Q: What is a better practice for extracting icons? I have created an explorer window that scans the directories upon loading for filetypes, etc. when it first loads, i use
internal static extern uint ExtractIconEx(string szFileName, uint nIconIndex, IntPtr[] phiconLarge, IntPtr[] phiconSmall, uint nIcons);

and
internal static unsafe extern int DestroyIcon(IntPtr hIcon);

to scan for currently registered icons and then i associate them with teh files im using. it works fine on my machine but when i run it on others, i get a low resource error.
so my question is what is a better practice? to go the way that i am, and load them all up, or everytime i need to enumerate a directory to look for the filetype and associate it.

A: As an alternative you could do this with system.drawing
var icon = System.Drawing.Icon.ExtractAssociatedIcon(@"c:\xxx\some.file");

(You would need to resize this for the small shell size)


text:
Q: How to count the number of times a value recurs in a recursive function? If you have a recursive function (e.g. the Fibonacci sequence):
def fib(n):
    """Return Fibonacci of n; assumes n is an int >= 0."""
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

How would one count, for example, the number of times fib(2) occurs when fib(20) is called?

A: You can use a decorator:
import functools

def count(f):
    """Count function calls."""
    @functools.wraps(f)
    def counted(*args, **kwargs):
        counted.count_calls += 1
        return f(*args, **kwargs)
    counted.count_calls = 0
    return counted

fib = count(fib)
fib(5)
fib.count_calls
# 15

Alternatively, you can now prepend any function definition using this decorator and the @ symbol:
@count
def fib(n):
    ...

fib(5)
fib.count_calls
# 15

Note, this decorator accumulates function calls:
fib(5)
fib(5)
fib.count_calls
# 30

This is a clever implementation that takes advantage of lesser known function attributes.  Note, the original decorator is modified from John DiNero's count function discussed in his lecture on Memoization where he addresses this specific issue.

A: You can use a dictionary to count all invocations of fib. The dictionary has to be cleared before the first call to fib.
calls = defaultdict(int)

In the function, update the corresponding entry in the dictionary before doing anything else:
def fib(n):
  global calls
  """Assumes n an int >= 0
     Returns Fibonacci of n"""
  calls[n] += 1
  if n == 0 or n == 1:
    return 1
  else:
    return fib(n-1) + fib(n-2)

A: How about:
def fib(n, counts_dict):
    counts_dict[n] += 1
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n-1, counts_dict) + fib(n-2), counts_dict

Where counts_dict = collections.defaultdict(int)

A: This is what i tried ... thinks like work fine
def fib(n):
    global counter
    if (n == 0 or n == 1):
        counter=counter+1
        return 1
    else:
        counter=counter+1
        return fib(n-1) + fib(n-2)
def countfib(n):
    global counter
    counter = 0
    fib(5);
    global count
    count=counter
    counter = 0
    return count
counter=0
count=0
print fib(5)
count=countfib(5)
print count

Output:

8
  15

A: It's not clear to me exactly what the recurring values you want to count are, so I'm guessing it's the number of times the (recursive) function was called with the same argument (or group of them, if there's more than one).
In the code below, a decorator named tally_recurring_args() is used to wrap the function in some code to do this. To simplify things and avoid reinventing the wheel, a collections.Counter is used to tally the number of calls of every unique combination of arguments to the function. This is made a attribute of the function so it can be easily referenced in the wrapper every call to the decorated function.
import collections
import functools

def tally_recurring_args(func):
    func._args_counter = collections.Counter()  @ add attribute to func

    @functools.wraps(func)
    def wrapper(*args):
        key = ', '.join(str(arg) for arg in args)
        func._args_counter[key] += 1
        return func(*args)

    return wrapper

@tally_recurring_args
def fib(n):
    """Return Fibonacci of n; assumes n is an int >= 0."""
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

print('fib(5) -> {}'.format(fib(5)))
for args, count in sorted(fib._args_counter.items()):
    print('fib({}): called {} time{}'.format(args, count,
                                             's' if count > 1 else ''))

Output:
fib(5) -> 8
fib(0): called 3 times
fib(1): called 5 times
fib(2): called 3 times
fib(3): called 2 times
fib(4): called 1 time
fib(5): called 1 time

A: def fib(n, x):
    c = 1 if n == x else 0

    if n == 0 or n == 1:
        return 1, c
    else:
        fA, cA = fib(n - 1, x)
        fB, cB = fib(n - 2, x)
        return fA + fB, cA + cB + c

If I've not messed up the logic, this function accepts n and x and returns a tuple (y, c) s.t. fib(n, _)=y and fib(x, _) was invoked c times during the calculation.
This is a purer alternative to the other proposed solutions that involve updating a dictionary. It rests on the assumption that OP only requires the number of times f(k, _) was invoked for one specific k, and so avoids filling a dictionary from which only one value is needed.

A: Without global variables:
from collections import defaultdict
def fib(n, count=None):
    if count is None:
        count = defaultdict(int)
    count[n] += 1
    if n in (0, 1):
        return 1, count
    return fib(n - 1)[0] + fib(n - 2)[0], count

The fib function now returns a tuple: the first element is the desired value and the second element is a dictionary containing the information of how many times each value the fib function was called on.

A: How about using an function attribute. Just like a static variable.
def fib(n):
    """Return Fibonacci of n; assumes n is an int >= 0."""
    If hasattr(fib, 'cnt'):
        fib.cnt += 1
    else:
        fib.cnt = 1
    if n == 0 or n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

fib.cnt =0

A: Using global:
c = 0
def fib(n):
    global c
    c += 1
    if n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fib(n-1) + fib(n-2)

A: This is another solution without global variable, but done through value passing:
def fibo(n, c):
if n <= 2 and n > 0:
    return n-1, c
else:
    n1, c1 = fibo(n-1,c+1)
    n2, c2 = fibo(n-2,1)
    return n1+n2, c1+c2


text:
Q: App Scope with Require AMD So I've got a large site that includes a requirejs amd app as a standalone plugin rather than as the whole site application.  I'd like to be able to access methods within the plugin eg. App.initialize(); when an independent login button is pressed.  But, 'App' isn't attached to window.App.  Where is 'App' and or how can I attach App to the global namespace, so I can access it from disparate parts of the site?
Thanks!


text:
Q: Remove common values with one specific group On a big dataset, I would like to delete the rows which present an id in common to the sample A. Then I would like to remove all the row from sample A.
 feature id sample
      a  1      A
      b  1      B
      c  2      A
      d  2      C
      e  3      A
      f  4      B
      g  4      C
      h  5      C
      i  5      C

The output should be:
 feature id sample
      f  4      B
      g  4      C
      h  5      C
      i  5      C

As my dataset as more than 8000 rows, I need another way to do it than saying row by row which one I want to delete.
I am not sure how to do that, any advice welcome.

A: Assuming you want to delete all the rows which has id same as the ids in "A", you could do
df[!df$id %in% df$id[df$sample == "A"], ]

#  feature id sample
#6       f  4      B
#7       g  4      C
#8       h  5      C
#9       i  5      C

Same with dplyr
library(dplyr)
df %>%  filter(!id %in% id[sample == "A"])

A: Here is a base R idea using ave,
with(dd, ave(sample, id, FUN = function(i)!'A' %in% i))

So to use it for indexing,
dd[as.logical(with(dd, ave(sample, id, FUN = function(i)!('A' %in% i)))),]
#  feature id sample
#6       f  4      B
#7       g  4      C
#8       h  5      C
#9       i  5      C

A: We can use subset
subset(df, !id %in% id[sample == "A"])
#    feature id sample
#6       f  4      B
#7       g  4      C
#8       h  5      C
#9       i  5      C


text:
Q: There's  all over my profile. :(
Possible Duplicate:
HTML tags showing in my profile

Something funny must be going on with the latest patch, I have a bunch of
 tags encoded to regular text such that I visually see rendered as:

I was lucky enough to have a computer....

The page serves this:

I was lucky enough to have a computer

Some encoding issues I would guess.

A: This should be fixed. We tightened the vice on some encoding stuff. Thanks for the heads-up.


text:
Q: Binding a User entity and a GlassFish Principal I have an entity class User that contains information such as username, first name, last name and a password and I have my GlassFish 3.1 server setup to perform authentication. So far, so good. After the container has authenticated a user, I need some way to bind the principal to the actual User entity. After all, GlassFish is telling me is that user "laurens" has authenticated, it is not giving me the corresponding User entity.
To that end I wrote a JSF managed bean UserController. What I would like to know is if this is the correct way to look the actual entity up and if there are any obvious pitfalls I am not seeing.
UserController features the following fields:
@EJB
private UserFacade userFacade;

private User user;

The userFacade is a stateless session bean to persist and find User instances. The user field is used by the JSF page to get and set properties on the user.
I use the following method to perform the binding accompanied by two helper methods:
@PostConstruct
private void init() {
    try {
        user = userFacade.find(getUserPrincipal().getName());
    } catch (NullPointerException ex) {
        // Intentionally left empty -- User is not logged in.
    }
}

private HttpServletRequest getHttpServletRequest() {
    return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
}

private Principal getUserPrincipal() {
    return getHttpServletRequest().getUserPrincipal();
}

The following methods are used by the JSF page to determine what components to show (if the user is already authenticated then there is no need to show a login form), authenticate the user if the "Login" button is clicked, or register as a new user when the "Register" button is clicked.
public boolean isAuthenticated() {
    return getUserPrincipal() != null;
}

public void authenticate() {
    try {
        getHttpServletRequest().login(user.getEmailAddress(), user.getPassword());
    } catch (Exception ex) {
        // TODO: Handle failed login attempt
    }
}

public void register() {
    userFacade.create(user);
}

Would this the correct way to go about?
Thanks!
Edit:
Thanks for the input both! I thought about it for a bit, and while I think moving the passwords to a different table is a little to much for me to handle at the moment, I do think I can address some of the issues by separating the UserController in a @RequestScoped AuthenticationController and a stripped down @SessionScoped UserController.
The AuthenticationController would have emailAddress and password fields, bound by the web page's emailAddress and password fields. It would additionally contain the public void authenticate() to authenticate the user and discard the credentials afterwards. The @SessionScoped UserController can then bind to the appropriate User entity without ever needing to know a password. In fact I believe I would be able to remove the password field from User altogether.

A: Your proposed approach has a few rough edges, but for the most part it is quite fine.
If you intend to store a reference to the User entity, then it is preferable to do so in a SessionScoped managed bean. This has it's pros and cons. The obvious advantage is that

*

*the User entity is available through out the application flow, across all pages. This would mean that you need to bind the Principal to a User entity only once for a session. And you can re-use the bound value through all pages, if the need arises.

The not-so-obvious disadvantage is that

*

*the password field would be stored in memory for quite a long duration. At best, you should attempt to nullify the password field of the entity after an authentication attempt (whether it is unsuccessful or not, irrespective of whether the field contains the password in clear or a hash). Also, it would make a lot of sense to define the password field as lazily fetched (FetchType of LAZY) as opposed to the default of eager fetch (FetchType of EAGER). If you implement this (in particular, nullification of the password field), you'll need to watch out for problems involving merge operations conducted on the User entity; in such an event, it might be better to have a separate entity to store passwords for users (quite unfortunate, but that is the extent to which you must bend your back to protect password and their hashes in certain applications).

Having said that, it is also necessary to ensure the following:

*

*The Anonymous user principal should be handled carefully. If you are not writing a filter that enforces an access control mechanism to protect your "private" pages of the application, you should worry a lot more about the way authorization logic in your pages are constructed, not that you do not have to worry at all when you use a filter. The Anonymous principal is just like any other principal, except that it isn't backed by an identity in a realm. If the Principal to User entity binding scheme fails for some reason, you must invalidate the session and redirect the user to the login page again, especially if your pages rely on the User entity instead of the Principal object to enforce access control checks.

*Ensure that you have a separate login page for the application. This is preferable in most applications that accept user credentials in a form, present in the login page; if the form is in a dialog or in some other contraption, a separate login page is usually not necessary. This is desirable for the simple reason that you would want your login process to implement the POST-REDIRECT-GET pattern - a user on successfully logging into your application must be redirected to the main page of the application. Failing to do so, would result in the scenario where a browser refresh (performed by any person having access to the terminal) would re-submit the credentials; quite obviously applications that use a modal dialog or something similar are less susceptible to this problem.

Update
This is based on the edited question. If you implement the authenticate method as proposed, you can implement your scheme of binding the User entity to the Principal only upon successful authentication.
The following is a reproduction of a similar implementation from my application:
public String authenticate()
{
    String result = null;
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    try
    {
        request.login(userId, password);
        result = "/private/MainPage.xhtml?faces-redirect=true";
    }
    catch (ServletException ex)
    {
        logger.error("Failed to authenticate user.", ex);
        FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, Messages.getString("Login.InvalidIdOrPasswordMessage"), null);
        FacesContext.getCurrentInstance().addMessage(null, facesMessage);
    }
    return result;
}

which is invoked from the facelet:
<h:form id="LoginForm" acceptcharset="UTF-8">

        <h:outputLabel for="userid" value="#{msg['Login.userid.label']}" />
        <h:inputText id="userid" value="#{loginBean.userId}" />

        <h:outputLabel for="password" value="#{msg['Login.password.label']}" />
        <h:inputSecret id="password" value="#{loginBean.password}" />

        <h:commandButton id="submit" value="#{msg['Login.submit.label']}"
            action="#{loginBean.authenticate}" />
</h:form>

Note the use of the POST-REDIRECT-GET pattern for the case where the authentication is successful. I've left a bit of code that relates to invalidation of the current session before redirection, to prevent session fixation attacks. The binding of the User entity to the Principal would be done in new session, as long as it is done in a session scoped bean.


text:
Q: Ploting density function over histogram of random generated values from normal distribution I am trying to generate 100 random data(s) from normal distribution, create histogram of it and put density function over the histogram.
So far i have created
set.seed(123)
rs <- rnorm(100, mean = weighted.mean(femals$Salary), sd = sd(femals$Salary))
h <- hist(rs, col = "lightgray" , density = 50 )
xfit <- seq(min(femals$Salary), max(femals$Salary), length = 40)
yfit <- dnorm(xfit, mean = mean(femals$Salary), sd = sd(femals$Salary))
yfit <- yfit * diff(h$mids[1:2]) * length(femals$Salary)
lines(xfit, yfit, col = "red", lwd = 2)

The result of this is

However i am unsure if this is correct. Isnt density function way to low for that histogram? Shouldnt density follow the edges of histogram? Is this correct or did i make mistake in my code?
the mean and standard deviaton are:
weighted mean(femals$Salary) =  5138.852
sed(femals$Salary) = 539.8707


text:
Q: Получение аватарки пользователя VK Api Есть вопрос,данный код раньше работал стабильно,но после мая перестал(спасибо новому API) не могу понять,что тут можно минимально изменить,чтобы вновь получать аватар пользователя?
Имя и т.д по прежнему получаю свободно
<?php
require_once 'vkapi.class.php'; #путь к файлу vkapi.class.php
    $api_id = '6623689'; #id приложения
    $secret_key = 'CneQh5ceNy5dF8NdvGDA'; #секретный ключ приложения
        $viewer_id = $_GET['viewer_id'];
// id пользователя,не знаю откуда брать будешь
$VK = new vkapi($api_id, $secret_key);
$respo = $VK->api('getProfiles', array('user_ids'=>$viewer_id,'fields'=>'photo,first_name,last_name,last_seen'));
$id    = $respo['response'][0]['uid'];
$foto  = $respo['response'][0]['photo'];
$name  = $respo['response'][0]['first_name'];
$fam   = $respo['response'][0]['last_name'];
$last_seen   = $respo['response'][0]['last_seen'];
?>

Вот мой vkapi.class.php
<?php

/**
 * VKAPI class for vk.com social network
 *
 * @package server API methods
 * @link http://vk.com/developers.php
 * @autor Oleg Illarionov
 * @version 1.0
 */

class vkapi {
    var $api_secret;
    var $app_id;
    var $api_url;

    function vkapi($app_id, $api_secret, $api_url = 'api.vk.com/api.php') {
        $this->app_id = $app_id;
        $this->api_secret = $api_secret;
        if (!strstr($api_url, 'http://')) $api_url = 'http://'.$api_url;
        $this->api_url = $api_url;
    }

    function api($method,$params=false) {
        if (!$params) $params = array();
        $params['api_id'] = $this->app_id;
        $params['v'] = '3.0';
        $params['method'] = $method;
        $params['timestamp'] = time();
        $params['format'] = 'json';
        $params['random'] = rand(0,10000);
        ksort($params);
        $sig = '';
        foreach($params as $k=>$v) {
            $sig .= $k.'='.$v;
        }
        $sig .= $this->api_secret;
        $params['sig'] = md5($sig);
        $query = $this->api_url.'?'.$this->params($params);
        $res = file_get_contents($query);
        return json_decode($res, true);
    }

    function params($params) {
        $pice = array();
        foreach($params as $k=>$v) {
            $pice[] = $k.'='.urlencode($v);
        }
        return implode('&',$pice);
    }
}
?>

A: Если еще требуется, без vkapi.class
Если нужны свои данные, user_ids можно удалить
$request_params = [
    'user_ids' => $viewer_id,
    'fields' => 'photo,first_name,last_name,last_seen',
    'access_token' => $token,
    'v' => '5.80'
];

$respo = json_decode(file_get_contents('https://api.vk.com/method/getProfiles?' . http_build_query($request_params)));

$id = $respo->response[0]->id;
$foto = $respo->response[0]->photo;
$name = $respo->response[0]->first_name;
$fam = $respo->response[0]->last_name;
$last_seen_time = $respo->response[0]->last_seen->time;
$last_seen_plat = $respo->response[0]->last_seen->platform;


text:
Q: Passenger with nginx: cannot load such file -- bundler/setup (LoadError) There is only one version of Ruby installed, and I have run gem install bundler && bundle install.
nginx conf
passenger_root /root/.gem/ruby/2.1.0/gems/passenger-4.0.52;
passenger_ruby /usr/bin/ruby;
server {
    listen 80;
    server_name example.com;
    root /srv/http/myrailsapp/public;
    passenger_enabled on;
    rails_env development;
}

Error Log
cannot load such file -- bundler/setup (LoadError)
/usr/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/usr/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/root/.gem/ruby/2.1.0/gems/passenger-4.0.52/lib/phusion_passenger/loader_shared_helpers.rb:263:in `block in run_load_path_setup_code'
/root/.gem/ruby/2.1.0/gems/passenger-4.0.52/lib/phusion_passenger/loader_shared_helpers.rb:366:in `running_bundler'
/root/.gem/ruby/2.1.0/gems/passenger-4.0.52/lib/phusion_passenger/loader_shared_helpers.rb:261:in `run_load_path_setup_code'
/root/.gem/ruby/2.1.0/gems/passenger-4.0.52/helper-scripts/rack-preloader.rb:100:in `preload_app'
/root/.gem/ruby/2.1.0/gems/passenger-4.0.52/helper-scripts/rack-preloader.rb:158:in `<module:App>'
/root/.gem/ruby/2.1.0/gems/passenger-4.0.52/helper-scripts/rack-preloader.rb:29:in `<module:PhusionPassenger>'
/root/.gem/ruby/2.1.0/gems/passenger-4.0.52/helper-scripts/rack-preloader.rb:28:in `<main>'

A: I have been solving similar issue.
My problem was in configuration of passenger_ruby /usr/bin/ruby; Which points to the incorrect version. My solution was to set the path to output of command which ruby
On the server I use rvm. But there are aslo other instalations of ruby.
At first try to test the environment. Go to the application directory and run passenger start. This will show you you, if the server is ready to run the app. Fix the errors...
If the message still says that
cannot load such file -- bundler/setup (LoadError)

run gem install bundler and re-check.
Then set up the path in NGINX to path from which ruby command and restart the appllication.

A: You need to change your passenger_root value. Like here in doc
For example my nginx config:
...
  passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
  passenger_ruby /usr/bin/ruby;
...

A: The phusion passenger could not find the ruby path, see if the ruby path is correct, or if the symbolic link was removed in the server update or other reason.
CentOS 7
Ruby 2.6.3
Rbenv
which ruby
# ~/.rbenv/shims/ruby
sudo rm /usr/bin/ruby # old ruby
sudo ln -s ~/.rbenv/shims/ruby /usr/bin/ruby # 2.6.3
 /usr/bin/ruby -v
# ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]
sudo service nginx restart


text:
Q: How to stop the grid from loading I have a ADF jsff page which contains a af:inlineFrame this frame invokes slickGrid, on save i validate the grid cells and error message is displayed by showing an alert message. Once i click on ok, i expect the grid to stay as it is but the grid gets loaded again. After displaying the alert message i have tried window.frames[0].stop(); but this didnt help
JSFF:
<af:inlineFrame id="slickFrame"
                                source="/js/views/tarAutomation.html"
                                sizing="preferred" shortDesc="Slick Grid">
                    <af:serverListener type="onLoadEvt" method="#{pageFlowScope.myBean.initializeGrid}" />
                    <af:clientListener method="triggerOnLoad" type="inlineFrameLoad"/>

on click of Save
function save() {
// Parse through the dirtied cells
  for(d in dirtyCells)
   {
     var dirtiedRow = dirtyCells[d].row;
     failures = //Gets the failure array
        if(failures.length>0){
          alert("Mandatory fields are not entered");
          grid.gotoCell(dirtyCells[d].row, dirtyCells[d].cell);
        // This is to set the focus on the errored cells
          window.frames[0].stop();
       }
        else{
            //Continue with the save operation
        }

Please let me know how to stop the grid from getting loaded. I want the loading to stop so that the user selected options are seen as errored.

A: It's likely this is just an HTML issue, nothing to do with the grid. It's likely that the save button submits the form. You need to return false from the javascript event to prevent the default action (the submission).
Have a look here: JavaScript code to stop form submission
<form name="myForm" onsubmit="return validateMyForm();">
<script type="text/javascript">
function validateMyForm()
{
  if(check if your conditions are not satisfying)
  {
    alert("validation failed false");
    returnToPreviousPage();
    return false;
  }

  alert("validations passed");
  return true;
}
</script>

A: I found a way to stop the grid from loading
In the Jsff javascript function add event parameter
At the end of this method add event.cancel() which would cancel the new events from being propagated
Further details are here
https://docs.oracle.com/cd/E16764_01/web.1111/b31973/af_event.htm


text:
Q: wpf application showing error on client PC while start I develop one WPF application .It works on my machine .But while runnning on client machine it showing this error
Problem signature:
  Problem Event Name:   CLR20r3
Problem Signature 01: Project.exe
Problem Signature 02: 1.0.0.0
Problem Signature 03: 55f94c7e
Problem Signature 04: PresentationFramework
Problem Signature 05: 4.0.30319.34209
Problem Signature 06: 5348b261
Problem Signature 07: 98f
Problem Signature 08: 0
Problem Signature 09: System.IO.FileLoadException
OS Version:   6.1.7601.2.1.0.256.48
Locale ID:    1033
Additional Information 1: 0a9e
Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
Additional Information 3: 0a9e
Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
.Net Framework 4 and 4.5 is there on client machine
How to solve this?

A: This is an application crash error.
The big thing here is that somewhere in your program threw a FileLoadExcepetion.
Explanation from MSDN:

The exception that is thrown when a managed assembly is found but cannot be loaded.

https://msdn.microsoft.com/en-us/library/system.io.fileloadexception(v=vs.110).aspx
Follow the solution in the article below and find the method which throw this exception in your application and then fix it.
http://blogs.msdn.com/b/oanapl/archive/2009/01/30/windows-error-reporting-wer-and-clr-integration.aspx
Hopefully this gives you enough context to fix your issue.


text:
Q: Is there a Java utility to verify if a string is a valid HTML escape character? I want a method in the following format:
public boolean isValidHtmlEscapeCode(String string);

Usage would be:
isValidHtmlEscapeCode("A") == false
isValidHtmlEscapeCode("ש") == true // Valid unicode character
isValidHtmlEscapeCode("ש") == true // same as 1513 but in HEX
isValidHtmlEscapeCode("�") == false // Invalid unicode character

I wasn't able to find anything that does that - is there any utility that does that?
If not, is there any smart way to do it?

A: Not sure if this is a perfect solution, but you can use Apache Commons Lang:
try {
    return StringEscapeUtils.unescapeHtml4(code).length() < code.length();
} catch (IllegalArgumentException e) {
    return false;
}

A: you might want to have a look at Apache commons StringUtils:
http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringEscapeUtils.html#unescapeHtml(java.lang.String)
with the unescapeHtml you could do sth. like:
String input = "A";
String unescaped = StringEscapeUtils.unescapeHtml(input);
boolean containsValidEscape = !input.equals(a);

A: public static boolean isValidHtmlEscapeCode(String string) {
    if (string == null) {
        return false;
    }
    Pattern p = Pattern
            .compile("&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([0-9A-Za-z]+));");
    Matcher m = p.matcher(string);

    if (m.find()) {
        int codePoint = -1;
        String entity = null;
        try {
            if ((entity = m.group(1)) != null) {
                if (entity.length() > 6) {
                    return false;
                }
                codePoint = Integer.parseInt(entity, 16);
            } else if ((entity = m.group(2)) != null) {
                if (entity.length() > 7) {
                    return false;
                }
                codePoint = Integer.parseInt(entity, 10);
            } else if ((entity = m.group(3)) != null) {
                return namedEntities.contains(entity);
            }
            return 0x00 <= codePoint && codePoint < 0xd800
                    || 0xdfff < codePoint && codePoint <= 0x10FFFF;
        } catch (NumberFormatException e) {
            return false;
        }
    } else {
        return false;
    }
}

Here's the set of named entities http://pastebin.com/XzzMYDjF

A: This should be the method you wanted:
public static boolean isValidHtmlEscapeCode(String string) {
String temp = "";
try {
    temp = StringEscapeUtils.unescapeHtml3(string);
} catch (IllegalArgumentException e) {
    return false;
}
return !string.equals(temp);
}

A: Try matching using a regular expression:
public boolean isValidHtmlEscapeCode(String string) {
    return string.matches("&;#([0-9]{1,4}|x[0-9a-fA-F]{1,4});");
}

Or to save some processing cycles you can reuse the regex for multiple comparisons:
Pattern pattern = Pattern.compile("&;#([0-9]{1,4}|x[0-9a-fA-F]{1,4});");

public boolean isValidHtmlEscapeCode(String string) {
    return pattern.matches(string);
}

The source of the regex can be found at RexLib.com


text:
Q: Change of basis of polynomial mapping. My question is whether I could change the basis of polynomial $P^{13}$ meaning changing $\{1,x,x^2,\ldots,x^{13}\}$ to $\{x^2,\ldots,x^{13},x,1\}$?

A: First of all the sets are identical since a set is only concerned with whether an element is in the set or not (and not concerned with the order of the elements).
With basis one often just mean a set of independent vectors spanning the space.
However in some cases one want to talk about ordered basis where one take order into account. Such a basis should not be written using set notation, but rather use tuple notation:
$$(1,x,x^2,\ldots,x^{13})$$
vs
$$(x^2,\ldots,x^{13},x,1)$$
By permuting the vectors in such a basis one will still end up with a basis since they still are linear independent and spans the same space. This has nothing to do with that the space is a space of polynomials.
To prove that we can consider an ordered base $e_j$ and a permutation $\Pi$ (a bijective mapping on the index set). This gives us a new base $f_j = e_{\Pi(j)}$.
Now we show that any vector $u$ can be written as a linear combination of $f_j$, but since $e_j$ is a base $u$ can be written in that base $u=\sum c_j e_j$, but since $\Pi$ is bijective it has an inverse and $e_j = f_{\Pi^{-1}(j)}$ so $u = \sum c_j f_{\Pi^{-1}(j)}$.
In similar way we can show that $f_j$ are independent. If $0 = \sum c_j f_j$ we have $0 = \sum c_{\Pi^{-1}(j)} e_{j}$ which means that $c_j=0$ since $e_j$ are independent.


text:
Q: DELETE Request with Body (Without using Deprecated HttpEntity) I wanted to execute a HTTP DELETE request with a Body. I am using Spring Framework.
In order to do that, I had to do the following modification:
RestTemplate _deleteManager;
_deleteManager = new RestTemplate();
_deleteManager.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
    protected HttpUriRequest createHttpRequest(HttpMethod httpMethod, URI uri) {
        if (HttpMethod.DELETE == httpMethod) {
            return new HttpEntityEnclosingDeleteRequest(uri);
        }
        return super.createHttpRequest(httpMethod, uri);
    }
});

public static class HttpEntityEnclosingDeleteRequest extends HttpEntityEnclosingRequestBase {
    public HttpEntityEnclosingDeleteRequest(final URI uri) {
        super();
        setURI(uri);
    }

    @Override
    public String getMethod() {
        return "DELETE";
    }
}

Then I use the _deleteManager to make the call
_deleteManager.exchange(url, HttpMethod.DELETE, requestEntity, ResponseClass.class);

This is working correctly however in the code HttpUriRequest and HttpEntityEnclosingRequestBase are marked as deprecated.
What alternative should I use instead? I searched online but couldn't find anything.
EDIT: Or a simple answer that shows how to do a DELETE request with a body is enough.
Thank you

A: Option A) Use Unirest
Unirest.delete("http://url.example.com").body("request-body").asString();

That's it.
Option B) If you do not want to use this library, use Apache HttpClient, which is the most widely used http library for Java. However you need to create a small class for delete with body to work:
import java.net.URI;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
    public static final String METHOD_NAME = "DELETE";
    public String getMethod() {
        return METHOD_NAME;
    }
    public HttpDeleteWithBody(final String uri) {
        super();
        setURI(URI.create(uri));
    }
}

and use it via:
HttpDeleteWithBody request = new HttpDeleteWithBody(url);
request.addHeader("accept-encoding", "gzip"); //add some headers if you like
request.setEntity(new StringEntity(body, "UTF-8"));
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(request);

A: Check the related topic in the official changelog of the 6.0. So you should use the HttpURLConnection class.
An example:
URL url = new URL("your_url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
    urlConnection.setRequestMethod("DELETE");
    urlConnection.setDoOutput(true);
    // Maybe you should set the request properties here too, but it depends on your body.

    OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
    osw.write("this_is_the_body");
    osw.flush();

    int HttpResult = urlConnection.getResponseCode();
    if(HttpResult == HttpURLConnection.HTTP_OK) {
        InputStream is = new BufferedInputStream(urlConnection.getInputStream());
        // Handle the response.
    } else {
        // ...
    }
}
finally {
    urlConnection.disconnect();
}


text:
Q: display property when doing show/hide I am working on a design with media queries here. In the larger design, I have a few items that are hidden by hide();.
But in the smaller design, I want them to stay shown. So I used a display:block !important value.
Well now the content in the larger version is set to display. Oh the confusion!
Style:
@media only screen and (min-width: 180px) {
    .backCat{display:block !important;}
}

@media only screen and (min-width: 768px) {
    .backCat{display:none;}  // no clue what to put here
}

HTML:

Releases

Strangers on a Plain

Released:August 2011

Nagano Car Rental

Released:August 2010

Panic Box

Released:May 2009

    More Releases

JS
$(document).ready(function() {
    $('.backCat').hide();
    $('.moreReleases').click(function(){
        $('.backCat').show(500);
        $('.moreReleases').hide();
    });
});

A: the !important declaration is taking precedence since the min-width condition in your first media query remains true when your second is satisfied. Change your first media query to @media only screen and (min-width: 180px) and (max-width: 767px). You might also get away with simply placing important behind your display: none; declaration as well.

A: You might need to set a max-width for the smaller screen version since 768 is at least 180

A: Ok, tested the idea I suggested above and it works:

Releases

Strangers on a Plain

Released:August 2011

Nagano Car Rental

Released:August 2010

Panic Box

Released:May 2009

    More Releases

On the small layout we don't do anything, just let the links display (and hide the more releases link since it's unneeded). On the larger display we hide the blocks by default and show the moreReleases link. Clicking the link does what it did before, showing the blocks and hiding the link.

A: .hide() is "browser-size agnostic" and will run regardless of what your browser size is and that's why .backCat is being removed on the smaller screen. You want to remove this from the js.
Once you have that gone, you'll need to remove !important so it reads:
@media only screen and (min-width: 180px) {
.backCat{display:block;}
}
Now .backCat will display on smaller screens but gets turned off in the bigger screen. What's left is you'll have to add stying for .moreReleases so that it shows (using display:block or something) when .backCat is hidden, and hides (i.e. display:none) when .backCat is shown.
Hope this helps!


text:
Q: NSArray Getting Out Of Order I use a PLIST to populate a TableView in my app.  I want the TableView to be in order of how items were added, due to needing a good way to edit it later on, so the indexPath.row will match up with the indexPath of the PLIST.  I get the TableView populated by going from the PLIST to NSDictionary to NSArray.  The issue is that the TableView keeps listing everything in alphabetical order and not the order it was listed
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:self.selectedCountry];
    _plist = [NSMutableDictionary dictionaryWithContentsOfFile: plistPath];
    _content = [_plist allKeys];


text:
Q: Spit PNG into multiple images on Ubuntu with imagemagick This image contains 30 blocks of user data. I plan to extract these 30 blocks as PNG files and then run tesseract-ocr to extract text from them. Can someone tell me how I can use imagemagick to get those 30 PNG files?

A: Imagemagick will work well. In their document , there are eamxamples that you can use
convert rose: -crop 40x30+10+10  crop.gif
# from point (40, 30) take a (width=10, height=10) frame and save into crop.gif

In your case, you have to find correct coordinate and size, then you can do it automatically. Just run and try, it will not consume too much time.
Hope that help

A: The following works for me in ImageMagick. I first crop to the array of boxes. Then I crop a set of 3x10 equal sized boxes.
convert image.png -crop 1125x1500+43+99 +repage -crop 3x10@ +repage result_%02d.png

See
http://www.imagemagick.org/Usage/crop/#crop_repage
http://www.imagemagick.org/Usage/crop/#crop_equal


text:
Q: bash control statment for when an option flag is used I trying to make control statement to check on a option flag is used or not?  For -o output.file if is used I would like to make equal to variable OUTPUTSUM = OUTPUTFILE and if there no -o option use then I have it defaulted to relative path of the script? I just not sure how to go about checking for -o option?
PSEUDO code
while getopts i:o:h OPTION
do
     case $OPTION in
         i)
             INPUTFILE=$OPTARG
             ;;
     o)
         OUTPUTFILE=$OPTARG
             ;;
         h)
             usage
         exit 1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [-o EXIST]; then

    OUTPUTSUM = OUTPUTFILE
else
   OUTPUTSUM = $SCRIPTPATH/SUMMARY
fi

A: bash parameter expansion: use default value if variable is unset or null:
outputsum=${outputfile:-"$scriptpath/SUMMARY"}

Get out of the habit of using $ALL_CAPS_VARNAMES -- one day you'll use "PATH" and break your script.


text:
Q: CSS: how can I do this page responsive? I have this map with animals on it, but it doesn't look good on mobile/tablet and higher desktop resolutions.
The page is here: https://rianco.ro/map/
Thank you in advance,
A
the screenshot is made with iphone6

    The code for the map is:
.harta-links {width:60px;height:60px;position:absolute;background-color:#f00;background:url(https://rianco.ro/wp-content/uploads/2018/05/pin.png) center center no-repeat;background-size: contain;}
.harta-links:hover {margin-top:-4px;}
.harta-links img {width: 39px;margin: 2px 0px 0px 11px;}
 #zoom {width:20px; height:20px;border:1px solid #000;}

The code to add an animal on the map is:

A: @media only screen and (max-width: 600px) {//Here set width on which you want to apply code bellow
   //Your css here for resolution under 600px
}

You can research a little bit css media query for responsive layout.
Here is some links for that.
https://www.w3schools.com/css/css_rwd_mediaqueries.asp
https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries


text:
Q: How to grep for a 7 digit hexadecimal string and return only that hexadecimal string? I am trying to extract all the leading 7 digit hexadecimal strings in a file, that contains lines such as:
3fce110:: ..\Utilities\c\misc.c(431): YESFREED (120 bytes) Misc

A: If all the lines in the file follow the given format then a couple of methods:
$ grep -o '^[^:]*' file
3fce110

$ awk -F: '{print $1}' file
3fce110

$ cut -d: -f1 file
3fce110

$ sed  's/:.*//' file
3fce110

A: egrep -o '^[0-9a-f]{7}\b' file.txt

*

*egrep is the same as grep -E; it uses extended regexp.

*-o prints only the matching part of each line.

*^ anchors the match to the beginning of the line.

*[0-9a-f]{7} matches seven hexadecimal characters. If you want to match uppercase letters add A-F here or add the -i flag.

*\b checks for a word boundary; it ensures we don't match hex numbers more than 7 digits long.


text:
Q: boost on Android using stlport In my Android App, I need to build both websocketpp (http://www.zaphoyd.com/websocketpp) and libjingle (https://code.google.com/p/libjingle/) and then I run into the following problem:
websocketpp is using the boost library (www.boost.org) which I can build fine with:
APP_STL         := gnustl_static

But with this setting when I link libjinge library, I got the error:
undefined reference to 'std::__node_alloc::_M_deallocate(void*, unsigned int)'

If I change to use stlport in Application.mk:
APP_STL         := stlport_static

Then I got error when compile websocketpp:
fatal error: array: No such file or directory

websocketpp include the array that I can only find here:
sources/cxx-stl/gnu-libstdc++/4.8/include/array

I can not link both stlport and gnustl libraries because I got error complaining about duplicate definitions.
So how can I solve this issue for my project that can use both tlport and gnustl?
[UPDATE]
It's definitely not possible to use both stlport and gnustl in the project, so I have to choose one. WebRTC is using stlport and gnustl is under GPL so stlport should be a better choice.
I am able to build the boost library (used by websocketpp) with some changes in file "boost/tools/build/v2/user-config.jam":
<compileflags>-I$(AndroidNDKRoot)/sources/cxx-stl/stlport/stlport
using stlport : android : $(AndroidNDKRoot)/sources/cxx-stl/stlport/stlport ;

And run bjam with stdlib=stlport-android option.
The compiling and linking is successful. However, when I run my app, it crashes when executing some code in the boost library.
Anybody has any luck on building and running boost library on Android using stlport?


text:
Q: Understanding what happens within function loop I would like to know why the inner for loop executes. My understanding is that since j = 1 and i = 0, j <= i; would produce nothing as j is already greater than i. Therefore, the inner loop would be skipped, producing the same result as the initial array.
void sortArray(int myArray[], int size)
{
    int num1 = 0;
    int num2 = 0;
    int temp = 0;

    for (int i = 0; i < size; i++)
    {
        int first = 0;

        for (int j = 1; j <= i; j++)
        {
            if (myArray[j] > myArray[first])
            {
                first = j;
            }

            temp = myArray[first];
            myArray[first] = myArray[i];
            myArray[i] = temp;
        }
    }
}

A: The inner loop is skipped during first iteration. After i is incremented, j is now equal to i, therefore the inner loop will execute 1 time. Inner loop exits, outer loop increments i by 1, inner loop now iterates twice as i == 2.
This will repeat until i == size - 1 OR i < size (same condition, different wording).

A: The inner loop should skip for 1 iteration of the outer loop then will run for 1 time as j<=i returns true. (first iteration i=0, second iteration i=1)
this is equivalent to:
for (int j = 1; j <= 0; j++)

After that the second loop will run 1 time equivalent to
for (int j = 1; j <= 1; j++)

and so on..
for (int j = 1; j <= 2; j++)


text:
Q: Maintain cardinality in hash map when removing objects from arraylist I wrote this method which extracts the max elem from a queue that contains Node objects. The main problem is that when I do the remove, the indexes of the elements decrease by 1, so in the hashmap I lost the correlation between Node-Position (my hashmap is: HashMap <Node<T,E>, Integer> hmap)
public Node extractMax() throws PriorityQueueException {
    if (getSize() == 0) throw new PriorityQueueException("Cannot read from an empty queue");
    Node max = getRoot();
    queue.remove(0);
    hmap.remove(max);
    heapify(0);
    return max;
  }

How can I solve it with a complexity <= O(n)?


text:
Q: Movilizer: Sorting Data Container without changing Array keys I have a data container, with 9 values in it. The order I want in my data container when it arrives is as follows:
<entry name="userId">
   <valstr>u517775</valstr>
 </entry>
 <entry name="beginTime">
   <valstr>2017-08-11 - 09:44:00</valstr>
 </entry>
 <entry name="endTime">
   <valstr>2017-08-11 - 09:44:15</valstr>
 </entry>
 <entry name="mailOffice">
   <valstr>insert function here</valstr>
 </entry>
 <entry name="eersteScore">
   <valstr>25.0</valstr>
 </entry>
 <entry name="verbetering">
   <valstr>-20.0</valstr>
 </entry>
 <entry name="procentueleScore">
   <valstr>5.0</valstr>
 </entry>
 <entry name="aantalVragen">
   <valstr>20</valstr>
 </entry>
 <entry name="pogingen">
   <valstr>2.0</valstr>
 </entry>

But somehow it always ends up in the same order, but not the one I want. I know this is because the array in Movilizer is actually a hashmap, and a way to solve it is using keys from 0-8 instead of strings. But is there a way I could achieve this without changing the keys?
My MEL code:
data['userId'] = $global: userID;
data['beginTime'] = $local: beginTime;
data['endTime'] = call($global: getDateTime)();
data['mailOffice'] = "insert function here";
data['eersteScore'] = $local: firstScore;
data['verbetering'] = verbetering;
data['procentueleScore'] = procentScore;
data['aantalVragen'] = $local: aantalVragen;
data['pogingen']= $local: pogingen;
writeContainer(concat(data['userId'], "-", strReplace(data['endTime'], " - ", "-")), data, 0);

Thanks in advance!

A: I believe you require help in other areas of your system design. The order of the elements in the hashtable itself and the order of the entry elements in the xml response should not have any impact. Maybe it will help to open another question in which you describe what you want to achieve to receive input about a best practice approach for that


text:
Q: How can i pass 'n' number of requests based on value extracted from json path extractor In Jmeter, I have extracted a value from json. The value is 2. My requirement is I need to send following HTTP samplers.
Here it is 2.
So I need to send the following 2 http requests.
http://IP:PORT/users/0?authSSOId
http://IP:PORT/users/1?authSSOId
If its 'n' request I need to pass upto 'n' counts in the url
How can i Achieve this

A: You can add loop controller which will execute HTTP request as per your extracted count. Structure will look like below:

A: Given you have this 2 living in a JMeter Variable, i.e. ${valueFromJson}

*

*Add While Controller to your Test Plan and put the following expression into the "Condition" input:
${__javaScript(${counter} < ${valueFromJson},)}

*Put a Counter as a child of the While Controller and configure it like:

*

*Start: 1

*Increment: 1

*Reference Name: counter

*Put your HTTP Request sampler after the Counter

The HTTP Request will be executed as many times as the ${valueFromJson} variable value


text:
Q: How can I send a react component as an input to html2canvas and jsPdf? I have a webpage I made in React.  It renders some charts.  The charts will appear slightly differently depending if the user is viewing the page on desktop or mobile.
I have used html2canvas and jsPDF to export the page to PDF.  The problem is that I ALWAYS want to export the charts in the format seen in mobile view.
I have thought of the following:

*

*rendering the mobile view inside a div with display set to none and using that div as the input to html2canvas.  This does not work.  I get an error.

*Trying the above, but instead of using the hidden div, just send the div as the input to html2canvas inline.  I do not know if you can even do this.

*Using React-pdf to output the pdf.  The problem here is that I do not know how to embed the charts when using react-pdf.
Does anyone have an idea of what I can try?
Thank you.


text:
Q: Compiling dict of users in Python for search results I am not very familiar with Python or SQL and have been tasked with creating a search results page to display user information from an SQL database. I am using flask, sending JSON objects from the python back-end to the javascript/jquery front-end. I have managed to display a user when there is only one user returned from a search (a search by email address) with the following code:
 user = db.execute(
            'SELECT * FROM user WHERE email = ?', (emailInput,)
        ).fetchone()
        if user is None:
            user_details = {
                'first' : 'error'
            }
            y = json.dumps(user_details)
            return jsonify(y)
        if user['first'] is None:
            first = ""
        else:
            first = user['first']
        if user['email'] is None:
            email = ""
        else:
            email = user['email']
        if user['last'] is None:
            last = ""
        else:
            last = user['last']
        if user['address_line1'] is None:
            address_line1 = ""
        else:
            address_line1 = user['address_line1']
        if user['address_line2'] is None:
            address_line2 = ""
        else:
            address_line2 = user['address_line2']
        if user['username'] is None:
            username = ""
        else:
            username = user['username']
        user_details = {
            'first': first,
            'last': last,
            'email': email,
            'address1': address_line1,
            'address2': address_line2,
            'username': username
        }
        y = json.dumps(user_details)
        return jsonify(y)

Now I want to upgrade this code with a fetchall() to return the user_details of every user fetched by the SQL call but I don't know how to go about it. Thanks in advance for the help.
EDIT:
what I really need help with is turning multiple structs like these:
    user_details = {
        'first': first,
        'last': last,
        'email': email,
        'address1': address_line1,
        'address2': address_line2,
        'username': username
    }

into one big struct like this:
        users = {
            user_details1 = {
                'first': first,
                'last': last,
                'email': email,
                'address1': address_line1,
                'address2': address_line2,
                'username': username
            }
            user_details2 = {
                'first': first,
                'last': last,
                'email': email,
                'address1': address_line1,
                'address2': address_line2,
                'username': username
            }
            etc.
        }

A: fetchall returns a list of lists, so you just need to iterate over the outer list (rows of the table).  For example:
users = db.execute(
            'SELECT * FROM user WHERE email = ?', (emailInput,)
        ).fetchall()
for user in users:
        if user['first'] is None:
            <etc>

A: Instead of spending a few hours solving this specific SQL problem, spend a few hours learning an ORM like sqlalchemy so you never have to write SQL again :)


text:
Q: React post Build - Classes & Hooks dont Render I finished working on an app project and I built the final project. The problem is that the classes and hooks get placed but didn't render in the final version for some reasons...
Here you can find the live version https://www.htfgamestudio100.com/
Inspecting it you will find the content div that has the main logic of the app. All the classes and hook functions didn't get render at all but the logic get placed correctly.

A: Style is missing width, height & background-size (cover/contains etc), as your image is in the background the button cant size around it, so you would need to specify the dimensions to 'contain' it correctly.
<button alt="Lost Ark WIP" title="WIP" value="" id="MonsterId1" style="background-image:url(https://i.stack.imgur.com/XePN4.jpg);height:10px; width:30px;background-size: cover;"></button>

see pen

A: I found the problem... For some reasons my div's opacity is dropped to 1% so they become invisible. I fixed the problem by finding where I use opacity and changed it from 90% to 0.9. Seems that react can't understand the opacity expressed in % for some reasons.


text:
Q: Test-Path - Variable Part of FileName - Variable doesn't get substituted SourceFile.txt has the below
<somepath>\filename_$tminus1.csv

The below is the script I've written.
$date = [DateTime]::ParseExact("21-Aug-18", "dd-MMM-yy", $null)

if ($date.DayOfWeek -eq "Monday") {
    $tminus1 = $date.AddDays(-3).ToString('yyyyMMdd')
    $tminus2 = $date.AddDays(-4).ToString('yyyyMMdd')
    Write-Host "Date vaulues set for Monday"
} else {
    $tminus1 = $date.AddDays(-1).ToString('yyyyMMdd')
    $tminus2 = $date.AddDays(-2).ToString('yyyyMMdd')
    Write-Host "Date vaulues set for Non-Monday"
}

$files = Get-Content -Path $PSScriptRoot\SourceFile.txt

foreach ($file in $files) {
    Convert-Path $file

    if (-not (Test-Path $file)) {
        echo ""
        Write-Host "$file doesn't exist"
    } else {
        echo ""
        Write-Host "$file exists"
    }
}

The Test-Path cmdlet doesn't get the variable value substituted while looking for the file. It prints the below.
<somepath>\filename_$tminus1.csv doesn't exist

I expect the $tminus1 value gets substituted as 20180823 so that the else part prints the below.
<somepath>\filename_$tminus1.csv exists

A: The problem is when you pull the text in from your CSV it is treated as a literal, as if it as was a single quoted string. You can force PowerShell to re-evalueate the string like so:
$file = $ExecutionContext.InvokeCommand.ExpandString($file)

Or an alternative method would be to change the text in the CSV to this:
<somepath>\filename_{0}.csv

You can then use the format string to apply the variable like so:
$file = $file -f $tminus1

A: When you read strings from a file, PowerShell does not perform the normal interpolation it does for strings in your code.  One way to get around this is to use Invoke-Expression.
Say you have a file (paths.txt) with these paths in it:
C:\Data\$dir1
C:\Data\$dir2

You can get the real paths like this:
$dir1 = "Directory1"
$dir2 = "Directory2"

Get-Content paths.txt |
    ForEach-Object {
        Invoke-Expression """$_"""
    }

This will output:
C:\Data\Directory1
C:\Data\Directory2

Obviously, you can capture these to a variable, send them along the pipeline, etc, instead of just outputting them.


text:
Q: ASP.NET: Does "Image control" have any other attribute that's used to get data besides ImageUrl? I've been struggling for a couple of days now on how to keep FileUpload web control data locate in a Wizard web control. When I go to a different step from the one in which the FileUpload control is located, the data is lost.
I've come across this article that shows how to keep the whole FileUpload Control in a Session State (How to Maintain FileUpload Control's State after PostBack).
In this article, the author uses session to store data
Session["FileUpload1"] = FileUpload1;

Now, thanks to the article, I'm able to keep a copy of the FileUpload control in the session and am able to invoke it in any wizard step I want.
Now, I'd like to know how, after re-creating the FileUpload control saved in the Session
FileUpload fp = (FileUpload)Session["FileUpload1"];

I can use that data from it to display the image that was uploaded.
Image1.ImageUrl =

It looks like using the ImageUrl attribute is the wrong way of doing it. So Is there any way I can get data from the FileUpload control to display an image? i.e. does Image control have any other attribute that's used to get data, besides ImageUrl
Thanks for helping

A: Are you talking about the <asp:Image> control? If so, then this is only used to render html.
<img src="" alt="" title="" class="" customattribute="" />

So what else are you wanting to do with it? If you are wanting to store an image before you save it locally, then I do not think this would be possible.
You would need to save the image from the FileUpload in between steps in order to display it.


text:
Q: Where to locate DNS server addresses on Windows 7 I had manually entered DNS server addresses in TCP/IP settings (Local Area Connection), but i accidentally removed them and i don't know where i got it from. The only thing i have is a system image backup, so i could restore it and read the DNS addresses, but that would be too cumbersome and i don't have a spare drive.
However i can open the VHD system image and browse all the folders.
Is there a physical location on the drive of where all the DNS entries are stored in a file or something?
Help would be much appreciated.

A: I've not actually tried this - however it seems correct
What you want is in the registry (on my system)  its at HKLM\System\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{GUID}\NameServer
So you need to grab the file which contains HKLM\System - which I believe is

C:\Windows\System32\config\system.

(no extension) and open it with regedit. Select the LOCAL_USERS  and use Load Hive  in RegEdit and navigate to the Key undert the hive you load.

A: I found the solution,

*

*Open the system image backup VHD file with 7-zip

*Browse to Windows\System32\config (where the actual registry files are located)
and copy the "SYSTEM" file

*Open the Registry Editor and click on "HKEY_LOCAL_MACHINE"

*Go to the File menu and click on "Load Hive"

*Select the "SYSTEM" file that you copied and open it, give it a name

*Now, in the loaded hive, navigate to
"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\services\Tcpip\Parameters\Interfaces"
click on the various keys and look at "NameServer" until you find all the DNS
entries

*After copying the DNS addresses, make sure to unload the hive afterwards


text:
Q: Typo3 9 - routing - cHash in news list I am using the following config.yaml for the standard news plugin:
NewsPlugin:
  type: Extbase
  limitToPages:
    - 3
    - 15
  extension: News
  plugin: Pi1
  routes:
    -
      routePath: '/l/{page}'
      _controller: 'News::list'
      _arguments:
        page: '@widget_0/currentPage'
    -
      routePath: '/tag/{tag_name}'
      _controller: 'News::list'
      _arguments:
        tag_name: overwriteDemand/tags
    -
      routePath: '/{news_title}'
      _controller: 'News::detail'
      _arguments:
        news_title: news
    -
      routePath: '/archiv/{year}/{month}'
      _controller: 'News::archive'
  defaultController: 'News::list'
  defaults:
    page: '0'
    news_title: ''
    tag_name: ''
    year: '2019'
    month: '01'
  aspects:
    news_title:
      type: PersistedAliasMapper
      tableName: tx_news_domain_model_news
      routeFieldName: path_segment

Now it all works pretty well, the only problem is, when I use the pagination, there is always a cHash attached to my url. Like a link to page 2 results in
http://www.example.com/newspage/l/2?cHash=313213213213213a2f13asf321
Any ideas why this happens?

A: A cHash will be added if the requirements are too loose or if there are no requirements at all. It can also be avoided with a StaticRangeMapper.
I'm also struggling with setting up the routeEnhancers for news. You may have a look at my approach for applying pagination without cHash.

A: Thanks to ben I found a solution that worked:
NewsPlugin:
  type: Extbase
  extension: News
  plugin: Pi1
  routes:
    -
      routePath: '/l/{page}'
      _controller: 'News::list'
      _arguments:
        page: '@widget_0/currentPage'
    -
      routePath: '/tag/{tag_name}'
      _controller: 'News::list'
      _arguments:
        tag_name: overwriteDemand/tags
    -
      routePath: '/{news_title}'
      _controller: 'News::detail'
      _arguments:
        news_title: news
    -
      routePath: '/archiv/{year}/{month}'
      _controller: 'News::archive'
  defaultController: 'News::list'
  defaults:
    page: '0'
    news_title: ''
    tag_name: ''
    year: '2019'
    month: '01'
  aspects:
    news_title:
      type: PersistedAliasMapper
      tableName: tx_news_domain_model_news
      routeFieldName: path_segment
    '@widget_0/currentPage':
      type: StaticRangeMapper
      start: '1'
      end: '1000'


text:
Q: How to run exec in binary nodejs App running as a Daemon in Linux? I have a nodejs App.When i start the App from CLI with nodejs app.js all works fine, but if the App runns as a daemon the exec command inside app don't works.

A: How are you running your app as a daemon? You can check the forever tool for that via npm, which will handle exec commands as supposed.


text:
Q: Disable headers in sub-files when compiled stand-alone I am writing a large report (using the report class), and hence have a "main" file alongside all the parts as separate TeX files. The subfiles package is used to import all of the part files into the "main" file.
Although this works perfectly fine when compiling from the "main" file, the headers (using fancyhdr) fail to render properly when compiling a part file stand-alone, due to the header definition relying upon undefined macros such as \thepart.
Is there a way to "detect" if a sub-file is being compiled stand-alone, and if so, specify something which would disable headers (such as \pagestyle{empty}) ?

A: The etoolbox package makes it easy to test if a control sequence is defined; this can also be done "manually" with e-TeX primitives such as \ifcsname:
\documentclass{article}
\usepackage{etoolbox}

\begin{document}

% We could of course factor out the "is" too, but let's favor clarity over
% trying to be smart.
\verb|\thepart|
\ifdef{\thepart}{is}{is not} defined.

\verb|\thechapter|
\ifdef{\thechapter}{is}{is not} defined.

\bigskip
% Alternatively:
\verb|\thepart|
\ifcsdef{thepart}{is}{is not} defined.

\verb|\thechapter|
\ifcsdef{thechapter}{is}{is not} defined.

\bigskip
% Using the underlying e-TeX primitive (requires a TeX engine with e-TeX
% extensions, but not the 'etoolbox' package):
\verb|\thepart|
\ifcsname thepart\endcsname
  is     % <--- space here
\else
  is not % <--- space here
\fi
defined.

% Terse version, for a change
\verb|\thechapter| is
\ifcsname thechapter\endcsname\else not \fi defined.

\bigskip
% Using TeX only (no e-TeX extension), we can test if a control sequence is
% either undefined or \let-equal to \relax:
\verb|\thepart| is
\expandafter\ifx\csname thepart\endcsname\relax
  either undefined or \verb|\let|-equal to \verb|\relax|.
\else
  defined.
\fi

\verb|\thechapter| is
\expandafter\ifx\csname thechapter\endcsname\relax
  either undefined or \verb|\let|-equal to \verb|\relax|.
\else
  defined.
\fi

\end{document}


text:
Q: Automatic thresholding I did pre-processing on images before object recognition in which following steps are included:

*

*Average filter is used to remove noise

*bwareaopen command is used to remove unwanted pixels.

*Dilation and closing is also performed to get clean image.

The problem is that thresholding value of all above specified operations are set according to one image but when I change the image then all these specified thresholding values do not work for the new image.
Is there any way to set the thresholding values in such a way that they work for 30 to 40 images captured at the same time using the same camera from fixed height. As it is not possible for me to change thresholding value of operations for every image.
Thanks in advance.


text:
Q: CSV , JAVA & HSQLDB im really new in java programming
i want to ask about reading a CSV in java and then upload it to HSQLDB.
i have been reading & try the example of solution through tutorial but still not really understand.
from my readings, most had suggest of using OpenCSV but

*

*can i read a csv with delimiter or nested delimiter with opencsv?

*

*opencsv reads my *.csv file in different way with multiple line in one column. all i want it to be read in a single row.

below is the example
B03BB510001T2001,,CHILDREN'S CHEWABLE MULTI VITAMINS*,,""PANTOTHENIC ACID 7.5MG,"
"PARA AMINO BENZOIC ACID (PABA) 250MCG,"
"FOLIC ACID 30MCG,"
"BIOTIN 50MCG,"
"THIAMINE MONO-NITRATE + B6 + B12 6.6MG,"
"CHOLINE 1MG,"
"VIT A + VIT E + VIT C REFER FILE,"
"INOSITOL 1MG"",,""TABLET, CHEWABLE"",,,,B03,REGISTERED,75MG"
BUT i want it to be displayed in a single row

*

*how can i insert directly from csv file into database?

*

*i am currently have to used HSQLDB [standalone server].
do i have to used third party tools to do this

**i only familiar reading & upload from csv into database using PHP & MYSQL not java &hsqldb
hope you can suggest & help me.

A: Here is a sample script I have used to load data into HSQL per fredt.  You will need to have a persistant DB to use a text table. If you run in the Database Manager just copy and execute one statement at a time.  You can also use sqltool (the sql script is in the same folder as the DB):
\i demotexttable.sql

Here is the demotexttable.sql
/* file.txt needs to be in the same folder as the database
   first line of file is a header, others lines are data
--start file.txt
Col1|Col2|Col3
abcdef|My Company Name|0
--end file.txt
*/

--create the schema
create schema imp;

--create the normal table
create cached table imp.normalTable (
       Col1 char(6),
       Col2 nvarchar(200),
       Col3 int
);

--create the table that table
create text table imp.textfiletable (
       Col1 char(6),
       Col2 nvarchar(200),
       Col3 int
);

--setup the text file table
set table imp.textfiletable source "file.txt;ignore_first=true;fs=|";

--insert data from text file into the `normal` table
INSERT INTO imp.normalTable (Col1, Col2, Col3) select Col1, Col2, Col3 from imp.textfiletable;

--we are done with the text file table
drop table imp.textfiletable;
commit;

I found a few errors in my earlier post, I have cleaned them up in this latest mod.

A: You can load a CSV file directly into HSQLDB.
There are two different ways:

*

*Use HSQLDB's TEXT TABLE feature. Your file shouldn't need any special setting as the delimiter is the default.

*Use HSQLDB's normal tables and load the CVS with SqlTool, which is an additional jar supplied with HSQLDB. SqlTool can be used not only with HSLQLDB, but also with MySQL and other databases.

See here for details:
http://hsqldb.org/doc/2.0/guide/texttables-chapt.html
http://hsqldb.org/doc/2.0/util-guide/sqltool-chapt.html#sqltool_csv-sect

A: As you know that CSV is nothing but a "Comma-Separated-Value". The reason why others suggested OpenCSV is because its has a commercially friendly license. Though apart from that one can use the normal way to retrieve the values.Which is read the values using FileInputStream.Please find the link:
http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
After that parse the individual String using delimiter.
eg: String[] tokens = wholeString.split(delimiter);
Now simply using the jdbc connectivity through using java.sql package one can easily store the values in hsql database.Please check out the link:
http://www.hsqldb.org/doc/guide/apb.html
Hope this helps you out;
Regards,
Anand


text:
Q: How to remove subsequent values after first instance only when other values are absent I am trying to remove zeros after the first instance of a zero, when all future values are 0. Eventually I would love to do this group_by species but baby steps. Here's an example;
# Sample
library(tidyverse)
id<-c("a","b","c","d","e","f","g","h","i","j")
time<-c(1,2,3,4,5,6,7,8,9,10)
value<-c(90, 50, 40, 0, 30, 30, 0, 10, 0, 0)
df<-data.frame(id, time, value)
df

   id time value
1   a    1    90
2   b    2    50
3   c    3    40
4   d    4     0
5   e    5    30
6   f    6    30
7   g    7     0
8   h    8    10
9   i    9     0
10  j   10     0

I would like to see observation id "j" and only observation id "j" removed. I am not even sure where to start. Any suggestions are much appreciated!

A: In base R only.It uses rle to get the number of trailing zeros, if any. Then subsets the dataframe with head.
r <- rle(df$value == 0)
if(r$values[length(r$values)]) head(df, -(r$lengths[length(r$values)] - 1))
#  id time value
#1  a    1    90
#2  b    2    50
#3  c    3    40
#4  d    4     0
#5  e    5    30
#6  f    6    30
#7  g    7     0
#8  h    8    10
#9  i    9     0

You can write a function with the code above, and maybe *apply it to groups.
trailingZeros <- function(DF, col = "value"){
    r <- rle(DF[[col]] == 0)
    if(r$values[length(r$values)] && r$lengths[length(r$values)] > 1)
        head(DF, -(r$lengths[length(r$values)] - 1))
    else
        DF
}

trailingZeros(df)

Note that this also works with a larger number of trailing zeros.
id2 <- c("a","b","c","d","e","f","g","h","i","j","k")
time2 <- c(1,2,3,4,5,6,7,8,9,10,11)
value2 <- c(90, 50, 40, 0, 30, 30, 0, 10, 0, 0, 0)    # One more zero at end
df2 <- data.frame(id = id2, time = time2, value = value2)

trailingZeros(df2)

A: here is a solution within the tidyverse which also works on a larger number of trailing zeros:
df <- tibble(id = letters[1:11], time = 1:11,
             value = c(90,50,40,0,30,30,0,10,0,0,0))
df %>%
  slice(n():1) %>%
  slice(c(which(cumsum(value > 0) > 0)[1] - 1, which(cumsum(value > 0) > 0))) %>%
  slice(n():1)

A: Tidyverse solution that also works with groups
based on sample data (without grouping)
code can be shortened, but this looks very readable ;-)
df %>%
  #arrange by id
  arrange( id ) %>%
  #no grouping valiable in sample data.. so don't use group_by here
  #group_by( group) %>%
  #create dummy's: position in group, last value of group, position of last non-zero in group, previous value (within group)
  mutate( pos_in_group = 1:n() ) %>%
  mutate( last_value = last( value ) ) %>%
  mutate( pos_last_not_zero = max( which( value != 0) ) ) %>%
  mutate( prev_value = lag( value ) ) %>%
  #filter all rows where:
  #   the last value of the group != 0 AND
  #   the previous row (within the group) != 0 AND
  #  the position of the row is 'below' the last non-zero measurement (in the group)
  filter( !(last_value == 0 & prev_value == 0 & pos_in_group >= pos_last_not_zero + 1 ) ) %>%
  #throw away the dummy's
  select( -c( pos_in_group, last_value, pos_last_not_zero, prev_value ) )

#   id time value
# 1  a    1    90
# 2  b    2    50
# 3  c    3    40
# 4  d    4     0
# 5  e    5    30
# 6  f    6    30
# 7  g    7     0
# 8  h    8    10
# 9  i    9     0

Example with some grouping involved
# Sample
library(tidyverse)
id<-c("a","b","c","d","e","f","g","h","i","j","k")
group<-c(1,1,1,1,1,1,2,2,2,2,2)
time<-c(1,2,3,4,5,6,7,8,9,10,11)
value = c(90,0,0,40,0,0,30,30,0,0,0)
df<-data.frame(id, group, time, value)

df
#    id group time value
# 1   a     1    1    90
# 2   b     1    2     0
# 3   c     1    3     0
# 4   d     1    4    40
# 5   e     1    5     0
# 6   f     1    6     0
# 7   g     2    7    30
# 8   h     2    8    30
# 9   i     2    9     0
# 10  j     2   10     0
# 11  k     2   11     0

df %>%
  #arrange by id
  arrange( id ) %>%
  #group
  group_by( group) %>%
  #create dummy's: position in group, last value of group, position of last non-zero in group, previous value (within group)
  mutate( pos_in_group = 1:n() ) %>%
  mutate( last_value = last( value ) ) %>%
  mutate( pos_last_not_zero = max( which( value != 0) ) ) %>%
  mutate( prev_value = lag( value ) ) %>%
  #filter all rows where:
  #   the last value of the group != 0 AND
  #   the previous row (within the group) != 0 AND
  #  the position of the row is 'below' the last non-zero measurement (in the group)
  filter( !(last_value == 0 & prev_value == 0 & pos_in_group >= pos_last_not_zero + 1 ) ) %>%
  #throuw away the dummy's
  select( -c( pos_in_group, last_value, pos_last_not_zero, prev_value ) )

# # A tibble: 8 x 4
# # Groups:   group [2]
#   id    group  time value
#   <fct> <dbl> <dbl> <dbl>
# 1 a         1     1    90
# 2 b         1     2     0
# 3 c         1     3     0
# 4 d         1     4    40
# 5 e         1     5     0
# 6 g         2     7    30
# 7 h         2     8    30
# 8 i         2     9     0


text:
Q: How to group rows in Excel The situation is as below:

A B C 3
A B C 4
A B D 1
A B E 2

How do I get to (in an automated manner)

A B C 7
A B D 1
A B E 2

A: You can use the SUBTOTAL feature (ribbon-menu -> data-tab) or a pivot table to do this.
SUBTOTALS miniHowTo
And here a way with pivot tables:


text:
Q: Problem with font size depending on screen resolution - QT I developed a QGIS plugin by designing the interface with QT Designer.
The inferface appears correctly on my computer (left image).
However, on some computers, I encounter size problems, especially font size (right image).
I noticed that the problem was encountered when in the windows settings "scaling and layout", the variable
"change the size of text, applications and other items" was set to 125% instead of 100% on my computer.

I have read a few things about the use of layout and the declaration of the environment variable QT_AUTO_SCREEN_SCALE_FACTOR =1.
Is there a trick to avoid this kind of problem?


text:
Q: how to findout which Class/Object is calling current winForm/object in c# hey guys, i have 3 winForms named carForm,parForm and updateForm, so there's updateForm.show() method in both carForm n parForm, while m in updateForm i want to know which class/form has called updateForm, so that i can update the respected class db. Currently i'm setting up a public global variable to verify that which form is calling updateForm..but i was thinkin' is there's another way to do this, i guess Reflection can solve this issue, but i'm not able to solve it, here's my code
///carForm
public class carForm:Form
{
    Program.globalvariable="CAR";    //global variable
    UpdateFrom updateForm=new UpdateForm();
    updateForm.Show();

}

///parForm
public class parForm:Form
{
     Program.globalvariable="PAR";
     UpdateFrom updateForm=new UpdateForm
     updateForm.Show();

}

///updateForm
public class updateForm:Form
{
    if(Program.globalvariable=="CAR")
       ///code for update CAR db table
    else if(Program.globalvariable=="PAR")
       ///code for update PAR db table

    Type obj = GetType();  //This is what i was tryin' using Reflection but giving error

}

so if i get the calling Class/Objects info, i can update respected DB table,
can ne1 know hw to do this with Reflection,

A: Put the argument in a constructor of updateForm
///carForm
public class carForm:Form
{
    UpdateFrom updateForm=new UpdateForm("CAR");
    updateForm.Show();
}

///parForm
public class parForm:Form
{
     UpdateFrom updateForm=new UpdateForm("PAR");
     updateForm.Show();
}

///updateForm
public class updateForm:Form
{
    private readonly string _key;
    public updateForm(string key)
    {
        _key = key;
    }

    public void SomeMethod()
    {
        // check for _key here.
    }
}

Edit:
If you want to have the actual type you can pass it directly, no need for reflection.
///carForm
public class carForm:Form
{
    UpdateFrom updateForm=new UpdateForm(this.GetType());
    updateForm.Show();
}

///parForm
public class parForm:Form
{
     UpdateFrom updateForm=new UpdateForm(this.GetType());
     updateForm.Show();
}

///updateForm
public class updateForm:Form
{
    private readonly Type _type;
    public updateForm(Type type)
    {
        _type = type;
    }

    public void SomeMethod()
    {
        // check for _type here.
    }
}

Edit 2:
But in general, passing the type like this smells like bad code. Your control flow will probably end up like a bowl of spaghetti.
If you want the updateForm to update some values on the other forms you should

*

*Send all relevant information about what questions/titles/etc to show in the updateForm in the constructor of the updateForm.

*In the updateForm, save relevant "answers" to public properties of updateForm

*Set DialogResult in updateForm to OK or Cancel depending on how you exit updatForm

*Call updateForm like this: if (updateForm.ShowDialog == DialogResult.OK) {// read all properties from updateForm}

A: You'd probably have to look at the StackTrace class if you wanted to automatically get that kind of information. Not sure about the performance of using it though...


text:
Q: Ошибка создания триггера CREATE TRIGGER `Delete Video` AFTER DELETE ON video
FOR EACH ROW
BEGIN
DELETE FROM usersalbumsvideo where id_video = OLD.idVideo;
DELETE FROM categorytovideo where idVideo = OLD.idVideo;
END

Название полей правильное.
Ошибка на строке 4

1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near '' at line 4


text:
Q: Defining Class in bootstrap Why do we define div class name as "col-lg-3 col-md-3 col-sm-12"? As far as I have seen we define only one class for a div. What is the use of defining 3 classes together for a div ? How it works ?

A: Coined from the bootstrap documentation, mixing several grid classes provides a more dynamic and powerful layout that can stack differently across different screen types.


text:
Q: How to change the name of a folder in Java I would like to change the name of a directory.
I have the next piece of code:
Files.move(dir.toPath(), newDir.toPath(), StandardCopyOption.REPLACE_EXISTING);

but I get this error when I execute the code, the next exception is returned.
java.nio.file.FileAlreadyExistsException: C:\ws\dir -> C:\ws\aux

I have checked that the folder C:\ws\newDir doesn't exists and C:\ws\dir does.
I have also tried File.renameTo() but it doesn't work with folders.

A: Based on this official tutorial
import static java.nio.file.StandardCopyOption.*;
...
Files.move(source, target, REPLACE_EXISTING);

Should works for you.
You could also use other copy options for the 3rd parameter.
For checking existence of File or Folder, checkout this link
Checkout this link.
BTW, make sure you have the right permission to move Dir/File, and you only move once.


text:
Q: red free support for images I am working on a web application for a opthology research firm. They work on cornea images and use red free light to identify lesions (artries and nerve fibers) easily. I have implemented the addAmbient() method provided by microsoft for this purpose and it is working fine.
<img id="eyepic" src="GetImage.jsp" height="1291" width="1944" STYLE="filter:light" onload="eyepic.filters.light.addAmbient(0,255,255,100)">
But the problem is this thing works only in IE. I am looking for a method to implement this for other browsers too. If anyone has any idea please help me.
Thanks

A: hey everyone thanks for responding.Actually i slved my problem a month ago,just forgot to update it here.I am now using java2D api for creating redfree images.It has BandCombineOp to manipulate pixels.
Thanks anyway


text:
Q: Laravel role based page access - Trying to get property of non-object - Auth::user() Still very new to Laravel 3 and working through some issues.
I'm trying to set up a role based access to page. Users are currently able to log in and that part works well but I want to restrict access to certain pages based on the users role eg admin, editor etc.
So, I've created a filter as follows:
Route::filter('check_roles', function () {

$current_url = URI::current(); //get current url excluding the domain.
$current_page = URI::segment(2); //get current page which is stored in the second uri segment. Just a refresher: //the first uri segment is the controller, the second is the method,
//third and up are the parameters that you wish to pass in

$access = 0;
$counter = 1;

//excluded pages are the pages we don't want to execute this filter
//since they should always be accessible for a logged in user
$excluded_pages = array(
    'base' => array('login', 'user/authenticate'),
    1 => array('user/profile', 'dashboard','dashboard/index','articles','articles/index', 'articles/create', 'articles/preview', 'articles/edit', 'user/profile', 'user/logout'),
    2 => array('articles/publish','user/create', 'user/edit'),
    3 => array('user/delete')
);

if (!in_array($current_url, $excluded_pages['base']) ) { //if current page is not an excluded pages
    if(Auth::user()->level < 4) {
    do {
        if (in_array($current_url, $excluded_pages[$counter])) {
            $access=1;

        }
        $counter++;

    } while ($counter < $user_level AND $counter < 4);

    if ($access == 0) { //if user doesn't have access to the page that he's trying to access

        //redirect the user to the homepage
        return Redirect::to('dashboard')
            ->with('error', 'You don\'t have permission to access the following page: ' . $current_url);
    }
    }
}

This is based on tutorial I found https://gist.github.com/anchetaWern/4223764
My thoughts were depending on user access level which is 'level' in the user object I'd filter the pages etc.
However I'm getting an error 'Trying to get property of non-object' this relates to this code:
if(Auth::user()->level < 4) {

testing Auth::user()->level in a view confirms the user is logged in. Can anyone advise why this doesnt work in the routes.php as a filter?
Thank you

A: Problem solved - I was using the incorrect syntax in my script which I realised once I posted here.
if($user_level = Auth::user()->level < 4) {

Should be:
if(Auth::user()->level < 4) {

Filter works now. However I'm looking at ways to improve as not sure this is the most efficient way now!
Thanks


text:
Q: Application with admob, screen rotation issue I'm working at small application, had almost everything done and worked nice until I added AdMob into. I have separated layout for portrait and landscape divided in two folders: layout and layout-land. Also the values used in that layouts are separated in same way. The problem is that after adding AdMob the screen stoped rotating at changing orientation. The stranges thing is that the screen in emulator,but not in device, can rotate from portrait to landscape only without turning back.
I added AdActivity into manifest with

    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"

and code for AdView is:
android:id="@+id/ad"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1.5"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="ca-app-pub-8671233073481795/9448252969"
        ads:loadAdOnCreate="true"
        ads:testDevices="TEST_EMULATOR,TEST_DEVICE_ID_GOES_HERE"
which is included into layouts.
Correct me if im wrong but becouse of   android:configChanges="keyboard|keyboardHidden|orientation
statement the android isn't maintain changing orientation of its own? So I must handle it myself by override the method OnConfigurationChanged, and move all values and layouts from "...-land" folders into layout/values folders with unique name? I hope there is a better way to do this, and a way to store values and layouts for landscape orientation in diffrent folders.
Thank you in advance.
Changing  the layout atributes for AdView doesn't helping, the screen is still turning from portrait to landscape but not vice versa
The problem is solved, it was some error with emulator, on device and in emulator on android 2.3+ everything works fine

A: Its only the AdMob's AdActivity that has the android:configChanges parameter. Probably for any full screen ads. For your Activities - handle it the way you want.
You also may want to use standard ad sizes as you appear to have a 0dp in your layout height. I would start with the suggested settings in the documentation of 'wrap_content' for both height and width and see if that changes anything.


text:
Q: AttributeError: 'set' object has no attribute 'items' python discord error Here is my code

*

*Btw i am running Windows 10 Home and  i am running Python 3.8.2 with VS code

*Any solution will do as long as it fixes my issue with Naro (My software For discord.com)

*Btw please leave ur github link in the solution if you have one so i can credit you on my github
4.FAQ
5.Q- What is this software used for
6.A- to troll people on discord

*Q- Can i get banned

*A- Yes because you are using a user account (Which violates TOS)

   import os
file = os.path.realpath(__file__)
f = open("Tokens.txt" , 'w+')
print ('Naro by hackamous')
print('1) Spam a Channel')
print('2) Spam Friend Requests')
print('3) spam DMs')
choice = input('Enter your choice:')
if choice == '1':
    server_id = input("Server id:")
    Channel_id = input("Channel id:")
    message = input('Message to spam:')
    while True:
        headers = {
            'authorization:' f"{f.readlines()}"
        }
        payload = {
            'content:' f"{message}"
        }
        total = f'https://discord.com/api/v9/channels/{server_id}{Channel_id}'
        requests.post(f'{total}' , headers = headers , data = payload)
        exit_1 = input('Exit y/n:')
        if exit_1 == 'y':
            exit()
        else:
            continue

if choice == '2':
    name = input('Username:')
    dircrim = input('discriminator:')
    while True:
        headers = {
            'authorization:' f"{f.readlines()}"
        }
        payload = {
            'discriminator:' f"{dircrim}"
            'username:' f"{name}"
        }
        total = f'https://discord.com/api/v9/users/@me/relationships'
        requests.post(f'{total}' , headers = headers , data = payload)
        exit_1 = input('Exit y/n:')
        if exit_1 == 'y':
            exit()
        else:
            continue

if choice == '3':
    cha_ID = input('Channel ID:')
    msg = input('Message:')
    while True:
        headers = {
            'authorization:' f"{f.readlines()}"
        }
        payload = {
            'content:' f"{msg}"
        }
        total = f'https://discord.com/api/v9/channels/{cha_ID}/messages'
        requests.post(f'{total}' , headers = headers , data = payload)
        exit_1 = input('Exit y/n:')
        if exit_1 == 'y':
            exit()
        else:
            continue'''

A: The problem is the syntax you're using to construct your dicts.  For example:
'content:' f"{message}"

This not a dict entry, but in fact is a single concatenated string.  As a result, instead of creating a dict, it is creating a set.
In order to make it a dict entry, the colon needs to be outside of the string, like this:
'content' : f"{message}"

All of the dicts have this same problem, and can be fixed the same way.