Q: MIPS sorting and array I have this homework problem.  I'm suppose to write a program that does the following:

*

*Sort the letters in the sentence into the ASCII collating sequence (i.e. alphabetically). Print the results and the total number of characters in the sentence.

*Next, print out a list of the number of times each letter occurred in the sentence.

*Finally, print out the total number of different characters in the sentence.

When I try to test out the first requirement, I don't receive the output string.
I also need help on doing the second two.  I'm fairly new to MIPS, and I have some understanding of it, but having some difficulty.  I modified some code for the sorting from example code I found.
        .data
length: .word   0
buffer: .space 255
prompt1:.asciiz  "Type in a sentence: "

after:  .asciiz  "\nString  after: "

    .text

# Start of code section

main:
      li       $v0, 4         # Prompt user for a text string
      la       $a0, prompt1      # address of string to print
      syscall
      li       $v0, 8         # Read in text string
      la       $a0, buffer
      li       $a1, 255
      syscall

      la       $t0, buffer    #  Read character from text string
      lw       $t1, length
      addu     $t0, $t0, $t1

# Call on QuickSort

        la      $a0, buffer       # Constant pointer to string

        add     $a1, $a0, 0      # Pointer to left end

        add     $a2, $a0, 25     # Pointer to right end

        jal     QS               # The one call from main

# Print out results

        la      $a0, after

        li      $v0, 4

        syscall

        la      $a0, buffer

        syscall

# End main

        li      $v0, 10

        syscall

QS:     sub     $sp, $sp, 16     # \
        sw      $a1, 0($sp)      #  \

        sw      $a2, 4($sp)      #   > Save registers

        sw      $t2, 8($sp)      #  /

        sw      $ra, 12($sp)     # / and return address

        bge     $a1, $a2, QSret  # Nothing to sort

        sub     $t3, $a1, $a0     # index i

        sub     $t4, $a2, $a0     # index j

        add     $t0, $t3, $t4     # t0 = i+j choose middle

        sra     $t0, $t0, 1       # t0 = (i+j) div 2

        add     $t0, $t0, $a0     # t0 -> A[(i+j) div 2]

        lb      $t5, 0($t0)       # t5 = pivot value

        lb      $t6, 0($a1)       # t6 = A[i] = left element

        sb      $t5, 0($a1)       # Swap them so pivot

        sb      $t6, 0($t0)       # is first element
#

        move    $t1, $a1         # Initdially i -> first (pivot) item a1

        add     $t2, $a2, 1      # Initially j -> just past last item a2

        lb      $t0, 0($a1)      # Pivot value in t0 (in $t5)

#
loop:
#

i_loop: add     $t1, $t1, 1      # i=i+1;

        lb      $t5, 0($t1)      # t5 = A[i]

        bgt     $t0, $t5, i_loop # until pivot <= A[i]

j_loop: sub     $t2, $t2, 1      # j=j-1;

        lb      $t6, 0($t2)      # t6 = A[j]

        blt     $t0, $t6, j_loop # until pivot >= A[j]
#

        bge     $t1, $t2, test   # if i<j swap
#

        sb      $t6, 0($t1)      # A[i] and

        sb      $t5, 0($t2)      # A[j]
#

test:   blt     $t1, $t2, loop   # until i >= j
#

        lb      $t5, 0($a1)      # swap a[a1] = pivot

        lb      $t6, 0($t2)      # and a[j]

        sb      $t5, 0($t2)      # now a[j] is

        sb      $t6, 0($a1)      # in its final position

# Done with partition

        lw      $a1, 0($sp)

        sub     $a2, $t2, 1

        jal     QS               # Recursive call on left

        add     $a1, $t2, 1

        lw      $a2, 4($sp)

        jal     QS               # Recursive call on right
#

QSret:  lw      $ra, 12($sp)     # \Replace return address

        lw      $t2, 8($sp)      #  \

        lw      $a2, 4($sp)      #   > and registers

        lw      $a1, 0($sp)      #  /
        add     $sp, $sp, 16     # /

        jr      $ra

A: buffer: .space 255

This fills buffer with zeroes.
li       $v0, 8         # Read in text string
la       $a0, buffer
li       $a1, 255
syscall

I don't know what environment you're using, but this typically works just like fgets() in C, so if you enter hello, your buffer will end up as:
+-----+-----+-----+-----+-----+-----+-----+-----+   more    +-----+
| 'h' | 'e' | 'l' | 'l' | 'o' |'\n' |  0  |  0  |..zeroes...|  0  |
+-----+-----+-----+-----+-----+-----+-----+-----+           +-----+

The code just after that doesn't seem to do anything useful:
la       $t0, buffer    #  Read character from text string
lw       $t1, length
addu     $t0, $t0, $t1

but length has never been written and $t0 isn't used again (until it's overwritten inside QS).
The call to QS passes a fixed value in $a2 (25 - why?).  Assuming that the QS routine actually works as advertised: if your original string is short, some of the zero bytes in the buffer will be included in the range that gets sorted, and so will end up at the beginning of the buffer - the range that gets sorted will look something like this:
+-----+   more    +-----+-----+-----+-----+-----+-----+-----+-----+
|  0  |..zeroes...|  0  |  0  |'\n' | 'e' | 'h' | 'l' | 'l' | 'o' |
+-----+           +-----+-----+-----+-----+-----+-----+-----+-----+

i.e. if the range that gets sorted includes any zero bytes, the first byte of the result will be zero, and so you will print an empty string.
Part 2: once you have a correctly sorted string, this should be straightforward, as all of the occurences of each character are adjacent.  Just walk along the string, and consider whether each character is the same as the previous one, or different.
Part 3: just needs an additional counter while doing the work for part 2.


Q: Angular custom-control-input doesn't work correctly with formControlName inside loop i want to apply a custom theme style on angular but checkbox didn't work correctly.
i have this part of code and worked very well :

                <input type="checkbox" class="form-control" id="field_check"  formControlName="checked">
                check

But when i try to add a custom class control not working :

                <input type="checkbox" class="custom-control-input" id="field_check" formControlName="checked">
                check

how to apply my class="custom-control-input" without losing the class="form-control" ? i have already tried this class="form-control custom-control-input" but didn't work
UPDATE
after inspect element i found this :

so when here is the result i got :

i have no access to css code custom-control-input and form-control how can i fix this ?

A: It should work ideally, it is best if you can see which style is applying on control using inspect element. May be it is overrided by form-control class. You might have to use ! Important in class.


Q: How to automate a large number of txt files to be imported from Perl to a SQL Server using DBI? I have attempted to transfer one txt file into a SQL Server from Perl, but I now need to create a DB in SQL that combines hundreds of txt files. Is there an automated way of doing this to save manually transferring all the txt files? I will insert my attempt of coding one txt file. I believe I need to use Bulk Insert to achieve this but I am unsure what code to use. Any advice on the problem would be really appreciated, and if there is anymore code you wish to see or a specific thing I forgot to mention then please comment and I will edit. Thank you.
#!/usr/bin/perl -w
use strict;
use DBI;
use Carp;

    # Connect to the data source and get a handle for that connection.
my $dbh = DBI->connect('dbi:ODBC:RegressionDBS') ||
    confess "Connection Failed: $DBI::errstr";

    # This query generates a result set with one record in it.
my $sql = "SELECT 1 AS test_col";
my $tablename = "RegressionTable";

open(FH, "newregression.txt") || die "cant open file";
my $Sqlh = $dbh->prepare("INSERT INTO RegressionTable (Ticker, TradeDate, HighPrice, LowPrice, TradePrice, TotalVolume, TotalValue) VALUES (?,?,?,?,?,?,?);") || confess $DBI::errstr;
while (my $line = <FH> )
{
$line =~/^(.*)(..)(..)$/;
my ($curTicker, $wTradeDate, $wHighPrice, $wLowPrice, $wTradePrice, $wTotalVolume, $wTotalValue);
    $curTicker=$1
    #$wTradeDate=
    $wHighPrice=$2;
    $wLowPrice=$1;
    #$wTradePrice=$1;
    #$wTotalVolume=$1;
    #$wTotalValue=$4;

$Sqlh->execute($curTicker, $wTradeDate, $wHighPrice, $wLowPrice, $wTradePrice, $wTotalVolume, $wTotalValue) || confess $DBI::errstr;
}

$Sqlh->finish();
$dbh->disconnect();

A: Ok, so you run
INSERT INTO RegressionTable (
  Ticker, TradeDate, HighPrice, LowPrice, TradePrice, TotalVolume, TotalValue
)
VALUES (?, ?, ?, ?, ?, ?, ?)

for every line in newregression.txt, and now you want to do it for multiple files. Why not wrap your code above in a subroutine, say insert_file(), then call it per file in a loop...
my @files = qw(red.txt green.txt blue.txt);
for my $file (@files) {
  insert_file($file);
}

Or if the target table varies per file, define a hash:
my %files = (
  'red.txt'  => 'RedTable',
  'blue.txt' => 'BlueTable'
);
while ( my ($file, $table) = each %files ) {
  insert_file($file, $table);
};

Not sure how you'd use Bulk Insert given the field separator in your data file seems to be indeterminate (i.e. the regex /(.*)(..)(..)/ defines field boundaries). You may need to use the FORMATFILE option. Also, if you generate a BULK INSERT statement using DBI, be aware that the user your SQL Server runs as must be able to read your data files over the filesystem (networked, local or otherwise).


Q: Div class nav bar I can’t post code here because it will fill up section but if someone could add me discord it would be much appreciated and much easier. Thank you! Kam#3585
Kam#3585 add me on discord thanks

A: You can use this code to create navbar

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Link

          Dropdown

          Action
          Another action

          Something else here

        Disabled

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>


Q: DLL uses another DLL in C++ I have a complex 3rd DLL by C++. (I compiled it and have .lib both).
I want to write a new my simple DLL, that using a few function in the 3rd DLL.
How to import a 3rd DLL in my DLL?
(Now, i got an error, When importing 3rd to my DLL, i could not load my DLL in any other application)

A: I found my issue, A stupid issue.
My 3rd DLL uses too much another DLL.
I missed a library, (I developed my App by C#, It did not notify me missed library)


Q: Creating a URLretreive function using urllib2 in python I want to have a function which can save a page from the web into a designated path using urllib2.
Problem with urllib is that it doesn't check for Error 404, but unfortunately urllib2 doesn't have such a function although it can check for http errors.
How can i make a function to save the file permanently to a path?
def save(url,path):
  g=urllib2.urlopen(url)
  *do something to save g to 'path'*

A: Just use .read() to get the contents and write it to a file path.
def save(url,path):
  g = urllib2.urlopen(url)
  with open(path, "w") as fH:
    fH.write(g.read())


Q: insmod: ERROR: could not insert module kernel.ko: Invalid parameters - Error related to naming scheme of kernel module I'm using C to create a custom kernel module to hook into the netfilter operation on my Ubuntu box. However, I'm running into a problem revolving around the module_param argument. When inserting the module, I'm attempting to add a custom field, specifically this will drop ICMP traffic when specified. The code compiles fine using a standard make file but when using insmod to insert it, I get the error
insmod: ERROR: could not insert module kernel.ko: Invalid parameters

I'm using the command
insmod kernel.ko dropicmp=1

From what I've read, this should work with the module params argument, but nothing I've tried has fixed this.
Please find my code below.
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/ip.h>
#include <linux/tcp.h>

static struct nf_hook_ops nfho;
struct iphdr *iph;
struct tcphdr *tcp_header;
struct sk_buff *sock_buff;
unsigned int sport, dport;

// command line argument | called using insmod kernel_firewall.ko drop_icmp=1
static int dropicmp = 1;

module_param(dropicmp, int , 0); // takes in an int from command line | (name, variable, permissions)

unsigned int hook_func(unsigned int hooknum,
                       struct sk_buff **skb,
                       const struct net_device *in,
                       const struct net_device *out,
                       int (*okfn)(struct sk_buff *)){

    sock_buff = skb;

    if (!sock_buff) { // if there is no socket buffer, accept
        return NF_ACCEPT;
    }

    iph = (struct iphdr *)skb_network_header(sock_buff); // using the socket buffer, create our ip header structure out of packets in it

    if (!iph) {
        printk(KERN_INFO "no ip header, dropping\n"); // self explanatory
        return NF_DROP;
    }

    if(iph->protocol==IPPROTO_TCP) {
        if(iph->saddr | 0x11000000){ // if the first prefix is in the 192 range | might need to change the if statement up | considering sprintf
            printk(KERN_INFO "192 subnet detected, dropping\n");
            return NF_DROP;
        }
        else{
            return NF_ACCEPT;
        }
    }

    if(iph->protocol==IPPROTO_ICMP) { // if ICMP

        if(dropicmp == 1){
            return NF_DROP; // drop our ICMP traffic if required
        }
        else{
            return NF_ACCEPT;
        }
    }

    return NF_ACCEPT; // default to accept

}

// initialize
static int __init initialize(void) {
    nfho.hook = hook_func;
    nfho.hooknum = NF_INET_POST_ROUTING;
    nfho.pf = PF_INET;
    nfho.priority = NF_IP_PRI_FIRST;
    nf_register_hook(&nfho);
    return 0;
}

// rmmod
static void __exit teardown(void) {
    nf_unregister_hook(&nfho);
}

module_init(initialize);
module_exit(teardown);

A: This was all due to my dumb naming scheme... I named the module kernel... Which is obviously already in use by the kernel...... So don't do that...


Q: karma test on angular 2 ag grid 'exports is not defined' Hey all I'm trying to test my table component that is a wrapper on the old and good ag grid.
I added the path to karma.conf.js  'node_modules/ag-grid-ng2/main.js'
Also I added the ag grid component in the test file:
import { RgGridComponent } from "../../shared/grid-control/grid-control.component";
import { AgGridNg2 } from 'ag-grid-ng2/main';
...
...
 declarations: [TracesTableComponent, RgGridComponent, AgGridNg2],
But when I try to run the test I get the message : "exports is not defined"
I can really use some help. thanks!

A: found the answer! I needed to install @types/jasmine and then import it like this:  import { } from 'jasmine';


Q: ascx control visible false displaying issues My user control is displaying only the first ascx but when I'm navigating to other ascx the content is not displaying what am I doing wrong??!
The idea is On my aspx page I have on the left hand side TreeView for each of every node in the TreeView I want to load a different ascx which going to change only the right hand side of the page.
aspx:
<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Masters/InternalReports.Master" CodeBehind="Reports.aspx.vb" Inherits="DispatchSoftware.Reports" %>
<%@ Register TagPrefix="ReportsPrefix" TagName="rptReports" Src="~/Controls/Reports/rptReport.ascx" %>
<%@ Register TagPrefix="ReportsPrefixTmeOfDay" TagName="rptTimeOfDay" Src="~/Controls/Reports/rptTimeOfDay.ascx" %>
<%@ Register TagPrefix="ReportsPrefixTrending" TagName="rptTrending" Src="~/Controls/Reports/rptTrending.ascx" %>
<%@ Register TagPrefix="ReportsPrefixTopSevenIncidents" TagName="rptTopSevenIncidents" Src="~/Controls/Reports/rptTopSevenIncidents.ascx" %>
<%@ Register TagPrefix="ReportsPrefixTimeCategoriesComparison" TagName="rptTimeCategoriesComparison" Src="~/Controls/Reports/rptTimeCategoriesComparison.ascx" %>
<%@ Register TagPrefix="ReportsPrefixIncidentPerCategory" TagName="rptIncidentPerCategory" Src="~/Controls/Reports/rptIncidentPerCategory.ascx" %>
<%@ Register TagPrefix="ReportsPrefixMaps" TagName="rptMaps" Src="~/Controls/Reports/rptMaps.ascx" %>

<asp:Content ID="Content1" ContentPlaceHolderID="LeftContent" runat="server">

                <asp:Label ID="lblFilter" runat="server" Text="Filter"></asp:Label>

             <telerik:RadPanelBar runat="server" ID="rpbMainMenu" Width="248px" Height="517px" ExpandMode="FullExpandedItem">
            <Items>
                <telerik:RadPanelItem ImageUrl="~/Images/Layout/Reports.png" Expanded="true" Text="Reports">
                    <ContentTemplate>

                            <telerik:RadTreeView runat="Server" ID="rtvReports" EnableDragAndDrop="false" Height="300px">
                                <Nodes>
                                    <telerik:RadTreeNode Text="Statistical Report" Value="StatisticalReport" Expanded="true" CssClass="GeneralFontShape">
                                        <Nodes>
                                            <telerik:RadTreeNode Text="Time of Day" Value="TimeofDay" >
                                            </telerik:RadTreeNode>
                                            <telerik:RadTreeNode Text="Trending" Value="Trending">
                                            </telerik:RadTreeNode>
                                            <telerik:RadTreeNode Text="Top 7 Incidents" Value="Top7Incidents">
                                            </telerik:RadTreeNode>
                                            <telerik:RadTreeNode Text="Incidents Per Category" Value="IncidentsPerCategory">
                                            </telerik:RadTreeNode>
                                        </Nodes>
                                    </telerik:RadTreeNode>
                                    <telerik:RadTreeNode Text="Incident Comparisons" Value="IncidentComparisons" Expanded="true" CssClass="GeneralFontShape">
                                        <Nodes>
                                            <telerik:RadTreeNode Text="Incident Loss" Value="IncidentLoss">
                                            </telerik:RadTreeNode>
                                        </Nodes>
                                    </telerik:RadTreeNode>
                                    <telerik:RadTreeNode Text="Geographic Locations" Value="GeographicLocations" Expanded="true" CssClass="GeneralFontShape">
                                        <Nodes>
                                            <telerik:RadTreeNode Text="Maps" Value="Maps">
                                            </telerik:RadTreeNode>
                                        </Nodes>
                                    </telerik:RadTreeNode>
                                </Nodes>
                            </telerik:RadTreeView>

                    </ContentTemplate>
                </telerik:RadPanelItem>
            </Items>
        </telerik:RadPanelBar>

</asp:Content>

<%--Right Handside--%>
<asp:Content ID="Content2" ContentPlaceHolderID="RightContent" runat="server">
    <ReportsPrefix:rptReports ID="ucReports" runat="server" Visible="True" />
    <ReportsPrefixTmeOfDay:rptTimeOfDay ID="ucTimeOfDay" runat="server" Visible="False" />
    <ReportsPrefixTrending:rptTrending ID="ucTrending" runat="server" Visible="False" />
    <ReportsPrefixTopSevenIncidents:rptTopSevenIncidents ID="ucTopSevenIncidents" runat="server" Visible="False" />
    <ReportsPrefixTimeCategoriesComparison:rptTimeCategoriesComparison ID="ucTimeCategoriesComparison" runat="server" Visible="False" />
    <ReportsPrefixIncidentPerCategory:rptIncidentPerCategory ID="ucIncidentPerCategory" runat="server" Visible="False" />
    <ReportsPrefixMaps:rptMaps ID="ucMaps" runat="server" Visible="False" />
</asp:Content>

VB Code:
Imports Telerik.Web.UI
Imports System.Drawing

Public Class Reports
    Inherits System.Web.UI.Page
    Private m_User As UserInfo = Nothing
    Private m_SessionID As String
    Private m_qrptTOD As String
    Private m_qrptTRN As String
    Private m_qrptTOS As String
    Private m_qrptIPC As String
    Private m_qrptCIL As String
    Private m_qrptGEO As String

    Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        m_User = New UserInfo()

        If m_User.UserID = 0 Then
            Response.Redirect(Globals.gRootRelativeSecureURL("/QuickLogOut.aspx?SessionID=" + m_User.SessionID + "&qCC=" & m_User.CompanyCode))
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        RetrieveAllQueryStringParams()

        If Not IsPostBack Then
            GenerateDataSets()
            GenerateLabels()
            GenerateLinks()
            GenerateControls()
            GenerateOther()
        End If

    End Sub

    Private Sub RetrieveAllQueryStringParams()
        Try
            If Not String.IsNullOrEmpty(Request.QueryString("SessionID")) Then
                m_SessionID = Request.QueryString("SessionID")
                m_qrptTOD = Request.QueryString("qrptTOD")
                m_qrptTRN = Request.QueryString("qrptTRN")
                m_qrptTOS = Request.QueryString("qrptTOS")
                m_qrptIPC = Request.QueryString("qrptIPC")
                m_qrptCIL = Request.QueryString("qrptCIL")
                m_qrptGEO = Request.QueryString("qrptGEO")
            ElseIf Not String.IsNullOrEmpty(Session("SessionID")) Then
                m_SessionID = Session("SessionID")
            End If

            If m_qrptTOD = "tod" Then
                '=== Clearing the right hand side and loading the new ascx.
                Me.Master.FindControl("RightContent").Controls.Clear()

                Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptTimeOfDay.ascx")))

            End If
            If m_qrptTRN = "trn" Then
                Me.Master.FindControl("RightContent").Controls.Clear()
                Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptTrending.ascx")))
            End If

            If m_qrptTOS = "tos" Then
                Me.Master.FindControl("RightContent").Controls.Clear()
                Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptTopSevenIncidents.ascx")))
            End If

            If m_qrptIPC = "ipc" Then
                Me.Master.FindControl("RightContent").Controls.Clear()
                Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptIncidentPerCategory.ascx")))
            End If

            If m_qrptCIL = "cil" Then
                Me.Master.FindControl("RightContent").Controls.Clear()
                Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptTimeCategoriesComparison.ascx")))
            End If

            If m_qrptGEO = "geo" Then
                Me.Master.FindControl("RightContent").Controls.Clear()
                Me.Master.FindControl("RightContent").Controls.Add(Page.LoadControl(("/Controls/Reports/rptMaps.ascx")))
            End If

        Catch ex As Exception

        End Try
    End Sub

    Protected Sub GenerateDataSets()
        Try

        Catch ex As Exception
        End Try
    End Sub

    Protected Sub GenerateLabels()

    End Sub

    Protected Sub GenerateLinks()
        Dim subTreeStatisticalReport As RadTreeNode = rtvReports.Nodes.FindNodeByValue("StatisticalReport")
        Dim subTreeIncidentComparisons As RadTreeNode = rtvReports.Nodes.FindNodeByValue("IncidentComparisons")
        Dim subTreeGeographicLocations As RadTreeNode = rtvReports.Nodes.FindNodeByValue("GeographicLocations")

        Dim statTimeOfDayNode As RadTreeNode = subTreeStatisticalReport.Nodes.FindNodeByValue("TimeofDay")
        Dim statTrendsNode As RadTreeNode = subTreeStatisticalReport.Nodes.FindNodeByValue("Trending")
        Dim statTopSevenIncidents As RadTreeNode = subTreeStatisticalReport.Nodes.FindNodeByValue("Top7Incidents")
        Dim statIncidentPerCategory As RadTreeNode = subTreeStatisticalReport.Nodes.FindNodeByValue("IncidentsPerCategory")
        Dim compIncidentLoss As RadTreeNode = subTreeIncidentComparisons.Nodes.FindNodeByValue("IncidentLoss")
        Dim GeoMaps As RadTreeNode = subTreeGeographicLocations.Nodes.FindNodeByValue("Maps")

        statTimeOfDayNode.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptTOD=tod")
        statTrendsNode.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptTRN=trn")
        statTopSevenIncidents.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptTOS=tos")
        statIncidentPerCategory.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptIPC=ipc")
        compIncidentLoss.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptCIL=cil")
        GeoMaps.NavigateUrl = Globals.gRootRelativeSecureURL("/Reports/Reports.aspx?SessionID=" + m_SessionID + "&qrptGEO=geo")

    End Sub

    Protected Sub GenerateControls()

    End Sub

    Protected Sub GenerateOther()

    End Sub
End Class


Q: Server side rendering using reactjs I have started to work on react server side rendering, Having some questions i.e how about routing and can i implement server side rendering for all pages in application,Please provide any example on server side rendering in reactjs,Thanks

A: for plain implementation in server side rendering you need to have different app entry point with StaticRouter instead of BrowserRouter
react-routed-dom documentation with implementation:
https://reacttraining.com/react-router/web/guides/server-rendering/putting-it-all-together


Q: android emulator access server in local network i am having difficulties to have my android app running in the emulator to connect to servers in my local network.
i am getting a
java.net.UnknownHostException

but the servers are resolvable fine from the machine where the emulator is run.
thanks for any help on this topic!

A: Try adding <uses-permission android:name="android.permission.INTERNET" /> to your manifest. This allows your application network access.
More can be found here.

A: You have to use 10.0.2.2 to access local server.


Q: Failing to capture process name and exit code in Exited eventhadler I have a pretty straight forward event handler on process exit that wants to log the process name and exit code.
This code runs perfectly in my local machine (Windows 10 pro, 64 bit) no matter how I end the process (calling Kill(), End Task from Task Manager or closing the app).
However the deployed version of the same code in Integration env (Windows Server 2016 DC, 64 bit) is failing with below error.

System.InvalidOperationException: Process has exited, so the requested
information is not available.    at
System.Diagnostics.Process.EnsureState(State state)    at
System.Diagnostics.Process.get_ProcessName()

Any resolutions/pointers in troubleshooting this will be helpful.
Event handler looks like below:
private static void MyProcess_Exited(object sender, EventArgs e)
{
    var process = sender as Process;
    var processExitLog = new StringBuilder()
                    .AppendLine($"{process.ProcessName} exited with code {process.ExitCode} at {process.ExitTime.ToString("s")}.")
                    .AppendLine($"Total uptime: {(process.ExitTime - process.StartTime).ToString("c")}")
                    .AppendLine($"Running threads: {process.Threads.Count}")
                    .AppendLine($"Peak physical memory utilization was: {process.PeakWorkingSet64}.")
                    .ToString();

    Console.WriteLine(processExitLog);
    Console.WriteLine();
}


Q: Enter text into the Chrome's address bar via Selenium is it possible to enter a text to the address bar in Chrome with Selenium? I would like to resolve domains and get the final URL. E.g. enter freshfruits.com resolves https://www.freshfruits.com.

A: Selenium does not support sending keys to the browser address bar, unfortunately.
Someone suggested a solution with win32com.client library here
Haven't tried it myself as I haven't been faced with this situation. The idea is you may need to consider workarounds, as this is outside the scope of Selenium.


Q: Reduce Object Array to Single Object Working with an array of objects like:
const objArr = [
  { k: 'row 1', v: '111' },
  { k: 'row 2', v: '222' },
  { k: 'row 3', v: null },
  { k: 'row 4', v: null },
];

What is the most efficient way to reduce into a single object using the value of k for the key and the value of v for the value?
Desired Outcome:
const obj = {
  'row 1': '111',
  'row 2': '222',
  'row 3': null,
  'row 4': null,
};

I have attempted to accomplish with a one-liner like:
const obj = objArr.reduce((obj, key) => ({ ...{ [key]: objArr.v[key] } }), {});


Q: Database design for time series Approximately every 10 min I insert ~50 records with the same timestamp.
It means ~600 records per hour or 7.200 records per day or  2.592.000 records per year.
User wants to retrieve all records for the timestamp closest to the asked time.
Design #1 - one table with index on timestamp column:
    CREATE TABLE A (t timestamp, value int);
    CREATE a_idx ON A (t);

Single insert statement creates ~50 records with the same timestamp:
    INSERT INTO A VALUES (
      (‘2019-01-02 10:00’, 5),
      (‘2019-01-02 10:00’, 12),
      (‘2019-01-02 10:00’, 7),
       ….
    )

Get all records which are closest to the asked time
(I use the function greatest() available in PostgreSQL):
    SELECT * FROM A WHERE t =
(SELECT t FROM A ORDER BY greatest(t - asked_time, asked_time - t) LIMIT 1)

I think this query is not efficient because it requires the full table scan.
I plan to partition the A table by timestamp to have 1 partition per year, but the approximate match above still will be slow.
Design #2 - create 2 tables:
1st table: to keep the unique timestamps and auto-incremented PK,
2nd table: to keep  data and the foreign key on 1st table PK
    CREATE TABLE UNIQ_TIMESTAMP (id SERIAL PRIMARY KEY, t timestamp);
    CREATE TABLE DATA (id INTEGER REFERENCES UNIQ_TIMESTAMP (id), value int);
    CREATE INDEX data_time_idx ON DATA (id);

Get all records which are closest to the asked time:
SELECT * FROM DATA WHERE id =
(SELECT id FROM UNIQ_TIMESTAMP ORDER BY greatest(t - asked_time, asked_time - t) LIMIT 1)

It should run faster compared to Design #1 because the nested select scans the smaller table.
Disadvantage of this approach:
 - I have to insert into 2 tables instead just one
 - I lost the ability to partition the DATA table by timestamp
What you could recommend?

A: I'd go with tje single table approach, perhaps partitioned by year so that it becomes easy to get rid of old data.
Create an index like
CREATE INDEX ON a (date_trunc('hour', t + INTERVAL '30 minutes'));

Then use your query like you wrote it, but add
AND date_trunc('hour', t + INTERVAL '30 minutes')
  = date_trunc('hour', asked_time + INTERVAL '30 minutes')

The additional condition acts as a filter and can use the index.

A: You can use a UNION of two queries to find all timestamps closest to a given one:
(
  select t
  from a
  where t >= timestamp '2019-03-01 17:00:00'
  order by t
  limit 1
)
union all
(
  select t
  from a
  where t <= timestamp '2019-03-01 17:00:00'
  order by t desc
  limit 1
)

That will efficiently make use of an index on t. On a table with 10 million rows (~3 years of data), I get the following execution plan:
Append  (cost=0.57..1.16 rows=2 width=8) (actual time=0.381..0.407 rows=2 loops=1)
  Buffers: shared hit=6 read=4
  I/O Timings: read=0.050
  ->  Limit  (cost=0.57..0.58 rows=1 width=8) (actual time=0.380..0.381 rows=1 loops=1)
        Output: a.t
        Buffers: shared hit=1 read=4
        I/O Timings: read=0.050
        ->  Index Only Scan using a_t_idx on stuff.a  (cost=0.57..253023.35 rows=30699415 width=8) (actual time=0.380..0.380 rows=1 loops=1)
              Output: a.t
              Index Cond: (a.t >= '2019-03-01 17:00:00'::timestamp without time zone)
              Heap Fetches: 0
              Buffers: shared hit=1 read=4
              I/O Timings: read=0.050
  ->  Limit  (cost=0.57..0.58 rows=1 width=8) (actual time=0.024..0.025 rows=1 loops=1)
        Output: a_1.t
        Buffers: shared hit=5
        ->  Index Only Scan Backward using a_t_idx on stuff.a a_1  (cost=0.57..649469.88 rows=78800603 width=8) (actual time=0.024..0.024 rows=1 loops=1)
              Output: a_1.t
              Index Cond: (a_1.t <= '2019-03-01 17:00:00'::timestamp without time zone)
              Heap Fetches: 0
              Buffers: shared hit=5
Planning Time: 1.823 ms
Execution Time: 0.425 ms

As you can see it only requires very few I/O operations and that is pretty much independent of the table size.
The above can be used for an IN condition:
select *
from a
where t in (
  (select t
   from a
   where t >= timestamp '2019-03-01 17:00:00'
   order by t
   limit 1)
  union all
  (select t
   from a
   where t <= timestamp '2019-03-01 17:00:00'
   order by t desc
   limit 1)
);

If you know you will never have more than 100 values close to that requested timestamp, you could remove the IN query completely and simply use a limit 100 in both parts of the union. That makes the query a bit more efficient as there is no second step for evaluating the IN condition, but might return more rows than you want.
If you always look for timestamps in the same year, then partitioning by year will indeed help with this.
You can put that into a function if it is too complicated as a query:
create or replace function get_closest(p_tocheck timestamp)
  returns timestamp
as
$$
  select *
  from (
     (select t
     from a
     where t >= p_tocheck
     order by t
     limit 1)
    union all
    (select t
     from a
     where t <= p_tocheck
     order by t desc
     limit 1)
  ) x
  order by greatest(t - p_tocheck, p_tocheck - t)
  limit 1;
$$
language sql stable;

The the query gets as simple as:
select *
from a
where t = get_closest(timestamp '2019-03-01 17:00:00');

Another solution is to use the btree_gist extension which provides a "distance" operator <->
Then you can create a GiST index on the timestamp:
create index on a using gist (t) ;

and use the following query:
select *
from a where t in (select t
                  from a
                  order by t <-> timestamp '2019-03-01 17:00:00'
                  limit 1);


Q: Looking for a book where the planet is a device to rebuild the universe I'm looking for a scifi book with an old guy and a group of youngsters that find an anomaly on a planet that looks like a massive pit but ends up being a gate to another world created by this race of aliens that are top shaped with tentacles coming from their mouths.
The old man turns out to be one of them but had forgotten everything until it started to come back when he came to that world. also the world has a seemingly infinite number of land types that cycle randomly, and when a person goes through this gate they get send to a specific land type and their body is changed in order to fit that space.
I think the plot revealed that the planet was a control device used to rebuild the universe. if anyone could help me that would be awesome.

A: This seems to be Midnight at the Well of Souls by Jack L Chalker, its the first in the Well of Souls series, 10 books about the Well World
Well of Souls

*

*Midnight at the Well of Souls (1977)

Below average in height and unprepossessing in appearance, Nathan Brazil is an unassuming if cynical starship owner, carrying passengers and cargo for a living - hardly the sort of person to hold the fate of the entire universe in his hands.
But when Nathan detours from his route to answer a distress call, a hidden stargate hurls him and his passengers to the Well World, the master control planet for the cosmos. Billions of years ago, a godlike race unlocked all the secrets of space and time and remade the universe according to their grand design. Then they vanished and left behind the Well World to maintain the pattern of the universe.
Now someone is searching for the planet's hidden control room - the Well of Souls - to seize control of the cosmos. Nathan must stop them, but this planet causes bizarre metamorphoses in visitors, changing them into centaurs, mermaids, and giant insects seemingly at random. As a result, Nathan no longer recognizes his friends, let alone his unknown enemies. His task seems hopeless - until his long-suppressed memories begin to return and he realizes who he really is.

*Exiles at the Well of Souls (1978)

*Quest for the Well of Souls (1978)

*The Return of Nathan Brazil (1979)

*Twilight at the Well of Souls: The Legacy of Nathan Brazil (1980)

*The Sea Is Full of Stars (1999)

*Ghost of the Well of Souls (2000)

Watchers at the Well

*

*Echoes of the Well of Souls (1993)

*Shadow of the Well of Souls (1994)

*Gods of the Well of Souls (1994)


Q: Elastic4s ngram mapping I have to create an ElasticSearch mapping like this using elastic4s:
  "mappings": {
    "properties": {
      "id": {
        "type": "keyword"
      },
      "name": {
       "type": "text",
       "analyzer": "ngram_analyzer",
       "fielddata": true
      },
      "lang": {
        "type": "keyword"
      },
      "order": {
        "type": "long"
      },
      "active": {
        "type": "boolean"
      }
      "description": {
        "type": "text"
      }
    }
  }

I can do
def mapping: Option[MappingDefinition] =
    Some(
      properties(
        KeywordField("id"),
        KeywordField("lang"),
        BasicField("order", "long"),
        BasicField("active", "boolean"),
        TextField("description")
      )
    )

for id, lang, order, active and description.
But, how can I do such mapping for name. the problem is analyzer and fielddata inside it.

A: You should use this:
TextField("name").fielddata(true).analyzer("ngram_analyzer")

You also need to make sure to properly create the ngram_analyzer in your index settings.


Q: spark - where is spark.sql.legacy.timeParserPolicy documented? Migration Guide: SQL, Datasets and DataFram refers to spark.sql.legacy.timeParserPolicy

Parsing/formatting of timestamp/date strings. This effects on CSV/JSON datasources and on the unix_timestamp, date_format, to_unix_timestamp, from_unixtime, to_date, to_timestamp functions when patterns specified by users is used for parsing and formatting. In Spark 3.0, we define our own pattern strings in Datetime Patterns for Formatting and Parsing, which is implemented via DateTimeFormatter under the hood. New implementation performs strict checking of its input. For example, the 2015-07-22 10:00:00 timestamp cannot be parse if pattern is yyyy-MM-dd because the parser does not consume whole input. Another example is the 31/01/2015 00:00 input cannot be parsed by the dd/MM/yyyy hh:mm pattern because hh supposes hours in the range 1-12. In Spark version 2.4 and below, java.text.SimpleDateFormat is used for timestamp/date string conversions, and the supported patterns are described in SimpleDateFormat. The old behavior can be restored by setting spark.sql.legacy.timeParserPolicy to LEGACY.

Spark Application Properties does not have the explanation. Where is it documented and what values are available to specify?

A: For some reason it does not appear it Spark configurations docs but you can find it in SQLConf.scala:

When LEGACY, java.text.SimpleDateFormat is used for formatting and
parsing dates/timestamps in a locale-sensitive manner, which is the
approach before Spark 3.0. When set to CORRECTED, classes from
java.time.* packages are used for the same purpose. The default
value is EXCEPTION, RuntimeException is thrown when we will get
different results.


Q: Generating relative paths with Jersey UriBuilder Using UriBuilder as follows:
UriBuilder.fromResource(My.class).path("resource").build().toString()

generates /my/resource.
I was wondering if there was a way to tell UriBuilder that I want to generate a relative path like so my/resource. This is useful in cases where I want to advertise resource URIs relative to the root URI (/my/resource being an absolute path and a relative URI to the root scheme + domain + port).
Does my question even make sense?


Q: cycling Ranksum on Stata I have some data with two different groupd of patients automatically exported from a diagnostic tool.
Variables are automatically nominated by the diagnostic tool (e.g. L1DensityWholeImage, L1WholeImageSHemi, L1WholeImageIHemi , L1WholeETDRS ,[...], DeepL2StartLayer, L2Startoffsetum, L2EndLayer, [...], Perimeter, AcircularityIndex )
I have to perform a Rank-sum test (or Mann-Whitney U test) with all the variables (> of 80) by group.
Normally, I should write each single analysis like that:
ranksum L1DensityWholeImage, by(Group)
ranksum L1WholeImageSHemi, by(Group)
ranksum L1WholeImageIHemi, by(Group)
ranksum L1WholeETDRS, by(Group)
Is there any way or code to write the command with a varlist? And maybe to obtain only 1 output result with all the p value?
e.g.: ranksum L1DensityWholeImage L1WholeImageSHemi L1WholeImageIHemi  L1WholeETDRS, DeepL2StartLayer L2Startoffsetum L2EndLayer Perimeter AcircularityIndex, by(Group)

A: A short answer is write a loop and customise output.
Here is a token example which you can run.
sysuse auto, clear

foreach v of var mpg price weight length displacement {
    quietly ranksum `v', by(foreign) porder
    scalar pval = 2*normprob(-abs(r(z)))
    di "`v'{col 14}" %05.3f pval " " %6.4e pval  "   " %05.3f r(porder)
}

Output is
mpg          0.002  1.9e-03   0.271
price        0.298  3.0e-01   0.423
weight       0.000  3.8e-07   0.875
length       0.000  9.4e-07   0.862
displacement 0.000  1.1e-08   0.921

Notes:

*

*If your variable names are longer, they will need more space.

*Displaying P-values with fixed numbers of decimal places won't prepare you for the circumstance in which all displayed digits are zero. The code exemplifies two forms of output.

*The probability that values for the first group exceed those for the second group is very helpful in interpretation. Further summary statistics could be added.

*Naturally a presentable table needs more header lines, best given with display.


Q: Executing external programs via commandline in a Grails application I am attempting to create a Java source file which will interface with my Grails application.  When a certain action is performed, I want this Java file to execute a program via commandline.  I am attempting to do this via the Runtime.getRuntime().exec() command, however I keep getting an error about the Runtime object being undefined.  Is it not possible to get a handle on this object through Grails?

A: If you are using Java 5 or later you are better off using ProcessBuilder rather than Runtime.exec. See here for more information.


Q: Find shortest path from s to every v with a limit on length
Let G(V,E) a directed graph with weights w:E->R. Let's assume |V| is dividable by 10. Let s in V. Describe an algorithm to find a shortest path from s to every v such that it contains exactly |V|/10 edges.

So at first I thought about using dynamic programming but I ended up with complexity of O(|V|^3) which apparently not optimal for this exercise.
We can't use Bellman-Ford (As far as I understand) since there might be negative cycles.
What could be an optimal algorithm for this problem?
Thanks
 EDIT
I forgot to mention a crucial information; Path can be not-simple. i.e. we may repeat edges in our path.

A: You can perform a depth limited search with limit of |V|/10 on your graph. It will help you find the path with the least cost.
limit = v_size / 10
best[v_size] initialize to MAX_INT

depth_limited(node, length, cost)
    if length == limit
        if cost < best[node]
            best[node] = cost
        return
    for each u connected to node
        depth_limited(u, length+1, cost + w[node][u])

depth_limited(start_node, 0, 0)

A: According to me Bellman Ford's algorithm SHOULD be applicable here with a slight modification.
After iteration k, the distances to each node u_j(k) would be the shortest distance from source s having exactly k edges.
Initialize u_j(0) = infinity for all u_j, and 0 for s. Then recurrence relation would be,
u_j(k) = min {u_p(k-1) + w_{pj} | There is an edge from u_p to u_j}

Note that in this case u_j(k) may be greater than u_j(k-1).
The complexity of the above algorithm shall be O(|E|.|V|/10) = O(|E|.|V|).
Also, the negative cycles won't matter in this case because we shall stop after |V|/10 iterations. Whether cost can be further decreased by adding more edges is irrelevant.


Q: How Can I Embed A Browser Window In Tkinter? I originally wondered about scraping the image from a site, however, somewhat giving up on that idea I am looking to embed a browser window into a Tkinter window, Ideally, it would be able to support multiple browsers for cross-platform support.
I have looked into the usage of Selenium but I am not entirely sure if it is possible to embed the Selenium browser instance into a Tkinter window. I have found no real solutions to this online and have no prior knowledge of embedding any sort of browser into Tkinter so I am really stuck and any help would be appreciated.


Q: Aligning an Image and text within a Div CSS I am trying to align an image and text within a div so it looks like the following

IMAGE          TEXT

However when I get them aligned as such, the background colour of the div no longer appears.
Can anyone suggest what I am doing wrong?
HTML:

Text

Good luck!!

css:
.introduction {
    margin: 0 50px;
    padding: 20px;
    background-color: #FFFFFF;
    color: #000000;
    -moz-border-radius: 10px;
    border-radius: 10px;
}
.image {
    width: 30%;
    float: left;
}
.text {
    width: 70%;
    float: left;
}

A: Putting the two floats in there side by side makes the parent container's height effectively 0. You can put a div with a style="clear:both;" before the parent's closing tag and you will get your background back.

    Text

Good luck!!

A: Something like this may achieve what you want:

Text

Good Luck

Since your p's aren't floated, they will hold your div open .. depending on the size of your image.

A: I would suggest you 2 solutions:
1) If you want to your output look like this:
IMAGE TEXT
IMAGE TEXT
      TEXT

HTML:

my text my text my text my text my text my text my text is so short I will die alone

CSS:
.ib{ display:inline-block;}
.whole{ vertical-align:top}

.ib img{width:30%; border:0;}
.ib p{width:70%;margin:0;padding:0;}

2) or like this:
IMAGE TEXT TEXT
TEXT TEXT

HTML:

my text my text my text is so short I will die alone

CSS:
.leftimg {
   float:left;
   margin-right:5px;
}

DEMO: http://jsfiddle.net/goodfriend/b66J8/37/


Q: Create groupings on data I have input data like this:

The output I require is grouping all the elements and giving distinct customers and total sales for each group. I have tried cross matrix, group by, and cube functions until now, but however, I am not getting the desired results.
Output expected:

Any help will highly appreciated.


Q: Python script as linux service/daemon Hallo,
I'm trying to let a python script run as service (daemon) on (ubuntu) linux.
On the web there exist several solutions like:
http://pypi.python.org/pypi/python-daemon/

A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. A DaemonContext instance holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state.

http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
However as I want to integrate my python script specifically with ubuntu linux my solution is a combination with an init.d script
#!/bin/bash

WORK_DIR="/var/lib/foo"
DAEMON="/usr/bin/python"
ARGS="/opt/foo/linux_service.py"
PIDFILE="/var/run/foo.pid"
USER="foo"

case "$1" in
  start)
    echo "Starting server"
    mkdir -p "$WORK_DIR"
    /sbin/start-stop-daemon --start --pidfile $PIDFILE \
        --user $USER --group $USER \
        -b --make-pidfile \
        --chuid $USER \
        --exec $DAEMON $ARGS
    ;;
  stop)
    echo "Stopping server"
    /sbin/start-stop-daemon --stop --pidfile $PIDFILE --verbose
    ;;
  *)
    echo "Usage: /etc/init.d/$USER {start|stop}"
    exit 1
    ;;
esac

exit 0

and in python:
import signal
import time
import multiprocessing

stop_event = multiprocessing.Event()

def stop(signum, frame):
    stop_event.set()

signal.signal(signal.SIGTERM, stop)

if __name__ == '__main__':
    while not stop_event.is_set():
        time.sleep(3)

My question now is if this approach is correct. Do I have to handle any additional signals? Will it be a "well-behaved Unix daemon process"?

A: Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use upstart.
Here's an example upstart config for a hypothetical Python service:
description "My service"
author  "Some Dude <blah@foo.com>"

start on runlevel [234]
stop on runlevel [0156]

chdir /some/dir
exec /some/dir/script.py
respawn

If you save this as script.conf to /etc/init you simple do a one-time
$ sudo initctl reload-configuration
$ sudo start script

You can stop it with stop script. What the above upstart conf says is to start this service on reboots and also restart it if it dies.
As for signal handling - your process should naturally respond to SIGTERM. By default this should be handled unless you've specifically installed your own signal handler.

A: Rloton's answer is good. Here is a light refinement, just because I spent a ton of time debugging. And I need to do a new answer so I can format properly.
A couple other points that took me forever to debug:

*

*When it fails, first check /var/log/upstart/.log

*If your script implements a daemon with python-daemon, you do NOT use the 'expect daemon' stanza. Having no 'expect' works. I don't know why. (If anyone knows why - please post!)

*Also, keep checking "initctl status script" to make sure you are up (start/running). (and do a reload when you update your conf file)

Here is my version:
description "My service"
author  "Some Dude <blah@foo.com>"

env PYTHON_HOME=/<pathtovirtualenv>
env PATH=$PYTHON_HOME:$PATH

start on runlevel [2345]
stop on runlevel [016]

chdir <directory>

# NO expect stanza if your script uses python-daemon
exec $PYTHON_HOME/bin/python script.py

# Only turn on respawn after you've debugged getting it to start and stop properly
respawn


Q: When to call File.Dispose() I am trying to use a text writer to write text to a file in .NET Core. The below code doesn't output anything to the file:
TextWriter writer = File.CreateText(@"...txt");
writer.Write("Hello World");

However, this does:
TextWriter writer = File.CreateText(@"...txt");
writer.Write("Hello World");
writer.Dispose();

Why is that? What does that extra line tell the program to do differently? I don't want to close the TextWriter because it is going to be writing logs, which are running constantly and indefinitely whilst my application is running.
How can I keep it open until the application stops running?
UPDATE
So the reason I want to do this, is I am using an SDK that writes its logs to a TextWriter:
TextWriterLogger(textWriter);
//Creates a logger that writes to a TextWriter. User is responsible for providing an instance of TextWriter that is thread safe.

But if I just enclose this in a using statement, logs won't be written because by the time they are ready to be written, the using statement will have executed and the TextWriter disposed.
Thanks

A: Dispose calls Flush, which writes the internal bytes stored in a buffer to disk
Without closing or disposing a file, you are leaving unmanaged resources around and will potentially lock the file, not to mention memory leaks. Instead always use a using statement
using (TextWriter writer = File.CreateText(@"...txt"))
{
   writer.Write("Hello World");
}

However if you want to continually write to the file, you will have to flush it
FileStream.Flush Method

Clears buffers for this stream and causes any buffered data to be
  written to the file.

TextWriter writer = File.CreateText(@"...txt");
...
writer.Write("Hello World");
...
writer.Flush(); // at this point the bytes are flushed to disk
...
...
writer.Dispose();

In short most streams are backed by an internal array (buffer), so you dont thrash writes. The Default size is 4k, when it hits the buffer size then it automatically flushes. If you want to see immediate writes, the you have to flush it every time
Lastly some streams have an auto flush feature, which can do this job for you
AutoFlush

Gets or sets a value indicating whether the StreamWriter will flush
  its buffer to the underlying stream after every call to Write(Char)

When you are finished with the stream always dispose it


Q: gdb layout asm doesn't work on mac? $ gdb test

(gdb) start
Breakpoint 1 at 0x100000ec8
Starting program: /private/tmp/test
Reading symbols for shared libraries +. done
Breakpoint 1, 0x0000000100000ec8 in main ()

(gdb) layout asm
Undefined command: "layout".  Try "help".

$ gdbtui
-bash: gdbtui: command not found

Is layout and gdbtui not available for Mac OS X? What are some alternatives?

A: According to this question there is no tui support on mac by default. So you have to compile gdb yourself with TUI enabled.


Q: Assembly 8088 - converting to hexadecimal I am trying to write an assembly code to do a file hexdump, just like in Linux when you do "hexdump -C sample.txt" from the command line. I got as far as opening the file and reading the contents into a buffer, but I can't get beyond, trying to convert those bytes to hexadecimal.
Any help would be greatly appreciated.
   _WRITE   = 4                !System call number for WRITE
   _READ    = 3                !System call number for READ
   _OPEN    = 5                !System call number for OPEN
   _EXIT    = 1                !System call number for EXIT
   _GETCHAR = 117                !System call number for GETCHAR
   _PUTCHAR = 122                !System call number for PUTCHAR
   _PRINTF  = 127                !System call number for PRINTF
   _SPRINTF = 121                !System call number for SPRINTF
   _SSCANF  = 125                !System call number for SSCANF
   _OPEN    = 5                !System call number for OPEN

   bufsiz  = 512                !bufsiz = 512

   .SECT .TEXT                !Start label
    start:
    MOV BP, SP            !System trap instruction
    MOV CX, de-greet
    PUSH CX
    PUSH greet
    PUSH _PRINTF
    SYS
    ADD SP, 8

    CALL GetFileInput

    Byte2Hexadecimal:

    !Conversion needs to take place here

    Word2Hexadecimal:

      !From Word to Hexadecimal needs to take place here

    GetFileInput:
    PUSH BP
    MOV BP,SP
    MOV DI, buf
    PUSH _GETCHAR

    next_char:SYS
    CMPB AL, '\n'
    STOSB
    JNE next_char
    JL 9f
    JE 1f
        MOVB (DI),0
        POP AX
        POP BP
        RET

    PUSH 0
    PUSH buf
    PUSH _OPEN
    SYS
    CMP AX,0
    JL 9f
    MOV (fildes),AX
    MOV SI,linh+2
    MOV BX,0

     1: CALL fillbuf
    CMP CX, 0
    JLE 3f
     2: MOV

      9: MOV SP,BP
     PUSH buf
     PUSH errmess
     PUSH _PRINTF
     SYS
     PUSH _EXIT
     PUSH _EXIT
     SYS

    OpenFile:

    fillbuf:
    PUSH bufsiz
    PUSH buf
    PUSH (fildes)
    PUSH _READ
    SYS
    ADD SP,8
    MOV CX,AX
    ADD BX,CX
    MOV DI,buf
    RET

   .EXIT:
    PUSH 0                !Return code
    PUSH _EXIT            !Return to OS
    SYS                !System trap instruction

    .SECT .DATA
    errmess:     .ASCIZ "Open %s failed\n"
    numfmt:         .ASCIZ "%d"
    greet:         .ASCIZ "Welcome to our program, please enter the file name: \n"
    de:         .BYTE 0

   .SECT .BSS
    linh: .SPACE 8192        !
    fildes: .SPACE 2        !Memory location for the fildes
     byte1:    .SPACE 8        !Memory location for the Byte
    addr:    .SPACE 8        !Memory location for the address
    word:   .BYTE  2          !Memory location for the byte
    buf:     .SPACE 80        !Memory location for the BUFF
    buffer: .SPACE bufsiz+2

A: There is no such thing as "converting the bytes into hexadecimal". The actual data is invariant and consists from binary ones and zeros. Your interpretation to these bits can be different, according to your needs. E.g., it can be interpreted as text character or decimal or hexadecimal or whatever value.
E.g.:
Binary 01010101 = decimal 85 = hexadecimal 55 = octal 125 = 'U' ASCII character.

A: A crude and simple implementation is to split the byte into two nibbles and then use each nibble as an index into a hex character "table".
; cdecl calling convention (google if you're not familiar with)

HEX_CHARSET        db '0123456789ABCDEF'

; void byteToHex(byte val, char* buffer)
proc byteToHex
    push bp
    mov bp,sp
    push di

    mov dx,[word ptr ss:bp + 4] ; the address of val
    mov di,[word ptr ss:bp + 6] ; the address of buffer

    ; high nibble first
    mov ax,dx
    mov cl,4
    shr al,cl
    push ax
    call nibbleToHex
    add sp,4
    stosb

    ; low nibble second
    mov ax,dx
    push ax
    call nibbleToHex
    add esp,4
    stosb

    pop di
    mov sp,bp
    pop bp
    ret
endp byteToHex

; char nibbleToHex(byte nibble)
proc nibbleToHex
    push bp
    mov bp,sp
    push si

    mov ax,[word ptr ss:bp + 4]
    and ax,0Fh    ; Sanitizing input param
    lea si,[ds:HEX_CHARSET]
    add si,ax
    lodsb

    pop si
    mov sp,bp
    pop bp
    ret
endp nibbleToHex

A: A hexadecimal digit has 4 bits in it. A byte has 8 bits in it or 2 hex digits.
To display a byte in hex, you need to separate each of those two 4-bit halves and then convert the resultant value of each (which, unsurprisingly, will be from 0 to 24-1, IOW, from 0 to 15 or from 0 to 0FH) to the corresponding ASCII code:
0 -> 48 (or 30H or '0')
1 -> 49 (or 31H or '1')
...
9 -> 57 (or 39H or '9')
10 (or 0AH) -> 65 (or 41H or 'A')
11 (or 0BH) -> 66 (or 42H or 'B')
...
15 (or 0FH) -> 70 (or 46H or 'F')
Once you've converted a byte into two ASCII characters you can call the appropriate API (system call) of your OS to display those characters either one by one or as a string (you'll probably need to append a zero byte after those two characters to make a string).
That's all.

A: The instructions explicitly say you're supposed to write this yourself!

; push ax  ; byte in al
; push outbuf
; call Byte2Hexadecimal
; add sp, 4

Byte2Hexadecimal:
    push bp
    mov bp, sp
    push di
    mov di, [bp + 4]  ; buffer to put it
    mov ax, [bp + 6]  ; we're only interested in al
    mov ah, al  ; make a copy
    mov cl, 4  ; ASSume literal 8086
    shr al, cl   ; isolate high nibble first
    add al, '0'  ; '0'..'9'
    cmp al, '9'  ; or...
    jbe skip
    add al, 7  ; 'A'..'F'
skip:
    stosb
    mov al, ah  ; restore our al from copy
    and al, 0Fh  ; isolate low nibble
    add al, '0'  ; etc...
    cmp al, '9'
    jbe skip2
    add al, 7
skip2:
    stosb
    pop di
    mov sp, bp
    pop bp
    ret

Untested(!)... something like that... (probably want to zero-terminate (or '$' terminate?) your buffer).
Insanely short way to convert nibble to hex ascii

cmp al, 0Ah
sbb al, 69h
das

You probably don't want to figure that one out... and das is dog slow anyway...
Now: What assembler? What OS?


Q: jQuery Add/Delete This snippet does what I want it to do with 1 exception.
It works correctly if the user presses "Add" over and over again - it removes the empty row and adds the new row.
If the user types something into the input field, that field is converted into table data.
The only problem I have is when the user presses "Add" twice, and the second "Add" is below the first.  It works if the second "Add" is above the first.
I'm sure it has something to do with the fact that I removed the row if the input value was empty.
<!DOCTYPE HTML>

<form name="myForm">

Add
Erase
One

Add
Erase
Two

Add
Erase
Three

<input name="Other">

</form>

A: This is happening because blur happens before click, in your code
$(this).parents("tr").remove();

is executing before the click happens, so there's actually nothing to click on (and bubble up to trigger the .live() event).  In your case, I would remove the add option from the currently being added row.


Q: android- handler.postDelayed how does it achieve the Delay for any task that had to be delayed I had been using: Handler.postDelayed(Runnable r,Long Delay) , but I just recently came across the documentation and it says this:

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached. The time-base is SystemClock.uptimeMillis(). Time spent in deep sleep will add an additional delay to execution.

I have two confusions in this:

*

*Is the delay achieved by adding the Runnable to the MessageQueue
after a specified delay of time?
Or,

*Is the Runnable added immediately and the function is delayed for
a specified time. If this is so there must be mechanism that the
Runnable is dequeued and put somewhere else so that other items in
the queue can be processed. How is the Runnable delayed and how is
the MessageQueue maintained during this delay?

A: runnable is immediately added to the message queue which can be seen in source code of the handler class postDelayed->sendMessageDelayed->sendMessageAtTime
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
{
    boolean sent = false;
    MessageQueue queue = mQueue;
    if (queue != null) {
        msg.target = this;
        sent = queue.enqueueMessage(msg, uptimeMillis);
    }
    else {
        RuntimeException e = new RuntimeException(
            this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
    }
    return sent;
}

queue.enqueueMessage runs a  for (;;) to delay the callback.
In this continuous loop message's time is checked for execution. you can see this in the source code

A: The structure we call Handler runs with a Looper which contains a MessageQueue inside it. A call to Handler.post(runnable) creates a new message for MessageQueue and puts it at the last of the queue, where its time is set as SystemClock.uptimeMillis(). Looper always loops for checking messages and if there is a message and the target time has been passed, it executes the Runnable inside it.
To clarify:
Handler.post(runnable) sends a message with SystemClock.uptimeMillis() where on the next check, the new SystemClock.uptimeMillis() becomes bigger than the message's execution time, allowing the Looper to fetch the runnable and execute it.
Now, if you use Handler.postDelayed(runnable, delay) it posts the message with SystemClock.uptimeMillis() + delay where the delay is in milliseconds, which we will call messageTime for now. What does the looper do? It checks the message, if SystemClock.uptimeMillis() is smaller than messageTime, it skips the execution. Looper always loops, so there becomes a time where SystemClock.uptimeMillis() actually becomes bigger than messageTime where the runnable becomes eligible for execution.
Unless you call Handler.postAtFrontOfQueue(runnable), the calls are always put to the bottom of the queue, not the top.
Finalize:
Handler.post(runnable) --> messageTime = SystemClock.uptimeMillis()
Handler.postDelayed(runnable, delay) --> messageTime = SystemClock.uptimeMillis() + delay.
Looper executes the runnables where SystemClock.uptimeMillis() >= messageTime. That's the gist of it.


Q: os.platform() Not Working Correctly In Website I'm using the built-in 'os.platform()' function in Node.js to get the home directory of a user when they sign in to a website so they can import files. In order to specify which path to look for those files in, I need to know the OS of the user's PC. When I run the code in my local server, it runs fine, returning "win32". However, when I deploy the website, it always reads "linux", which I can only assume is the operating system of the server. How can I make sure that "os.platform()" returns the client's OS and nothing else?
I should also mention that I am running this code with a console.log(os.platform()) in getInitialProps(). I've tried using navigator, window, and process.env.HOME but none of those have worked for me, as they always return undefined inside of getInitialProps().


Q: angularjs: if statement for displaying one image versus another i am new to angularjs.  i am trying to display a table with some data read from a db. one of the pieces of data i receive from DB is called IS_LOCKED.  if it's 1, i want to display an image of a locked padlock, else display an image of an unlocked padlock.
if i do the following in angular where i write out "LOCKED" and "UNLOCKED", the output table is correct:

            {{ x.NAME }}
            {{ x.IS_LOCKED==1 ? "LOCKED" : "UNLOCKED" }}

if i do the if statement and print out the url, it doesn't work....i get the code back and both images display, ie:  "{{ x.IS_LOCKED===1 ? (locked padlock image here) : (unlocked padlock image here)}}"

         {{ x.NAME }}
         {{ x.IS_LOCKED==1 ?  : }}

tried doing some ng-switch and other things, but kept getting compile errors.  sorry, new to angular...not sure if i am doing this correctly.  anyone know how to do this right?

A: Use ng-src


Q: toggle class content on click from nav I have a simple page with 15 elements in the Nav bar (only 4 in the jsfiddle example to keep the code short).
I have a javascript that moves the border-bottom display on click on the nav bar elements but I would also like the content of the div underneath to change based on which nabber item is clicks.
This is the jsfiddle.
Ive tried getElementByID but I somehow cant seem to change the class under my #tabs-content div...
I would like a javascript loop that changes the content of each section element's class from hide to show or show to hide depending on what the content is.
This is the o'clock event in my
*

Dashboard

and I would like it to change the class from hide to show for id=section2 and from show to hide for section2:

1

2

Any ideas please?
Cheers,
M.

A: Is this what you are looking for? Since you have the id of each section in the href you can pull that to load the appropriate one:
JS
var currentTab = $(this).find("a").attr("href");
$(currentTab).show().siblings("section").hide();

Change CSS (unless you want the elements to take up space on the page its better to set to display: none):
#tabs-content section.show {
  display: block
}

#tabs-content section.hide {
  display: none;
}

JSFIDDLE


Q: Using QGIS Expression String Builder to display selected multiple layers in a map in print composer In QGIS, in a Map's item properties, inside print composer, there is an option to "lock layers" (display layers) based on an expression, by using QGIS "expression string builder".
I can use as expression the name of a layer in my QGIS project, and that layer will display in the map in the print composer. I'm sure I am missing some basic operator, but how can I display more than one layer? Which function or operator do I need to use?

A: The answer lies in the documentation.
The expression must be similar to this:
concat ('layer 1', '|', 'layer 2')

In QGIS 3.2, you will now see the expected format for any expression. Read more in the changelog.


Q: Unit testing the obvious While trying to write test cases for a class whose functionality deals more with boiler plate code than business logic. I started wondering if unit testing is really worth for this class. But then again, when using TDD, we are advised to write test for any piece of logic we add.
As an example the below class, just uses DI to inject dependencies and get config parameters to set up the running of the application. Other than unit testing if dependencies are correctly injected, or if destroy is called when running finishes(which would be unit testing the java CDI framework than my own code), what else I can unit test?
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;

@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class PipsAlprConnectionRunner {
    @Inject
    private PipsAlprConfiguration config;

    @Inject
    private PipsAlprConnector connector;

    @Inject
    private Scheduler scheduler;

    @Inject
    @PipsAlprAdapterService
    private ServiceStatus status;

    private Timer connectorTimer = null;

    @PostConstruct
    public void initialized() {
        status.started();
        connectorTimer = scheduler.schedule(connector, 0,
                1000 * config.getPollPeriodSeconds());
        status.operational();
    }

    @PreDestroy
    public void destroy() {
        connectorTimer.cancel();
        connector.shutdown();
        status.stopped();
    }
}

I was unable to think of any testing scenarios to utilize TDD, on the above class, so just came up with the code, and now i am wondering what exactly can i unit test here.

A: Well, a case can be made that the class does something. It changes a status, it starts a timer. You can inject mocks of these objects into the class via Mockito and then make sure, that initialized() and destroy() both do what you expect them to do to these mocks.
@RunWith(MockitoJUnitRunner.class)
public class PipsAlprConnectionRunner {

    @Mock
    private PipsAlprConfiguration config;

    @Mock
    private PipsAlprConnector connector;

    @Mock
    private Scheduler scheduler;

    @Mock
    private ServiceStatus status;

    @InjectMocks
    private PipsAlprConnectionRunner pipsAlprConnectionRunner ;

    @Test
    public void initialized_should_set_status_started() {
         pipsAlprConnectionRunner.initialized();
         Mockito.verify(status).started();
    }

    // etc.
}

It's pretty much a question of personal taste if you want to create one method per "point of failure" or one method per method/test.
Personally, I would say that the goal is 100% coverage, so even pretty simple classes that mainly delegate should be covered. What happens if someone changes anything? The test ensures that such changes will not break existing functionality.


Q: How to get all the categories and sub categories in PostgreSQL? I am creating a small ecommerce demo app using .net core 5 with EF core and postgres 10.
I am trying to get all the categories and sub categories on my home page.
Here is my category hierarchy:
Men (Parent category)

*

*Topwear (Sub Category)

*

*Formal Shirts (leaf level category)

*T-Shirts (leaf level category)

Women

*

*India & Fusion Wear

*

*Kurtas & Suits

*Sarees

*FootWear

*

*Flat

*Heels

Here is my create table and insert script:
CREATE TABLE category
(
    id                uuid      DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL,
    parent_id         uuid                                             NULL,
    name              character varying(255)                           NOT NULL,
    short_description character varying(255)                           NOT NULL,
    activate_on       date                                             NULL,
    deactivate_on     date                                             NULL,
    url_segment       character varying(255)                           NOT NULL,
    meta_keywords     character varying                                NOT NULL,
    meta_description  character varying                                NOT NULL,
    sort_order        integer                                          NOT NULL,
    created_on        timestamp DEFAULT CURRENT_TIMESTAMP,
    created_by        character varying(100),
    modified_on       timestamp DEFAULT CURRENT_TIMESTAMP,
    modified_by       character varying(100),
    is_active         boolean
);

INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment,
                             meta_keywords, meta_description, sort_order, created_on, created_by, modified_on,
                             modified_by, is_active)
VALUES ('0ca0c27c-f45b-4768-a3cb-958bfbf6df26', '6dfdf5e4-673b-4134-b4a9-3a0b14b50e6a', 'T-Shirts', 'T-Shirts',
        '2021-02-21', NULL, 'men-tshirts',
        't shirt for mens india, t shirt for men online, polo t shirts, sport t shirt, black t shirt, blue t shirt, white t shirt',
        'Men''s T-shirts - Buy T-shirts for men online in India. Choose from a wide range of polo, round, V neck & more Men''s T-shirts in various designs at Myntra.',
        1, '2021-02-21 13:17:15.652506', 'glenn', NULL, '', TRUE);
INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment,
                             meta_keywords, meta_description, sort_order, created_on, created_by, modified_on,
                             modified_by, is_active)
VALUES ('6927198d-9240-43b0-853a-0507cad3b529', '6dfdf5e4-673b-4134-b4a9-3a0b14b50e6a', 'Formal Shirts',
        'Formal Shirts', '2021-02-21', NULL, 'men-formal-shirts',
        'Men''s formal shirts, formal shirts for men, slim fit formal shirts for men, latest formal shirts for men, formal shirts for men online, formal shirts for men India',
        'Formal Shirts for Men - Shop for trendy men''s formal shirts online in India at Myntra. ✯Free Shipping ✯Easy returns and exchanges ✯COD',
        2, '2021-02-21 13:21:16.125333', 'glenn', NULL, '', TRUE);
INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment,
                             meta_keywords, meta_description, sort_order, created_on, created_by, modified_on,
                             modified_by, is_active)
VALUES ('0d3f9e43-12a2-4f8c-a008-a45cbf15fedd', NULL, 'Women', 'Women', '2021-02-21', NULL, 'women',
        'women online shopping, online shopping for women, women clothing, women dresses online',
        'Online Shopping for Women. Shop Online from a wide range of womens clothing, shoes, Ladies bags & more in India @ Myntra ✯Free Shipping ✯COD ✯Easy returns and exchanges.',
        0, '2021-02-21 13:26:04.447031', 'glenn', NULL, '', TRUE);
INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment,
                             meta_keywords, meta_description, sort_order, created_on, created_by, modified_on,
                             modified_by, is_active)
VALUES ('6dfdf5e4-673b-4134-b4a9-3a0b14b50e6a', 'eb81c712-0643-45a2-b597-129a1f9892e2', 'Topwear', 'Topwear',
        '2021-02-21', NULL, 'top-wear', 'mens topwear', 'mens topwear', 1, '2021-02-21 13:12:30.518814', 'glenn',
        NULL, '', TRUE);
INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment,
                             meta_keywords, meta_description, sort_order, created_on, created_by, modified_on,
                             modified_by, is_active)
VALUES ('eb81c712-0643-45a2-b597-129a1f9892e2', NULL, 'Men', 'Men', '2021-02-21', NULL, 'men',
        'Men Topwear, Men Topwear in India, buy Men Topwear online in india, online store for Men Topwear, Shop online for Men Topwear, online shopping for Men Topwear, Online shopping for Men Topwear in India, reviews and prices',
        'Men Topwear Online. Shop for Men Topwear in India ? Buy latest range of Men Topwear at Myntra ? Free Shipping ? COD ? Easy returns and exchanges',
        0, '2021-02-21 13:10:29.204689', 'glenn', NULL, '', TRUE);
INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment,
                             meta_keywords, meta_description, sort_order, created_on, created_by, modified_on,
                             modified_by, is_active)
VALUES ('731b01bd-fab7-475e-adb2-6322eb9eac68', '0d3f9e43-12a2-4f8c-a008-a45cbf15fedd', 'India & Fusion Wear',
        'India & Fusion Wear', '2021-02-21', NULL, 'fusion-wear',
        'indo western fusion dresses, fusion kurtis, fusion saree, fusion dress, designer fusion wear, ethnic fusion wear, fusion wear online, indo western fusion, fusion outfits',
        'Buy Latest Collection of Women Fusion Wear online in India. Choose From Kurtas, Designer Sarees, Dresses, Lehenga Choli & more of brands like Mitera, Anouk, Biba & more at Myntra Fashion store ✯ COD ✯ Discounts',
        1, '2021-02-21 13:32:52.616545', 'glenn', NULL, '', TRUE);
INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment,
                             meta_keywords, meta_description, sort_order, created_on, created_by, modified_on,
                             modified_by, is_active)
VALUES ('3715c7fc-3c0e-4ee4-8fa0-dfd48e8e3a3a', '731b01bd-fab7-475e-adb2-6322eb9eac68', 'Sarees', 'Sarees',
        '2021-02-21', NULL, 'saree',
        'saree, sarees, women saree, new saree collection, fancy saree, online saree shopping, saree blouse designs,latest saree,new saree design,latest saree design, sari online',
        'Saree - Pick from the designer range of Saris online for ladies & girls. Buy formal, partywear, casual Sarees in various prints, patterns, types & more at Myntra store.',
        1, '2021-02-21 13:35:26.166935', 'glenn', NULL, '', TRUE);
INSERT INTO public.category (id, parent_id, name, short_description, activate_on, deactivate_on, url_segment,
                             meta_keywords, meta_description, sort_order, created_on, created_by, modified_on,
                             modified_by, is_active)
VALUES ('34c0d8ef-19a0-4f3a-8439-6d0510cfba04', '731b01bd-fab7-475e-adb2-6322eb9eac68', 'Kurtas & Suits',
        'Kurtas & Suits', '2021-02-21', NULL, 'women-kurtas-kurtis-suits',
        'kurtis online, designer kurti, ladies designers kurtis, designers kurtis, designer kurtis online, designers kurtis, suits online',
        'Women Kurtis & Kurtas Suits - Buy Designer Kurtas & Kurtis for Ladies online. Pick from Huge range kurtis, kurtas sets & suits for Women at Myntra ✯ COD ✯ Easy returns and exchanges',
        2, '2021-02-21 13:36:59.067196', 'glenn', NULL, '', TRUE);

I want to bring all the categories from my database in such a way that it is easy to bind on UI side like the above category hierarchy.
Can anybody help me with the query?

A: ---------- Revised
The determination of Parent, Sub, Leaf is relative simple:

*

*Row Child id is null then Parent.

*Row child id is not null and row has child row then Sub.

*Otherwise leaf.

The only difficultly is 2 above.
Now this can be flushed out a couple ways:

*

*With the same basic recursive CTE apply both lead and lag functions
in the main query then check for nulls. But with a hierarchy this gets messy in a hurry. So lets reject that idea.

*With slight modification to the CTE the non-recursive select is
Parents. In the recursive select see if the current has a child row
then Sub Category.

Modifying the CTE is not terribly bad, but select for it being a parent is still somewhat nasty looking. So the following abstracts this into a simple SQL function that returns the appropriate type (given that the id is known to be a child).
create or replace
function category_sub_or_leaf(id_in uuid)
  returns text
  language sql
  strict
as $$
    select case when exists (select null
                               from category
                               where parent_id = id_in
                            )
                then '(Sub Category)'
                else '(leaf level category)'
             end  ;
$$;

And the resulting query as:
with recursive heir (id, parent_id, name, short_description, sort_order, root_path, lev, cat_level) as
    ( select  id, parent_id, name, short_description, sort_order,(name)::text, 1, '(Parent Category)'
        from category
       where parent_id is null
      union all
      select c.id, c.parent_id, c.name, c.short_description, c.sort_order, root_path || '>'||(c.name)::text, lev+1
           , category_sub_or_leaf(c.id)
        from category c
        join heir     h
          on c.parent_id = h.id
    ) --select * from heir;
select  (rpad(' ', 4*(lev-1),' ') || short_description) || ' ' || cat_level   description
  from heir
 order by root_path,lev,sort_order;

See revised demo: Demo also flushes out Women's Foot Ware to provide and extra layer in Sub Category. I.E 2 layers of sub category. But as I did not want that much typing I modified table to not require anything but the necessary columns.
---------- Orig
What you are looking for is a recursive cte. Here the first (non-recursive term) select gets the rows which do not have parent_id defined. Then the recursive term (after union) looks back to the previous row and retrieves the child rows. (A poor description at best.) The query builds the path back to the first parent and the current depth. These generated columns are then used to provide order and indentation of the results. See Demo.
with recursive heir as
     ( select  id, parent_id, name, short_description, (name)::text path, 1 lev
         from category
        where parent_id is null
       union all
       select c.id, c.parent_id, c.name, c.short_description, path ||'>'||(c.name)::text, lev+1
         from category c
         join heir     h
           on c.parent_id = h.id
     )
select (rpad(' ', 4*(lev-1),' ') || short_description) short_description
  from heir
 order by path, lev ;

Note: Demo built with Postgres 13 so function gen_random_uuid() substituted for uuid_generate_v4().


Q: How to use ContactsContract as a Table in ContentProvider While setting the table viasetTable method in the query method of my ContentProvider, I am doing something like this :
queryBuilder.settable(getTable());

where my getTable() is :
private String  gettable(){
    String table;
    StringBuilder sb = new StringBuilder();
    sb.append(Table_1_Name);
    sb.append(" LEFT JOIN ");
    sb.append(Table_1_Name);
    sb.append(" ON (");
    sb.append(Table_1_Name.ID);
    sb.append(" = ");
    sb.append(Table_1_Name.ID);
    sb.append(")");
    table = sb.toString();
    return table;
}

Now instead of using Table_2_Name , i need to use ContactsContract.CommonDataKinds.Phone table. How can i do this. I need to filter some records in my where clause but first i dnt know how to use  ContactsContract.CommonDataKinds.Phone as a Table.


Q: Preventing suspend / sleep / hybernate of a server running LXDE on Ubuntu 18.04 after power up before login as a user Anyone knows how to keep an Ubuntu 18.04 file server with LXDE from going to a low power mode after power up?
Problem description:
I usually access my home server remotely with teamviewer. If power goes down and comes back up the computer reboots. After a short time, it goes to a low power mode and I cannot access it remotely.
If I see this happens and quickly login as a user and then go away, the computer does not go to that low power mode.
(I think the low power mode is called "suspend" but I'm not sure, maybe is sleep. I don't believe is hybernate because the desktop shows up quickly when I press the computer's power button.)
Update on Nov. 19, 2019:
Two things I tried that did not fix the problem:

*

*Disabling ACPI in the BIOS setup

*Masking these four things: sleep.target suspend.target hibernate.target hybrid-sleep.target (sudo systemctl mask [list of four], and then: sudo systemctl status [list of four] to confirm.)


Q: Sort (categories,Price...), number of products per page not working? I used magento 1.7 and i have a problem.
I am in my catalog that i have many categories list and Sort by Categories , Price ...
The problem when i go to the second page in the catalog it does not work, the url (from myurl to myurl#!___SID=U&p=2) is changed but the list of products does not change.
It does not work also when i click in the sub categories and or sort price.
What is my problem?

A: The problem is the # in the URL. This avoids the p parameter to be send to PHP, therefore it is not processed.
Whatever adds the # to the URL needs to be repaired.

A: In your \app\etc\local.xml set
<disable_local_modules>true</disable_local_modules>

If your problem disappears than it was caused by some module from local pool.
If it did not help, go to \app\etc\modules and disable all modules from community pool.
If problem disappears enable modules one by one to find out one which brakes catalog list behavior.


Q: Django how to use distinct() How to use distinct() in django

what i tried:
views.py
def gradescales(request):
    grade = gradeScalesSetting.objects.all().values_list('Rounding','Configuration').distinct()
    print(grade)
    return render(request, 'Homepage/gradescale.html',{"gradeScalesSetting":grade})

the result i got:

UPDATE this is data from my admin site

A: Probably the way you are using won't work. Because, you are sending a list but you are probably iterating through a queryset in template. Also, the way you are using distinct won't work. Because you are using 'Rounding','Configuration' togather, hence it will generate something like this:
<QuerySet [('Use Percentage Only', 'Up'), ('Use Percentage Only', 'Down'), ('Use Percentage Only', 'Half'), ...>

So you can try like this(without distinct):
grade = list(gradeScalesSetting.objects.all()) # < DB hit once

rounding = []
configuration = []

for i in grade:
   if i.Rounding not in rounding:
       rounding.append(i.Rounding)
   if i.Configuration not in configuration:
      configuration.append(i.Configuration)
return render(request, 'Homepage/gradescale.html',{"rounding":rounding, "configuration":configuration})

// in template
<select>
{% for r in rounding %}
   <option value={{r}}>{{r}}</option>
{% endfor %}
</select>

But with distinct you might have to hit the DB twice:
rounding = gradeScalesSetting.objects.all().values_list('Rounding', flat=True).distinct()
configuration = gradeScalesSetting.objects.all().values_list('Configuration', flat=True).distinct()


Q: ¿Como evitar que los eventos de un control se ejecuten tantas veces como se ingrese a una pagina con el data-dom-cache en true? Tengo una pantalla de captura, la cuál tiene el data-dom-cache activado, en la cuál debo seleccionar un cliente y uno o más productos, para hacerlo debo cambiar al listado de clientes que es una pagina aparte, lo mismo aplica para productos. Esto funciona correctamente,  el problema surge cuando doy clic en un colapcible (este se abre y se cierra varias veces)  o bien activo o desactivo un flipswitch se activa y desactiva tantas veces como se haya salido de la pantalla de captura para seleccionar clientes y productos, en el caso del flipswitch se tiene un evento change asignado en el cuál se agrego un console.log para comprobar lo que se comenta. Este comportamiento solo lo hace una vez, ya que si vuelvo a dar clic en el flipswitch trabaja normal.
Es un proyecto que trabaja en conjunto con cordova para dispositivos Android-iOS
El html tiene la etiqueta:

Datos documentos

           Datos documentos:
           <select class="flipSelect" id="opcCambiaEstado" data-role="flipswitch">
               <option value="0">No</option>
               <option value="1">Si</option>
           </select>

    `</div>`

Los eventos son asignados a través de un archivo js en la creación de la página.
$(document).on('pagecreate', '#CapturaDetalleCFDis', function(event) {
$("#pantallaCaptura #opcCambiaEstado").on("change", function(event) {
event.preventDefault();
documentos.cambioEstado();
event.stopPropagation();
event.stopImmediatePropagation();
return false;
});
});


Q: Micro-Service Simulator - Dapr pubsub I am trying to create a micro-service simulator using Dapr. Currently I can publish a message to a topic and another service subscribes to it. I want to able able to simulate a process where, once the subscriber receives the message, it will make an api call to another micro-service. These services do not do anything, since it is a simulator I just want to orchestrate service calls based on the topic each micro service subscribes to.This is the flow I am after :

*

*[Service - A ] publishes a message to a topic

*[Service - B ] Subscribes to the message published by service A and call another service, [ Service - C]

publisher code --> Service -A
@RestController
public class ServiceAController
{
String TOPIC_NAME = "test";
String PUBSUB_NAME = "simulatorpubsub";

//publish a topic in redis pubsub broker
@RequestMapping(path = "/hello")
public String someMethod()
{
    String str = "hello";
    DaprClient client = new DaprClientBuilder().build();
    client.publishEvent(
            PUBSUB_NAME,
            TOPIC_NAME,
            str).block();

    return "Message Delivered";
}
}

Subscriber Code-->Service - B
this is where i want to call another service , lets say C with url localhost:8091/hello-there
@RequestMapping
public class ServiceBController
{

private static final Logger logger =
LoggerFactory.getLogger(ServiceBController.class);

private static final HttpClient httpClient = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .connectTimeout(Duration.ofSeconds(10))
        .build();

RestTemplate restTemplate = new RestTemplate();
@Topic(name = "test", pubsubName = "simulatorpubsub")
@PostMapping(path = "/test")
public ResponseEntity<String> getCheckout(@RequestBody(required = false)
CloudEvent<String> cloudEvent) throws IOException, InterruptedException {
**I think this is where i am messing things up**
//        String url = "localhost:8091/hello-there";
//        HttpRequest request = HttpRequest.newBuilder()
//                .GET()
//                .uri(URI.create(url))
//                .build();
// HttpResponse response =
//  httpClient.send(request,HttpResponse.BodyHandlers.ofString());

    logger.info("Received :"  + cloudEvent.getData());
    return ResponseEntity.ok("SUCCESS");
 }
}


Q: jQuery Cookies not being set in Safari and IE Im using the jquery.cookie plugin to save my application data like this:
$.cookie('cookieTest', 'appDataHere', { expires: 7, path: '/' });
alert( $.cookie("cookieTest") );

But for some reason the above outputs "undefined" in Safari and IE..
Any ideas?
Works fine in FF and Chrome..


Q: Find files whose names are shorter than 7 characters and rename them to the .new file name Find files whose names are shorter than 7 characters and rename them to the .new file name
ls | grep -E "^.{,6}$"| xargs -I {} -t mv {} .new

no work

A: Use a for loop and a globbing pattern like this: for file in !(???????*); do mv $file $file.new; done
Thanks to xenoid for the correct glob pattern.

A: Using find with-regex:
... and assuming the files are in the current directory (given the initial question)
find -regextype egrep -regex '^.{1,6}$' -exec mv {} .new

Regexps in find accept various syntaxes so it is a good idea to be explicit. Also if you want so scan several directories, take note than unlike name, -regex applies to the whole path to the file, so an adequate patching pattern would then be '.*/[^\]{1,6}'

A: Considering that files with names of 1-6 characters are not those with 7 characters or more:
mv !(???????*) .new

(???????* matches names of 7 characters or more, and the !() negates it). This answer assumes that you have only one possible match (which your question seems to imply in its present form).
If you have several matches then use the pattern in afor loop:
for f in !(???????*); do ... ; done


Q: Find duplicate in data frame and change identified value I am stuck with probably a stupid and easy to solve issue.
I have a trigger that code 1 when the computer key is pressed (and) and 0 when the key is released. I need to identify each trigger start and stop (i.e., first and last 1) and replace the 1 in between by 0. The data record is time (continuous, t below) and value (electrodermal activity, value). To process the data more quickly, I need to preprocess it, that is identify the 1 corresponding to the beginning and the end of the window of interest.
Please find an exemple of the code:
t <- seq(0.1,10,0.1)

value <- rnorm(length(t), mean=1, sd=2)

trig <- c(rep(0,20),rep(c(rep(1,10), rep(0,10)),4))

id <- 1:length(t)

the expected output is
trig_result <- c(rep(0,20), rep(c(1, rep(0,8),1,rep(0,10)),4)); length(trig_result)

The use of duplicate only identify the first 1 and the last one but not the intermediate value. I have seen similar post, but none solve the identification issue.
I look into dplyr function but I cannot figure out how to replace the 1 in 0 to end the preprocessing phase.
Your help will be greatly appreciated.
Sincerely your,

A: Here's a base R solution with rle and cumsum:
result <- rep(0,length(trig))
result[head(cumsum(rle(trig)$lengths)+c(1,0),-1)] <- 1
all.equal(result,trig_result)
#[1] TRUE

Note that this solution assumes the data begins and ends with 0.

A: Here is another base R solution, using logical vectors.
borders <- function(x, b = 1){
  n <- length(x)
  d1 <- c(x[1] == b, diff(x) != 0 & x[-1] == b)
  d2 <- c(rev(diff(rev(x)) != 0 & rev(x[-n]) == b), x[n] == b)
  d1 + d2
}

trig <- c(rep(0,20),rep(c(rep(1,10), rep(0,10)),4))
tr <- borders(trig)

The result is not identical() to the expected output because its class is different but the values are all.equal().
trig_result <- c(rep(0,20), rep(c(1, rep(0,8),1,rep(0,10)),4))
identical(trig_result, tr)  # FALSE
all.equal(trig_result, tr)  # TRUE

class(trig_result)
#[1] "numeric"
class(tr)
#[1] "integer"

A: One option is to create a grouping index with rle or rleid (from data.table)
library(data.table)
out <- ave(trig, rleid(trig), FUN = function(x)
      x == 1 & (!duplicated(x) | !duplicated(x, fromLast = TRUE)))
identical(trig_result, out)
#[1] TRUE

A: You'd like to find the starts and ends of runs of 1s, and remove all 1s that aren't the start or end of a run.
The start of a run of ones is where the value of the current row is a 1, and the value of the previous row is a 0. You can access the value of previous row using the lag function.
The end of a run of 1s is where the current row is a 1, and the next row is a zero. You can access the value of the next row using the lead function.
library(tidyverse)
result = tibble(Trig = trig) %>%
    mutate(StartOfRun = Trig == 1 & lag(Trig == 0),
           EndOfRun = Trig == 1 & lead(Trig == 0),
           Result = ifelse(StartOfRun | EndOfRun, 1, 0)) %>%
    pull(Result)


Q: What happens step by step when using "rm -rf directory"? Let's assume that I have 150 GB of data in a directory and I have accidentally run this command for a directory.
Suddenly I realised, I should not put "/" in the beginning of directory and I cancelled command with Ctrl+C after a few seconds.
The directory is still there and there are currently folders from a to z but if it was windows I would know what is gone and what is not. I tried to test this command in a test server and I assumed that the command will delete folders starting with 0-9, then to a-z. In my tests, I couldn't verify this theory because either everything is gone or nothing got deleted.
Still curious though. Is that the case ? How this command exactly works step by step ? Did I lose some data ?

A:
How this command exactly works step by step ?

Recursively. rm will not delete a directory if its not empty. For that reason, it will first recurse into it, and delete its contents ("regular" files). This means that the unlinking process starts at the deepest level in your directory hierarchy, and goes up removing directories once they've been emptied. I guess you could put it this way (even though there may be slight variations) :
/
---- somedir                        <-- (5)
-------- a                          <-- (4)
------------ a                      <-- (3)
---------------- a                  <-- (2)
-------------------- somefile1.txt  <-- (1)
-------------------- somefile2.txt  <-- (1)
-------------------- somefile3.txt  <-- (1)
-------------------- [...]
---------------- b                  <-- (2)
---------------- [...]              <-- (2)
------------ b                      <-- (3)
------------ [...]                  <-- (3)
-------- b                          <-- (4)
-------- [...]                      <-- (4)

     ^   ^   ^   ^   ^
    (5) (4) (3) (2) (1)

By the way, rm has a -v option which will help you understand what happens as it runs.
-v, --verbose
    explain what is being done

Did I lose some data ?

Yes (that's very likely), at the bottom of your directory hierarchy. Unlinking a file is really quick, and if these files were small enough, it didn't take long for the kernel to get rid of data blocks associated with each one of them.
Go as far as you can within your directory: files like /dir/a/e/g/r/c/somefile (assuming the alphabetical sorting goes that far) are likely to be gone... Of course, the amount of data you lost depends on how quickly you hit Ctrl + C.