text:
Q: python ssh script error Just a bit of background, I'm writing a script to ssh to several remote servers and copy my public key to them.  I embarked on writing a custon ssh client because I can't install any of the external python modules.  To make a long story short, the company I work for says, if it isn't part of the standard python library, you can't use it.
After weeks of searching I found a script that I thought was the answer to all of my prayers.  I've modified it to suit my needs but I'm getting a variable not found error and I need a little guidance in figuring it out.
Here's the script:
#!/usr/bin/python

import pty, re, os, sys, stat, socket
from getpass import getpass

class ssherror(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class sshclient:
    def __init__(self, ip, passwd, user, port):
        self.ip = ip
        self.passwd = passwd
        self.user = user
        self.port = port

    def runcmd(self, c):
        (pid, f) = pyt.fork()
        if pid == 0:
            os.execlp("ssh", "ssh", '-p %d' % self.port, self.user + '@' + self.ip, c)
        else:
        return (pid, f)

    def pushfile(self, src, dst):
        (pid, f) = pty.fork()
        if pid == 0:
            os.execlp("scp", "scp", '-P %d' % self.port, src, self.user + '@' + self.ip + ':' + dst)
        else:
            return (pid, f)

    def pushdir(self, src, dst):
        (pid, f) = pty.fork()
        if pid == 0:
            os.execlp("scp", "scp", '-P %d' % self.port, "-r", src, self.user + '@' + self.ip + ':' + dst)
        else:
            return (pid, f)

    def _read(self, f):
        x = ''
        try:
            x = os.read(f, 1024)
        except Exception, e:
            pass
        return x

    def connect(self, pid, f):
        output = ''
        got = self._read(f)
        m = re.search('authenticity of host', got)
        if m:
            os.write(f, 'yes\n')
            while True:
                got = self._read(f)
                m = re.search('Permanently added', got)
                if m:
                    break

            got = self._read(f)
        m = re.search('assword:', got)
        if m:
            os.write(f, self.passwd + '\n')
            tmp = self._read(f)
            tmp += self._read(f)
            m = re.search('Permission denied', tmp)
            if m:
                raise Exception('Invalid passwd')
            got = tmp
        while got and len(got) > 0:
            output += got
            got = self._read(f)
        os.waitpid(pid, 0)
        os.close(f)
        return output

    def cmd(self, c):
        (pid, f) = self.runcmd(c)
        return self.connect(pid, f)

    def push(self, src, dst):
        s = os.stat(src)
        if stat.S_ISDIR(s[stat.ST_MODE]):
            (pid, f) = self.pushdir(src, dst)
        else:
            (pid, f) = self.pushfile(src, dst)
        return self.connect(pid, f)

def sshconnect(ip, passwd, user, port=22):
    s = sshclient(ip, passwd, user, port)
    return s.connect(pid, f)

def sshpush(ip, passwd, src, dst, user, port=22):
    s = sshclient(ip, passwd, user, port)
    return s.push(src, dst)

passwd = getpass()
src = '/path/to/dir/being/copied'
dst = '/path/to/destination/directory'
user = os.getlogin()
port = portnum
hosts = ['host1', 'host2', 'host3']
for host in hosts:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    except socket.error, msg:
        print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
        sys.exit()

    print 'Socket Created'
    try:
        ip = socket.gethostbyname(host)
    except socket.gaierror:
        print 'Hostname could not be resolved. Exiting...'
        sys.exit()

    print 'Ip address of ' + host + ' is ' + ip
    sshconnect(ip, passwd, user, port)
    sshpush(ip, passwd, src, dst, user, port=22)
    print 'ssh directory copied to ' + host

I've made quite a few changes to it but I'm still getting the following error:
Traceback (most recent call last):
  File "ssh.py", line 129, in <module>
    sshconnect(ip, passwd, user, port)
  File "ssh.py", line 99, in sshconnect
    return s.connect(pid, f)
NameError: global name 'pid' is not defined

I know I need to define the pid, but I'm drawing a blank on the best way to go about doing it.  Any assistance, suggestions, Advil would be most sincerely appreciated!!!

A: Typos on line:
20: (pid, f) = pyt.fork() (should be pty)
24: nothing after else:
93: pid and f are not defined in this function scope -> this is your problem.
106: portnum is not known in this scope
Do they allow you to use an proper IDE with code validation? Switch to it.
Otherwise if you like it barebone vi go for an static source checker.
Looking at the code snippet from Paul Mikesell I think you don't need your sshconnect function at line 91. Just make a call to sshclient.push like you do in your next function (sshpush) and it will connect for itself.


text:
Q: Get stylesheet from upload folder Wordpress I'm working on a project and I want to enqueue a stylesheet file located in
http://mysite.fr/wp-content/uploads/2016/custom/master.css
So I wrote this line of code
wp_enqueue_style( 'custom-style', get_template_directory_uri().'/uploads/2016/custom/master.css', false,'1.1','all');

but it does not work.

A: <link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri(); ?>/uploads/2016/custom/master.css" />

Add the above link in your header.php

A: You can use content_url() function to get wp-content directory url instead of template directory,
wp_enqueue_style( 'custom-style', content_url().'/uploads/2016/custom/master.css', false,'1.1','all');

Hope that helps...

A: You can change custom-style and then try the bottom code
wp_enqueue_style( 'uniqueid-custom-style', site_url().'/wp-content/uploads/2016/custom/master.css', false,'1.1','all');

redpajama_set_name: RedPajamaStackExchange


text:
Q: The approximation of the unique solution by the FEM Let consider the weak formulation of an elliptic PDE $a(u,v) = l(v)$, where $a$ is coercive and bounded and $l$ is a bounded functional on the Hilbert space $V=H^1(\Omega)$ (or $H^1_0(\Omega)$). Then, Lax Milgram will tell us there exists a UNIQUE solution $u \in V$ of the above problem for all $v \in V$. After that, we consider $V_h$ a finite dimensional subspace
of V (in practice, we will use piecewise polynomials to construct this subspace) and we change our weak formulation to find $u_h \in V_h$ such that $a(u_h,v_h) = l(v_h)$ for all $v_h \in V_h$.
My question is that we know that the solution is UNIQUE and it's contained in the $V$ space, and we know that $V_h \subset V$, So what if $u \in V-V_h$, what is the benefit to try finding $u_h$ ? and if $u \in V_h$, is it $u_h = u$ ??

A: The point is to find a good approximation to $u$. Céa's lemma tells you that
$$
\|u-u_h\|\leq c\inf_{v\in V_h}\|u-v\|,\qquad\qquad(*)
$$
that is, the error of $u_h$ is, up to a constant factor, as good as the error of the best approximation from $V_h$. So if $V_h$ has good approximation properties, then $u-u_h$ will be very small.
This also answers your second question, because if $u\in V_h$, then the right hand side of $(*)$ is $0$, and hence $u-u_h=0$.


text:
Q: How can I assign a null value to a query param in ColdFusion? I have a database table with an int column that can also be null. Adding an int to the column is fine, but setting it back to null causes an error. Since ColdFusion does not support null values, I usually pass the value as an empty string:
local.myParam = "";

This causes an error however, that "" is not of type numeric.
post.addParam(name="parentId", cfsqltype="CF_SQL_INTEGER", value=arguments.parentId);

Any ideas how I can work around this limitation?

A: If you want the empty string to be sent as null, you can do something like this:
post.addParam(... null=len(trim(local.myParam)) ? false : true ...);

Which is to say, <cfqueryparam> and addparam support a null argument in addition to the others like name or cfsqltype. Setting null as true will provide the given value to the database as a proper null. For convenience, I'm using the ternary conditional operator to inline a true or false value. You could achieve the same thing, old-school, by using iif().

A: I think you want this...
null=yesNoFormat(NOT len(trim(local.myParam)))


text:
Q: Printing Index of Object I have created an object array as such:
object[,] Values = new object[17, 5];

Layer1[0, 0] = neuron1;
Layer1[1, 0] = neuron1;
Layer1[2, 0] = neuron2;

etc.
I have written a function to loop through the object array which is:
static void Loop_Through_Layer(object[,] Layer1)
{
    //Loop through objects in array
    foreach (object element in Layer1)
    {
        if (element != null)
        {
            //Loop through objects in array
            foreach (object index in Layer1)
            {
                if (index != null)
                {
                    //Need to print indexes of values
                    Console.ReadLine();
                }
            }
        }
    }
}

What I am attempting to do it so print the location of every value within the object array through using the for loop but I am unsure how to reference these coordinates?

A: You can use the bounds and a for loop to get the values:
for (int x = 0; x < Layer1.GetLength(0); x++)
{
    for (int y = 0; y < Layer1.GetLength(1); y++)
    {
        //
        // You have position x and y here.
        //
        Console.WriteLine("At x '{0}' and y '{1}' you have this value '{2}'", x, y, Layer1[x, y]);
    }
}

A: You can't with foreach since it "flattens" the array - you could use two plain for loops instead:
//Loop through objects in array
for(int i = 0; i < Layer1.GetLength(0); i++)
{
    for(int j = 0; j < Layer1.GetLength(1); j++)
    {
        var element = Layer1[i,j];
        if (element != null)
        {
             //Need to print indexes of values
             Console.WriteLine("Layer1[{0},{1}] = {2}", i, j, element);


text:
Q: EXCEL VBA, PARSING & REQUEST UPDATEDATA I have a some question. I want to parsing XML realtime data some website.
I'm using below Function.
Function GetHTML(URL As String) As String

Dim HTML As String
With CreateObject("MSXML2.XMLHTTP")
    .Open "GET", URL, False
    .Send
    GetHTML = .ResponseText
End With

End Function

But, It doesn't respond recent(=renewed data) data.
Just, first request data are holding.
How Could I get recent data from website?


text:
Q: PostgreSQL Data Type Can someone advise me on the SQL data type that should be used for a DICOM UID, 1.2.840.113986.3.2702661254.20150220.144310.372.4424 as a sample.  I would like to use it as a primary key as well.

A: There are two options available here- either use a less-than-ideal data type which already exists, of which "text" is almost certainly the best option, or implement a custom data type for this particular type of data.
While the best built-in option is "text", looking at the example provided, you would likely get significant performance and space benefits from using a custom data type, though it would require writing code to implement it.
A final option to consider is to use a surrogate key for that data.  To do this, you would build a table which contains a "bigserial" column and then a "text" column.  The "text" column would hold the long form of the value as you have it shown above and the "bigserial" column would provide an integer (64bit with bigserial, 32 bit if you use "serial" instead) which you would then use in all of your tables, instead of the long form.


text:
Q: Android app "Device or resource busy" when accessing USB device via JNA In making use of JNA in an Android app, I encounter a LastErrorException with the message Device or resource busy when I attempt to perform an ioctl operation on a USB device. I cannot guess why this is or what to do about it. Can anyone offer any guidance at all?
I am in fact using a 3rd-party snippet, whose source is viewable here.
The error I get reads as follows:
E/AndroidRuntime: FATAL EXCEPTION: Thread-556
  Process: edu.ucdavis.auditoryenhancer, PID: 31335
  com.sun.jna.LastErrorException: [16] Device or resource busy
      at com.sun.jna.Native.invokeInt(Native Method)
      at com.sun.jna.Function.invoke(Function.java:390)
      at com.sun.jna.Function.invoke(Function.java:323)
      at com.sun.jna.Library$Handler.invoke(Library.java:236)
      at java.lang.reflect.Proxy.invoke(Proxy.java:393)
      at biz.source_code.usb.$Proxy0.ioctl(Unknown Source)
      at biz.source_code.usb.UsbIso.setInterface(UsbIso.java:414)

My own code that leads up to this error stack is as follows:
// the variable "dev" is an instance of android.hardware.usb.UsbDevice
UsbInterface interface = dev.getInterface(2);
UsbEndpoint endpoint = dev.getEndpoint(0);
UsbDeviceConnection connection = usbMgr.openDevice(dev);
new UsbIso(connection.getFileDescriptor(), 1, endpoint.getMaxPacketSize());
try {
    usbIso.setInterface(getInterfaceNumber(), getAlternateSetting());
} catch (IOException e) {
    e.printStackTrace();
    return false;
}


text:
Q: Can't find the difference between malloc() and calloc() in C (running from Virtual Machine Linux) *Note: This is not a duplicate question, since the answer you refer to does not answer my question. I know what malloc() and calloc() should do, but wonder why there doesn't seem to be a difference when using it with Virtual Machine.
I know what the difference should be - malloc() just allocate you the memory, while calloc() initialize it with 0's.
The thing is, in my code it doesn't show up, and malloc() doesn't seem to be giving any difference while running from my Virtual Machine Ubuntu. I ran it a few times, and malloc acts exactly like calloc.
Note - I just checked it with my actual hard drive, and it seems to work ok, there I do get different results.
The code:
#include <stdio.h>
#include <stdlib.h>

int main(){
int i,n;
float *ptr1, *ptr2;
printf("enter a total number of float items: ");
scanf("%d", &n);

ptr1 = malloc(n*sizeof(float));
ptr2 = calloc(n, sizeof(float));

printf("malloc     |    calloc\n");
printf("----------------------\n");
for(i=0;i<n;i++)
printf("%-10f  %10f\n", *(ptr1+i), *(ptr2+i));
printf("\n");
free(ptr1);
free(ptr2);
return 0;
}

A: calloc guarantees you to have a zeroed memory chunk, while malloc not. Then it may happen that malloc does it, but never rely on it.

A: The memory obtained from malloc can contain anything. It might contain zeroes or it might contain something else.
The following example shows (on most platforms) that memory returned from malloc has not been set to 0:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  char *p;
  int i;

  for (i = 0; i < 1024; i++) {
    p = malloc(1024);
    strcpy(p, "something else");
    free(p);
  }
  p = malloc(100);  // Get a fresh memory block
  printf("%s\n", p);  // You should not access the memory returned from malloc without assigning it first, because it might contain "something else".
  return 0;
}

The program could do anything, we don't even know if the string is NUL-terminated, but on most platforms the output will be:

something else


text:
Q: Now that I can run TeX on my iPad, what shall I TeX? I have just learnt that there is a TeX implementation now on the iPad (original source this answer to Is there a (La)TeX distribution running on iPad?).  As the author of the blog post I TeX therefore iPad, this clearly warrants an update.  I've downloaded the application and can confirm that it really does compile TeX documents without an internet connection (not that I disbelieved them, but some things just need confirmation).  But clearly I need to experiment a bit before writing "I TeX therefore iPad: the return of the lion".
Moreover, there is a fairly big caveat: it runs plain TeX.  I know almost nothing about plain TeX.
Whence a double question:

*

*What would people like to read in a blog post?  What are the features that would be of most interest (think also about the editor and environment)?  (Try to make your request substantial - give some criteria to check.)  What edge cases do you want testing to see if it really is TeX?
(Added in Edit) After seeing the first couple of answers below, I can provide a slightly more focussed version of the my original first question.  I'm still interested in answers to the above so I'll leave it as it is, but I've also created a chat room http://chat.stackexchange.com/rooms/4598/tex-on-the-ipad for anything that is more discursive: use the chat room for things that won't stand the test of time.
The environment is an editor from which TeX is run.  The format is plain TeX.  It can be linked to Dropbox so I can upload files from my computer TL distribution.  I can use \input (I haven't tested if it searches any subdirectories).  What files would be useful for me to upload?

*How do I, a LaTeX-user, best convert to plain TeX?  What resources are there for me to learn what I can and cannot do?  (Apart from reading every single one of morbusg's posts.)  In particular, given that it would like like I won't be able to use this for editing existing documents, what kind of document is plain TeX best suited for?

A: there is a TeX package miniltx:
\input miniltx

\font\myTT=cmr5 at 20pt

\newcommand\stuff{%
  Here comes some text $\ldots$ which should
  be typeset $\ldots$}
\newenvironment{morestuff}
  {\myTT}
  {\par}

\stuff

\morestuff
foo bar baz
\endmorestuff

foobar
\bye

A: Try doing Knuth's original trip test; the manual is here.

A: there's still a plain tugboat style, provided in tex live in the subdirectory .../tex/plain/tugboat-plain/.  you'll need two of the files there for this exercise: tugboat.sty and tugboat.cmn.
a periodic tex hyphenation exception list appears in tugboat.  every time it's published, the cumulative collection is posted to ctan, where it appears in info/digests/tugboat/hyphenex/tb0hyf.tex.  this is constructed in plain tex.  (that's more a matter of age of the original column and inertia than of unsuitability of latex.  it works, so i have no interest in converting it.)
both the file for the hyphenation collection and the tugboat "header" files (.sty and .cmm) contain some interesting macro code, so you might even learn some useful texniques from examining them as well as the contents of the article.
and if you find some bad hyphenations in other places that you think should be added to the exception list, you are invited to send them to me for consideration.

A: I'm mainly trying to answer (2).
What isn't bundled in the format compared to LaTeX is a big list, but perhaps some important ones include: hyperlinks, label/ref, toc, sectioning below first level (\beginsection), lists below two levels (\item & \itemitem), and font selection scheme (there are \bf, \it, etc., but no size change for example). Most of these can be made available if you can do \input eplain.
That said, I think you'd be surprised how much you can do with just plain TeX. Especially math-heavy documents tend to look rather nice in my opinion. Although on that front, what is missing is script and "blackboard bold" (if you can \input amstex [or was it amssym.def?] then you get \Bbb). Some useful display math commands include \displaylines for free-form multi-line displays, \eqalign for math axis centered alignments, and \eqalignno, for display-wide alignments where you can number each line if you want. (Just remember the lines are seperated with a \cr instead of LaTeX \\.)
There is only one general \proclaim macro for proofs, lemmas, corollarys and what have you.
With XeTeX you can have a lot more math stuff available with Unicode and fonts like Cambria Math, Asana Math, Neo Euler, and of course STIX/XITS Math. But I'm not sure if one can install extra fonts for i-devices. I have collected some little helpers for plain XeTeX with the help of tex.sex people here (I'm sorry to say it's a bit of a mess still, I need to get everything organized).
I feel that plain TeX is suitable for any kind of documents, and to help with using it, there is a very nice reference card made by J.H. Silverman here: http://www.math.brown.edu/~jhs/ReferenceCards/TeXRefCard.v1.5.pdf


text:
Q: Edge warning says "'content-type' header charset value should be utf-8" Edge dev-tools is nice helping out, but some errors I just don't know how to fix.
Apparently there's something wrong with the index.html and two SVG-files. One SVG uses img-tag and the other SVG uses CSS.
I tried among other things adding this to the SVG:
<?xml version="1.0" encoding="utf-8"?>

And for both the html-file and svg-files I tried variations of these
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

Also, the last one, why would Edge care if firefox doesn't support a feature?

A: I was facing the same issue
The browser just wants you to define the mime type
    <link rel="stylesheet" href="styles.css" type="text/css">


text:
Q: Is there a way i can loop coin prices from FTX, i am getting error I want to get the values when i run the code by looping them but i am getting errors
key = 'https://ftx.com/api/markets'

currencies = ['BNB', 'AVAX', 'DOT', 'LTC', 'BCH']

# base_currency = 'ETH'
quote_currency = 'USD'

for i in currencies:
    url = key + currencies
    data = requests.get(url)
    data = data.json()

df1 = pd.DataFrame(url).json()
df1['result']

And i am getting errors when i output it
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-d4cc3a7de331> in <module>
      7
      8 for i in currencies:
----> 9     url = key + currencies
     10     data = requests.get(url)
     11     data = data.json()

TypeError: can only concatenate str (not "list") to str

A: You need to construct the URL with its 3 component parts - i.e., the base URL, currency and quote currency. Always a good idea to do some validation.
import requests
import json

currencies = ['BNB', 'AVAX', 'DOT', 'LTC', 'BCH']
quote_currency = 'USD'
url = 'https://ftx.com/api/markets'

for currency in currencies:
    api = f'{url}/{currency}/{quote_currency}'
    try:
        (r := requests.get(api)).raise_for_status()
        if (j := r.json()).get('success'):
            print(json.dumps(j['result'], indent=2))
    except requests.exceptions.HTTPError as e:
        print(f'{api} -> {e}')

Note:
Requires Python 3.8+


text:
Q: Arguments validation in factory constructor? Good day. I hope you can help me.
Let's say, I have a class. Its constructor has some parameters. Inside the constructor, one or more values passed as arguments at the instantiation time are validated. If one of them is not valid, an exception is thrown.
I also have a factory class, whos factory method should create an object of the above type. The factory constructor has some of the parameters defined in the class above. The other parameters, needed for creating the object, are defined in the factory method.
I would like to ask: Should the arguments passed to the factory constructor be validated too - in an identical manner as in the class constructor?
Thank you for your time and patience. Feel free to ask me anything.

I also prepared an example (in PHP). In regard to it, should a validateColor method be defined in the HatFactory too, although the identical validation already happens in the Hat class?
test.php
<?php

use Tests\HatFactory;

$hatFactory = new HatFactory('yellow');

$hat1 = $hatFactory->createHat('AdiDix');

$hat2 = $hatFactory->createHat('NiKy');

echo '
' . print_r($hat1, TRUE) . '
';

echo '
' . print_r($hat2, TRUE) . '
';

Tests/Hat
<?php

namespace Tests;

class Hat {

    /**
     * Hat brand.
     *
     * @var string
     */
    private $brand;

    /**
     * Hat color.
     *
     * @var string
     */
    private $color;

    /**
     * @param string $brand Hat brand.
     * @param string $color Hat color.
     */
    public function __construct(string $brand, string $color) {
        $this->validateColor($color);

        $this->brand = $brand;
        $this->color = $color;
    }

    /**
     * Validate the hat color.
     *
     * @param string $color Hat color.
     * @throws Exception Color not allowed.
     */
    private function validateColor(string $color) {
        if ($color !== 'red' && $color !== 'blue') {
            throw new Exception('The selected color is not allowed!');
        }
    }

}

Tests/HatFactory.php
<?php

namespace Tests;

use Tests\Hat;

class HatFactory {

    /**
     * Hat color.
     *
     * @var string
     */
    private $color;

    /**
     * @param string $color Hat color.
     */
    public function __construct(string $color) {
        $this->validateColor($color);

        $this->color = $color;
    }

    /**
     * Create a hat.
     *
     * @param string $brand Hat brand.
     */
    public function createHat(string $brand) {
        return new Hat($brand, $this->color);
    }

    /**
     * Validate the hat colour.
     *
     * @param string $color Hat color.
     * @throws \Exception Color not allowed.
     */
    private function validateColor(string $color) {
        if ($color !== 'red' && $color !== 'blue') {
            throw new \Exception('The selected color is not allowed!');
        }
    }

}

A: In my opinion, taking into account your implementation of the factory -where the color is also a constructor argument- you should add validation as well, because the color is a property of the factory itself, and the factory shouldn't exist in an invalid state...
Think that, right now, the $color property is only used in the createHat method, which creates a Hat object, but there's nothing that prevents that in the future that property might be used for something else as well... maybe you add a createTopHat method that creates a TopHat that doesn't have validation in the constructor... or maybe you want to add a getColor method in order to organize your factories by color... or anything you can imagine!
If the color was an argument of the createHat method itself, then you should probably avoid the duplicate validation, but as long as the factory requires a valid color to exist, it should be validated...
That said, assuming the validation of the color is always the same for the Hat and the HatFactory (which seems to be now, but doesn't need to be!), you could move that to some ColorValidator class to keep DRY - that'd be a good idea imo


text:
Q: Como colocar 2 eventos .click() em um button Eu estou fazendo um painel de administrador, onde tem as seguintes opções de buttons
Dashboard class="dashboard-button"
Settings class="settings-button"
Contents class="contents-button"
Feedback class="feedback-button"
Todos eles tem o mesmo id id="options"
E ao clicar em akgum button, aparece um nav em baixo com as opções de links
E o meu jquery está assim
$(".dashboard-button").click(function(){
    $(".navbar-dashboard").addClass("active");
});

Obs a classe navbar-dashboard é a que vai aparecer ao clicar no button
Ja a classe active é a que tem o css display bloxk pois inicialmente a navbar tem display none
Resumindo o que eu quero é, ao clicar no button, a navbar aparece
E se o usuario clicar novamente no mesmo button, ela some
Alguem poderia me iluminar? To a uma hora quebrando a cabeça pra achar uma solução kkkkk

A: Você pode verificar se existe a classe active com hasClass. Se ela existir, remova-a com removeClass. E se não existir, adicione-a com addClass.
$(".dashboard-button").click(function(){
    if ($(".navbar-dashboard").hasClass("active")) {
        $(".navbar-dashboard").removeClass("active");
    } else {
        $(".navbar-dashboard").addClass("active");
    }
});

Fiz um exemplo funcionando:
https://jsfiddle.net/8m75jozh/1/

A: Só exemplificando o que o Gabriel José de Oliveira disse ali nos comentários:
$(".dashboard-button").click(function(){
    $(".navbar-dashboard").toggleClass("active");
});

A função toggleClass adiciona a classe quando não existe e remove a classe quando ela existe.
Mais informações: https://api.jquery.com/toggleClass/


text:
Q: Error getting values from JSON nested with spaces in PHP I am trying to get values from a nested JSON, which contains keys with spaces.
I am having this error:

*

*Notice: Trying to get property 'Submit Date' of non-object in
json.php on line 47

*Notice: Trying to get property 'Entry ID' of non-object in json.php
on line 46
    {
         "entries": [
             {
                 "values": {
                            "Entry ID": "INC000000001",
                             "Submitter": "Remedy Application Service",
                             "Assigned Group": "TI WIN",
                             "Priority": "Medium",
                             "Submit Date": "2022-07-20T22:27:01.000+0000",
                             "Assignee": "Example asignee"
                             },
                  "_links": {
                            }
              }
                     ]

      }

My PHP Code
 <?php
    $response = curl_exec($curl);
    $data = json_decode($response);
    foreach($data->entries as $entr)
    {

        foreach($entr->values as $valores)
         {

           $entry_id=$valores->{'Entry ID'};
           $submit_date=$valores->{'Submit Date'};
          }
    }
   ?>

print_r output:
Array
(
    [entries] => Array
        (
            [0] => Array
                (
                    [values] => Array
                        (
                            [Entry ID] => INC000000001
                            [Submitter] => Remedy Application Service
                            [Assigned Group] => TI WIN
                            [Priority] => Medium
                            [Submit Date] => 2022-07-20T22:27:01.000+0000
                            [Assignee] => Example asignee
                         )
                 )
        )
)

Where is the error?
any method to get the values?

A: Your code is inconsistent with your print_r output; in your code $data will be an object (because you have not specified the $associative parameter to json_decode) which looks like this:
stdClass Object
(
    [entries] => Array
        (
            [0] => stdClass Object
                (
                    [values] => stdClass Object
                        (
                            [Entry ID] => INC000000001
                            [Submitter] => Remedy Application Service
                            [Assigned Group] => TI WIN
                            [Priority] => Medium
                            [Submit Date] => 2022-07-20T22:27:01.000+0000
                            [Assignee] => Example asignee
                        )
                    [_links] => stdClass Object
                        (
                        )
                )
        )
)

The values property of each entry in the entries array is an object, not an array, so you can't iterate it. Instead, just access the properties directly:
foreach($data->entries as $entr) {
    $entry_id=$entr->values->{'Entry ID'};
    $submit_date=$entr->values->{'Submit Date'};
    var_dump($entry_id, $submit_date);
}

Output (for your sample data):
string(12) "INC000000001"
string(28) "2022-07-20T22:27:01.000+0000"

Demo on 3v4l.org


text:
Q: Is there any way to regexp CSS to increase a property value depending on their position? I am preparing a web with @keyframe-animations. To get the desired effect currently I have the following code...
index.htm

Section 1

Section 2

Section 3

Section 4

    ...

style.css
article {
    ...
}
        article > div {
            background-color: lightblue;
            display: block;
            height: 50px;
            width: 100%;
            /**/
            animation-name: animation-example;
            animation-duration: 0.5s;
            animation-iteration-count: 1;
        }
                    article > div:nth-of-type(1) {
                        animation-delay: 0.0s;
                    }
                    article > div:nth-of-type(2) {
                        animation-delay: 0.2s;
                    }
                    article > div:nth-of-type(3) {
                        animation-delay: 0.4s;
                    }
                    article > div:nth-of-type(4) {
                        animation-delay: 0.8s;
                    }
                    ...

As you can see, each

 node has the same animation, BUT with different delay, increasing it by 0.2s.
The question is, in pure CSS, is it possible to "regex-it" somehow to make it work for every item placed there without having to set it for each one?
If not possible in pure CSS, is it possible to achieve this in any CSS metalanguage like SASS, LESS, ...?
If also no, what would be the best way to get this? (JavaScript, PHP, ...)
Thanks in advance.

EDIT: I choose the LESS question as it was the nearest to my needs. Said that, I probably will go for the @Raymond Nijland's answer and use PHP to set these special CSS variables.

A: While it's not possible in pure CSS, you can do it in LESS with a recursive mixin:
.generate-delays(10); // 10 would be your maximum number of items
                      // - set higher if needed

.generate-delays(@n, @i: 1) when (@i =< @n) {
  article>div:nth-of-type(@{i}) {
    animation-delay: ((@i - 1) * 0.2s);
  }
  .generate-delays(@n, (@i + 1));
}


text:
Q: Probability of the existence of a specific pattern in one million coin flips I came across this question while preparing for an interview.
Given a coin with head-up probability p, flip it $N = 1,000,000$ times. What is the probability that a string of "HHHHHHTTTTTT" (i.e. 6 heads followed by 6 tails) exists? Can this pattern be generalized?
Any idea on the question? Thanks in advance!
This question has two related questions:

*

*Average number of the pattern.

*Average number of the pattern of at least 6 tails in a row.
For Question 1, one can solve it using the linearity of expectation. Specifically, let $X_i$ be a binary variable indicating whether there is one such pattern starting at the ith flip. Then the average number of the pattern across all one million flips is just
\begin{align*}
E \sum_{i=1}^{N-11} X_i &= \sum_{i=1}^{N-11} E X_i \\
&= (N-11) p^6(1-p)^6.
\end{align*}
Question 2 can be solved in a similar way. The only difference is that this time $X_i=1$ requires that the $(i-1)$th flip is a head. Hence
\begin{align*}
E \sum_{i=1}^{N-5} X_i &= E X_1 + \sum_{i=2}^{N-5} E X_i \\
&= (1-p)^6+(N-6) p(1-p)^6 \\
&=(1+Np-6p)(1-p)^6.
\end{align*}


text:
Q: Find duplicate column values across multiple workbooks, and extract columns row data to new sheet I have multiple Excel workbooks some having multiple worksheets.
I'm trying to export the duplicates across the workbooks into a new workbook using Column A of each workbook as the unique value. All the workbooks are in the same directory.
The following doesn't work for workbooks with multiple sheets and is not accurate for some workbooks.
Sub CheckDuplicateAcrossWorkbook()
    Dim fName As String, fPath As String, wb As Workbook, sh As Worksheet, i As Long
    Set sh = ActiveSheet
    fPath = ThisWorkbook.Path & "\"
    fName = Dir(fPath & "*.xls*")

    Do
        If fName <> ThisWorkbook.Name Then
            Set wb = Workbooks.Open(fPath & fName)
            If sh.Range("B1") = "" Then
                sh.Range("A1") = "Source"
            End If
            wb.Sheets(1).UsedRange.Offset(1).Copy sh.Cells(Rows.Count, 2).End(xlUp)(2)
            With sh
                .Range(.Cells(Rows.Count, 1).End(xlUp)(2), .Cells(Rows.Count, 2).End(xlUp).Offset(, -1)) = fName
            End With
            wb.Close
        End If
        Set wb = Nothing
        fName = Dir
    Loop Until fName = ""
End Sub

The original code removes the first five rows and 8th row with the header being row 7.
Sub CheckDuplicateAcrossWorkbookOriginal()
    Dim fName As String, fPath As String, wb As Workbook, sh As Worksheet, i As Long
    Set sh = ActiveSheet
    fPath = ThisWorkbook.Path & "\"
    fName = Dir(fPath & "*.xls*")
    Do
        If fName <> ThisWorkbook.Name Then
            Set wb = Workbooks.Open(fPath & fName)
            If sh.Range("B1") = "" Then
                wb.Sheets(1).Range("A7", Sheets(1).Cells(7, Columns.Count).End(xlToLeft)).Copy sh.Range("B1")
                sh.Range("A1") = "Source"
            End If
            wb.Sheets(1).UsedRange.Offset(8).Copy sh.Cells(Rows.Count, 2).End(xlUp)(2)
            With sh
                .Range(.Cells(Rows.Count, 1).End(xlUp)(2), .Cells(Rows.Count, 2).End(xlUp).Offset(, -1)) = fName
            End With
            wb.Close
        End If
        Set wb = Nothing
        fName = Dir
    Loop Until fName = ""
    For i = sh.UsedRange.Rows.Count To 2 Step -1
        If Application.CountIf(sh.Range("B:B"), sh.Cells(i, 2).Value) = 1 Then Rows(i).Delete
    Next
End Sub

A: You need to loop through each sheet of the opened file, rather than just using the first one. Try this... note the addtion of eSheet.
Sub CheckDuplicateAcrossWorkbook()
Dim fName As String, fPath As String, wb As Workbook
Dim sh As Worksheet, i As Long, eSheet As Worksheet
Set sh = ActiveSheet

fPath = ThisWorkbook.Path & "\"
fName = Dir(fPath & "*.xls*")
        Do
            If fName <> ThisWorkbook.Name Then
                Set wb = Workbooks.Open(fPath & fName)

                    For Each eSheet In wb.Worksheets
                        If sh.Range("B1") = "" Then
                            sh.Range("A1") = "Source"
                        End If
                        eSheet.UsedRange.Offset(8).Copy sh.Cells(Rows.Count, 2).End(xlUp)(2)
                    With sh
                        .Range(.Cells(Rows.Count, 1).End(xlUp)(2), .Cells(Rows.Count, 2).End(xlUp).Offset(, -1)) = fName
                    End With
                Next eSheet
                wb.Close
            End If
            Set wb = Nothing
            fName = Dir
        Loop Until fName = ""
End Sub

A: I feel like some people here won't like this solution, because it's not a coding solution, but this will work for you Kaiju.

https://www.rondebruin.nl/win/addins/rdbmerge.htm
I don't know what kind of 'duplicate' you are trying to find, but when everything is merged together, you can do whatever you need to do. The merge process is pretty intuitive. Just follow the steps in the landing page, and you should get what you want.


text:
Q: is there any "onCreate" method for Android widgets? I'm following this tutorial for adding EULA to my Android application, but i have two problems:
1) My app is based on widget and i would like to show my EULA as soon as widget is started. Is there any "onCreate" method for widgets?
2) If user refuse EULA, i would like to close my app. I'm C# programmer, so i don't know if there's any "Exit()" method for Android apps. How to forcefully close my app without user's action?

A: According to the android doc page for AppWidget, you may be interested in the onEnabled and onDisabled methods:
onEnabled(Context)
This is called when an instance the App Widget is created for the first time.
For example, if the user adds two instances of your App Widget, this is only called the first time.
If you need to open a new database or perform other setup that only needs to occur once for all App Widget instances, then this is a good place to do it.

onDisabled(Context)
This is called when the last instance of your App Widget is deleted from the App Widget host.
This is where you should clean up any work done in onEnabled(Context), such as delete a temporary database.

So, if the user refuses, you can call onDisabled(Context)

A: There isn't an onCreate() per se, but there is a way to show an activity when your widget is first added. One way of doing this is the following.
In your AppWidget provider XML file be sure to add as a property of appwidget-provider:
android:configure="your.eula.activity"

and don't forget to declare your.eula.activity in your AndroidManifest.xml
<activity android:name="your.eula.activity">
     <intent-filter>
           <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
     </intent-filter>
</activity>

And in your.eula.activity's onCreate() you should call
 setResult(RESULT_CANCELED);
 finish();

A: Can't you just show the EULA when you do your initialization and so forth? I'm not familiar with your code, so I'm not sure if it's possible in your case, but it's a possibility.
To end an activity, simply call this.finish().


text:
Q: onchange on different select element different result i'm new on react/typescript world here i have two Select elements one is normal and another is antd version, for some reason on antd version onchange wont give any error but on normal version i get this error:
(JSX attribute) React.SelectHTMLAttributes<HTMLSelectElement>.onChange?: React.ChangeEventHandler<HTMLSelectElement> | undefined
Type '(customerId: string) => void' is not assignable to type 'ChangeEventHandler<HTMLSelectElement>'.
  Types of parameters 'customerId' and 'event' are incompatible.
    Type 'ChangeEvent<HTMLSelectElement>' is not assignable to type 'string'.ts(2322)
index.d.ts(2274, 9): The expected type comes from property 'onChange' which is declared here on type 'DetailedHTMLProps<SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement>'

my code is this :

  <Select id="senderId" onChange={setSender}>
        {customerList.map((item, idx) => (
          <option key={idx} value={item.id}>
            {item.name}
          </option>
        ))}
      </Select>

just change first letter of Select to lower case you will get normal select

A: In your select, you need to use a different function, because antd receive a key in the onChange event. https://codepen.io/Cuchu/pen/xxgxZmo?editors=001
The select component onChange event uses an event as a parameter.
setSender = (event) => {
    customerId = event.target.value;
    /* continue */
}

Check the console here: https://codesandbox.io/s/frosty-breeze-4jlc7?file=/src/App.js
const setSender = (event) => {
    /* I am not sure about this in typescript */
    if(event instanceof String) {
       customerId = event;
    } else {
       customerId = event.target.value;
    }
    /* customerId = event.target.value; */

    if (customerId === null || customerId === "") {
       setSelectedCustomerId("");
    } else {
       setSelectedCustomerId(customerId);
    }
};

Your function ^^^
But don't copy and paste, check and analyze the different.
onChange with antd receives a string (key selected).
onChange with select receives an event.
Last comment, I think that you need to use {}
<select id="senderId" size={4} onChange={setSender}>


text:
Q: jQuery onClick once with on/off switch I am trying to figure out how to do something but can not figure out the correct terminology to do so.
What I am trying to do is have a textbox (#price) that when clicked once it will open up a pdf calculator that will then either prefill the textbox when completed or will then allow the user to enter the amount in. But I also want this to work if the textbox is "tabbed" over to also instead of the onClick. (Maybe onBlur) Basically anytime that textbox is used I need it to work like that. But how do I make the onClick know when the amount is ok to be entered or if the calculator needs to open?
What also makes this tricky is I need to have an On/Off switch basically a checkbox that when checked it allows that pop up pdf calculator and when its not checked it just ignores it and allows the price to be entered still.
Does anyone have any suggestions or pointers in how I can achieve this goal?

A: Bind event handler to focus event (blur is for when control looses focus).
$("#price").on({
 "focus": eventHandler
})

Then in your eventHandler() check if calculator needs to be invoked, by checking if it's already opened: $("#calculatorDiv").is(":visible"), and checking if your checkbox is 'checked': $("#checkboxId").is(':checked'), and depending on that open it.

A: The event(s) you are looking for is onFocus and onBlur. I would bind a function to the onFocus event that first checks if the corresponding checkbox has a "true" (or "checked") value, then continue if it does and do nothin if it doesn't.
I'd create an example in jsfiddle for you if I wasn't answering this from my phone.

A: 1. A textbox (#price) that when click once it will open up a pdf calculator
Use jQuery's click() handler or bind("click", ...)
var $price = $("#price");
$price.click(function() {
    $("#pdf_calculator").fadeIn();
});

2. But I also want this to work if the textbox is "tabbed" over to also
Use the focus event to know when an input is active (i.e, has been "tabbed" to). Alternatively, the blur event can be used if you want to know when a user is "leaving" the input field. ('blur' is the opposite of 'focus')
$price.on("focus click", function() {
    $("#pdf_calculator").fadeIn();
});

3. But how do I make the onClick know when the amount is ok to be entered or if the calculator needs to open?
Grab the amount typed in by the user, convert it to a numerical value, then perform your validation steps.
$price.on("focus click", function() {
    // Do some validation checking on the amount entered.
    var enteredValue = parseFloat($price.val());
    if (!isNaN(enteredValue) && enteredValue > 0) {
        $("#pdf_calculator").fadeIn();
    }
});

4. What also makes this tricky is I need to have an On/Off switch basically a checkbox that when checked it allows that pop up pdf calculator and when its not checked it just ignores it and allows the price to be entered still.
Simply check that the checkbox is checked using jQuery's is(":checked") then combine the steps above, and your fully working code looks like this:
var $price = $("#price");

$price.on("focus click blur", function() {

    // your checkbox element
    var checkbox = $("#show_calculator");

    // Check if the checkbox is checked
    if (checkbox.is(":checked")) {

        // convert the entered string to a number
        // then validate it according to your needs
        var enteredValue = parseFloat($price.val());
        if (!isNaN(enteredValue) && enteredValue > 0) {

            // if all conditions are met,
            // show the pdf calculator
            $("#pdf_calculator").fadeIn();
        }
    }
});

Click here to review a working jsfiddle of these ideas.
As for the pdf form (and getting values in and out again of a pdf form) there isn't a straight-forward method that doesn't involve a 'hack' (that may or may not work across different browsers). If the pdf only has ONE input, then you can capture the keyboard events on your form popup, and send them back to the HTML form (which is an ugly hack), but if this were my project, I would just convert the pdf functionality to javascript, and then you have all the freedom you need, and your calculator is 100% compatible with the rest of your application.
Hope this helps!


text:
Q: Jython When dmgr is down, how can we restart the application on my server dmgr is down, how can I stop/start the application running on server1?
wsadmin script throwing exception.
Thanks
SF

A: Use the -host and -port options of wsadmin to point to server1.
Alternatively, restart the dmgr.

A: If servers is federated, we can't connect to server directly. we need dmgr and nodeagent running to stop/start only application.
or
Server has to be standalone.
Thanks
-SR


text:
Q: jQuery: Backstretch with Blurjs I'm using Backstretch to display my background image. Then I want to use Blur.js to have elements blur the background. Using blur.js on the backstretched image doesn't work. I assume it is because Blur.js uses the CSS property background-image and Backstretch just displays the image with .
How do I make these two compatible?
The code inside of these plugins is pretty complicated.

A: This might do what you need (not using blur.js). Just adding some CSS blurring to the div backstretch creates.
<style>
    div.backstretch {
      -webkit-filter: blur(5px);
      -moz-filter: blur(5px);
      -o-filter: blur(5px);
      -ms-filter: blur(5px);
      filter: blur(5px);

      margin: -10px; /* Added to get rid of white blur borders */
    }
</style>


text:
Q: Check if Mac process is running using Bash by process name How do you check if a process on Mac OS X is running using the process's name in a Bash script?
I am trying to write a Bash script that will restart a process if it has stopped but do nothing if it is still running.

A: This simple command will do the trick.  The brackets around the process name prevent the grep command from showing in the process list.  Note there is no space after the comma.  There may be some portability issues as ps on some unix systems may require a dash before the options:
ps axo pid,command | grep "[S]kype"

The advantage is that you can use the results in an if statement like this:'
if [[ ! $(ps axo pid,command | grep "[i]Tunes.app") ]]; then
    open -a iTunes
fi

Or if you prefer this style:
[[ ! $(ps axo pid,command | grep "[S]kype") ]] && open -a Skype  || echo "Skype is up"

Another advantage is that you can get the pid by adding a pipe to awk '{print $1}'.
echo "iTunes pid: $(ps axo pid,command | grep "[i]Tunes.app" | awk '{print $1}')"

A: Parsing this:
ps aux | grep -v grep | grep -c [-i] $ProcessName

...is probably your best bet.
ps aux lists all the currently running processes including the Bash script itself which is parsed out by grep -v grep with advice from Jacob (in comments) and grep -c [-i] $ProcessName returns the optionally case-insensitive integer number of processes with integer return suggested by Sebastian.
Here's a short script that does what you're after:
#!/bin/bash
PROCESS=myapp
number=$(ps aux | grep -v grep | grep -ci $PROCESS)

if [ $number -gt 0 ]
    then
        echo Running;
fi

EDIT: I initially included a -i flag to grep to make it case insensitive; I did this because the example program I tried was python, which on Mac OS X runs as Python -- if you know your application's case exactly, the -i is not necessary.
The advantage of this approach is that it scales with you -- in the future, if you need to make sure, say, five instances of your application are running, you're already counting.  The only caveat is if another application has your program's name in its command line, it might come up -- regular expressions to grep will resolve that issue, if you're crafty (and run into this).
Research the Darwin man pages for ps, grep, and wc.

A: You can use either killall or kill, depending on if you are trying to find the task by PID or by name.
By Name:
if ! killall -s -0 $PROCESS_NAME >/dev/null 2>&1; then
  # Restart failed app, or do whatever you need to prepare for starting the app.
else
  at -f $0 +30seconds # If you don't have this on cron, you can use /usr/bin/at
fi

By PID:
if ! kill -0 $PID 2>/dev/null; then
  # Restart app, do the needful.
else
  at -f $0 +30seconds
fi

If you look at the OSX Manual you will see a different set of process management commands; since it's not the linux kernel, it makes sense that they would manage processes differently.
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/killall.1.html
A sample output from my terminal (striking out the user and hostname, of course):
user@localhost:~$ kill -0 782 # This was my old, stale SSH Agent.
bash: kill: (782) - No such process
user@localhost:~$ echo $?
1

user@localhost:~$ kill -0 813 # This is my new SSH agent, I only just created.
user@localhost:~$ echo $?
0

The return code from a kill -0 will always result in a safe way to check if the process is running, because -0 sends no signal that will ever be handled by an application. It won't kill the application, and "kill" is only called "kill" because it's usually used to stop an application.
When you look at the interfaces it uses in the source, you'll see that it's actually interacting with the process table directly (and not grepping a potentially loaded output from ps), and just sending a signal to an application. Some signals indicate the application should shutdown or stop, while other signals tell it to restart services, or re-read configuration, or re-open file descriptors to log files that have been recently rotated. There are a plethora of things that "kill" and "killall" can do that doesn't terminate the application, and it's used regularly to simply send a signal to the application.

A: A shorter solution:
if pgrep $PROCESS_NAME; then
    echo 'Running';
fi

Explanation:
pgrep exits with 0 if there is a process matching $PROCESS_NAME running, otherwise it exist with 1.
if checks the exit code of pgrep, and, as far as exit codes go, 0 is success.

A: I lack the reputation to comment on the killall answer above, but there's killall -s for doing it without sending any signals:
killall -s "$PROCESSNAME" &> /dev/null
if [ $? -eq 0 ]; then
    echo "$PROCESSNAME is running"
    # if you also need the PID:
    PID=`killall -s "$PROCESSNAME" | awk '{print $3}'`
    echo "it's PID is $PID"
fi

A: Another way is to use (abuse?) the -d option of the killall command.  The -d options won't actually kill the process, but instead print what will be done.  It will also exit with status 0 if it finds a matching process, or 1 if it does not.  Putting this together:
#!/bin/bash
`/usr/bin/killall -d "$1" &> /dev/null`
let "RUNNING = ! $?"     # this simply does a boolean 'not' on the return code
echo $RUNNING

To give credit where its due, I originally pulled this technique from a script in the iTunes installer.

A: It has for sure!
pgrep, pkill and pfind for OpenBSD and Darwin (Mac OS X)
http://proctools.sourceforge.net
(also available via MacPorts: port info proctools )
pidof by nightproductions.net

A: I've extended a pidof script found on the net to use regular expressions (usually substrings) and be case insensitive
#!/bin/sh
ps axc  |awk "BEGIN{ n=tolower(\"$1\")}\
    tolower(\$5) ~n {print  \$1}";

just create a script named "pidof" with this content, and put it in you path, i.e. in one of the dirs in
echo $PATH

and make it executable (maybe using sudo)
chmod 755 /usr/local/bin/pidof

and use it like this, of course
kill -9 `pidof pyth`

A: does Mac have pidof? ...
if pidof $processname >/dev/null ; then echo $processname is running ; fi

A: Perhaps too late for the OP but this may help others who find this thread.
The following modification of the amrox theme above works well for restarting applications on my OS X:
killall -d TextEdit &> /dev/null && killall TextEdit &> /dev/null; open -a TextEdit

I use the following AppleScript to update and restart daemons:
tell application "System Events" to set pwd to POSIX path of container of (path to me)
do shell script "launchctl unload -w /Library/LaunchDaemons/time-test.plist; cp -f " & quoted form of pwd & "/time-test.plist /Library/LaunchDaemons; launchctl load -w /Library/LaunchDaemons/time-test.plist" with administrator privileges

It assumes the original or updated plist file is in the same directory as the AppleScript.


text:
Q: Preferred way to terminate `ssh -N` in background using bash? I've started ssh -N <somehost> & in a bash script (to create a tunnel), and the connection persists after the script ends, and I see with ps that the ssh process has detached.
I am currently killing the background job with kill jobs -p, but is there a better way to do that?

A: Do you manually end your script?
if so:
     Try to catch the QUIT signal (or others) inside your script (use the
 trap builtin command I think). Then kill ssh.

else:
     Kill ssh at the end of your script.


text:
Q: Piping input into Plink in Windows batch file adds extra line feeds I'm trying to write a batch file to run in Windows 10 Pro that will use Plink to establish an SSH session to a remote server and execute some commands.  Everything works well, except for whatever reason I end up with extra line feeds with each ECHO command I pipe in.  Normally, this isn't an issue, until the command I'm running requires some specific user feedback, namely, pressing Y to confirm an action.  Since it receives the extra line feed after testing STSTest command and before receiving the Y character, it throws an error.
Here's my batch script:
set PATH=C:\Program Files\PuTTY;%PATH%
set TestNum=%1

(
    TIMEOUT /t 1 > nul
    ECHO cd /usr/bin/core/test
    ECHO rm STS_*.txt
    ECHO rm STS_T1_Test%TestNum%.txt
    ECHO ./STSTest --T 2 --i %TestNum%
    TIMEOUT /t 1 > nul
    ECHO Y
    TIMEOUT /t 1 > nul
    ECHO exit
) | plink -ssh 192.168.1.20 -l root -pw ***

Does anybody have an idea on how to eliminate that extra line feed so that Y is entered in the correct order after the STSTest command is entered?

Here's a simpler example demonstrating what I'm fighting.  If I define this simple batch file:
(
    TIMEOUT /t 1 > nul
    ECHO cd /
    ECHO cd usr
    ECHO cd bin
    ECHO cd core
    ECHO cd test
    TIMEOUT /t 1 > nul
    ECHO exit
) | plink -ssh 192.168.1.20 -l root -pw ***

The results from the command window look like:
Last login: Wed Jul 29 23:53:30 2020 from 192.168.1.7
root@core-A:~# cd /
root@core-A:/#
root@core-A:/# cd usr
root@core-A:/usr#
root@core-A:/usr# cd bin
root@core-A:/usr/bin#
root@core-A:/usr/bin# cd core
root@core-A:/usr/bin/core#
root@core-A:/usr/bin/core# cd test
root@core-A:/usr/bin/core/test#
root@core-A:/usr/bin/core/test# exit

I get an extra line feed after every ECHO command.

A: When you are executing plink without any command on its command-line, plink starts an interactive terminal session. That has lot of unwanted side effects. Including those that you face.
Add -T switch to plink command line to avoid that:
(
...
) | plink -T -ssh 192.168.1.20 -l root -pw ***

Another option is doing everything on the server-side and specifying full command on the plink commandline (in this case, you will also need to add the -batch switch):
plink -ssh 192.168.1.20 -l root -pw *** -batch "cd /usr/bin/core/test && rm STS_*.txt && rm STS_T1_Test%TestNum%.txt && (echo Y | ./STSTest --T 2 --i %TestNum%)"

Or some combination of both these methods.

Similar questions:

*

*Windows batch scripting: SSH with Plink showing strange sequences in output

*Executing command using Plink does not work, but does in PuTTY

*Script via Plink in .bat behaves differently

A: A batch file echo uses the Windows line ending (carriage return+line feed).
Combine the newline hack with the no line ending hack:
@echo off
REM don't remove blank lines below
set NLM=^

set NL=^^^%NLM%%NLM%^%NLM%%NLM%

(
    <nul set /P=foo%NL%
    <nul set /P=foo%NL%bar%NL%
) > test.txt

and test.txt becomes (hex output)
66 6F 6F 0A 66 6F 6F 0A 62 61 72 0A     foo.foo.bar.


text:
Q: (Flask) How to make an If statement in html that detects the last item in a for loop

        {% for post in posts %}

                {{ post.title }}

                {{ post.subtitle }}

Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}

            {% if post == posts[-1]  %}

            {% else %}

            {% endif %}
          {% endfor %}

Im making a web application on flask and this is the snippet of my code to the articles template I have a sqlite database that contains the articles, how can I make an if statement that detects if the post is the last in the loop since im making an hr per article but not on the last one
{% if post == posts[-1]  %} doesn't seem to work.

A: By Default Flask uses jinja2 as default Template Engine[1] and that's what you're using. Jinja2 provides loop.last variable[2] that you can use as follows:

        {% for post in posts %}

                {{ post.title }}

                {{ post.subtitle }}

Posted by {{ post.author }} on {{ post.date_posted.strftime('%B %d, %Y') }}

            {% if loop.last  %}

            {% else %}

            {% endif %}
          {% endfor %}


text:
Q: Regex with optional groups I am looking for a single regex to match the following 4 cases (grabbing the id's so I can re-write the urls)
http://localhost/gallery/test-name/123456
http://localhost/gallery/test-name/123456/
http://localhost/gallery/test-name/123456/video-name/159
http://localhost/gallery/test-name/123456/video-name/159/

Current Regex is below, but its not grabbing ids correctly in all cases. Any experts out there know what I'm doing wrong?
^(.*)/gallery/(.*)/([0-9]{1,15})(/)?((.*)/([0-9]{1,15})(/)?)?

A: .* (your second use of it) is greedy. So it consumes everything until your last ID. That's why the first ID gets lost if you have two of them. Make it ungreedy instead:
^(.*)/gallery/(.*?)/([0-9]{1,15})(/)?((.*?)/([0-9]{1,15})(/)?)?

I also added a ? to the last .* in case you want to add more parameters to this. However, simply splitting the string / might be much simpler anyway.

A: By just changing the second .* in your regex to .*?, you should get the capture groups you expect for your example string:
^(.*)/gallery/(.*?)/([0-9]{1,15})(/)?((.*)/([0-9]{1,15})(/)?)?

Example: http://www.rubular.com/r/CdBgdA1PlY

A: I know it's not exactly what you were wanting, but have you considered something along the lines of:
string l_url = "http://localhost/gallery/test-name/123456/video-name/159";
string l_id = l_url.Split( '/' )[5];

As you did not specify a language, the above is in C#, but could be easily converted to any other language.


text:
Q: reportportal.io port to 8080 Im new to docker and reportportal.io and when i do the following command below.
sudo docker-compose -p reportportal up -d --force-recreate
Its trying to create a containter for port 8080 which is being used by jenkins. I received no error at all on my mint machine.
CONTAINER ID        IMAGE                                                     COMMAND                  CREATED              STATUS              PORTS                                                                      NAMES
678d7741cbc4        reportportal/service-analyzer:4.3.0                       "/service-analyzer"      50 seconds ago       Up 37 seconds       8080/tcp
So what i did is change anything in the yml file that has 8080 to 8083 but still its using that port. How do i get around this?

A: you need to change only gateway exposed port
  - "8080:8080" # HTTP exposed

change it like
  - "8080:9090" # HTTP exposed

see codeline here:
https://github.com/reportportal/reportportal/blob/master/docker-compose.yml#L69

A: Looks like you are not doing the port mapping correctly inside the docker-compose.yml file. Please share the docker-compose file.

A: It is helpful if share docker file.
Try to run it like this docker-compose -p 8080:8083 -d --force-recreate
refer the following here


text:
Q: Sequel class table inheritance I am hoping to start a project using Multiple/Class table inheritance in Rails. To do this i am planning to use Sequel instead of ActiveRecord. The Docs can be found here - Sequel - class table inheritance
I have the Plugin working to an extent, I can call child.first and it will give me the first of the child classes, which is not the first of the parent class, and it includes the data from the child table. The problem is going the other way...
So if i load a db row via the parent class, which happens to be a child2 class
p = Parent.first <Parent @values = {kind = "Child2"}>

and then try to get the child data by using the refresh command listed in the docs it SHOULD give me
p.refresh <Parent @values = {kind = "Child2", child2data = "data from child 2 table"}>

but it doesnt, it just returns the unaltered parent
I have included a model map in my parent class
 plugin :class_table_inheritance,:key=>"kind", :model_map=>{"Child1"=>:Child1,"Child2"=>:Child2}

And i have played about with different values and other nonsense it to try and get it to work, but no success.
What i ideally want is to be able to find the parent and call a method to instance the child class so
p = Parent.first
c = p.child
c <Child2 @values = {kind: "Child2", Child2data: "data from child2 table">

I feel like i can probably hack/add a method to my parent class to do this but it just feels quite simple at this point that i shouldnt have to, also the fact that the refresh method doesnt work worries me and id like that to be resolved
Any one have an answer? ty for reading
p.s. i am using rails 5, the rails-sequel gem, and am working in a project that is more or less blank, i just want to have a decent CTI setup because to me it seems so much more elegant than Polymorphic associations.

A: Use :key=>:kind in the plugin call, that should fix your issues.  If you want a p.child method, use associations instead of the class_table_inheritance plugin.


text:
Q: ligand topology preparation using gromacs After running this step to create ligand topology for molecular dynamic simulation protein-ligand complex:
python cgenff_charmm2gmx_py3_nx2.py JZ4 jz4_fixed.mol2 jz4.str charmm36-mar2918.ff

It showed some tracebacks and import error:

cannot import 'gcd' from 'fraction' (/usr/lib/python3.10/fractions.py).

How to fix this problem in Ubuntu with python3.10 version?


text:
Q: Quitting Xcode 8 and reopening it breaks constraints in my Xib file encountering a very frustrating issue. I have a Xib file for my custom UITableViewCell. I set the constraints up and there are no warning or issues and the app runs fine. However if I close the Xcode and reopen it they are set to different values and the entire view is broken.

There seems to be no way to fix this, even if I reset to a previous commit the view remains broken. Has anyone else encountered this? Is there a fix?

A: Please try Xcode 8.1 which addresses the following:
Xcode 8.0 did not always restore view frames from storyboards and xibs when layouts were ambiguous. Xcode 8.1 fixes several of these issues. If you have encountered these issues, resolve the ambiguity in the Auto Layout issues and update frames. Xcode 8.1 will persist them correctly. (28221021, 28244619)
(If not, please file a bug with http://bugreport.apple.com.)


text:
Q: Inconsistently getting 'FirebaseError: Response is not valid JSON object.' I'm working on a react-native app with spotify integration. I've set up the oAuth flow w/ auth code grant where I can get the authorization code. I've then set up cloud function on firebase to proxy the actual token exchange (I don't want to reveal my secret to the client!). I've added logs and can see that the function is correctly completing the exchange with the spotify token endpoint, and receiving a refresh and access token.
const tokenRequeset = functions.https.onCall(async (data, context) => {

      // spotify network request, error handling, etc here ....

      // I want to emphasize that this network request completes
      // properly - my log statement below verifies in server logs
      // that I'm getting the expected value.
      const resp = await axios.post(
          "https://accounts.spotify.com/api/token",
          QueryString.stringify({
            grant_type: "authorization_code",
            code: code,
            redirect_uri: redirectURI,
          }),
          {
            headers: {
              "Authorization": `Basic ${BEARER_TOKEN}`,
              "Content-Type": "application/x-www-form-urlencoded",
            },
          }
      );

      console.log(resp.data.access_token);
      return { status: "success", token: resp.data.access_token };
});

export default tokenRequest

resp.data.access_token is the JWT access token used to hit the spotify API - it's a string value according to the API. (I'd provide an example one, but it is an auth token)
However, when I try to use the firebase/functions package to call my function from my app, I will sometimes get a 'FirebaseError: Response is not valid JSON object.'
What makes this extra fun is that it's inconsistent - yesterday I had the issue, and then it went away (without changing my code!). I was able to hit both the local emulator function and then the deployed function no problem, but today the 'FirebaseError: Response is not valid JSON object.' error is back.
I have checked the logs for the failed invocations both locally and on the deployed function, and in both cases the spotify API call is working - I'm getting all the expected behavior right up until the return (which isn't working for some reason).
On the client side, I'm configuring firebase like so:
const firebaseConfig = {
  // Shhhhhh
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const functions = getFunctions(app);
// Uncomment to run locally
connectFunctionsEmulator(functions, "localhost", 5001);

export { app, functions };

And then exposing and calling it like so:
const SpotifyAuth = httpsCallable(functions, "spotify-auth");

const resp = await SpotifyAuth(code, redirectURI)

(I know this isn't full code - I grabbed the relevant portions. Happy to provide more if needed).
I tried looking up this error, and I found results from ~2018/2020 with the old style of firebase/functions, but they seem to be related to region and I'm deployed in the default us-central1 - according to the SDK documentation that means I shouldn't touch it.
The existing solutions to the problem also seem to be based on the old style of function calls, rather than the more recent httpsCallable() and getFunctions(app).
I'm going insane trying to figure out why sometimes I'm getting this error
EDIT:
More information on the error - I ran my code again today and didn't see the error locally, but I DID see it when I hit the deployed function.

Again, I want to emphasize that I think the error is in the firebase network response - if you look at the network request I receive a 200 but the response is empty.

Did an additional full mockup of a function to see what would happen:
const test = functions.https.onCall((data, context) => {
  console.log("function call");
  return { status: "success", token: "asdfasdfasdfasdfasfs" };
});

export default test;

I'm getting the same error.
UPDATE:
I've given up on using the sdk and onCall method for firebase cloud functions - all of my testing thus far indicates that this is a bug or error on the google cloud function side, and there's nothing I can do from my side.
The good news is the onRequest approach seems to not have this issue - it's behaving properly and reliably.
I really hope that I've messed up along the way and there's a solution I've missed - the SDK seems fantastic and I like the integration it (is supposed to) offer, but as far as I'm aware right now unless there's a bug fix (or update to the documentation if I'm doing something wrong) it seems like it simply won't work.
I'm still planning on using firebase, but from my experience thus far I'd advise anyone early in their server work to consider using another offering (at least if you need to use the functions - I was able to get storage working).


text:
Q: XPages extlib oneui layout - How to add placebar actions dynamically I want to add actions dynamically in PlaceBar (extlib oneui application layout).
We have couple of urls stored in some configuration documents. Based on these URLs I want to create Container node having Basic Child nodes in it. Every child node use one URL from list.
How I can create container node and add child nodes to it dynamically? any sample SSJS/Java/CSJS code for this?
Thank you..

A: Have a look at the Repeat Node (xe:repeatTreeNode) which is described in the XPages Extension Library book on page 245.
Here's a very simple example (taken directly from the book):
<xe:repeatTreeNode var="val">
   <xe:this.value>
      <![CDATA[#{javascript:return [
        ["Home","home"],
        ["Domino","domino"],
        ["OneUI","oneui"]
      ];}]]>
   </xe:this.value>
   <xe:this.children>
      <xe:basicLeafNode>
         <xe:this.submitValue><![CDATA[#{javascript:return val[1]}]]></xe:this.submitValue>
         <xe:this.label><![CDATA[#{javascript:return val[0]}]]></xe:this.label>
      </xe:basicLeafNode>
   </xe:this.children>
</xe:repeatTreeNode>

A: Thank you for the quick reply. This is very useful information for me.
Another way I found out based on XSnippet code and some reverse engg. from java code in xpage as follow :
var oneui = getComponent("applicationLayout1");
var uiConfig = oneui.getConfiguration();
var containerNode:com.ibm.xsp.extlib.tree.complex.ComplexContainerTreeNode = new com.ibm.xsp.extlib.tree.complex.ComplexContainerTreeNode();
containerNode.setLabel("Cluster Applications");

var docAppProfile = docColl.getFirstDocument();
while(docAppProfile != null)
{
    var children:com.ibm.xsp.extlib.tree.complex.ComplexLeafTreeNode = new com.ibm.xsp.extlib.tree.complex.ComplexLeafTreeNode();
    children.setComponent(oneui);
    children.setLabel(docAppProfile.getItemValueString("appTitle"));
    children.setHref(docAppProfile.getItemValueString("appURL"));
    children.setImage(docAppProfile.getItemValueString("appLogoThumb"));
    containerNode.addChild(children);

    children = null;
    var tempDoc = docColl.getNextDocument(docAppProfile);
    docAppProfile = null;
    docAppProfile = tempDoc;
}
uiConfig.addPlaceBarAction(containerNode);

This is sample code only. Converted this is into java code and serialized to improve performance and load it only once in application.
Thank you again for help.

A: basically its the same code you listed above, but in Java.  and then this small code in the faces-config.xml file
<lifecycle>
    <phase-listener>com.company.app.phaselisteners.PlaceBarInjector</phase-listener>
</lifecycle>

package com.company.app.phaselisteners;

public class PlaceBarInjector implements PhaseListener {

      private static final long serialVersionUID = 1L;

      public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

    public void beforePhase(PhaseEvent event) {
        UIComponent oneui = JSFUtil.findComponent("applicationLayout1");
    Configruation uiconfig = oneui.getConfiguration();
    ComplexContainerTreeNode containerNode = new ComplexContainerTreeNode();
    containerNode.setLabel("Cluster Applications");

    Document docAppProfile = docColl.getFirstDocument();
    while(docAppProfile != null)
    {
            ComplexLeafTreeNode children = new ComplexLeafTreeNode();
            children.setComponent(oneui);
            children.setLabel(docAppProfile.getItemValueString("appTitle"));
        children.setHref(docAppProfile.getItemValueString("appURL"));
            children.setImage(docAppProfile.getItemValueString("appLogoThumb"));
            containerNode.addChild(children);

            Document tempDoc = docColl.getNextDocument(docAppProfile);
            docAppProfile = tempDoc;
    }
    uiConfig.addPlaceBarAction(containerNode);
    }

    public void afterPhase(PhaseEvent event) {
        System.out.println("END PHASE " + event.getPhaseId());
    }

}

A: Another thing you can do is use a PhaseListener to inject the Items into your Container Node before render response.  Then you could control it in a single place for all of your pages.


text:
Q: Knockoutjs 1.3.0 beta control flow binding foreach I am having a very hard time using the foreach control flow binding in my project.
Fiddler: http://jsfiddle.net/mbynum/YVVbg/
Summery of Fiddler:
Javascript:
var viewModel = {
    Chart: {
        Name: "something"
    },
    VarsOptions: ko.observableArray([{
        Name: "test1"},
    {
        Name: "Test2"}])
};

ko.applyBindings(viewModel);

HTML:

Something?

I am referencing the knockout: http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-1.3.0beta.js
from github:
https://github.com/SteveSanderson/knockout/downloads
I have seen people on fiddler get this to work. I dont see how my code is different or why it might not be working. I am beginning to believe it might be the way I am setting up my javascript object.

A: Here is your issue:

Should be:


text:
Q: How extract TileMatrixSet from GeoServer in order to pass it to create WMTSTileService? I am trying to mock GetMap requests and had an issue on how to create valid BBox values for the requests so they would HIT the cached layer. I got an answer from Ian Turton How properly calculate BBox for mocked GetMap request? on how to calculate valid BBox but I. However I need to automate this process and parsing WMTS capabilities document is not what I would like to do. Ian's suggested usage of WMTS instead of WMS has a drawback - I need to know rows and columns for each zoom level I want to hit and I want to hit specific area only. I see no easy way to automate correct zoom level/column/row combination selection.
  What I think is the best way to generate correct BBox parameters for GetMap requests is to call org.geotools.data.wmts.client.WMTSTileFactory.findTileAtCoordinate(...) with the random coordinates I can easily generate. Later I would get ReferencedEnvelope from the Tile and would ask for the lower and upper corner coords and that would be it but... findTileAtCoordinate(...) needs parameter of type org.geotools.tile.TileService and in order to create WMTSTileService object I need to pass a bunch of parameters among which is org.geotools.data.wmts.model.TileMatrixSet. Now I don't want to manually parse WMTS capabilities document to create TileMatrixSet object. I would expect there should be a way to create service which needs only GeoServer address and a layer name so it could fetch all the data about layer (BoundingBox, EPSGCode, TileMatrixSet and so on) so I could pass them to WMTSTileFactory.findTileAtCoordinate(...). Is there a such service? Maybe I am doing wrong approach?

A: IIRC (and I was supposed to document this last year) you need to create a WMSTSTileService which takes the base URL of the server. You can then either issue a getTiles request or grab the TileMatrixSet from it using getTileMatrixSet().
    String serverURL="http://localhost:8080/geoserver/gwc/service/wmts?"
    WebMapTileServer wmts = new WebMapTileServer(serverURL);
    WMTSCapabilities capabilities = wmts.getCapabilities();
    WMTSLayer layer = (WMTSLayer) capabilities.getLayer("topp:states");

    request.setLayer(layer);

    request.setRequestedWidth(800);
    request.setRequestedHeight(400);

    String format = "image/png";
    List<String> formats = layer.getFormats();

    if (!formats.contains("image/png")) {
        format = (String) formats.get(0);
    }
    request.setFormat(format);

    ReferencedEnvelope re = new ReferencedEnvelope(-180, 180, -90, 90, CRS.decode("EPSG:4326"));
    request.setRequestedBBox(re);

    // System.out.println(request.getFinalURL());
    Set<Tile> responses = (Set<Tile>) wmts.issueRequest(request);

    for (Tile response : responses) {
        // System.out.println("Content Type: " + response.getContentType());
        // System.out.println(response.getTileIdentifier());
        BufferedImage image = response.getBufferedImage();
        //do what ever you want with the image.
    }


text:
Q: Bottom Navigation View With Left Righ Space Issue I am newbie in android, i am use bottom navigation view with two menus
but im getting left right space
Here is my Navigation View,
<android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"

        app:itemBackground="@color/colorRed"
        app:itemIconTint="@color/colorWhite"
        app:itemTextColor="@color/colorWhite"
        app:menu="@menu/bottom_bar_menu"/>

Please check Image

A: According to Material design guidelines
You can't use two menus with bottom navigation use, instead of bottomNavigation view use tab layout
Check this link for guidlines https://material.io/guidelines/components/bottom-navigation.html#bottom-navigation-usage
Still, if you want to use bottom navigation view
Try This inside BottomNavigationView
android:background="@color/colorRed"

A: Solution
Inside BottomAppBar set attribute
android:padding="0dp"

A: If there are fewer than three destinations, consider using tabs instead.
In Bottom


text:
Q: How to Compare 2 UiLabel's Width? I have 2 UILabel in My TableView.
For E.g.
label1=@"Mihir";
label2=@"Oza";

My Question is how to check which label's text width is bigger in dynamically not static? I mean how to compare two label's text width of?
Actually I want which label has bigger width of text.

A: I think you want to compare the lenght of UILabel texts, rather than there size. Try following:
if (label1.text.length > label2.text.length)
    NSLog(@"label1 text is longer");
else (label1.text.length < label2.text.length)
    NSLog(@"label2 text is longer");
else // if they are of same length
    NSLog(@"Both labels' text lengths are equal.");

A: Depend which approach would you like to use.

*

*By number of characters

*By width (irrespective of number of characters)
KKKK (4 K's) is smaller then iiiii (5 i's) if we compare by length
BUT
KKKK (4 K's) is greater then iiiii (5 i's) if we compare by width after calling sizeToFit.
Sample code as below.
LabelCompareViewController.h
#import <UIKit/UIKit.h>

@interface LabelCompareViewController : UIViewController

@end

LabelCompareViewController.m
#import "LabelCompareViewController.h"

@interface LabelCompareViewController () {
    UILabel *label1;
    UILabel *label2;
    UILabel *label3;
    UILabel *label4;
}

@end

@implementation LabelCompareViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    label1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 300, 40)];
    label2 = [[UILabel alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
    label3 = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 40)];
    label4 = [[UILabel alloc] initWithFrame:CGRectMake(10, 400, 300, 40)];

    label1.text = label2.text = label3.text = label4.text = @"";

    label1.textColor = label2.textColor = label3.textColor = label4.textColor = [UIColor blueColor];

    [self.view addSubview:label1];
    [self.view addSubview:label2];
    [self.view addSubview:label3];
    [self.view addSubview:label4];

    label1.text = @"KKKK";
    label2.text = @"iiiii";

    NSString *op1 = @"Comparing Length : ";

    if (label1.text.length>label2.text.length) {
        op1 = [op1 stringByAppendingString:@"1>2"];
    } else if (label2.text.length>label1.text.length) {
        op1 = [op1 stringByAppendingString:@"2>1"];
    } else {
        op1 = [op1 stringByAppendingString:@"1==2"];
    }

    label3.text = op1;
    // gives output 2>1

    // after sizeToFit
    [label1 sizeToFit];
    [label2 sizeToFit];

    op1 = @"Comparing sizeToFit : ";

    if (label1.frame.size.width>label2.frame.size.width) {
        op1 = [op1 stringByAppendingString:@"1>2"];
    } else if (label2.frame.size.width>label1.frame.size.width) {
        op1 = [op1 stringByAppendingString:@"2>1"];
    } else {
        op1 = [op1 stringByAppendingString:@"1==2"];
    }

    label4.text = op1;
    // gives output 1>2

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Screenshot

A: What you call label1 and label2 are actually instances of NSString and not UILabel. This is an important difference since NSString only represents the string datatype on iOS (a concatenation of characters) and UILabel on the other hand is a UI Element that has a frame with width and height and displays a text (of type NSString).
To me it looks like you just want to compare the length of the strings, not the width of a UILabel.
This you can do by using the length method of NSString.
if ([label1 length] < [label2 length]){
   NSLog(@"label2 is longer than label1");
}
else {
   NSLog(@"label1 is longer than label2");
}

If you actually want to compare the width of two instances of UILabel check @godomey's answer!
Update:
You have to be very careful what exactly you want to compare, from your question it doesn't become quite clear!
If you want to compare the number of characters that are displayed on each of the labels, then you will have to use:
if ([label1.text length] < [label2.text length]){
   NSLog(@"the text of label2 is longer than the one of label1");
}
else {
   NSLog(@"the text of label1 is longer than the one of label2");
}

If you want to use compare the actual width (measured in pixels) of the elements that are displayed on the UI, you need to use
if (label1.frame.size.width < label2.frame.size.width){
   NSLog(@"the width of label2 is greater than the one of label1");
}
else {
   NSLog(@"the width of label1 is greater than the one of label2");
}

A: More shortly you can try like this:-
(label1.text.length > label2.text.length)?NSLog(@"label1 text is longer"): NSLog(@"label2 text is longer");


text:
Q: Windows Sidebar Gadget Reload I am trying to develop a Windows Desktop widget for Windows 7. Just wondering if there is an easy way to reload the widget or have some form of debug code that will reload the widget every 10 seconds.
The reason I ask is while developing the widget, if I change anything I need to close the widget and readd to the desktop to show my changes.
Cheers.

A: I do this using a simple batch file that kills sidebar.exe, copies the unzipped gadget files over, and then restarts sidebar.exe.  This method also preserves settings between gadget updates.
This is the batch file.  You'll have to modify src and dst appropriately.  You might have to run it from an elevated command prompt if you haven't disabled UAC.
@setlocal
@echo off

:: Kill the current sidebar process
taskkill /f /im sidebar.exe

:: Update files
set src="%CD%\source"
set dst="%USERPROFILE%\appdata\local\microsoft\windows sidebar\gadgets\YourGadget.gadget"

xcopy /s /y %src% %dst%

:: Relaunch sidebar
start "" "%ProgramFiles%\Windows Sidebar\sidebar.exe"

@endlocal

A: Do you only need to reload the gadget upon making changes to it?
In A Heterodox Visual Studio Gadget Template the author has put together a gadget template which has a c# project attached that bundles and deploys your gadget when you run it.
Alternatively, you may be interested in the link down the page: Create a Vista Gadget Using Visual Studio IDE
Both involve the use of Visual Studio, which may not be your preferred method of development, but you can get Visual Web Developer Express for free from Microsoft, and I know for fact that the template works in that.


text:
Q: FIRRemoteConfig.activateFetched() fails I've implemented FIRRemoteConfig and added my first value in the firebase console.  However, when I try to activate the fetched values it fails and my remote value  is never available.
    let remote = FIRRemoteConfig.remoteConfig()
    #if DEBUG
        let expiration: TimeInterval = 0
        remote.configSettings = FIRRemoteConfigSettings(developerModeEnabled: true)
    #else
        let expiration: TimeInterval = 24*60*60
    #endif

    var map = [String:NSObject]()
    let defaults = RemoteSettings.defaults.keys
    for key in defaults.keys {
        map[key.rawValue] = defaults[key] as? NSObject
    }
    remote.setDefaults(map) // Have confirmed that map is valid here

    remote.fetch(withExpirationDuration: expiration, completionHandler: { (status, error) in
        // status always == .success, but remote.activateFetched() always returns false.
        if status == .success && remote.activateFetched() {
            print("applied remote settings")
        } else {
            print("failed to apply remote settings: \(error)")
        }
    })

A: As @Sunil Phani Manne mentioned, using the method with expiration value really works and forces remoteConfig to activate immediately.
    self.remoteConfig?.fetch(withExpirationDuration: 0.0, completionHandler: { (status, error) in
        let result = self.remoteConfig?.activateFetched()
        print(result)
    })

A: Using remote.activateFetched() fails, but using FIRRemoteConfig.remoteConfig().activateFetched() is successful.  Perhaps google wants us to use remoteConfig() every time rather than holding onto a specific instance.
Additionally, a look at the documentation mentions that this will actually fail if the fetched settings have already been applied previously.

Returns false if no Fetched Config was found, or the Fetched Config was already activated.

A: I figured out after a lot of trial and error. The problem is with the expiration value, set the expiration value to 0 seconds to see the immediate results put into effect!
I hope this could save a lot of time for others guys!


text:
Q: Increase gyroscope data collection on Chrome in Android Environment: Chrome browser on Android.
I've been trying to collect data from the gyroscope at a speed of 30fps, but no matter how fast I call the function, the new data doesn't go anywhere close to that. I mean, you can call the API as much as you want, but you'll get duplicated data.
Any ideas?
Thanks

A: Well, it turns the constructor has a frequency parameter I didn't see. Someone else pointed it out to me.
I add both options, for the gyroscope alone and the Absolute Orientation Sensor
https://developer.mozilla.org/en-US/docs/Web/API/Gyroscope
https://developer.mozilla.org/en-US/docs/Web/API/AbsoluteOrientationSensor
Thanks


text:
Q: .htaccess .php rewrite with / after So I am currently rewritting my urls and removing the .php extension using the following:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

So if I load up the about.php page, http://example.com/about it displays what I want, is there a way to make http://example.com/about/ display the about.php page as well, as well as all the other files like this.

A: You can drop the trailing slash if it exists, in your capture regex, like so:
RewriteRule ^([^\.|/]+)$ $1.php [NC,L]

This will send requests for both about and about/ to about.php.


text:
Q: XSLT: How do I trigger a template when there is no input file? I'm creating a template which produces output based on a single string, passed via parameter, and does not use an input XML document.  xsltproc seems to happily run with a single parameter specifying the stylesheet, but I don't see a way to trigger a template without an input file (no parameter to xsltproc to run a named template, for example).
I'd like to be able to run:
xsltproc --stringparam bar baz foo.xsl

But I'm currently having to run, with the "main" template matching "/":
echo '<xml/>' | xsltproc --stringparam bar baz foo.xsl -

How can I get this to work?  I'm sure I've seen other templates in the past which were meant to be run without an input document, but I don't remember how they worked or where to find them again.  :-)

A: Actually, this has been done quite often.
In XSLT 2.0 it is defined in the Spec. that providing an initial context node is optional.
If no initial context node is provided (no source XML document), then it is important to provide the name of a named template which is to be executed as the entry point to the transformation.
In XSLT 1.0 one can provide to the transformation its own primary stylesheet module (file) as the source XML document, and of course, the transformation can completely ignore this source XML document. This technique has long ago been demonstrated and used by Jeni Tennison.
For example:
<?xml-stylesheet type="text/xsl" href="example.xml"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">

Hello, world!

    </xsl:template>
</xsl:stylesheet>

When the above code is saved in a file named "example.xml" and then the folder contents is displayed with Windows Explorer, double-clicking on the file "example.xml" will open IE and produce:
Hello, world!

A: In general, you cannot do this with XSLT - specification requires there to be an input document, and for the processing to start with applying any available templates to its root node. Some XSLT processors might give a way to do what you want (e.g. execute a named template) as an extension, but I don't know any such, and it doesn't seem that xsltproc is one of them, judging from its man page.
In fact, this sounds pretty dubious in general, as the purpose of using XSLT to produce some output from a plain string input is unclear - it's not the kind of task it's generally good at.


text:
Q: How could I fix Error during compodoc run in angular? enter code here> Blockquote
I have next error during compodoc run in angular (npx compodoc -p tsconfig.app.json src)
How can I fix it?
Ooops error during main graph generation, moving on next part with main graph disabled : : Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /usr/local/lib/node_modules/@compodoc/compodoc/node_modules/@aduh95/viz.js/sync/index.js
    require() of ES modules is not supported.
    require() of /usr/local/lib/node_modules/@compodoc/compodoc/node_modules/@aduh95/viz.js/sync/index.js from /usr/local/lib/node_modules/@compodoc/compodoc/node_modules/@compodoc/ngd-transformer/dist/engines/dot/dot.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
    Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /usr/local/lib/node_modules/@compodoc/compodoc/node_modules/@aduh95/viz.js/package.json.

A: I had the same issue. I updated the Node version from 12.16.3 to 14.16.1 and that fixed it.


text:
Q: Is there a setting to force Adium to open a new chat in a new window? For Adium, a single window holds many chats.
from official link (http://trac.adium.im/wiki/TabbedMessaging)
"A single window might contain 10 different tabbed chats"
Is there any setting where I can force Adium to open new chat in new window?

A: Yes. Under Preferences -> General, uncheck the box called 'Create new chats in tabs' as on the screenshot below.


text:
Q: Volt templates - how to ignore PHP tags? I'd like to distribute .volt template files to my system's registered users, however I want it to strip away all <?php tags.
Can it be done using some sort of callback?
Thanks!

A: There are the table with all available filters
http://docs.phalconphp.com/en/1.2.6/reference/volt.html#filters
but if you want something else, you should write your own filter, which you would use in volt:
http://docs.phalconphp.com/en/1.2.6/reference/volt.html#id3
something like this: (not tested)
$compiler->addFilter('escapePHP', function($resolvedArgs, $exprArgs) {
    return str_replace(array('<?', '<?php'), '', $resolvedArgs);
});


text:
Q: Moving between lines in VIM Let's say I have a file with N lines. I'm at line X and I'd like to move to line Y, where both X and Y are visible on screen. I can do that by typing :Y<cr>, but if Y>99 that's a lot of typing. I can also do abs(Y-X)[kj] (move up or down by abs(Y-X)), but for big X,Y computing this difference mentally isn't so easy.
Is there a way to exploit the fact, that both X,Y are visible on screen and move between X and Y fast?

A: You can :set relativenumber which does that Y-X computing for you (only in Vim >= 7.3).

A: You can use H, M or L to go the top, middle and bottom of the screen.

A: Perhaps you can make use of H, M, or L.
These keys jump the cursor to display lines:
H    "Home" top of screen
M    "Middle" middle of screen
L    "Last" last line of screen

With a count, they offset:  4L would go to the third line above the last (1L is the same as just L).
Personally, I make heavy use of the m command to mark a line for navigation.  From where I am now, hit mq to mark the position with label q; then navigate to another line, and ma to mark it with label a; and from then on I can hit 'q to jump to position q and 'a to jump to position a.  (q and a are arbitrary; I use those mostly due to their position on a QWERTY keyboard.)
One you have the marks, you can use them for commands.  To delete from the current position to the line marked with q, you just use: d'q
There is a variant, where instead of single quote you use back quote.  This takes you to the exact position on the line where you placed the mark; the single quote uses the start of the line.
Those marks work even for ex (command line) commands.  To limit search and replace to a specific set of lines, I mark the beginning and end lines respectively with labels b and e, and then do my search and replace like so:
:'b,'es/foo/bar/g

A: Dropping my dime in the pond:
I find that traversing code is exceptionally easy with text objects. I rarely do use jk/JK for larger jumps any more. Instead I navigate for whitespace lines using { and }
Since on any one screen there are usually only so-many whitespace delineations (and they are very easily visually recognized and counted), I find that e.g.
   3}j
lands me on the intended line a lot more often than, e.g., a guesstimated
     27j
To top it all, many 'brace-full' programming languages have opening braces at the start of functions. These can be reached with [[ resp. ]]. So sometimes it is just a matter of doing, e.g.
   2[[}
(meaning: go to start of previous function, after the first contiguous block of lines)

A: My version of VIM lets you guestimate a number immediately before hitting J or K to go that many lines.
15K goes up 15 lines

A: The tougher vimmer you are becoming, the bigger amount of lines you can count at first glance.
Don't know, maybe there are some clever techniques, but I just type something like 17k/23j and so on.
also, searching some word on the string you want to jump works.
also, zz (center screen) is sometimes helpful in this cases.