text:
Q: How to use an getter method as a property when I json_encode a Doctrine entity? For example, in the class
/**
 * @Doctrine\ORM\Mapping\Entity
 */
class Example
{
    /**
     * @var int The id
     *
     * @Doctrine\ORM\Mapping\Id
     * @Doctrine\ORM\Mapping\GeneratedValue
     * @Doctrine\ORM\Mapping\Column(type="integer")
     */
    public $id;

    /**
     * @var string
     *
     * @Doctrine\ORM\Mapping\Column(type="string")
     */
    public $name;

    public function getRandomNumber()
    {
        return rand();
    }
}

When I call the json_encode() with this entity, it not bring the getRandomNumber() value as an property of the class.
I would like it returns:
{
    "id": 1,
    "name": "foo",
    "randomNumber": 123456
}

But it returns:
{
    "id": 1,
    "name": "foo"
}

A: You should use JMSSerializer bundle!
I use it in all my websites, and it is really a great solution.
https://jmsyst.com/libs/serializer
It uses annotations, and creates json-serialized entities. It takes attributes values of your entity, but with a specific annotation @Accessor, it uses the specified getter to get his value.
For example:
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Accessor;

/**
 * @Expose
 * @Accessor("getRandomNumber")
 */
public $randomNumber;

public function getRandomNumber(){
    return rand();
}

A: json_encode will return a JSON object with the public properties of the object passed to it. If you want to include randomNumber you could make it a public property and set it in the constructor like
/**
 * @Doctrine\ORM\Mapping\Entity
 */
class Example
{
    /**
     * @var int The id
     *
     * @Doctrine\ORM\Mapping\Id
     * @Doctrine\ORM\Mapping\GeneratedValue
     * @Doctrine\ORM\Mapping\Column(type="integer")
     */
    public $id;

    /**
     * @var string
     *
     * @Doctrine\ORM\Mapping\Column(type="string")
     */
    public $name;

    /**
     * @var int
     */
    public $randomNumber;

    public function __construct() {
      $this->randomNumber = $this->getRandomNumber();
    }

    public function getRandomNumber()
    {
        return rand();
    }
}

For more complex serialization of objects you might want to look at the symfony serializer

A: You could implement the interface \JsonSerializable to specify data which should be serialized to JSON:
class Example implements \JsonSerializable
{
    // ...

    public function jsonSerialize()
    {
        // mixed data which can be serialized by json_encode()
        return array(
            'id' => $this->id,
            'name' => $this->name,
            'randomNumber' => $this->getRandomNumber(),
        );
    }
}

A: Use the virtual property
Info: https://jmsyst.com/libs/serializer/master/reference/annotations#virtualproperty
/**
 * @Doctrine\ORM\Mapping\Entity
 */
class Example
{
    /**
     * @var int The id
     *
     * @Doctrine\ORM\Mapping\Id
     * @Doctrine\ORM\Mapping\GeneratedValue
     * @Doctrine\ORM\Mapping\Column(type="integer")
     */
    public $id;

    /**
     * @var string
     *
     * @Doctrine\ORM\Mapping\Column(type="string")
     */
    public $name;

    /**
     * @Serializer\VirtualProperty()
     */
    public function getRandomNumber()
    {
        return rand();
    }
}


text:
Q: Wordpress custom plugin shortcode wpdb unknown I'm writing a custom plugin in wordpress and I'm using a shortcode for the first time.
Until now my shortcode works but now I want to execute a query in the function of that shortcode to get all the employees from a specific employee group id
   [employee_group_tag group_id=2]

This is the file that has my shortcode functionality:
    <?php
/*
Plugin Name: Employees
Plugin URI: xxx
Description: xxx
Version: 1.0
Author: xxx
Author URI: http://www.blabla.com
*/

   global $wpdb;

   function employee_shortcode_func( $atts ) {
    extract( shortcode_atts( array(
        'group_id' => '0',
    ), $atts ) );

    // Alle werknemers ophalen adhv van group_id
    $sql = 'SELECT * FROM wp_werknemers_employees WHERE employee_employee_group_id = ' . $group_id;
    $results = $wpdb->get_results($sql);

    return 'test';
}
add_shortcode( 'employee_group_tag', 'employee_shortcode_func' );

But when I run this it gets stuck on $wpdb->get_results($sql) because when I leave this out it displays my page correctly but when I want to fill it with employee details I only get the half of my page. So it "breaks"
I tried to do (which works in all my other files)
  require_once("../../../wp-config.php")

But it doesn't work...
Is it possible that it's not working because its in my "main" plugin file? Because in all my other files I can use wpdb when I use the require function...
any ideas?

A: From the PHP Manual:

For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
$a = 1;
include 'b.inc';

Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:
$a = 1; /* global scope */

function test()
{
    echo $a; /* reference to local scope variable */
}

test();

The last example does not work, as $a is not defined inside the scope of the function.
Just like in your case, for it to work you have to use:
function employee_shortcode_func( $atts ) {
    global $wpdb;
    // etc
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: IE9 not Loading Javascript file from internal server I am building a API using MVC 4. In the config, has a attribute to point the server that holds the API's resources (JS, CSS, IMG, ...).
I ran into an issue with IE. When I get this page(partial code below) via AJAX, IE gets 2 errors: "SCRIPT257: Could not complete the operation due to error 80020101" and A syntax error on line 2. This same code works fine in Chrome and other browsers
@{
   string server = System.Configuration.ConfigurationManager.AppSettings["server"]; // http://SomeServerName
}
<script src="@Url.Content(@server + "/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

I got around the issue by moving that Javascript file to the client page, I would prefer not to have to have the client of the API have Jquery.unobstrusive-ajax.min.js as required file.
P.S. All Objects and arrays had tailing commas removed.


text:
Q: Aplicar função por grupos ou fatores no R Prezadas e prezados,
Preciso calcular o crescimento populacional relativo dos municípios brasileiros, de um ano para o outro (população final menos a população inicial, dividido pela população inicial). Para isso, fiz uma simples função:
var_rel <- function(x,y){
  ((x-y)/y)*100
}

Em que x é a população de 2019 e y a população de 2014.
No entanto, não estou conseguindo aplicar um comando que rode a função por município. Isto porque eu preciso garantir que o x (população de 2019) e y (população de 2014) sejam do mesmo município.
Hoje, minha função é aplicada da seguinte maneira:
var_rel(pop[pop$ano=="2019","qtd_pop_mun"], pop[pop$ano=="2014","qtd_pop_mun"])

No entanto, pode ocorrer de ser utilizado como x a população de 2019 de um município e como y a população de 2014 de outro município. Dessa forma, preciso garantir que isso não ocorra.
Tentei usar a função tapply, mas como a função que criei var_rel possui argumentos x e y, não sei como incluir ambos na tapply.
O meu objeto tem uma coluna pra ano (de 2014 a 2019), outra pro tamanho da população e outra pro código do IBGE de município (5570 municípios do Brasil).
Eu preciso resolver isso utilizando a função que criei para o cálculo da variação relativa, pois em outros momentos terei cálculos mais personalizados, em que haverá necessidade de gerar uma função própria, como já fiz nesse momento.
Obrigado!
    ano key_cd7_ibge_mun qtd_pop_mun qtd_pop_est qtd_pop_pais
1  2014          1100015       25652     1748531    202768562
2  2015          1100015       25578     1768204    204450049
3  2016          1100015       25506     1787279    206081432
4  2017          1100015       25437     1805788    207660929
5  2018          1100015       23167     1757589    208494900
6  2019          1100015       22945     1777225    210147125
7  2014          1100023      102860     1748531    202768562
8  2015          1100023      104401     1768204    204450049
9  2016          1100023      105896     1787279    206081432
10 2017          1100023      107345     1805788    207660929
11 2018          1100023      106168     1757589    208494900
12 2019          1100023      107863     1777225    210147125
13 2014          1100031        6424     1748531    202768562
14 2015          1100031        6355     1768204    204450049
15 2016          1100031        6289     1787279    206081432
16 2017          1100031        6224     1805788    207660929
17 2018          1100031        5438     1757589    208494900
18 2019          1100031        5312     1777225    210147125

A: Usando data.table:
library(data.table)

dados <- fread(text =
'ano,key_cd7_ibge_mun,qtd_pop_mun,qtd_pop_est,qtd_pop_pais
2014,1100015,25652,1748531,202768562
2015,1100015,25578,1768204,204450049
2016,1100015,25506,1787279,206081432
2017,1100015,25437,1805788,207660929
2018,1100015,23167,1757589,208494900
2019,1100015,22945,1777225,210147125
2014,1100023,102860,1748531,202768562
2015,1100023,104401,1768204,204450049
2016,1100023,105896,1787279,206081432
2017,1100023,107345,1805788,207660929
2018,1100023,106168,1757589,208494900
2019,1100023,107863,1777225,210147125
2014,1100031,6424,1748531,202768562
2015,1100031,6355,1768204,204450049
2016,1100031,6289,1787279,206081432
2017,1100031,6224,1805788,207660929
2018,1100031,5438,1757589,208494900
2019,1100031,5312,1777225,210147125')

> dados[, .(crescimento = (qtd_pop_mun[.N]-qtd_pop_mun[1])/qtd_pop_mun[1]*100), by = key_cd7_ibge_mun]
   key_cd7_ibge_mun crescimento
1:          1100015  -10.552783
2:          1100023    4.863893
3:          1100031  -17.310087

data.table é ótimo para realizar operações por grupos em grandes tabelas de dados. A sintaxe é similar à de bancos de dados SQL, consulte a vinheta de introdução do pacote para mais informações: vignette('datatable-intro', 'data.table')
Um data.frame pode ser convertido para data.table usando setDT(seu.data.frame), mas é melhor usar fread para ler diretamente seu arquivo.

A: Esta é uma solução R base.
Adota a estratégia split/apply/combine de Hadley Wickham.
A função var_rel é reescrita para ter um só argumento.
var_rel <- function(x){
  100*(x[2] - x[1])/x[1]
}

i1 <- pop$ano == 2014
i2 <- pop$ano == 2019
sp <- split(pop[i1 | i2, c(1, 3)], pop$key_cd7_ibge_mun[i1 | i2])
sapply(sp, function(DF){
  var_rel(DF[['qtd_pop_mun']])
})
#   1100015    1100023    1100031
#-10.552783   4.863893 -17.310087


text: Q: Is there a way to get a photo of the store front from the Google Place API? I understand how to use the Place API in conjunction with the Place Photos API to retrieve media, but there does not seem to be a way to request the photo reference for the picture of the front of a store like the ones Google usually uses in their own search results. Am I missing a parameter here that will always deliver that photo that they use?


text:
Q: Achieving batch matrix multiply using tensordot I'm trying to achieve the same behaviour as np.matmul parallel matrix multiplication using just tensordot,dot and reshaping etc.
The library I am translating this to using does not have a matmul that supports parallel multiplication, only dot and tensordot.
Additionally I want to avoid iterating over the first dimension, and want to do this using a set of matrix multiplications and reshaping (want as much of it to run using BLAS/GPU as i have large numbers of small matrices to calculate in parallel).
Here is an example:
import numpy as np

angles = np.array([np.pi/4, 2*np.pi/4, 2*np.pi/4])

vectors = np.array([ [1,0],[1,-1],[-1,0]])

s = np.sin(angles)
c = np.cos(angles)

rotations = np.array([[c,s],[-s,c]]).T

print rotations

print vectors

print("Correct: %s" % np.matmul(rotations, vectors.reshape(3,2,1)))

# I want to do this using tensordot/reshaping, i.e just gemm BLAS operations underneath
print("Wrong: %s" % np.tensordot(rotations, vectors, axes=(1,1)))

The output of this is:
Correct: [[[  7.07106781e-01]
  [  7.07106781e-01]]

 [[  1.00000000e+00]
  [  1.00000000e+00]]

 [[ -6.12323400e-17]
  [ -1.00000000e+00]]]

Wrong: [[[  7.07106781e-01   1.11022302e-16  -7.07106781e-01]
  [ -7.07106781e-01  -1.41421356e+00   7.07106781e-01]]

 [[  6.12323400e-17  -1.00000000e+00  -6.12323400e-17]
  [ -1.00000000e+00  -1.00000000e+00   1.00000000e+00]]

 [[  6.12323400e-17  -1.00000000e+00  -6.12323400e-17]
  [ -1.00000000e+00  -1.00000000e+00   1.00000000e+00]]]

Is there a way in which I can modify the second expression in order to get the same result as the first, just using dot/tensordot.
I believe it is possible, and have seen some comments online, but never any examples

A: We need to keep one aligned and keep that also at the output. So, tensordot/dot won't work here. More info on tensordot might explain it somehow on why it won't. But, we can use np.einsum, which in most cases (in my experience) is seen to be marginally faster than np.matmul.
The implementation would look something like this -
np.einsum('ijk,ik->ij',rotations, vectors)

Also, it seems the desired output has one trailing singleton dim. So, append a new axis there with None/np.newaxis, like so -
np.einsum('ijk,ik->ij',rotations, vectors)[...,None]


text:
Q: Retrieving data from JSON object using substring If i have the following JSON object:
taxcodes = {
   "CA_MONO CO": {
          "Rate": 1,
          "Country": "United States"
       }
}

Using taxcodes["CA_MONO CO"].Rate works perfectly in retrieving the rate of 1.
Now my issue is, if i had a variable lets say: x = "CA_MONO CO_MAMMOTH LAKES".
taxcodes[x].Rate will not work obviously because of the _MAMMOTH LAKES.
So what I did was cut all strings after CO_, which gave me CA_MONO then added ' CO' back on to the end of the string which gave me CA_MONO CO.
var modifiedx = x.substring(0, x.indexOf('CO_')) + ' CO';
I then attempted to pull the data using taxcodes[modifiedx].Rate, which did not pull the data.

A: You have an extra space when you append the + ' CO'

taxcodes = {
   "CA_MONO CO": {
          "Rate": 1,
          "Country": "United States"
       }
}

x = "CA_MONO CO_MAMMOTH LAKES"

var modifiedx = x.substring(0, x.indexOf('CO_')) + 'CO';

console.log(
 taxcodes[modifiedx].Rate
);

A: That's because you have an extra space from ' CO'. So the value was "CA_MONO  CO" rather than "CA_MONO CO". Just remove it:
var modifiedx = x.substring(0, x.indexOf('CO_')) + 'CO';

A: var modifiedx = x.substring(0, x.indexOf('CO_')) + ' CO';

should be
var modifiedx = x.substring(0, x.indexOf('CO_')) + 'CO';


text:
Q: how python manage object delete or destruction guys, I am rather new to python and learning it to build a gui application (with wypython). I have a question related with object destruction in python.
e.g. in myFrame I have onNew (create a new document) and onOpen (open a file) method.
briefly, it looks like this.
def onNew
    self.data=DataModel()
    self.viewwindow=ViewWindow(self.data)

def onOpen
    dlg = wx.FileDialog(self, "Open file", os.getcwd(), "", "*.*", wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.data=DataModel.from_file(...)
            self.view=View(self.data)

now, I want to consider "if the user click open or new again, after he click either before."
so for the window classes, I could call the self.viewwindow.Destroy() to destry the windows. what about the data model object? If I first call new: self.data=DataModel(), then call open and re-assign self.data=DataModel.from_file(...), what about the old instance? Do I need destruct it myself or python will manage this destruction?

A: Python has garbage collection. As long as you don't have any references to the old object hanging around it will be collected.
As soon as you say self.data = somethingElse then the old self.data won't have any references to it (unless another object had a reference to your object's self.data).


text:
Q: Alternative to database project in VS 2008 professional Is there an alternative to the Visual Studio 2008 Team System Edition - Database project (GDR professional) for Visual Studio 2008 Professional edition?
Or is it really one of the selling points for Team System edition.

A: SQL tools from RedGate


text:
Q: Ubuntu 19.04 problems install upgrades When trying to update I get an error message
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

But when I try to run this command the screen goes completely black and nothing happens.  From what I can tell it is trying to install Linux headers when this happens.  This is a fresh install of less than a week old. At this time I can not install anything new or update anything. How do I solve this issue?
Log File:
12:50:16 systemd-journal: Journal stopped
12:50:16 kernel: Sending SIGTERM to remaining processes...
12:50:16 kernel: Syncing filesystems and block devices.
12:50:16 kernel: printk: systemd-shutdow: 78 output lines suppressed due to ratelimiting
12:50:16 systemd: Shutting down.
12:50:15 NetworkManager: <info>  [1565373015.4510] exiting (success)
12:50:15 systemd: Stopped Raise network interfaces.
12:50:15 NetworkManager: <info>  [1565373015.4124] caught SIGTERM, shutting down normally.
12:50:15 systemd: Stopping Network Manager...
12:50:15 pulseaudio: E: [alsa-sink-HDMI 1] alsa-sink.c: Error opening PCM device hdmi:0,1: No such file or directory
12:50:15 systemd: Stopped D-Bus User Message Bus.
12:50:15 systemd-logind: Removed session 2.
12:50:15 systemd: Stopping D-Bus User Message Bus...
12:50:15 gdm-x-session: (II) Server terminated successfully (0). Closing log file.
12:50:14 systemd: Stopped ACPI event daemon.
12:50:14 (sd-pam): pam_unix(systemd-user:session): session closed for user gdm
12:50:14 systemd: gdm.service: Succeeded.
12:50:14 gdm3: Child process -1517 was already dead.
12:50:14 systemd: Started Exit the Session.
12:50:14 gdm3: Child process -1517 was already dead.
12:50:14 systemd: systemd-exit.service: Succeeded.
12:50:14 gdm-x-session: (II) systemd-logind: releasing fd for 13:65
12:50:14 systemd: Stopped sandboxed app permission store.
12:50:14 systemd-logind: Removed session c2.
12:50:14 gdm-x-session: (II) systemd-logind: releasing fd for 13:64
12:50:14 systemd: Stopping User Manager for UID 123...
12:50:14 gdm-x-session: (II) Server terminated successfully (0). Closing log file.
12:50:13 gdm3: Freeing conversation 'gdm-launch-environment' with active job
12:50:13 systemd: Stopped Network Manager Wait Online.
12:50:13 dbus-daemon: [system] Activation via systemd failed for unit 'accounts-daemon.service': Refusing activation, D-Bus is shutting down.
12:50:13 systemd: Stopped target Network is Online.
12:50:13 gdm3: Tried to look up non-existent conversation gdm-launch-environment
12:50:13 gdm-x-session: (II) systemd-logind: releasing fd for 13:68
12:50:13 avahi-daemon: avahi-daemon 0.7 exiting.
12:50:13 dbus-daemon: [system] Activating via systemd: service name='org.freedesktop.Accounts' unit='accounts-daemon.service' requested by ':1.478' (uid=0 pid=3680 comm="gdm-session-worker [pam/gdm-launch-environment] " label="unconfined")
12:50:13 systemd: Stopped CUPS Scheduler.
12:50:13 gdm3: Failed to list cached users: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name :1.7 was not provided by any .service files
12:50:13 systemd: Stopped PackageKit Daemon.
12:50:13 udisksd: udisks daemon version 2.8.2 exiting
12:50:13 systemd: Stopped Accounts Service.
12:50:13 apport:    ...done.
12:50:13 systemd: Stopped LSB: Record successful boot for GRUB.
12:50:13 dbus-daemon: [session uid=1000 pid=3647] AppArmor D-Bus mediation is enabled
12:50:13 systemd: Stopping Authorization Manager...
12:50:13 avahi-daemon: Leaving mDNS multicast group on interface lo.IPv4 with address 127.0.0.1.
12:50:13 systemd: Stopped target Host and Network Name Lookups.
12:50:13 avahi-daemon: Leaving mDNS multicast group on interface enp7s0.IPv4 with address 192.58.0.150.
12:50:13 systemd-logind: Session c2 logged out. Waiting for processes to exit.
12:50:13 systemd: Stopping CUPS Scheduler...
12:50:13 avahi-daemon: Leaving mDNS multicast group on interface enp7s0.IPv6 with address fe80::fd7:6a47:d5ba:6c3c.
12:50:13 systemd-logind: Session 2 logged out. Waiting for processes to exit.

A: I would suggest the following:
Option # 1:
Try fixing the missing packages by running the following command in the terminal:
sudo dpkg --configure -a && sudo apt update --fix-missing && sudo apt install -f && sudo apt full-upgrade

If errors are encountered, try removing the the apt lock by running the following in the terminal:
sudo rm /var/lib/apt/lists/lock

Then:
sudo rm /var/cache/apt/archives/lock

Then run the command again:
sudo dpkg --configure -a && sudo apt update --fix-missing && sudo apt install -f && sudo apt full-upgrade

If this does not solve the problem, please move to option # 2 below.
Option # 2:
To attempt to repair broken packages in the recovery mode, please follow these steps ( It is advised to connect your machine to Internet via Ethernet cable before you start ):

*

*Reboot your system.

*Hold the Shift key as soon as you pass the BIOS logo to enter the GRUB boot menu. You might need to repeat steps 1 and 2 a few times before you finally succeed.

*Once you see the options screen, select Advanced options for Ubuntu and press Enter:

*In the next screen select the second line (the on with recovery mode) and press Enter:

*Wait for the initial boot process to finish and a second screen with options appears. Select Enable networking and press Enter:

*If presented with a yes/no screen, choose yes and press Enter:

*If all goes well, you should be now connected to the Internet. You will know if it succeeds when the options screen shows up again. Now select Repair broken packages and press Enter:

*If presented with a yes/no screen, choose yes and press Enter:

*When you see at the command prompt Do you want to continue? type Y and press Enter:

*If all goes well, the options screen will show up again:

*Reboot your machine.


text:
Q: How do you deal with bosses that think you're slacking off? What do you do when your boss asks, "What the hell do you do all day anyway? Everything is always running fine..."?
How do you best convey the value of your job as a sys admin? (No, leaving is not an option)
I don't think anyone outside IT would understand if you tell them every little thing you do all day.
And I'm not talking about pointy-haired bosses (they're fine bosses overall), but they just don't understand what the job entails.

A: Drag your boss out of the office and have a face to face talk. Try to present documentation of day to days activities and what each project or system does for the company. Don't forget to present the consequences of a system not functioning properly. Probably, try to sit him or her next to you and explain the complexity of the network or systems. Explain to him or her this is not like opening Internet Explorer or adding RAM to a system.
Yes, the point is to try and explain something he or she won't understand. That should make his or her mouth drop.
Short and sweet make it a take your boss to work day. Be friendly, informative and willing to respond.
Good Luck!

A: First find out what your boss thinks your job's responsibilities are and what the job  entails.  If those things are being done I'd ask him which part he's unsatisfied with.  If the answer is none it's time to start looking for a new gig.  Life's far too short, and if you are looking here, you're far too bright to waste any time trying to "prove" you're not wasting time.  No amount of effort will ever convince someone with their outlook that you are working, or there really isn't any business value in the things that you do.  It would be one thing if you are on a contract and, since you are paid by the hour, asked to justify each hour.  A regular employee is employed becaue someone thinks there is a regular task(s) that has to be completed.  If that doesn't provide enough value then it's pretty tough to justify no matter how good you are at it.

A: Keep a log of what you do on a daily basis, and keep a 'personal achievement file' - basically a list of all the things you've accomplished that have either improved the level of service that you can offer, saved the company money, or generally have improved things. It also comes in very useful around appraisal/evaluation time, as well as forming most of what you'll want to add to your resume when trying to find a new job.

A: Another tricky area is that it depends on your 'role'.
A database administrator would be harder to 'account' for their role, compared to say tech support, which is constantly 'fire-fighting' user issues/ requests.
And when you're doing a wide range of jobs, research and development is crucial to expanding and improving the environment - even if the 'powers that be' dont understand why you're spending 4 hours installing a 'test' server to see whether a new product on the market is worth considering.
At the end of the day, it does come down to how you respond to emergencies, and the relationship you have with your boss / managers higher up. They'll value you in your position as tech-support (or which ever role you're in) and they'll value you as a person.
By the same token - how do CEO's justify their positions?

A: In most cases where I've had to provide a detailed log, I have set up an issue tracker with a knowledge base (where one did not previously exist).  Doing so not only allows me to track what I've done, but it also provided users with a resource to turn to before contacting the support staff.

A: The age old problem. If it all runs well they wonder why they're paying you. If it doesn't run well they wonder why they're paying you. There's no simple answer but in my previous position I would sometimes allow a small problem to occur, just so they remembered I was there. Other times I would simply remind them of what they had under my predecessor.
Depending on my mood, sometimes I would explain how I fill my day, usually in fine enough detail to ensure they lost interest. Other times it would be something like "Everything's running properly isn't it? What more do you need from me?". They didn't like those replies but also couldn't argue with them.

A: This answer isn't easy, but it works.
Track your time hourly. Produce a weekly status report on what you spent your time on. Doing both of these will add a 10% overhead to your current job- at first.
Report time spent into reactive and proactive parts.
Track commitments, internal and external, in both directions. That means, if you order something, someone has an external commitment to deliver the goods to you. If you have committed to stand up a server by a deadline, track when the request came in and what the status is on it. If you need requirements on how to install some software, track when you first made the request and how many times you have followed-up.
Next time your boss asks "what have you been doing", whip out your last weekly report and then go through (in mind-boggling boring detail) where each item currently stands. After a while, they get the idea, this guy manages himself, don't need to manage him. If the manager decides to micro-manage, being more organized than the other players means that your commitment list will be the basis of management, meaning you get to set the priorities.

A: Depends on your relationship with them. Chances are that if they are asking you this question then you have little to no personal relationship with them.
Chances are if they ask you this question, and you're a direct report of theirs, then they need to shape up to know what their employees are doing. If you're not a direct report to them, then they shouldn't be asking you this question in the first place.
All in all its a very unprofessional thing to be doing in the first place. But that's not the question.
I find the best analogy is to servicing a car.
If you work as a mechanic in a motor pool, your job is to make sure each car is serviced and running smoothly, that you know who has which vehicle and making sure that each vehicle is correctly registered, insured and roadworthy. And if you do your job correctly nobody will ever know. Stop doing your job and within a few months when the car is running rough, tyres are slippery, transmission jerky and steering wobbly everyone will know about it.
The fact that everything is running smoothly means that you're actually working hard. If you stop working hard, everything will stop running smoothly.

A: I may have to sit on the other side of this one.  First; I'll point out that the busier I am doing technology tasks that are "on my plate" the less I am connected to what my staff is doing and the more I have to ask.  Most of the time I tend to need to connect with what they're working on, not that they're working.  If I have to ask too often, it's usually because I'm not balancing my personal technical load with my management responsibilities as well as I ought to.
But that's a quick conversation, not a request to provide time tracking.  There are times I have to ask for time tracking - from time to time, usually right after I recommend that we add staff, the amount of scrutiny that I come under with what I'm doing with the people we already have has a tendency to increase.  It's a fair question:  "we need three more programmers."  "What are you doing with the ones you have?"  Your boss may be asking you this for good reason.
I think at the end of the day, assess your relationship with your workplace, and the manager you report to directly. From time to time we are all asked to justify things we wish we didn't have to justify; we're all asked to perform the mundane tasks that we wish we didn't have to do.  If the over all balance is good, try to be forgiving of the details.  If over all the balance is bad, well, then you know what that means.  The problem isn't time tracking.

"I don't think anyone outside IT would
  understand if you tell them every
  little thing you do all day."

Try.  I've found plenty of non technology managers that do honestly try to keep some basic understanding of what technical folks are doing.  Try keeping a log for a few days "Logged in to router, reviewed tunnel config, realized it was wrong, updated it, contacted the client to verify that it was still running.  30 minutes.
And if you find that frequently you're being questioned on the what - sell your boss on larger items before you do it.  "Hey, found this really cool thing that I think could have a huge positive business impact  - fewer tech support calls, less downtime, increased productivity and sales - I'm going to try to find some time Wednesday to play with it, get it installed on a VM and make sure it will work for us" "Hey that's great" is better than "you spent four hours doing what again?" after the fact.  Maybe not about everything - not even necessarily daily (though if things are rough right now, maybe daily isn't a bad idea) - but do try to communicate with non-techies.  It can even come in handy down the road as a skill in its own right.
BTW - my current technical answer to this solution is something along the lines of reporting off of our ticket system and svnstats reporting off of our subversion repository.  I find the graphs, charts, and the actual notes of all the checkins is a nice way to provide feedback and a sense of movement to non-technical management on long term things, and the ticket tracking reports for the shorter term, all hopefully without having to force our fine technical staff to waste their precious time typing things twice.  At least I hope it works out, fingers crossed...

A: To my mind, there's no simple answer. I think that employees should have a clear "value proposition", and while I don't think that an employee should spend a large fraction of their time describing that value, I don't think it's unreasonable for an employee (or their manager) to spend some time defining it.
I had a boss that was a bit this way. I kept a log of my activities (and the time associated) such that over 90% of my work day, each day, was accounted for. (I'm a combination of irritating jerk and overly literal, so I actually got that number over 95% for awhile.) I kept this up for a period of time, and met with him to discuss it. (Since I was a billable resource as well as being the in-house network administrator some large fraction of my time, which was billable, was already documented this way anyway.)
Had my boss been reasonable, I think that would've probably been enough. I would've updated the documentation on a recurring basis so that he had some idea of what I spent my time doing. For items that were a direct response to an issue, I logged my times and activities as I always did. For more "soft" items like training, conversations with co-workers, etc, I probably would have only revisited that time accounting once a quarter and produced some kind of "at a glance" view of how I spent my average day.
It ended up that I quit and started my own company, though, because (for a variety of reasons) my boss wasn't reasonable. That might not be for everybody, but it's suited me fine. >smile<
If your bosses are rational, I would think that the time and activity logs (which you really should be producing anyway and entering into whatever change control system you use) should be enough to justify your existence.
If your bosses end up being unreasonable you may want to look for greener pastures.

A: Take a weeks vacation, and tell your boss you're not arranging for a delegate to cover you.
Although, he's as likely to be even madder with you when you get back :)

A: tell him you spend each day taking proactive and preemptive actions to keep everything running fine
then whip out a list of the 1001 things you do each week to back this up - he'll shut up
then ask for a raise

A: Two pieces of advice:

*

*Make sure you and your boss are on
the same page about what your job
description is.  Ask him to define
what it is you are supposed to be
doing or ask what he thinks you
aren't doing.  If you are already
doing those things, explain them.

*Try to improve your social
relationship with your boss.  If he
likes you, he is more likely to give
you the benefit of the doubt and not
worry when he doesn't know
specifically what you are doing.

A: Talk to you boss, and try to get him to understand that the less he hears about you, the better you are doing your job.  My last review, my boss was extatic because he never has anyone calling him mentioning my name.  To him, that means I am doing my job, and it's one less thing he needs to worry about.

A: Establish a ticket-system, so your work gets documented and your boss can read
by himself, what you are doing all day.
Works quite well in my company.

A: Another use for all those monitoring & automation systems.  Forward him copies or screenshots of the backup report, the temperature monitoring, the uptime report, etc, etc - along with your notes on what needs to be done, or what steps you took as a result of your findings.  That might provide an easier way to get into the discussion about how these items can take up 5% or 200% of a working day, depending on severity.
These kinds of people view IT as overhead, an expense much like rent.  However, our job is far more like shooting at a target strapped to a buffalo, while we stand on a train with a monkey jumping on our heads.  It's not the same thing every day.  It's ever-changing, and you couldn't be sitting around bored collecting a paycheck for nothing if you tried.
That brings up a good point about availability, as well.  If you're a guy short in sales, you make fewer sales.  A guy short in accounting, um, the paperwork piles up?  A guy short in IT means that someone, or some department, or some business function throughout the company will not work.  This doesn't make the case for IT to sit around playing Doom all day, but it does explain why you don't have a skeleton crew, if you expect the rest of the business to avoid constant interruption.

A: Track your time for a a few weeks in detail. I was in the same boat. There's a Adobe Air app called Klok that makes it a bit easier to track and report once its setup. Track everything in minute detail, if you spend 30 mins in the morning reading overnight email alerts track it, on the flip side if your spend 2 hours a day getting coffee you need to know for your own info.
Best of luck.

A: i have the same problem with many clients, i now just choose to use a time tracking software that starts the clock stops the clock and allows me to describe the issue.
end of month i send out invoices with a granular list of all the activities and a pie chart of the division of projects. the pie chart helps isolate users that really really waste my time with lame issues.
best of luck.

A: First of all, do not swamp your boss in piles of details about every little thing that you do. It is a good idea to track all of that for your own personal information, but the boss should only be presented with summaries such as "resolved 18 logging issues".
You should try to have a face-to-face private meeting with your boss every month to review your job description, your planned activities (at a high level) and your personal development (training courses, reading books, reviewing serverfault postings for good ideas). If you do that, your boss will know what you do, your job description and planned activities will get his support. Also, if he decides that task X is not important, then when all hell breaks loose and you fix it, he will be happy, and probably praise your effort to senior management. You shouldn't tell anyone that the boss essentially created the issue in the first place, because this is common practice in office politics. In fact, the boss may have pushed down the priority of that task because he WANTED all hell to break loose, because he trusts you to fix it promptly, and because senior management is asking him why they should not fire him and his whole department.
Don't be anal about this. Track your work, summarise the work and the results of that work in plain English. Whenever you save money (compared to some alternative) or provide support to a revenue-earning activity, give that activity special notice. Things like "saved $x by configuring BIND on Internet-facing server" and "provided Widget application transaction volumes and average transaction times to sales team who won the Acme account".
In the world of business doing a good job technically, is not enough. You need to learn how to communicate what you have done and relate it to the health of the business. If you can't do that, then you may find yourself out of a job. That hurts you, and it could hurt your former colleagues if your job really was important to the business.

A: I would say do nothing. This boss sounds like he's shirking the key management responsibility of knowing what's going on, so the effort isn't worth it. Be happy you're doing the right thing, that's the most important view.


text:
Q: Query Param value is not set by Jersey ServletContext servletContext = request.getServletContext();
rd = servletContext.getRequestDispatcher("/rest/v1/code?param1=" + URLEncoder.encode(code, "UTF-8") + "&param2=" + value);
rd.forward(request, response);

When I directly invoke the uri "rest/v1/code" with param1 value as "dsk?text=sas" encoded input. I'm able to receive the param1 value in Jersey resource.
But dispatching via the above servlet resource, the query param values are set as null in Jersey resource.
This problem arises only when the param1 contains '?' as a part of input. Kindly help me resolve this problem.
@GET
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
public Response getResponse(@QueryParam("param1") String param1))

Note : Inside the jersey resource
String str = request.getQueryString(); gives me "text=sas";
the param1 value is not set, it is null
whereas request.getParameter("param1") gives me actual value ("dsk?text=sas")


text:
Q: Check if given date is available from multiple table I am working on online reservation system where customer will search for room available with time and number of people. My database table looks like this:
Table: Property

id
property_name
property_number

1
abc property
AB-123

2
def property
DF-343

property_number is unique field
Table: Rooms

id
Room Name
Capacity
property_number

1
Room one
150
AB-123

1
Room two
500
AB-123

2
Room one
500
DF-343

property_number is foreign key from table property
Table: Booking

id
property_number
room_id
book_status
book_start
book_end

1
AB-123
1
active
2021-06-06 10:00:00
2021-06-06 18:00:00

property_number is foreign key from table property
room_d is foreign key from table Room
book_status : completed, pending, running, cancelled. If booking status is completed or cancelled than user should be able to book.

User Search Field

*

*Reservation Date

*Reservation Start Time

*Reservation End Time

*Total no of People

*User Submits Specific Property Number

Solution Tried
$property = Property:::where('status','active')->where('property_number',$property_number)->firstOrFail();
$bookings = $property->bookings()
                        ->whereBetween('event_date_start',[$event_start,$event_end])
                        ->orWhereBetween('event_date_end',[$event_start,$event_end])
                        ->orWhere( function ( $query ) use ($event_start,$event_end) {
                            $query->where('event_date_start' , '<', $event_start)->where('event_date_end','>',$event_end);
                        })
                        ->get();

Model Structure
Table: **Property**
Class Property extends Model {
  public function bookings(){
    return $this->hasMany(Bookings::class,'property_number','property_number');
  }
  public function rooms(){
    return $this->hasMany(Rooms::class,'property_number','property_number');
  }
}
Table: **Rooms**
Class Rooms extends Model {
 public function property(){
   return $this->belongsTo(Property::class,'property_number','property_number');
 }

 public function bookings(){
   return $this->hasMany(Bookings::class,'room_id');
 }
}

Table: **Bookings**
Class Bookings extends Model {
}

This way it checks only property not every room associated with the property.

*

*How to check if any room is available for booking for provided property.*


text:
Q: Where do Powershell windows go when opened via a startup script? I have set up a task manager task to run a script on my VM startup which runs multiple commands needed to get my React app with an express/mongodb backend running. Does anyone know what happens to the Powershell windows which are opened because when I log in there is nothing on my desktop. I hope this makes sense below is the script I am running. Thank you.

start cmd.exe /k pm2 ls

TIMEOUT 30

start cmd.exe /k pm2 resurrect

TIMEOUT 30

cd C:\Users\devuser\Desktop\product_manager\product_manager

start cmd.exe /k serve -s build

PAUSE

A: You are not saying, how you set up the scheduled task.

1 - When the computer starts
or
2 - When I logon

I am assuming that because you said...

run a script on my VM startup

... it's item 1.
Unless you specifically start PowerShell with 'NoExit', then calling powershell.exe will run whatever code you tell it to then close when done.
powershell -noexit -file SomeScript.ps1

PowerShell command line options
PowerShell[.exe]
      [-PSConsoleFile  | -Version ]
      [-NoLogo]
      [-NoExit]
      [-Sta]
      [-Mta] ...
-NoExit
Does not exit after running startup commands.

Unless that code is still running when you logon, it's not supposed to be seen.  Doing this on startup, then the code is not tied to a user session and you can only see sessions you started.
Just curious though...
If you are using a Startup task, why do you want to see the powershell.exe console when you log on.


text:
Q: android app development-passing parameter to database I am trying to connect my app to database on localhost server.I can connect to it ut the problem is how to pass the parameter from app to php script.for eg i want all names having age less than 10 so i will pass the parameter to php.below is my code for connecting to database.please provide good reference
/*    */
enter code here
public class TestExternalDatabaseActivity extends Activity {
/** Called when the activity is first created. */

TextView resultView;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   StrictMode.enableDefaults(); //STRICT MODE ENABLED
   resultView = (TextView) findViewById(R.id.result);

    getData();
}
public void getData(){
    String result = "";
    InputStream isr = null;
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://localhost/tahseen0amin/php/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
}
catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
        resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        }
        isr.close();

        result=sb.toString();
}
catch(Exception e){
        Log.e("log_tag", "Error  converting result "+e.toString());
}

//parse json data

   try {
   String s = "";
   JSONArray jArray = new JSONArray(result);

   for(int i=0; i<jArray.length();i++){
       JSONObject json = jArray.getJSONObject(i);
       s = s +
               "Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
               "Age : "+json.getInt("Age")+"\n"+
               "Mobile Using : "+json.getString("Mobile")+"\n\n";
   }

   resultView.setText(s);

   } catch (Exception e) {
// TODO: handle exception
   Log.e("log_tag", "Error Parsing Data "+e.toString());
}

}

}


text:
Q: Why do X-wings change wing configuration? The X-wing fighters can change their wing configuration, from the X shape during battle to flat wings (the wings on the same side fold together) during FTL travel.
I'm guessing that the real world explanation is something like, "it looks cool". But what is the in-universe explanation?
There is no (little) resistance in space, so wing configuration wouldn't make that much difference. I can't see it making much change to performance, e.g. in angular momentum, either.

A: Those wings are called S-Foil

Historically, S-foils had been developed to address overheating issues on wing-based starfighters. Because of the proximity of engines and weapons systems to narrow wiring that fit inside the thin wings, an excess of heat could cause mechanical meltdowns that would be devastating to the capacity of the fighters to function.

also

They [X-wing] had two pairs of wing-like strike-foils, or S-foils, mounted at the rear of the craft on opposite sides. The foils on each side locked in place flush against each other; during combat, however, the foils were folded out to increase the spread coverage of the laser cannons mounted at the tips of the foils. This gave the craft its distinctive "X"-like appearance when viewed from the front or rear. The cannons on some earlier models could not be fired with the S-foils in locked position, perhaps as a safety feature. During hyperspace travel, the S-foils remained locked to conserve energy.
T-65 X-wing on starwars wikia.

A: I'm seeing some suggestions about increased maneuverability. Well... no good can really come of applying real-world science to Star Wars. Case in point, get ready to fall asleep:
Aerodynamically speaking, the change in configuration would have a negligible effect on maneuverability or, if anything, could make the X-wing LESS maneuverable when flying in an atmosphere. In sciency terms, maneuverability is the inverse of stability; if a plane is more stable, it's less maneuverable, and vice versa.
So first we look at the TOP wings. If we look at the design of most real-world private and commercial airplanes, the wings are constructed with a slight upward angle--referred to as "dihedral"--when viewed from the front. This is the greatest contributor to stability on the roll axis of an airplane because the inward tilt of each wing's lift vector tends to roll the plane back to a wings-level attitude.
Next look at the bottom wings. Since someone's already mentioned the Harrier, let's use that: The Harrier's wings are built with a heavy downward angle--or "anhedral." This makes the aircraft extremely maneuverable, which implies a huge loss of stability due to the outward cant of the lift vectors.
The result seems like an equal and opposite effect on maneuverability: the dihedral top wings negate the effect of the anhedral bottom wings, leaving us with an unchanged situation.
BUT--without jumping too far down yet another aerodynamic rabbit hole--the addition of another wing plane adds a complication suffered by real-world biplanes, in which the top wing tends to undermine the lift of the bottom wing, leading in THIS case to a net increase in stability--in other words, a net decrease in maneuverability.
Ergo, under the shackles of real-world science, the change in wing configuration has, at best, no effect, and at worst, a negative effect on the X-wing's maneuverability. Best to just drink the koolaid.

A: For an in-world explanation, I would posit the theory that the wings close for normal travel and hyperspace for the purpose of strength and stability in the wings and they open during combat for two reasons.  First is that by spreading the blasters apart they give it a greater field of fire and greater chance of hitting the enemy.  Second, by moving the engines a bit further apart it could aid in making the craft more maneuverable and better able to change its angle of attack with less thrust.

A: I've read that the closed position was required for atmospheric flight.
The Z-95 was the X-Wing's precursor.  There were likely many design choices in the Z-95 that made it cheaper to design the X-Wing as a transformer then to redesign it from scratch.

A: The reason may be for accuracy. According to the X-wing series by Michael A. Stackpole, the weapons are calibrated to a certain distance (usually a few hundred meters). It seems to me that it would be most effective for these four blasters not to fire in two closely grouped pairs, but to be more spread out.
Additionally, the purpose of the wings coming together likely makes atmospheric flight easier (more airplane-like), so the reason for them being separate in attack position may be less significant than the reason for them being together in standard flight mode.

A: Landing? As they are never shown flying in the atmosphere in a lift generating motion. They seem to take off more like a harrier(with endless fuel). So never any need for them to generate lift. Pretty good question. I think the model builders just came up with something cool and lucas said ok.

A: Wings closed: all energy to engines, weapon capacitors empty and cool. Wings being closed is for landing and storage purposes as well, and maybe wings closing when weapons are disabled is an automatic feature e.g 'Navigation mode' usually engaged prior to landing/docking.
Wings open: provides cooling for weapons energy capacitors which are stored in the wings, the capacitors and Taim&Bak lasers produce massive amounts of heat so both the weapons and capacitors are kept at a distance from each other to better dissipate heat and radiation.
Since the X-wing didn't see combat every time it flew, its wings remained mostly in closed position, seldomly activated for combat.
How's that for a theory?

A: In real aerial dog fights, the wing cannons of an aircraft are calibrated to have the bullet´s trajectory converge at a certain distance before the aircraft. This is where the ideal shooting distance is indicated in the gunsight. Moving the guns further apart in fighting configuration gives the engineers a wider range to tilt the guns to form a firing cone.
From a movie makers point of view, unfolding the wings to attack gives the spaceship a more menacing, warlike appearance, similar to a japanese judoka assuming fighting stance.


text:
Q: Why don't iframes in different div element work? Fiddle

Why is it that only one of the iframes will work at the same time? Is something wrong with my javascript?
function test(){
    document.getElementById('src1').src='http://cnn.com/'
}
function test1(){
    document.getElementById('src2').src='http://stackoverflow.com/'
}

test();
test1();

A: It does work, it's just stackoverflow which is preventing you to embed it's URL in an iframe for security reasons ...
You may see, even Google prevents an user to embed the google URL to be used in an iframe
function test1(){ //Alter the URL in this function
    document.getElementById('src2').src='https://stackoverflow.com/'
}

Demo
Prevent iframe stealing

A: It's not because there are two iframes it's because stackoverflow has a special header:
X-Frame-Options set to SAMEORIGIN
that header prevents the browser to render the page inside an iframe
read more here:
X-Frame-Options


text:
Q: Opendaylight Export/Import using Daexim doesnt transition to "Complete" state We are performing online export/import using "Daexim". We are scheduling export job and checking its status using
http://<controller-ip>:<restconf-port>/restconf/operations/data-export-import:status-export

This URL used to return "complete" status till "Boron", but in Nitrogen we observed the state transitions from "scheduled" -> "in-progress" -> "initial". We are not getting "complete" state after "in-progress".
Please let us know how to identify the status of export/import job.
Export URL
https://<odl-node>/restconf/operations/data-export-import:schedule-export/

Payload
{
   "input": {
     "data-export-import:run-at": 500
   }
}

A: This most probably indicates that the import failed, for whatever reason.  have you checked the karaf.log for any ERROR related log entries in general, and specifically anything that looks like it could provide you details about what could have failed during the import?
BTW you can get more direct developer support on the mailing list of ODL's daexim project on https://lists.opendaylight.org/mailman/listinfo/daexim-dev.


text:
Q: Generating images of 3D array from any point of view I have a 3D array representing a 3D object (x,y,z). The values stored in the array are RGB colors. Is it possible to generate an image of the object from any given point of view?

A: That is certainly possible. The keywords here are transformation and projection, basically you define a point for every (3D) Pixel inside your array. Then you multiply all the points with a bunch of matrices and get a 2-dimensional result.
Here is an article about how OpenGL does it's transformations:
http://www.songho.ca/opengl/gl_projectionmatrix.html
You could mimic the whole pipeline in C++ to produce a bitmap on your CPU or use OpenGL directly which would be a thousand times faster. When using OpenGL you could also view your model in realtime from all sides, but that would essentially be a full 3D-Application.


text:
Q: Splice Function in Javascript is adding 4 empty rows to my array? I want to remove all the rows whose length is less than some value. I'am using Splice function in javascript to do this.
for (var i = 0; i < table.length; i++) {

    if (table[i].length<=6) {
         table.splice(i, 1);
    }
}

but two  rows with length:0 are being added at the beginning and at the end of my array  this is the actual array
extra rows added after being spliced
whis is this happening?
how can i get rid of it?

A: I suggest to splice from the end to start, because if an element is spliced, the following elements are move a place in front of the array.

var table = [
        [0, 1, 2, 3, 4, 5],
        [],
        [0],
        [],
        [],
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
        [0, 1, 2, 3, 4, 5, 6, 7],
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        [0, 1, 2, 3, 4, 5, 6, 7, 8],
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        [0],
        [0],
        [],
        [],
        [1]
    ],
    i = table.length;

while (i--) {
    if (table[i].length <= 6) {
        table.splice(i, 1);
    }
}

console.log(table);

A: Try with this:
for (var i = 0; i < table.length; i++) {

    if (table[i].length<=6) {
        table.splice(i, 1);
        i--;
    }
}

After deleting a row you have to decrease the index to the array because the elements of the array have been shifted by the precious removal.


text:
Q: Powershell script that looks for processes and returns process, computername and username I'd like to search through ten terminal servers after users that are running a specific program. I want the output to include process, computername and user.
This command basically does what I want:
Invoke-Command -ComputerName (Get-Content .\test-servers.txt) -ScriptBlock { get-wmiobject win32_process|where{$_.name -eq "iexplore.exe" }|select name, __SERVER,@{n="owner";e={$_.getowner().user}}} | Format-Table name, PSComputerName, owner -AutoSize

name         PSComputerName owner
----         -------------- -----
iexplore.exe mrdsh-test     dojo03
iexplore.exe mrdsh-test     dojo03
iexplore.exe mrdsh-test     baob12
iexplore.exe mrdsh-test     baob12

But when I try to create a script which takes the process as a parameter I can't get it to work.
CmdletBinding()]
Param (
[parameter(mandatory=$true)][string]$process
)

Invoke-Command -ComputerName (Get-Content .\test-servers.txt) -ScriptBlock { get-wmiobject win32_process | where{param($process)$_.name  -eq $process } | select name, __SERVER,@{n="owner";e={$_.getowner().user}}} | Format-Table name, PSComputerName, owner -AutoSize

I haven't managed to send the $process parameter to the server that's invoking the command. How to I do that? Or is there an easier way to look for processes and return process, computername and username?

A: You have param($process) in your where scriptblock, and you don't set it, so it will be empty.
Edit:
As requested, taking param out the following works on my machine:
[CmdletBinding()]
Param (
[parameter(mandatory=$true)][string]$process
)

Invoke-Command -ScriptBlock { get-wmiobject win32_process | where{ $_.name  -eq $process } | select name, __SERVER,@{n="owner";e={$_.getowner().user}}} | Format-Table name, PSComputerName, owner -AutoSize

It also works in Powershell version 1:
powershell -version 1.0 -noprofile -Command ".\test.ps1 -process 'chrome.exe'"

works just fine.


text:
Q: Modbus4J Modbus RTU master Currently I am working with the Schneider Power Logic electrical device. I want to read the data from the device and show the value in my system. So far, I discover J2mod, Jamod and Modbus4Java library. I used all modbus4java to connect and get the device's data.
Actually I still confuse whether I suppose to create Master side or Slave side. Based on my understanding, the device will be Slave and my system will be Master (1st question).
Below is the setting AT MY DEVICE. It indicate that the device in slave mode and its protocol is Modbus RTU. So, I need to create a master apps to communicate with it right which is using the ModbusRTU protocol right ? (2nd question)

*

*Mode: Slave

*Protocol: Modbus RTU

*Address: 1

*Baud Rate: 38400

*Parity: None

Below is the code of my apps act as the Master and using the ModbusRTU protocol
public static void main(String[] args) throws ModbusTransportException, ErrorResponseException {
    ModbusFactory factory = new ModbusFactory();

    SerialParameters params = new SerialParameters();
    params.setCommPortId("COM6");
    params.setBaudRate(9600);
    params.setDataBits(8);
    params.setStopBits(1);
    params.setParity(0);

    ModbusMaster master = factory.createRtuMaster(params);

    master.setTimeout(1000);
    master.setRetries(0);
    long start = System.currentTimeMillis();

    try {
        master.init();
    } catch (Exception e) {
        System.out.println( "Modbus Master Init Error: " + e.getMessage());
          return;
    }

    try {
        System.out.println("Reg. 1001 Value:" + master.getValue(1, RegisterRange.HOLDING_REGISTER, 3110, DataType.FOUR_BYTE_FLOAT_SWAPPED));
    }
    finally {
        master.destroy();
    }

    System.out.println("Time elapsed: " + (System.currentTimeMillis() - start) + "ms");
}

This is the code that I get from the sample code provide by the Modbus4Java page. The other thing that concern me is the value of params.setCommPortId("COM6"); What other value than "COM6" that I can put there. Because basically it receive a String value. So am I able to put any String value to it ? And what is the function of this particular setCommPortID. (3rd question)
Looking at the sample code provide by the Modbus4Java page, it does not put the IP address of the device. But in my case, my device got an IP address. And the IP address only use in the Slave apps only. How should my system recognize the IP address of the device ? (4th question).
And after I run this code snippet, I got an error:
    Stable Library
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7
Modbus Master Init Error: com.serotonin.io.serial.SerialPortException: gnu.io.NoSuchPortException
Please, please and please help me. I been stuck with this almost a month. Really hope someone out there will be able to help me. Thank you in advance for any kind of help and suggestion.

A: I'm the maintainer for j2mod, so my answer is going to suggest you look at the test programs which are included with j2mod.  You can find j2mod on SourceForge at this URL --
https://sourceforge.net/projects/j2mod/
I'm pretty good about answering questions there, but I also follow stackoverflow, so I can explain more here as well.  There are a LOT of questions in here, so I apologize in advance if I've missed anything.
The Schneider device is the slave, or "server" and your application is the master or "client".  Modbus is a master/slave protocol, with the master initiating all requests.  Your application will be the master and responsible for making all requests of your device.
The exact communications will be provided by the device documentation.  In this instance, you indicate that the device uses 38400 baud, and so forth.  Those are the parameters you will use to update SerialParameters with the RXTX library (which just so happens to also be used by j2mod).
The value passed to setCommPortId() is the Windows COM port identifier - you should be able to pass any value which is associated with an actual COM port -- "COM1", "COM2", etc.  Note that some USB converters change their COM port each time they are used, so you may be chasing port names.
You mentioned that your device also has an IP address.  You cannot use the RTU classes and methods to access a Modbus/TCP device.  The same is true for jamod and j2mod - most Modbus libraries have different classes for RTU and TCP transports (as well as ASCII and UDP, for libraries which support those other transports).


text:
Q: python multiprocessing pipe poll bug Using pipes for process communication with the multiprocessing library I noticed some strange behaviour of the poll function. If I close the other end of the pipe poll() returns true which is kind of odd. The python docs dont really tell what to expect. Still I was thinking poll() would at least return false if there is definitely nothing in the pipe and the other end is even closed. I use python3.3.2 but it seems to be the same for python 2.7.5. Is this intended or a bug and if it´s not a bug what is it good for?
import multiprocessing

if __name__ == '__main__':

    con = multiprocessing.Pipe(True)
    con1, con2 = con

    print(str(con1.poll())) #prints False
    con2.close()
    con1.close()

    con = multiprocessing.Pipe(True)
    con1, con2 = con

    con2.close()
    print(str(con1.poll())) #prints True
    con1.close()

A: I don't think this is a bug. I agree, the documentation is not clear in this respect, but there are several reasons why this behavior should be expected, and the opposite would cause more harm than good:

*

*other functions of the same name in different contexts, like the system call poll on sockets/file descriptors, do the same; closing the other end is an event on the pipe, so poll should indicate there is something to be done on this side too

*returning True from the method can be understand as saying that subsequent recv will not block - exactly the case here

*calling poll with a non-zero timeout or with None would mean blocking even when there is nothing to wait for, when the other side has closed.

Also note that there would be no good means of detecting that the other end closed, if poll returned False.


text:
Q: How to evaluate length of side of triangle I came across the following question whilst preparing for the GRE exam, where only a basic calculator with no trigonometric functions is allowed.

The question asks which quantity is bigger, the length AC or the value 3.
Is there a way I can answer this question without explicitly computing the value of any trigonometric function.

A: Call the base of the vertical line D.  BCD is half an equilateral triangle, so  $CD=1$.  BD is less than $2$ (it is $\sqrt 3$, which you can find from Pythagoras, but we don't need that.)  ABD is an isosceles triangle, so $AD=BD$ and is less than $2$.  Therefore $AC \lt 3$

A: This question expects you to already know the properties of two types of triangles.
First, let the intersection of AC and the altitude of triangle ABC be called point D.

*

*In a 30-60-90 triangle, the side lengths are in the ratio 1:$\sqrt{3}$:2
Since we are given that BC=2, BD=$\sqrt{3}$ and DC=1

*In a 45-45-90 triangle, the side lengths are in the ratio 1:1:$\sqrt{2}$
Since we have determined that BD=$\sqrt{3}$, AD=$\sqrt{3}$ as well (and    AB=$\sqrt{6}$).
Lastly, since we know AD+DC=AC
AC=1+$\sqrt{3}$
Since 3 = 1+2 = 1+$\sqrt{4}$, we can conclude that 3 > AC


text:
Q: Android:Cache Validity for an Image using coil in jetpack I am facing issue in setting validity for Cache in android jetpack using coil.
What I Need: In Android Jetpack compose, I need to download an SVG image from the Url and store it to the cache. But the cache should store the image only for 20 seconds. so within the 20 seconds, there should not be any further image request. For this 20 seconds, the image should display from the cache. After 20 seconds, I want the image, should get cleared from the cache.
What's the problem I am facing: The image is not getting cleared from the cache even after 20 seconds. I am using Coil for the jetpack compose jetpack coil and  Jetpack header for Cachecontrol
Thanks in Advance....
In Application Class, I created a single instance ImageLoader
val imageLoader = ImageLoader.Builder(applicationContext)
            .componentRegistry {
                add(SvgDecoder(applicationContext))
            }
            .okHttpClient {
                OkHttpClient.Builder()
                        .cache(CoilUtils.createDefaultCache(applicationContext))
                        .addNetworkInterceptor(provideCacheInterceptor(10))
                        .build()

            }
            .memoryCachePolicy(CachePolicy.DISABLED)
            .diskCachePolicy(CachePolicy.ENABLED)
            .build()

    Coil.setImageLoader(imageLoader = imageLoader)

In Moment.class:
val singleInstanceImageLoader = context.imageLoader
val imageRequest = ImageRequest.Builder(context)
                .data(decodedURL)
                .memoryCachePolicy(CachePolicy.DISABLED)
                .diskCachePolicy(CachePolicy.ENABLED)
               .addHeader("Cache-Control", "max-age=20,public")
               .build()

        val imagePainter = rememberCoilPainter(
                request = imageRequest,
                imageLoader = singleInstanceImageLoader
        )

        Image(
                painter = imagePainter,
                contentDescription = null,
                modifier = Modifier
                        .wrapContentSize(Alignment.Center)
                        .padding(0.dp, 15.dp, 0.dp, 15.dp)

        )

A: I got a reply from coil:

This isn't a bug. Looking at your code, you're setting the
cache-control header for the request. You need to set it for the
response using a network interceptor.

But I tried this approach and it also didn't work.
Hope this might be useful for someone else though.


text:
Q: How to sort by date but based on day (floored day) in mongoose (node.js) The goal is to sort by date but floored to nearest day as I'm also sorting by user votes. Basically, to sort by day and highest votes so the most votes for the day come up.

A: Pretty sure you need to store both the precise date and a pre-floored date in your mongodb data and then sort by the pre-floored one. You will see this pattern a lot for doing case-insensitive search on string fields as well. With mongoose, you can use a pre-save hook to automatically set the pre-floored date based on the precise date. Once the data is there, the sorting part just works normally.


text:
Q: Shortening if statement with repetition Below are some if statements for passing the pilot of a robot the correct directions based on where he in on a map and what direction he's facing.
There a bit if repetition, but when i tried to combine conditionals the program stopped working.
Any tips for shortening this?
        int changeX= x-lowest.getX();
        int changeY= y-lowest.getY();
        if(changeX!=0){
            System.out.println("x changed");
            if(changeX<0 && robot.getFacing()== 'N'){
                robot.checkDirection('L','W');
            }
            else if(changeX<0 && robot.getFacing()== 'W'){
                robot.checkDirection('L','W');
            }else if(changeX<0 && robot.getFacing()== 'S'){
                robot.checkDirection('R','W');
            }else if(changeX<0 && robot.getFacing()== 'E'){
                robot.checkDirection('R','W');
            }else if (changeX>0 && robot.getFacing()== 'S'){
                robot.checkDirection('L','E');
            }else if (changeX>0 && robot.getFacing()== 'E'){
                robot.checkDirection('L','E');
            }else{
                robot.checkDirection('R', 'E');
            }
        }else{
            System.out.println("y changed");
            if(changeY<0 && robot.getFacing()== 'N'){
                robot.checkDirection('L','S');
            }else if(changeY<0 && robot.getFacing()== 'W'){
                robot.checkDirection('L','S');
            }else if(changeY<0 && robot.getFacing()== 'E'){
            robot.checkDirection('R','S');
            }else if(changeY<0 && robot.getFacing()== 'S'){
                robot.checkDirection('R','S');
            }else if (changeY>0 && robot.getFacing()== 'S'){
            robot.checkDirection('L','N');
            }else if (changeY>0 && robot.getFacing()== 'E'){
                robot.checkDirection('L','N');
            }else{
                robot.checkDirection('R','N');
            }
        }
        //change the current cell and the x/y
        currentCell = lowest;
        x=lowest.getX();
        y=lowest.getY();

        if(goal()){
            moving=false;
            System.out.println("Goal Achieved!");
        }
    }
}

A: As a start, you can at least extract the robot.getFacing() call so you're not repeating it.  Then you can combine some of the statements with ||:
String facingDirection = robot.getFacing();

if (changeX != 0){
    System.out.println("x changed");

    if(changeX<0 && (facingDirection == 'N' || facingDirection == 'W')) {
        robot.checkDirection('L','W');
    }else if(changeX<0 && (facingDirection == 'S' || facingDirection == 'E')) {
        robot.checkDirection('R','W');
    }else if (changeX>0 && (facingDirection == 'S' || facingDirection == 'E')) {
        robot.checkDirection('L','E');
    }else{
        robot.checkDirection('R', 'E');
    }
} else {
    System.out.println("y changed");

    if(changeY<0 && (facingDirection== 'N' || facingDirection== 'W')) {
        robot.checkDirection('L','S');
    }else if(changeY<0 && (facingDirection== 'E' || facingDirection== 'S')) {
        robot.checkDirection('R','S');
    }else if (changeY>0 && (facingDirection== 'S' || facingDirection== 'E')) {
        robot.checkDirection('L','N');
    }else{
        robot.checkDirection('R','N');
    }
}

If you wanted to take it a step further, you could extract the parameters (eg 'R', and 'N') into two separate variables, and then set them all at the end, as well.  This would reveal some possible patterns in your data, as well as reduce the duplication of the checkDirection calls.

A:

*

*Instead of if-else use if statements to determine the specific direction.

*Also, since you have two options for every direction 'N', 'E', 'W', 'S' have a condition for the direction and then check the x>0 or x<0

Example;
if(changeX!=0){
    if(getDirection() == 'N'){
          if(x>=getX()){
               System.out.println("N Direction");
          }else{
               System.out.println("S Direction");
          }
    }

    // for East
     if(getDirection() == 'E'){
          if(x>=getX()){
               System.out.println("N Direction");
          }else{
               System.out.println("S Direction");
          }
    }

    // for West
    ..........
    ..........

    // for South
    ..........
    ..........
}

// Here you remove the if-else since this will be
// more clear and maintainable.
// If you have a huge logic, in if(){} by the time you come to else,
// you need not go back to check what was the if condition.
// One more benefit of this is if they are isolated, and independent task, you
// can encapsulate the logic in a method.

if(changeY!=0){
    if(getDirection() == 'N'){
          if(x>=getX()){
               System.out.println("N Direction");
          }else{
               System.out.println("S Direction");
          }
    }

    // for East
     if(getDirection() == 'E'){
          if(x>=getX()){
               System.out.println("N Direction");
          }else{
               System.out.println("S Direction");
          }
    }

    // for West
    ..........
    ..........

    // for South
    ..........
    ..........
}

A: I would create some kind of easy-to-read-and-modify configuration and use it, without the if statements.
A quick example just to ilustrate the concept:
    Map<ConfigKey, Pair<Character, Character>> config = new HashMap<ConfigKey, Pair<Character, Character>>();
    config.put(new ConfigKey("X", "DEC", "NW"), Pair.of('L', 'W'));
    config.put(new ConfigKey("X", "DEC", "ES"), Pair.of('R', 'W'));
    config.put(new ConfigKey("X", "INC", "NW"), Pair.of('R', 'E'));
    config.put(new ConfigKey("X", "INC", "ES"), Pair.of('L', 'E'));

    config.put(new ConfigKey("Y", "DEC", "NW"), Pair.of('L', 'S'));
    config.put(new ConfigKey("Y", "DEC", "ES"), Pair.of('R', 'S'));
    config.put(new ConfigKey("Y", "INC", "NW"), Pair.of('R', 'N'));
    config.put(new ConfigKey("Y", "INC", "ES"), Pair.of('L', 'N'));

    String axis   = (changeX != 0) ? "X" : "Y";
    int change    = (changeX != 0) ? changeX : changeY;
    String incDec = (change   > 0) ? "INC" : "DEC";
    String direction = (Arrays.asList('N','W').contains(facingDirection)) ? "NW" : "ES";

    Pair<Character, Character> result = config.get(new ConfigKey(axis, incDec, direction));
    robot.checkDirection(result.getLeft(), result.getRight());


text:
Q: Is there a way to programmatically set an interface MTU using C in Linux? At the moment my program is making a system() call to ifconfig to do this.
It seems a bit messy - maybe ifconfig is not on the path, or in some non-standard location. And then I'd need to check for the iproute2 equivalent in case of failure.
Is there a way to set this programmatically using C?

A: You can set the SIOCSIFMTU field in an ioctl call, something like this:
struct ifreq ifr;
ifr.ifr_addr.sa_family = AF_INET;//address family
strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name));//interface name where you want to set the MTU
ifr.ifr_mtu = 9100; //your MTU size here
if (ioctl(sockfd, SIOCSIFMTU, (caddr_t)&ifr) < 0)
  //failed to set MTU. handle error.

The above code will set the MTU of a device(as in ifr.name) using ifr_mtu field in the ifreq structure.
Refer: http://linux.die.net/man/7/netdevice

A: You can also use netlink. The full example:
#include <stdio.h>
#include <string.h>
#include <net/if.h>
#include <sys/socket.h>
#include <linux/rtnetlink.h>

#define IFACE_NAME "enp5s0"

int main(void) {
     int ret, nl_sock;
     unsigned int mtu = 8000;
     struct rtattr  *rta;
     struct {
          struct nlmsghdr nh;
          struct ifinfomsg  ifinfo;
          char   attrbuf[512];
     } req;

     nl_sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
     if(nl_sock < 0) {
          perror("socket():");
          return -1;
     }

     memset(&req, 0, sizeof req);
     req.nh.nlmsg_len   = NLMSG_LENGTH(sizeof(struct ifinfomsg));
     req.nh.nlmsg_flags = NLM_F_REQUEST;
     req.nh.nlmsg_type  = RTM_NEWLINK; // RTM_SETLINK
     req.ifinfo.ifi_family = AF_UNSPEC;
     req.ifinfo.ifi_index  = if_nametoindex(IFACE_NAME);
     if(!req.ifinfo.ifi_index) {
          perror("if_nametoindex():");
          return -1;
     }
     printf("%s index: %d\n", IFACE_NAME, req.ifinfo.ifi_index);
     req.ifinfo.ifi_change = 0xffffffff;
     rta = (struct rtattr *)(((char *) &req) + NLMSG_ALIGN(req.nh.nlmsg_len));
     rta->rta_type = IFLA_MTU;
     rta->rta_len = RTA_LENGTH(sizeof(unsigned int));
     req.nh.nlmsg_len = NLMSG_ALIGN(req.nh.nlmsg_len) + RTA_LENGTH(sizeof mtu);
     memcpy(RTA_DATA(rta), &mtu, sizeof mtu);

     ret = send(nl_sock, &req, req.nh.nlmsg_len, 0);
     if(ret < 0) {
          perror("send():");
          return -1;
     }

     return 0;
}

Also read: rtnetlink(3), rtnetlink(7)


text:
Q: why RestTemplate cannot be auto-wired without specifying the bean creation configuration I did not find reason as to why spring provided this approach. is it because, we can configure rest template as per application requirement, like setting up timeout...etc. then give it to spring? if not why ?

A: Clearly justified in the documentation

Since RestTemplate instances often need to be customized before being used, Spring Boot does not provide any single auto-configured RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder which can be used to create RestTemplate instances when needed


text:
Q: How to custom value of Form Field in AntD? I am handling Form.Item with Ant Design, everything works fine, however I want to custom the value of Form.Item like below code example:
  const onFinish = (values) => {
    console.log('Values received:', values);

    /*

      Normally we would get the result like:
      {
        email: 'abc@gmail.com'
      }

      ===================================================

      But as expected, when user input an email
      i want to get the result directly with object format like this:
      {
        email: { email: 'abc@gmail.com', rule: 'user' }
      }

    */
  };

  return (
    <Form
      name="user_information"
      onFinish={onFinish}
    >
      <Form.Item
        label="Email"
        name="email"
        rules={[
          {
            required: true,
            message: 'Your email cannot be empty!',
          },
        ]}
      >
        <Input placeholder="Enter your email" />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit">
          Update now
        </Button>
      </Form.Item>
    </Form>
  );

I tried providing value prop to <Input /> component but it not works.
So what does I need to provide to  Form.Itemor Input to solve the above problem?
Thanks!

A: Antd Form gives us the values when submitting the form of all the form control inputs in the form of the object where the key would be the name of the form control inputs and value would be the value given by the user.
The best practice which I know about is that we should never change the input values before submitting the form manually otherwise our form may show unexpected behavior which we can't figure out.
However, if you want to do a post request with a payload of data that is slightly different than the form values, then you can modify the form data before submitting the request.

const [formValues, setFormValues] = useState()

const onFinish = (values) => {
  console.log("Values received:", values);

  // modify the form value here
  // remember don't change `values`, preserve the form value in some other variable or state.
  const keys = Object.keys(changedValues);

  let newValues = { [keys[0]]: { [keys[0]]: changedValues[keys[0]]} }

  console.log(newValues);

};

return (
  <Form name="user_information" onFinish={onFinish}>
    <Form.Item
      label="Email"
      name="email"
      rules={[
        {
          required: true,
          message: "Your email cannot be empty!",
        },
      ]}
    >
      <Input placeholder="Enter your email" />
    </Form.Item>

    <Form.Item>
      <Button type="primary" htmlType="submit">
        Update now
      </Button>
    </Form.Item>
  </Form>
);


text:
Q: Start and end dates of time periods defined by a column in a data frame I have a database of hourly data organized in rows and would like to reshape it in such as way as to obtain the start and end times when the data are within a certain criteria
Consider the following case example, one column is the sequential hourly times, and in the second column is the dummy variable data.
Yrs=  data.frame(Date=seq(as.POSIXct("2019-02-04 01:00:00",tz="UTC"), as.POSIXct("2019-02-04 23:00:00",tz="UTC"), by="hour"))
Yrs$Var=c(1:12,1:11)

I would like to obtain the start and end dates of the period in which the Variable was between say 3 and 7.
Expected result:
StartDate               EndDate
2019-02-04 03:00:00     2019-02-04 07:00:00
2019-02-04 15:00:00     2019-02-04 19:00:00

I figure I can create a new column indicating the rows where the criteria is met, but do not know how to get the start and end of those consecutive periods
Yrs$Period= ifelse(Yrs$Var >= 3 & Yrs$Var <=7, 1, 0)

I found a reverse example to this problem here Given start date and end date, reshape/expand data for each day between (each day on a row)
but I am struggling to figure this out. Any help will be greatly appreciated.

A: Maybe something like:
library(data.table)
setDT(Yrs)[, .(StartDate=Date[Var==3L], EndDate=Date[Var==7L]),
    by=.(c(0L, cumsum(diff(Var) < 1L)))][, -1L]

output:
             StartDate             EndDate
1: 2019-02-04 03:00:00 2019-02-04 07:00:00
2: 2019-02-04 15:00:00 2019-02-04 19:00:00

A: Why not filter and spread ?
library(dplyr)

Yrs %>%
  filter(Var == 3 | Var == 7) %>%
  group_by(Var) %>%
  mutate(ind = row_number()) %>%
  spread(Var, Date) %>%
  select(-ind) %>%
  rename_all(funs(c("Start_Date", "End_Date")))

#  Start_Date          End_Date
#  <dttm>              <dttm>
#1 2019-02-04 03:00:00 2019-02-04 07:00:00
#2 2019-02-04 15:00:00 2019-02-04 19:00:00


text:
Q: wysiwyg inline markup editor? What I mean by this is something a bit like the stackoverflow markup editor (type markup with realtime rendering) but in a single element, as opposed to having a second window.
This would let the user type "[[blahblah]]" and the text would get swapped out for a link to /blahblah. If the user hits backspace, the link should change back to "[[blahblah]". This is a fairly basic use case, I have a few more interesting uses for such a library.
I can imagine writing some editor which redirects keystrokes to a textarea, then re-renders to an overlay after each keystroke, and re-positions the caret on the overlay, but it sounds pretty fiddly! Is there some library that does this, where you define a simple grammar and it does the rest?
edit:

A: I was looking for something like this:
http://podio.github.io/jquery-mentions-input/


text:
Q: Why can a script with a "#!/bin/sh" shebang use bash-only features? When I run the following script :
#!/bin/sh

declare path="my.path"

if [[ "$path" =~ \. ]] ; then
    echo "yes"
else
    echo "no"
fi

I got yes printed.
But if I am not mistaken, declare and [[ ]] are not available in POSIX shell ; so how come this script does not throw any error ?
I run the script on git for Windows, could it explain this odd behavior ?

A: /bin/sh is a link to your actual shell. It does not mean that you are running pure POSIX. The Git for windows homepage makes very clear that you are running bash, as does your git-bash tag.
Even on Linux, /bin/sh can still be bash:
ls -la /bin/sh
lrwxrwxrwx. 1 root root 4 Mar 27 09:33 /bin/sh -> bash


text:
Q: Behavior of a gradient system Let $\frac{d}{dt}(x,y) = -\nabla g(x,y)$ be a planar system, where $g(x,y)=x^{2}y^{4}$. Show that for $t \to \infty$, $\Phi(t,(x,y))\to 0$ for all $(x,y)\in \mathbb{R}^{2}$ \ $(\{x=0\} \cup \{y=0\})$.
Al right, what I've tried is:
lets write this as a system,
$\dot x = -2xy^{4}$
$\dot y = -4x^{2}y^{3}$
Is it enough to consider the Lyapunov function $V(x,y)=x^{2}+y^{2}$ for $(x,y)=(0,0)$ to say that all trajectories converge to $0$ for all $(x,y)\in \mathbb{R}^{2}$ \ $(\{x=0\} \cup \{y=0\})$ when $t\to \infty$? (I guess that $\Phi(t,(x,y))$ is the function for trajectories given certain $t$ and certain $(x,y)$, but not so sure really).

A: EDIT:
I have noticed it later, sorry for that. But the time derivative of the $V$ in this answer is not negative definite, it is negative semi-definite (i.e. zero also on coordinate axes) and in fact when I plot the phase plot of the system, not all the initial points converge to origin. So the claim in the question is wrong, not all the initial conditions except the ones on coordinate axes converge to origin.
We define a function on $(x,y)$ plane $V(x,y) = x^2+y^2$. This function has positive value everywhere in $(x,y)$ plane except at the origin $(x,y)=(0,0)$, where it is zero. Then we find the time derivative of $V$:
$\frac{dV}{dt} = \frac{\partial V}{\partial x} \frac{dx}{dt} + \frac{\partial V}{\partial y} \frac{dy}{dt} = 2x(-2xy^4) + 2y(-4x^2y^3) = -4x^2y^4 -8x^2y^4$
which is negative everywhere on the (x,y) plane except at the origin and on the coordinate axes(x=0 or y=0) where it is zero.
Now, $V$ is positive everywhere except at origin and it's time derivative is negative everywhere except at the coordinate axes and the origin meaning it will decrease all the time if it is not at the origin. Therefore whichever $(x_0,y_0)$ you choose which is not on the coordinate axes (x or y or both are zero), $V$ is going to decrease towards origin as time goes to infinity and the corresponding $(x,y)$ pair will converge to origin.
To analyze the case when $x=0$ or $y=0$, note that in that case both derivative of $x$ and $y$ are both zero, and so it will remain there forever.

A: We can find a first integral $F(x, y)$ for the system by solving $\nabla F \cdot \nabla g = 0$. When $g = X(x) Y(y)$, a solution is
$$F = \int \frac Y {Y'} dy - \int \frac X {X'} dx.$$
Now since $y^2 - 2 x^2$ is a first integral, a trajectory that doesn't start on the lines $y^2 - 2x^2 = 0$ cannot converge to the origin.


text:
Q: Float in csv file with awk I have one column like that in my csv :
Last Mont Evolution (%)
0.00%
4.35%
4.17%
0.00%
7.29%
6.21%
4.10%
0.00%
-0.03%
2.78%
2.46%
-1.09%
19.18%
12.32%

I want to extract values higher than 4%, so I do this :
awk '$1>4 {print $1}' file.csv | sort -r -n

The output is : 7.29% 6.21% 4.35% 4.17% 4.10%
But where are the values 19.18% and 12.32% ?
Can you help me ?

A: Because of the percent sign, you are dealing with strings.  Tell awk and sort to use percent as a delimiter and everything works:
awk -F% '$1>4 {print $1}' file.csv | sort -t% -r -n

Output:
19.18
12.32
7.29
6.21
4.35
4.17
4.10

A: You don't have to do the -F%, you can let awk "convert" your strings to numbers:
awk '$0+0>4' file

This will output all percentage greater than 4%. If you want the output to be sorted, pipe to sort


text:
Q: Video Container for 1080p video for SD DVD (using Apple suite) This may be a bit of a stretch to post here (in terms of whether people will have an answer), since this is a fairly specific question about video work, although I am performing the entirety of this work within FCP 7, Compressor, and DVD Studio Pro.
I have 2 hours of footage edited from a HD Camcorder in FCP 7, and I need to get it onto a DVD. I want to use the highest quality container I can, and I want to be able to author and preferably burn the DVD within DVD Studio Pro. Unfortunately, DVDSP doesn't support MPEG-4, which is one of the nicest containers to put 1080p video into. It supports MPEG, which offers considerably less options for compression, and data rates.
Ultimately, my question is HOW can I export my video out of FCP (or Compressor) so that I'm sitting on a high quality file that will fit on one DVD and be compatible with DVD Studio Pro (4.7GB)? I just finished a 24 hour Compressor job with the default setting "HD DVD 60 minutes", but it gave me a 5.1GB file, which is of no use to me. The aspect ratio is also forced and it looks terrible.
HELP!

A: Just to get this 'answered' for anyone else who might come across this question.
There is no way to get 1080p or 1080i video onto a DVD. DVD's only support SD images (this goes for the disks themselfs, and the players).
You can however use BluRay to burn HD video, though this would require a BluRay burner and a BluRay player.
Have a look here for more info: http://en.wikipedia.org/wiki/DVD-Video

A: SD dvd only works with mpeg-2, and doesn't support HD signal, export your video as SD 16:9 from compressor, if you want HD on a disk has to be blu-ray


text:
Q: Magento - Cannot send headers, headers already sent controllers/AccountController.php, line 252 Having a bit of issues after a customer registers. The registration is going fine and all the data is being submitted but after a customer registers they are getting hit with this is in the face
"Cannot send headers; headers already sent in /customers/b/5/f/smkdwholesale.com/httpd.www/app/code/community/Exinent/CustomerActivation/controllers/AccountController.php, line 252"
I've had a look at the code and can't seem to find the issue. Here it is:
} catch (Exception $e) {
echo $e->getMessage(); // line 252
Mage::log($e->getMessage());
}

A: change
catch (Exception $e) {
echo $e->getMessage(); // line 252
Mage::log($e->getMessage());
}

to
catch (Exception $e) {
    //echo $e->getMessage(); // line 252
    Mage::log($e->getMessage());
    }

because echo stop the page to redirect another page. you can check your error log in var/log folder.


text:
Q: Testing a function that throws on failure What is the best way of testing a function that throws on failure? Or testing a function that is fairly immune to failure?
For instance; I have a I/O Completion Port class that throws in the constructor if it can't initialise the port correctly. This uses the Win32 function of CreateIoCompletionPort in the initialiser list. If the handle isn't set correctly - a non-null value - then the constructor will throw an exception. I have never seen this function fail.
I am pretty certain that this (and other functions like it in my code) if they fail will behave correctly, the code is 50 lines long including white-space, so my questions are
a) is it worth testing that it will throw
b) and if it is worth testing, how to?
c) should simple wrapper classes as these be unit-tested?
For b) I thought about overriding CreateIoCompletionPort and passing the values through. In the unit test override it and cause it to return 0 when a certain value is passed in. However since this is used in the constructor then this needs to be static. Does this seem valid or not?

A: If you are doing this in .NET, there is an ExpectedException attribute that you can add to your test:
[Test, ExpectedException(typeof(SpecificException), "Exception's specific message")]
public void TestWhichHasException()
{
    CallMethodThatThrowsSpecificException();
}

Test will pass if the exception of that type and with the specified message is thrown. The attribute has other overloads including having InnerExceptions, etc.

A: It is definitely worthwhile to test failure conditions, both that your class properly throws an exception when you want it to and that exceptions are handled properly in the class.
This can easily be done if you are acting on an object passed in to the constructor... just pass in a mock.  If not, I tend to prefer to have the functionality moved to a protected method, and override the protected method to evoke my failure case.  I will use Java as an example, but it should be easy enough to port the ideas to a C# case:
public class MyClass {
    public MyClass() throws MyClassException {
        // Whatever, including a call to invokeCreateIoCompletionPort
    }

    protected int invokeCreateIoCompletionPort(String str, int i) {
        return StaticClass.createIoCompletionPort(str, i);
    }
}

public class MyTest {
    public void myTest() {
        try {
            new MyClass();
            fail("MyClassException was not thrown!");
        } catch (MyClassException e) {
        }
    }

    private static class MyClassWrapper extends MyClass {
        @Override
        protected int invokeCreateIoCompletionPort(String str, int i) {
            throw new ExpectedException();
        }
    }
}

As you can see, it is pretty easy to test whether an exception is being thrown by the constructor or method you are testing, and it is also pretty easy to inject an exception from an external class that can throw an exception.  Sorry I'm not using your actual method, I just used the name to illustrate how it sounded like you are using it, and how I would test the cases it sounded you wanted to test.
Basically, any API details you expose can usually be tested, and if you want to KNOW that exceptional cases work as they should, you probably will want to test it.

A: You should consider writing your code in such a way that you can mock your I/O completion port. Make an interface/abstract class that exposes the methods you need on the I/O object, and write and test implementation that does things like it's supposed to (and an option to simulate failure perhaps).
AFAIK it's a common practice to mock external resources when unit testing, to minimize dependencies.

A: Sound like C++ to me. You need a seam to mock out the Win32 functions. E.g. in your class you would create a protected method CreateIoCompletionPort() which calls ::CreateIoCompletionPort() and for your test you create a class that derives from you  I/O Completion Port class and overrides CreateIoCompletionPort() to do nothing but return NULL. Your production class is still behaving like it was designed but you are now able to simulate a failure in the CreateIoCompletionPort() function.
This technique is from Michael Feathers book "Working effectively with legacy code".


text:
Q: Exponential time of entrance to a store Suppose that the time between entrance of two consecutive customers to a store follows an exponential distribution of mean 2 minutes. A person is observing this store at a time and see there are no customers inside. what is the probability that  after 5 minutes, no customers enter the shop.

I think the answer is very easy. Because exponential distribution is memoryless We simply find $P(X\geq 5) = 1-P(X\leq5) = 1-( 1 - e^{- \frac{1}{2} 5}) = e^{-\frac{1}{2} 5}$
Is my reasoning correct? it seems the problem is very easy but I found this in an exam and it was marked as medium difficulty.


text:
Q: Getting the envelope of a family of curves. When getting the envelope of a family of curves that represent the general solution of an ODE, why do we differentiate wrt c and equate to zero? I would like a simple proof or a good reference for this.
I mean for example, the ODE
$$y=2xy'+y^2y'^3$$
has a general solution
$$y=2c\frac{x}{y}+\frac{c^3}{y}$$
If we differentiate the general solution w.r.t. $c$, we will get the singular solution which is the envelope of the general solution
$$y^4=-\frac{32}{27}x^3.$$

A: Consider the diagram

where the point of intersection is a point near the evelope. The smaller $\mathrm{d}c$, the closer to the envelope we get.
This means that the point on the envelope is at the intersection of
$$
f(x,c)=0
$$
and
$$
\frac{\partial}{\partial c}f(x,c)=0
$$

Example
The family of lines parametrized by $a$:
$$
\frac{x}{1-a}+\frac{y}{a}=1
$$
Take the derivative with respect to $a$:
$$
\frac{x}{(1-a)^2}-\frac{y}{a^2}=0
$$
Solve simultaneously
$$
x=(1-a)^2\qquad y=a^2
$$

The family of lines is in black and the envelope is in  green. The envelope follows the intersection of adjacent curves.


text:
Q: Change shortcut in Firefox for "next tab" to F3? I know that Ctrl + PgUp / PgDn will switch to the next or previous tab in Firefox.
However I would much prefer to use F2 / F3 for the same purpose, similar to the old Maxthon behaviour. Is this possible?

A: The SwiftTabs addon should do what you're looking for.


text:
Q: Databricks Python vs Scala I have a cluster in databricks. Before importing the data, I want to choose among python vs scala, which one is better in terms of read/write large data from the source?

A: For the dataframe api, it should be the same performance.  For the rdd api, scala is going to be faster.

A: I would choose scala , my two cents on this subject:
Scala:

*

*supports multiple concurrency primitives

*uses JVM during runtime which gives is some speed over Python

Python:

*

*does not support concurrency or multithreading (support heavyweight process forking so only one thread is active at a time)

*is interpreted and dynamically typed and this reduces the speed

Also I recommend this article: https://databricks.com/blog/2016/07/14/a-tale-of-three-apache-spark-apis-rdds-dataframes-and-datasets.html