text:
Q: Why is my speed only limited to 12% of my max bandwidth? I subscribed in a 1Mbps broadband internet (data only). The provider said that customers would only get 60% of it which is approximately 600kbps of the 1Mbps, which is enough for me. But I've been observing my download speed and it is limited to only 12%, i can't get past 120kbps. Every time my DL speed exceeds 120kbps it suddenly drops down again. I think mine is filtered. Is there a way around this? My modem router is Prolink ADSL2+.

A: Are you sure that you're not hitting 120 kilobytes per second (kB/sec) (which is close enough to 1 megabit per second [mbps])? 1 kB/sec is the same as 8 kilobits per second (kbps)
See Wikipedia for more explanation on data rate units.

To bring an end to all the speculation going on here... what does http://www.speedtest.net/ tell you?

A: 1Mbps = 1 Mega bit per second and 1 byte = 8 bits so 1 Mbps = 0.125 Mega byte per second.
Bit is typically represented by a lowercase b. While byte is typically represented by an uppercase B
So 8 Mbps = 1 MBps.
This is a classic marketing ploy since all the speeds look like they're 8x faster.
On the plus side, you're actually getting the full bandwidth you're paying for. I pay for a line that's up to 10 Mbps and only ever get about 8 Mbps.
Edit: If you understand the bit vs byte issue, then make sure the speed readings you're getting are correct. Running a speed test while no other internet activity is happening is the best way to get an accurate reading of your connection speed, applications often have an inaccurate speed reading.

A: Actually, there are three things going on. One is the bits versus bytes issue that others have mentioned. Another is that line speeds are reported in decimal units, not binary units. And a third is that the line has to carry not just data but also address and control information.
A 1Mbps line carries 1,000,000 bits per second, or 125,000 bytes per second. Address and control information takes about 4% of the bandwidth, leaving about 120,000 bytes per second for data. A kilobyte of data is 1,024 bytes, so that means you would expect 117KB/s.
So you're dead on.

A: To try to simplify the other answers, providers report in Bits because they give higher numbers. Most applications report in bytes.
1mbps connection = 128KB/s. When downloading in Firefox, Steam, uTorrent, etc. the highest speed you will ever see is 128KB/s.
To reinforce what is happening, the difference between bytes and bits is 1/8, or 12.5%. This is surely what you're seeing.
As far as seeing the actual cap, your bandwidth is limited to the advertised 1mbps by the company, and you can often see the bandwidth jump initially beyond the limit before the ISP caps the speed. As an example, I have a 10mbps connection, but our ISP offers a 20mbps package. While my speed is usually maxed out at 1.25MB/s, I can initially see the speed jump up to 2MB/s before slowing down to the speed I'm paying for.

A: Some ISPs do take measures to cap bandwidth. Some have even covertly resorted to traffic shaping (limited speed based on the type of data). Whether they have the right to is debatable (see net neutrality).
Comcast was recently caught doing this with bitorrent data.
You can try to test this by downloading from various sources one at a time using different protocols and see if there are discrepancies. Keep in mind your speed is limited by the capacity of your download source as well. An overloaded website is going to be a slow download no matter what you try to do on your end.

A: I think your question is about file transfer rate, not differences in in connection rates.  It is not about bits or bytes or 1024.
Your file transfer rate will not be synchronous with your connection rate, it will be about 1/8th of the connection rate.  that is a MAX rate, so add to that the normal lag of the internet and you get total slowdown.  This is an internet fact.
A fact, that those of use using FTP have to deal with.  I have attampted to research the issue, but there is not alot of information out there, since not alot of people do FTP, some who do don't realize they are (Google Docs), most FTP activity is small files, and for large files you can just stream the content.
Generally, this is not a problem for DL, since we all have 10M or better home connections, so you can DL at about 1M.
Where this really sucks is on Upload.  Home internet connections have an upload rate of less then 1M, usually 768K or 512K.  1/8th of that sucks, about 100k is what  i get on a good day, average is around 35k.


text:
Q: RichEmbed field values may not be empty how to fix? i keep getting the error: RichEmbed field values may not be empty. and cant find out what the problem is. it does everything instead of reacting on his own command.
it says in chat /userinfo @name but then gives me the error and doesnt show the info it should
const Discord = require ('discord.js');
const bot = new Discord.Client();
const config = require ('./SecretStuff/config.json')
const prefix = config.prefix;
const snek = require ('snekfetch');

bot.on('ready', () => console.log("online!"));

bot.on("guildMemberAdd", (member) => {
    let guild = member.guild;
    let memberTag = member.user.tag;
    if(member.guild.channels.find(channel => channel.name === "welcomechannel"));
       guild.systemChannel.send("/userinfo" + " <@" + member.id + ">" )
    }

);

bot.on('message', async (msg) => {

if (msg.content.startsWith(prefix + "userinfo")) {
    let member = msg.mentions.users.first() || msg.author;
    let userembed = new Discord.RichEmbed()
        .setColor(msg.guild.member(member).highestRole.color)
        .setThumbnail(member.displayAvatarURL)

        .setTitle(`Here is ${member.username}'s info.`)
        .addField(`Name:`, member.username, true)
        .addField(`Id:`, member.id, true)
        .addField(`Bot:`, member.bot ? "Yes" : "No", true)
        .addField("Game:", msg.guild.member(member).presence.game ? msg.guild.member(member).presence.game.name : "Not Playing", true)
        .addField("Nickname:", msg.guild.member(member).nickname ? msg.guild.member(member).nickname : "None", true )
        .addField("Last Messsage:", member.lastMessage, true)
        .addField(`Roles:`, msg.guild.member(member).roles.map(s => s).join(" | "), true)
        .addField("Created At:", member.createdAt, true)
        .addField("JoinedAt:", msg.guild.member(member).joinedAt, true)
        msg.channel.send(userembed);
}

    });

let token = config.token;
bot.login(token)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mat-Table overlapping menu above when scrolling I've got a mat-toolbar placed above a mat-table inside a mat-tab, I'd like to keep the toolbar and the table headers visible at all times, however, when I scroll down the page, the toolbar becomes overlapped with the table.  The headers scroll up to the top of the mat-tab and I can't seem to get the table headers to stop at the bottom of the mat-toolbar.
Looking around, people have suggested using the sticky position css property, which works to keep my toolbar visible, but the table headers still overlap.  I'm not sure how to fix this.  Example below:
Image of header position before scroll

Image of header position after scroll

Layout
<mat-tab-group>
    <mat-tab>

            <mat-toolbar fxLayout="row" fxLayoutAlign="start space-between" ngClass="table-toolbar sticky-top">
                ....BUTTONS....
            </mat-toolbar>

                    ....TABLE....

    </mat-tab>
</mat-tab-group>

Styles
.table-toolbar {
    height: 80px !important;
    padding-left: 24px !important;
    min-height: 80px !important;
}

.sticky-top {
    top: 0 !important;
    z-index: 1000 !important; // This only makes it appear above or below the table
    position: sticky;
}

A: You could try overriding the mat-table header top position. Normally it is set to 0, You could override to the pixels you need. Here is the example.
https://stackblitz.com/angular/glmqladoole

.mat-table-sticky{
  top:80px !important;

}


text:
Q: Creating Double Record in SQL with SCOPE_IDENTITY Used (C #) I am developing a desktop application with c #.
I am trying to capture the last ID of the record added in SQL with Scope Identity.
It's worth it, but it creates duplicate records in the sql database.
Note: I apologize for the bad english (translated by Google Translate :))
On SQL Server (SP)
ALTER PROCEDURE [dbo].[ztSinifEgitimiEkle]
@islev                 NVARCHAR(MAX),
@ztSinifEgitimiDurumAtamaID            INT,
@ztSinifEgitimiDurumKisiID                 NVARCHAR(30),
@ztSinifEgitimiDurumKisiTipiID             TINYINT  ,
@ztSinifEgitimiDurumKatilim            BIT,
@ztSinifEgitimiEgitimAdi                 VARCHAR(50),
@ztSinifEgitimiAtamaEgitimID           int,
@ztSinifEgitimiAtamaEgitmenID          CHAR(30),
@ztSinifEgitimiAtamaKisiTipiID         TINYINT,
@ztSinifEgitimiAtamaTarihSaat          DATETIME,
@ztSinifEgitimiAtamaSüre               varchar(50),
@ztSinifEgitimiAtamaKategoriID         INT,
@ztSinifEgitimiAtamaEgitimTipi         Smallint
AS
/*
İşlev 0 ise : ztSinifEgitimiDurum2 tablosuna Insert Eder
İşlev 1 ise : ztSinifEgitimi2 tablosuna Insert Eder
İşlev 2 ise : ztSinifEgitimiAtama2 tablosuna Insert Eder

*/
IF @islev='0'
BEGIN
INSERT INTO [dbo].[ztSinifEgitimiDurum2]
        (
          AtamaID,
          KisiID ,
          KisiTipiID ,
          Katilim
        )
VALUES  (
          @ztSinifEgitimiDurumAtamaID   ,
          @ztSinifEgitimiDurumKisiID    ,
          @ztSinifEgitimiDurumKisiTipiID    ,
          @ztSinifEgitimiDurumKatilim
        )
END

IF @islev='1'
BEGIN

INSERT INTO [dbo].[ztSinifEgitimi2]
           (
           [EgitimAdi]
           )
     VALUES
           (@ztSinifEgitimiEgitimAdi
           )
SELECT SCOPE_IDENTITY() -- Son Kaydın IDsi

END

IF @islev='2'
BEGIN

INSERT INTO [dbo].[ztSinifEgitimiAtama2]
           ([EgitimID]
           ,[EgitmenID]
           ,[KisiTipiID]
           ,[TarihSaat]
           ,[Süre]
           ,[KategoriID]
           ,[EgitimTipi])
     VALUES
           (
            @ztSinifEgitimiAtamaEgitimID   ,
            @ztSinifEgitimiAtamaEgitmenID  ,
            @ztSinifEgitimiAtamaKisiTipiID ,
            @ztSinifEgitimiAtamaTarihSaat  ,
            @ztSinifEgitimiAtamaSüre       ,
            @ztSinifEgitimiAtamaKategoriID ,
            @ztSinifEgitimiAtamaEgitimTipi
          )

END

MY C# Code
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {

                if (egitimadi.Text.Length!=0)
                {
                    if (baglan.State == ConnectionState.Closed)
                        baglan.Open();

                    SqlCommand sqlCmd = new SqlCommand("ztSinifEgitimiEkle", baglan);
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@islev", 1);
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiDurumAtamaID", 0);
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiDurumKisiID", "");
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiDurumKisiTipiID", 8);
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiDurumKatilim", 1);
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiEgitimAdi", egitimadi.Text);
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiAtamaEgitimID", 1);
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiAtamaEgitmenID", "");
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiAtamaKisiTipiID", 8);
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiAtamaTarihSaat", "2017-01-01");
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiAtamaSüre", "");
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiAtamaKategoriID", 0);
                    sqlCmd.Parameters.AddWithValue("@ztSinifEgitimiAtamaEgitimTipi", 0);

                    String LastID = sqlCmd.ExecuteScalar().ToString();
                    sqlCmd.ExecuteNonQuery();

         SqlCommand sqlCmd2 = new SqlCommand("ztSinifEgitimiEkle", baglan);
                    sqlCmd2.CommandType = CommandType.StoredProcedure;
                    sqlCmd2.Parameters.AddWithValue("@islev", 2);
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiDurumAtamaID", 0);
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiDurumKisiID", "");
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiDurumKisiTipiID", 8);
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiDurumKatilim", 1);
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiEgitimAdi", "");
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiAtamaEgitimID", LastID);
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiAtamaEgitmenID", "");
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiAtamaKisiTipiID", 8);
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiAtamaTarihSaat", "2017-01-01");
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiAtamaSüre", "");
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiAtamaKategoriID", 0);
                    sqlCmd2.Parameters.AddWithValue("@ztSinifEgitimiAtamaEgitimTipi", 0);

                    sqlCmd2.ExecuteNonQuery();

                    button4.Enabled = false;
                    yenile();
                }
                else
                {
                    MessageBox.Show("Lütfen Tüm Bilgileri Doldurunuz.");
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Hata Mesajı");
            }
            finally
            {
                baglan.Close();
            }
        }
    }
}

After Scope on SQL
  https://prnt.sc/hvybtx
  http://prntscr.com/hvyctw
  http://prntscr.com/hvydd5

A: You are executing the command twice:
String LastID = sqlCmd.ExecuteScalar().ToString();
sqlCmd.ExecuteNonQuery();

Just do the first one.
As an aside, I prefer to use OUTPUT to get the last identity.
INSERT INTO [dbo].[ztSinifEgitimi2]
       (
       [EgitimAdi]
       )
OUTPUT inserted.ID -- or whatever your identity column is named....
VALUES
       (@ztSinifEgitimiEgitimAdi
       )


text:
Q: Supporting iOS 16 widget while maintaining compatibility with iOS 15 I can get accessory widget working in iOS 16, but my app needs to support iOS 15.
if #available(iOS 16, *) cannot be used in WidgetBundle.
@main
struct RememberWidgetBundle: WidgetBundle {
    @WidgetBundleBuilder
    var body: some Widget {
        RememberAccWidget() <-- only available in iOS 16.
        RememberWidget()
    }
}

@available(iOS 16, *)
struct RememberAccWidget: Widget {
    let kind: String = "Remember Accessory 1"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            RememberAccWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("Accessory Widget")
        .description(helpText)
        .supportedFamilies([.accessoryInline, .accessoryRectangular])
    }
}


text:
Q: binary file invalid content reading I would like to write a program that opens a text file that contains numbers.
The program should create a new binary file in which the first number is the number of numbers in the whole line.
My problem is that when I want to check if the program has written the numbers well, the number of numbers is written well, but the rest is the same for each line
EXAMPLE:

1.2222 0.2222 1111 0.111112 111111 5 3 1 9
4 4.33333 3.222  31.222
83883838 73.383883 83.344449494
12.3333 44444 322 9999.99999 7

this is what a file should look like

9 1.2222 0.2222 1111 0.111112 111111 5 3 1 9
4 4 4.33333 3.222  31.222
3 83883838 73.383883 83.344449494
5 12.3333 44444 322 9999.99999 7

and this is how it looks to me

9 12.3333 44444 322 9999.99999 7
4 12.3333 44444 322 9999.99999 7
3 12.3333 44444 322 9999.99999 7
5 12.3333 44444 322 9999.99999 7

#include <stdio.h>
#include <stdlib.h>
#define IN 1
#define OUT 0

struct rec
{
    size_t num;
    char *arr;
};

int number_of_numbers(char * buffer)
{
    int counter, state;
    int i;
   i=counter = state = OUT;

    while((buffer[i]!='\n')&&(buffer[i]!=EOF))
    {
        if(buffer[i]==' '||buffer[i]=='\t') state = OUT;
        else if(state==OUT)
        {
            state = IN;
            counter++;
        }
        i++;
    }

    return counter;
}

int how_many_lines(char *buffer)
{
    int i,counter;

    i=0;
    counter = 1;
    while(buffer[i]!=EOF)
    {
        if(buffer[i]=='\n') counter++;
        i++;
    }

    return counter;
}

int main()
{
    FILE *f,*f_2;

    long lSize;
    char *buffer;
    struct rec r;

    int i;

    f = fopen("f", "r");
    f_2=fopen("nf", "wb");
    if(!f) return 1;

    fseek(f, 0, SEEK_END);
    lSize = ftell(f);
    rewind (f);

    buffer = (char*)malloc(sizeof(char)*lSize);
    r.arr = (char*)malloc(sizeof(char)*lSize);

    while(fgets(buffer,lSize,f)!=NULL)
   {
       r.num = number_of_numbers(buffer);
       r.arr = buffer;
       fwrite(&r, sizeof(struct rec), 1, f_2);
   }
    fclose(f_2);

    f_2=fopen("nf", "rb");
    for(i=0; i<4; i++)
       {
         fread(&r,sizeof(struct rec),1,f_2);
           printf("%d %s \n",r.num, r.arr);

       }

    fclose(f);
    free(buffer);
    fclose(f_2);
    return 0;
}

I don't know if the problem lies in the record, if you read it or maybe somewhere else

A: struct rec
{
    size_t num;
    char *arr;
};

While writing a size_t to a file may make some sense, writing a char * to a file doesn't really make any sense. Remember, a char * is a fixed-length pointer that holds the address at which something is stored. What the point of writing the address at which something is stored into a file?
buffer = (char*)malloc(sizeof(char)*lSize);

Okay, so buffer always contains the address of this one block of memory that you allocated.
   r.arr = buffer;

So the value of r.arr is always the address of that one single block of memory. What's the point of writing the address of a block of memory to a file? And what's the point of writing the address of the very same block of memory to a file over and over? Maybe you want to try writing the contents of that buffer to the file instead?


text:
Q: M13Checkbox set Mixed CheckState on click I try to implement a M13Checkbox in tableViewCell.
I implemented a method responding to "ValueChanged" event but if I call sender.setCheckState(.Mixed, animated: false) in this method, the display of the checkbox is .Checked.
However if I do print(sender.checkState) the state of the checkbox is .Mixed.
Anything that i'm missing ? Do i use the write event?
Thanks for your help !
edit:
Event present in OptionsViewController:
  @IBAction func optionCheckChange(sender: M13Checkbox) {
    let rowPoint = sender.convertPoint(sender.frame.origin, toView: self.optionsTableView)
    let indexPath = self.optionsTableView.indexPathForRowAtPoint(rowPoint)
    sender.setCheckState(.Mixed, animated: false)
    print(sender.checkState)
  }

OptionTableViewCell code:
import UIKit
import M13Checkbox

class OptionTableViewCell: UITableViewCell {

  // MARK: Properties
  @IBOutlet weak var checkbox: M13Checkbox!
  @IBOutlet weak var label: UILabel!

  override func awakeFromNib() {
    super.awakeFromNib()
  }

  override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
  }

}


text:
Q: How install and run Android app on device by gradle task? Gradle 2.14

android {
    dev {
    }
}

   task runAppDev(type: Exec, dependsOn: 'installDev') {
        description "Install and run app (dev env)"
        android.applicationVariants.all { variant ->
            if ("installDev".toUpperCase().endsWith(variant.getName().toUpperCase())) {
                commandLine getRunAppCommandLine(variant)
            }
        }
    }

    def getRunAppCommandLine(variant) {
        List<String> commandLine = ["adb", "shell", "am", "start", "-n", variant.getApplicationId() + "/.activity.SplashActivity"]
       return commandLine
    }

Run my task by: gradlew runAppDev
Result:
Installing APK 'app-dev.apk' on 'Nexus 5 - 6.0.1' for app:dev
Installed on 1 device.
:app:runAppDev
BUILD SUCCESSFUL
So, my application success installed on device, but NOT run on device.

A: I found bug. I send incorrect adb arg. Here fix:
 def getRunAppCommandLine(variant) {
   List<String> commandLine = ["adb", "shell", "monkey", "-p", variant.getApplicationId() + " 1"]
   return commandLine
}


text:
Q: How to create unscubscribe functionality to let user unsubscribe from in-app subscription purchase? I am building code to let a user subscribe to an in-app purchase subscription.
But I do not see any tutorials or examples (even from the official site) to let the user unsubscribe. Could anyone please point me to a tutorial for this, or please explain how users can unsubscribe from my in-app subscriptions?
Thank you@

A: That is not possible.  Users have to go to iTunes and set the subscription to not auto-renew themselves.


text:
Q: Why is this code for getting a two-digit month number not working? I'm trying to produce a line item ID by turning the date (in cell A2, formatted as YYYY-MM-DD) into a six-digit date followed by a sequential identifier - the end result for the fourth edit made today, for instance, would be 151209-4.
The date is in A2, the sequence number is in B2.
I've tried =MONTH(A2) on its own, and it returns the right month. However, as soon as I try to use =TEXT(MONTH(A2),"mm") or any variation of it, it just keeps spitting out January.
The full function I'm using is
=IF(ISBLANK(A2),"",CONCATENATE(RIGHT(YEAR(A2),2), TEXT(MONTH(A2),"mm"), TEXT(DAY(A2),"dd"), "-", B2))

Any idea what could be the problem?

A: This should work:
=IF(ISBLANK(A2),"",CONCATENATE(TEXT(A2,"yy"),TEXT(A2,"mm"),TEXT(A2,"dd"),"-",B2))


text:
Q: How to put a matrix in Reduced Echelon Form
5. (6 pts)
  Find a basis for the following subspace:
  $$
  \left\{
    \begin{bmatrix}
       r -  s - 2t -  u \\
      -r + 2s + 5t + 2u \\
            s + 3t +  u \\
      3r +  s + 5u
    \end{bmatrix}
    \in \mathbb{R}^4
  :
    \text{$r, s, t$ and $u$ are scalars}
  \right\}.
$$
Original image here.

So I have this matrix:
$$\begin{pmatrix}
1 &-1 &-2 &-1 \\
-1 &2& 5 &2 \\
0 &1 &3 &1 \\
3 &1 & 0 & 5
\end{pmatrix}
$$
If I compute the the matrix in reduced echelon form, I get:
$$\begin{pmatrix}
1&0&1&0\\
0&1&0&3\\
0&0&1&-2/3\\
0 & 0 & 0 & 0
\end{pmatrix}$$
Please note that i want to put the matrix in reduced echelon form , and not row reduced echelon form.
I  know that the three rules of reduced echelon form are:
1) The first non zero number of a row is 1 (leading entry).
2) An all zero row is placed at the end of the matrix.
3)A leading entry of a row is placed to the right of a leading entry of the previous row.
If it were to be in row reduced echelon form , then another property would hold, or else that each column that contains a leading entry, all other entries in the same column are zeros.
So is my matrix correctly put in a row echelon form ?

A: I think you are confused on terminology. Your matrix is correctly put into one of its row echelon forms. Note that these are not unique, as we could add the second row to the first row and the result would still be in row echelon form, that is,
\begin{pmatrix}
1&1&1&3\\
0&1&0&3\\
0&0&1&-2/3\\
0 & 0 & 0 & 0
\end{pmatrix}
Is still in row echelon form. In order to get to the reduced row echelon form (sometimes called reduced echelon form), we must, as you said, make $0$'s in every column which contains a leading $1$. In your example, we can subtract the third row from the first
\begin{pmatrix}
1&0&1&0\\
0&1&0&3\\
0&0&1&-2/3\\
0 & 0 & 0 & 0
\end{pmatrix}
to obtain
\begin{pmatrix}
1&0&0&2/3\\
0&1&0&3\\
0&0&1&-2/3\\
0 & 0 & 0 & 0
\end{pmatrix}
Which is now in reduced row echelon form. Hopefully that clears up any confusion you had.

A: With reference to the original problem we need to find a basis for
$$\begin{bmatrix}
r-s-2t-u \\
-r+2s+5t+2u \\
s+3t+u \\
3r+s+5u
\end{bmatrix}=\begin{pmatrix}
1 &-1 &-2 &-1 \\
-1 &2& 5 &2 \\
0 &1 &3 &1 \\
3 &1 & 0 & 5
\end{pmatrix}\begin{pmatrix}
r \\
s \\
t \\
u
\end{pmatrix}$$
note that the LHS is a vector $\in \mathbb{R^4}$ and in the RHS the given coefficients are arranged by columns, therefore we need to find a basis for the column space of the matrix in on the RHS.
Then we have
$$\begin{pmatrix}
1 &-1 &-2 &-1 \\
-1 &2& 5 &2 \\
0 &1 &3 &1 \\
3 &1 & 0 & 5
\end{pmatrix}\to \begin{pmatrix}
1 &-1 &-2 &-1 \\
0 &1& 3 &1 \\
0 &1 &3 &1 \\
3 &1 & 0 & 5
\end{pmatrix}\to \begin{pmatrix}
1 &-1 &-2 &-1 \\
0 &1& 3 &1 \\
0 &1 &3 &1 \\
0 &4 & 6 & 8
\end{pmatrix}\to \begin{pmatrix}
1 &-1 &-2 &-1 \\
0 &1& 3 &1 \\
0 &0 &0 &0 \\
0 &0 & -6 & 4
\end{pmatrix}\to \begin{pmatrix}
1 &-1 &-2 &-1 \\
0 &1& 3 &1 \\
0 &0 & -6 & 4\\
0 &0 &0 &0
\end{pmatrix}$$
which is the RREF. From here we can conclude that a basis is given by the first three vectors of the original matrix that is
$$\{(1,-1,0,3),(-1,2,1,1),(-2,5,3,0)\}$$
Note that we can also continue and obtain
$$\to \begin{pmatrix}
1 &0 &1 &0 \\
0 &1& 3 &1 \\
0 &0 & 1 & -\frac23\\
0 &0 &0 &0
\end{pmatrix}\to \begin{pmatrix}
1 &0 &0 &\frac23 \\
0 &1& 0 &3 \\
0 &0 & 1 & -\frac23\\
0 &0 &0 &0
\end{pmatrix}$$
the latter is the Gauss-Jordan form of the RREF but it is not needed to establish a basis for the given subspace.


text:
Q: ipad SplitView title on popup How do you change the the title on the popup window in a split-view project? It currently says "Root View Controller" in a split-view project?

A: If you don't mind having the same title when it's also in landscape mode (no popup), then in the viewDidLoad method of RootViewController, you can do:
self.title = @"Title Here";

or in IB:

*

*open MainWindow.xib

*double-click the Split View Controller

*click on the navigation bar (where it says "Root View Controller")

*in the Navigation Item Attributes Inspector, you can enter a new title

If you want one title in landscape and another for the popup, that can be done by adding code in the willHideViewController and willShowViewController delegate methods.  In the standard split view template, these are implemented in DetailViewController.
The code would be (assuming the left side view controller is a navigation controller like in the template):
//in willHideViewController:
((UINavigationController *)aViewController).topViewController.title
    = @"Title For Popup Mode";

//in willShowViewController:
((UINavigationController *)aViewController).topViewController.title
    = @"Title For Landscape Mode";


text:
Q: Is image slider possible in wordpress post I am writing a post in which I've following images line by line which I need to set as a slider.
Theme is generatepress.

Will it require coding or a plugin will help.
Looking forward for helpers. Any source is appreciated

A: I'm not familiair with generatepress, but with almost any theme; if you want to customize the content with functionality that is not in the theme, you will have to use either a plugin or code a child theme.
There are lots of slider plugins out there, so just read their intro's and documentations. I mean...   click
Look for plugins that can insert sliders with shortcodes, or have other means of inserting sliders into existing pages, so that you can still use generatepress for pages and posts.


text:
Q: Javascript Regex to filter String I need Regex to filter string to fit with the following conditions :

*

*The total length of the string cannot exceed 300 characters.

*The string cannot contain more than 4 hashtags.

*The string cannot contain more than 1 URL.

*The string cannot consist of all capital letters.

Example Valid Text :

Developers trust #StackOverflow to help solve #coding problems and use
  Stack Overflow Careers to find job opportunities. Please visit
  https://stackoverflow.com/

Example Invalid Text :

Developers trust #StackOverflow to help solve #coding problems and use
  Stack Overflow Careers to find job opportunities. Please visit
  https://stackoverflow.com/ or https://stackoverflow.com/company/about

Invalid string above because there are containing two URL.
Any help would be appreciated and thank you very much :)

A: I think this will help you
^(?!^([^#]*#[^#]*){5,}$)(?!(.*http(s{0,1}):\/\/){2,})(?=.*[a-z]).{0,300}$

*

*(?!^([^#]*#[^#]*){5,}$) this will ensure that string should not contain more then 4 #

*(?!(.*http(s{0,1}):\/\/){2,}) this will ensure that string should not contain more then 2 url

*(?=.*[a-z]) this will ensure that string should contain at least 1 lower case letter

*.{0,300} this will ensure that string should contain not more then 300 charter


text:
Q: Where is the KEYDEF in sort command? I need to sort the results of 'du' command by file or folder name, file size, or last modified time in various situations, and appending ' | sort -k 2' command after 'du' command sorts the results by folder names, which I learned from this question.
Sort by filename with du command
In the sort command manual (RHEL 7.6), it reads
-k, --key=KEYDEF          sort via a key; KEYDEF gives location and type
KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a
field number and C a character position in the field;
but still don't understand what it means.
Does F=2 means file name?
Then what is the F for the file size or last modified time?
Then where can I find the 'KEYDEF'?
I carefully read this document:
https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html
but still can't find the information.

A: F is the field number, and by default, the sort command defines a field as text surrounded by white space. The -b and -t options can change the default; the document you reference contains a lengthy headache-inducing discussion about the details of specifying field separators depending on locale and such.
You ask "what is the F for the file size or last modified time?". sort doesn't have the notion of file size or modified time. Since your goal is to filter the output of du, run your du command and count the fields.
For example, when I run du without option, I get two fields per line, the size and the file/directory name:
$ du .
8       ./ruby
4       ./nextcloud/data/nextcloud
12      ./nextcloud/data/database/nextcloud
4       ./nextcloud/data/database/performance_schema
4       ./nextcloud/data/database/mysql
... etc ...

In case you need to sort files and directories under the current directory, du . | sort -n does the trick, because sort sorts on the first field by default. The -n option is required to sort numerically rather than alphanumerically:
$ du . | sort -n
4       ./bitwarden/data/icon_cache
4       ./.cache/obexd
4       ./.cache/pip/wheels/2c/4a/61/5599631c1554768c6290b08c02c72d7317910374ca602ff1e5
4       ./.cache/pip/wheels/33/56/20/ebe49a5c612fffe1c5a632146b16596f9e64676768661e4e46
4       ./.cache/pip/wheels/88/a7/30/e39a54a87bcbe25308fa3ca64e8ddc75d9b3e5afa21ee32d57
4       ./.cache/pip/wheels/fc/a8/66/24d655233c757e178d45dea2de22a04c6d92766abfb741129a
... etc ...

You can add -r to display big files first.
To sort by pathname:
du . | sort -k 2

I don't have a quick solution for sorting by filename, i.e. by the last component of the pathname. I think sort alone can't to that, because you would need to figure out which subfield is the filename, and the subfield number varies. Here is a partial solution (it only works for pathnames that contain a slash):
$ du . | sed 's|\(.*\)/\(.*\)|\1/\2 \2|' | sort -k3
5639116 .
12      ./.cache/pip/http/9/8/7/0 0
12      ./.cache/pip/http/9/c/b/c/0 0
12      ./.cache/pip/http/c/0/4/0/0 0
12      ./.cache/pip/http/f/0/3/0 0
12      ./.cache/pip/http/f/e/d/0 0
136     ./.cache/pip/http/4/8/d/7/0 0
164     ./.cache/pip/http/a/0 0
16      ./.cache/pip/http/0/0/9/7/0 0
16      ./.cache/pip/http/2/8/0 0
... etc ...

I don't know if there is any combinations of options that makes the du command print the modified time. If there is one, let me know, and I will point out which field it is.


text:
Q: How to toggle a button when another button is clicked? I have 2 sample buttons, and what I need is when a user clicks on the second button, the first button will change its text.
Please see sample below:

$(document).ready(function() {
  $('#anchor-sample-btn').on('click', function() {
    var text = $('#anchor-sample-btn').text();
    if (text === "On") {
      $(this).html('Off');
    } else {
      $(this).text('On');
    }
  });
});

<button class="outline" id="anchor-sample-btn">On</button>

 When the second btn is clicked, the first btn should change to On if it's Off, and vice versa

<button class="outline">When I'm clicked, toggle the first btn on/off</button>

Also, how do I disable the first button when it's clicked for 5 seconds to prevent double click?
EDIT:
When the first btn is clicked, it should still change text and be disabled for 5 seconds.
The second button is just an alternative to perform the same function of the first btn, so it should toggle the first on/off.
Thanks a lot in advance!

A: You can do it in many ways, this is one way (not using jQuery).

const $btnOne = document.querySelector('#button-one');
const $btnTwo = document.querySelector('#button-two');

let buttonOneIsOn = true;

$btnTwo.addEventListener('click', () => {
  buttonOneIsOn = !buttonOneIsOn;
  $btnOne.innerText = buttonOneIsOn ? 'On' : 'Off';
});

$btnOne.addEventListener('click', () => {
  buttonOneIsOn = !buttonOneIsOn;
  $btnOne.innerText = buttonOneIsOn ? 'On' : 'Off';

  $btnOne.disabled = true;
  setTimeout(() => {
    $btnOne.disabled = false;
  }, 5000);
});
<button id="button-one">On</button>

When the second btn is clicked, the first btn should change to On if it's Off, and vice versa

<button id="button-two">When I'm clicked, toggle the first btn on/off</button>

A: One approach is to just trigger the click on the first when the second is clicked

$(document).ready(function() {
  // nothing changed here
  $('#anchor-sample-btn').on('click', function() {
    var text = $('#anchor-sample-btn').text();
    if (text === "On") {
      $(this).html('Off');
    } else {
      $(this).text('On');
    }
  });

  // listener on second button that triggers first
  $('#button-2').click(function(){
     $('#anchor-sample-btn').click()
  })

});

<button class="outline" id="anchor-sample-btn">On</button>

 When the second btn is clicked, the first btn should change to On if it's Off, and vice versa

<button class="outline" id="button-2">When I'm clicked, toggle the first btn on/off</button>

A: To avoid repetition, you could add them to the buttons with that have the same classes.

const btns = document.querySelectorAll('.outline');
const anchorBtn = document.querySelector('#anchor-sample-btn');
let btnOn = true;

btns.forEach(btn => {
  btn.addEventListener('click', (e)=> {
    let target = e.target;
    anchorBtn.textContent = btnOn ? 'Off' : 'On';
    btnOn = !btnOn;
    if(target.id === 'anchor-sample-btn'){
      target.disabled = true;
      setTimeout(()=>{
        target.disabled = false;
      },5000);
    }
  });
});
<button class="outline" id="anchor-sample-btn">On</button>

 When the second btn is clicked, the first btn should change to On if it's Off, and vice versa

<button class="outline">When I'm clicked, toggle the first btn on/off</button>

A: Check out which button should have onclick event and how you handle it.

$(document).ready(function() {
  $('#clickme').on('click', function() {
    var target = $('#anchor-sample-btn');
    var text = target.text();
    if (text === "On") {
      target.text('Off');
    } else {
      target.text('On');
    }
  });
});

<button class="outline" id="anchor-sample-btn">On</button>

 When the second btn is clicked, the first btn should change to On if it's Off, and vice versa

<button id="clickme" class="outline" href="#anchor-sample-btn">When I'm clicked, toggle the first btn on/off</button>


text:
Q: if- else statement in one line code python; syntax error I just want to convert the number in text and if it is a text just return the word, but I get a syntax error after else. Is it possible to write the statement in one line?
text = [p.number_to_words(words) for words in text if words.isdigit() else words]

A: Just move the if ... else before the for ... in:
text = [p.number_to_words(words) if words.isdigit() else words for words in text]


text:
Q: update row if already exists in mysql I have a table in mysql like this
Name              Result
T1_09_03_2010     fail
T2_09_03_2010     pass
T3_09_03_2010     pass
T4_09_03_2010     fail
T5_09_03_2010     fail
T6_09_03_2010     pass
T7_09_03_2010     fail

Well, T1_09_03_2010 is testcase name. If for some reason the developer wants to test the same testcase again in the same day, using the same name then, I need a way to update the already existing row based on the result.
Say , for example T1_09_03_2010 has failed in this context and if this is run again and the result is pass, it should update the row, but if the result if fail, then it should leave the result as it is I mean ignore the new insert and carry on with others.
Thanks.

A: here is an example syntax for mysql:
INSERT INTO users (username, email) VALUES ('Jo', 'jo@email.com')
ON DUPLICATE KEY UPDATE email = 'jo@email.com'

A: You should use the INSERT... ON DUPLICATE KEY UPDATE .. syntax.


text:
Q: Angular : how to exclude the angular app from optimizer For test purpose, I'd like to exclude my angular app from being optimized when running ng build, but at the same time I want the vendor files to be optimized.
I cannot find a way to do that. I can exclude files from being build, but that's not what I'm looking for. Is this possible ?
This is my build command :
ng build --prod --configuration=deploy
with :

"deploy": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": true,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "angularApp/environments/environment.ts",
                  "with": "angularApp/environments/environment.deploy.ts"
                }
              ]
            }

A: use this cmd for building your project
ng build --vendor-chunk
--vendor-chunk — extract all vendor (library) code into separate chunk


text:
Q: MS SQL login periodically doesn't work
*

*Instance info: Microsoft SQL Server 2017 (RTM-CU13) Standard Edition (64-bit) on Windows Server 2019 Datacenter

*Location: AWS

A Java app on another AWS server logs into the SQL instance using a local SQL account, and 95% of the time, the login connects, and everything is fine. The other 5% I get following error:

"Login failed for user 'Blah.' Reason: Failed to open the explicitly specified database 'Blah_Database.' [CLIENT: xxx.xxx.xxx.xxx]"

I know the 2 IP's that the login request is coming from and the connection string names the database which is present. The permissions are set correctly.
I've captured the event running a Profiler Trace looking for Event Class "Audit Failed Login." But, This doesn't give me any more info than the SQL error log.
Any other event classes I can add to the profiler to gather more info?
I've verified the the database Auto-Close feature is off. I've also increased the remote login timeout to 30.

A: Perhaps AWS has some stuff similar to Azure Serverles' functionality? I.e., it takes a while to spin up the database. I would increase the connection timeout drastically as a first test and then take it from there.

A: @Alonzo, once it happened to me that we upgraded a software through a setup.exe file.
The installation was fine but because there was a load balancer involved the upgrade actually took place only on 4 databases out of 5.
In the end 80% of our transactions were successful and 20% were failing for no reason.
It took us some time to understand that we had to manually apply that upgrade also on the 5th database.
So check if you find yourself in this scenario.


text:
Q: Скрыть текст в Inkscape Есть 1000 svg картинок внутри которых содержится слои с изображением и текст, мне нужно экспортировать только изображения в *.png, как скрыть или удалить текст?,так как руками не вариант экпорт делаю через командную строку >inkscape D:\Test\1.svg -С -e D:\Test\1.png но в этом случае экпортируется все включая текст. На официальном сайте не нашел инфу какой командой выполнить скрытие / удаление текста в *.svg перед экспортом. Спасибо за помощь.

A: Решение простое:
Удалит слой с текстом
ваш_svg --select=название_слоя_с_текстом --verb=EditDelete --verb=FileSave --verb=FileQuit


text:
Q: Extension created via contentful-cli does not load on localhost I was trying to create my own UI field extension using the steps given on Contentful documents below:
https://www.contentful.com/developers/docs/extensibility/ui-extensions/managing-a-ui-extension/
For some reason my localhost:1234 server runs but nothing is loaded... The sdk's init function does not seem to fire due to which there is nothing getting added in the root div.
I also tried cloning the sample extension
https://github.com/contentful/extensions/tree/master/samples/external-api
This too does not load anything on localhost
Please help if anyone has successfully tried this before

A: Contentful DevRel here.
The idea behind Contentful UI extensions and Apps is that they are websites that run in an iframe in the the Contentful UI.
// the below callback will only be called
// when the code runs in a iframe in the Contentful UI
window.contentfulExtension.init(function (sdk) {
  var value = sdk.field.getValue();
  sdk.field.setValue("Hello world!");
});

You're right, that the init block above is not firing when you're opening your locally running extension server in your browser. The reason here is that the Extensions SDK provides functionality and communication with the surrounding Contentful Interface. Without Contentful UI around it, it won't work.
The SDK will only call your init callback when localhost or any other URL is loaded inside the Contentful UI. For a development flow of UI Extensions or Apps localhost will be loaded right in the UI until you deploy your extension. :)
I don't know how you set up your extension so far, but I recommend to have a look at the video in the docs that you linked. It goes into detail of how to set up a UI extension in the Contentful UI.


text:
Q: evaluate the integral \[\int_{a>0}^{\infty}\frac{1}{1+x^{\alpha /2}}dx\] Could you  please help to evaluate the above integral
A form based on hypergeometric functions will be considerered closed form

A: Using Mathematica you can get the result for special values of $\alpha$ or $a$:
Assuming:
$$
\left(1\leq a ~~ \text{Or} ~~ \alpha <  \frac{2\pi}{\arccos(a)} ~~ \text{Or} ~~ \exp\left(\frac{2i\pi}{\alpha}\right) \notin \text{I}\!\text{R}\right) ~~ \text{And} ~~ \alpha>2
$$
you get
$$
\int_{a>0}^{\infty}\frac{1}{1+x^{\alpha /2}}\,\text{d}x= \frac{2a^{1-\alpha/2}}{\alpha-2}\, _0F_2\left(1;\frac{b-2}{\alpha};2-\frac{2}{\alpha};-a^{-b/2}\right)
$$


text:
Q: Suffix '-ine' vs. suffix '-like' In previous questions we learnt how to use words like 'asinine', 'bovine', 'canine' and 'feline', so, after some deep thoughts,  a question arose in my  mind: why does English, in some cases, not use the suffix -ine when describing an animal trait or characteristic present or recognizable in the human beings?
For example, after some searches I observed that you cannot say 'bulline' but you must say 'bulllike', you cannot say 'birdine', but you must say 'birdlike', and so on.
Can anyone explain, also in reference to 'bull', why in some cases you prefer '-ine' and in others you use '-like'?

A: As @Mitch indicates in the comment, the basic answer is that *-ine occurs with the Latinate  terms and *-like with the Saxon ones.
Part of the reason is that genitive declension of these words in Latin has this basic ending.
English word / Latin nominative / Latin genitive / English adjective
Cow / bos / bovis / bovine
Cat / feles / felis / feline
Dog / canis / canis / canine
Snake / serpens / serepentis / serpentine
There may be ones where we simulate the same *-ine without a Latin origin, but I cannot think of any off the top of my head.


text:
Q: UIAccelerometer is Deprecated ios7 how to use in ios7    UIAccelerometer
- (void)setupAccelerometer
    {
      UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
      accelerometer.updateInterval = 10.0f / 30.0f;
      accelerometer.delegate = self;
    }

A:     // Configure Core Motion for getting Accelerometer data
//=========================================================

self.motionManager = [[CMMotionManager alloc] init];
if ([self.motionManager isAccelerometerAvailable]) {

    // Accelerometer is vailable. Configure to get acceleration

    [self.motionManager setAccelerometerUpdateInterval:(1.0 / 15)];

    [self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {

       // Your own code here

    }];

For more information, You can refer the Apple documentation right here :
CoreMotion

A: you can still use it... but the new way is to use CMMotionManager


text:
Q: Second handler cannot run inside toggle-event i try to create simple show/hide box using toggle but when box is open the button will change to "-" and when box closed, button will change back to "+"
you can check my jsfiddle here
i try with this code using first and second handler
$(document).ready(function () {
    //default
    $('.content').hide();

    $('#b_1').click(function () {

        $('.content').toggle(function () {
            $('#b_1').prop('value', '-');    //first handler
        },
            function() {
            $('#b_1').prop('value', '+');    //second handler
        });

    });
});

but second handler not working ..

A: I have seen people using second handler in toggle.. but of what I know there is no second handler in toggle function.. check the docs..(let me know if I am wrong).. if its the toggle-event then it is deprecated in jQuery 1.8 and removed in jQuery 1.9.
Anyway here is how I would do to solve your problem
$('#b_1').click(function () {

 $('.content').toggle('slow',function () {
     if($('.content').is(':visible')){
        $('#b_1').attr('value', '-');
     }else{
        $('#b_1').attr('value', '+');
     }
 });
 });

working fiddle here

A: Try
<script type="text/javascript">

    $(function()
    {
        $('.content').hide();

        $('#b_1').toggle(function ()
        {
            $(this).attr('value', '-');
            $(this).next('.content').show();
        },
        function()
        {
            $(this).attr('value', '+');
            $(this).next('.content').hide();
        });

    });

</script>

A: Better handle your toggle() manually.
$('#b_1').click(function () {

    var $button = $(this);
    $('.content').toggle(function () {
        var symbol = $button.attr("value"),
            newSymbol = symbol == "+" ? "-" : "+";

        $button.attr("value", newSymbol);
    });

});

JSFiddle.

A: You can try this: fiddle
$(document).ready(function () {
    var i = 0;
    $('.content').hide();
    $('#b_1').click(function () {
        if (i == 0) {
            $('.content').toggle('slow', function () {
                $('#b_1').val('-');
                i = 1;
            });
        } else if (i = 1) {
            $('.content').toggle('slow', function () {
                $('#b_1').val('+');
                i = 0;
            });
        }
    });
});


text:
Q: How to Importrange + Count on Google Sheets? I'm trying to import data from another worksheet and count it simultaneously. It's only producing 1 for me, rather than 11 - which is what it should be.
I've tried the following:
=COUNT(IMPORTRANGE("URL","Shirts!F:F"))

A: first you need to run your importrange formula and allow access to link your sheets:
=IMPORTRANGE("URL", "Shirts!F1")

then try:
=COUNT(IMPORTRANGE("URL", "Shirts!F:F"))

also make sure your set is numeric

A: To count cell that not blank please use:
=COUNTA(IMPORTRANGE("URL","Shirts!F:F"))


text:
Q: JavaFX - Passing values Im aware this problem is pretty common, but I'm running out of options. Tried every solution and nothing is working for me.
What I'm trying to do is simply pass some values from 1 JFX window to another.
here is my login method inside loginController class
public void login(ActionEvent event){
    try{
        if(loginModel.isLogin(txtUsername.getText(), txtPassword.getText())){
            try {
                ((Node)event.getSource()).getScene().getWindow().hide();
                Stage primaryStage = new Stage();
                FXMLLoader loader = new FXMLLoader();
                mainViewController sendHello = loader.<mainViewController>getController();
                sendHello.getUser(txtUsername.getText());
                Pane root = loader.load(getClass().getResource("mainView.fxml").openStream());
                primaryStage.setTitle("Kcalculator");
                primaryStage.setScene(new Scene(root));
                primaryStage.setResizable(false);
                primaryStage.show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else{
            Alert alert1 = new Alert(Alert.AlertType.INFORMATION);
            alert1.setTitle("Login failed");
            alert1.setHeaderText(null);
            alert1.setContentText("The username or password you have entered is invalid.");
            alert1.showAndWait();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

and here is my mainViewController class
public class mainViewController implements Initializable{

    @FXML
    private Label userLbl = new Label();

    public void getUser(String user){
        userLbl.setText("Welcome " + user);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }
}

after trying several solutions, Im still getting NullPointerException after "successfull" login.

A: You need to load the fxml before loader.getController can return anything other than null:
FXMLLoader loader = new FXMLLoader();

// load fxml
Pane root = loader.load(getClass().getResource("mainView.fxml").openStream());

// get controller created using fx:controller attribute in the fxml
mainViewController sendHello = loader.<mainViewController>getController();

// use controller
sendHello.getUser(txtUsername.getText());

Note that the fx:controller attribute needs to be assigned the correct value for this to work of course.

A: I am recently had to develop a login for an app. This app opens the proper view for the users account type. It uses sqlite to store and retrieve info about the users and to store and retrieve encrypted passwords. You might find this helpful.

Controller

import java.io.IOException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class FXMLDocumentController implements Initializable {

    @FXML private TextField tfUsername;
    @FXML private PasswordField pfPassword;
    @FXML private Button btnSignIn;

    @FXML
    void handlebtnSignIn(ActionEvent event){

        int userID = 0;
        String username = "", accountType = "";
        byte[] encryptedPassword = null, salt = null;
        if(tfUsername.getText().length() > 0 && pfPassword.getText().length() > 0)
        {
           try(Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
                PreparedStatement  stmt = createPreparedStatement(conn, tfUsername.getText());
                ResultSet rs = stmt.executeQuery())
            {
                while(rs.next())
                {
                    userID = rs.getInt("user_id");
                    username = rs.getString("username");
                    encryptedPassword = rs.getBytes("password");
                    salt = rs.getBytes("salt");
                    accountType = rs.getString("account_type");
                }

                if(tfUsername.getText().equals(username) && authenticate(pfPassword.getText(), encryptedPassword, salt))
                {
                    Stage stage = new Stage();

                    stage.setWidth(1080);
                    stage.setHeight(720);
                    Parent fxmlLoader = null;

                    switch(accountType)
                    {
                        case "administrator":
                            stage.setTitle("Tech Services Console");
                            System.out.println("I just signed in as an administrator");
                            fxmlLoader = FXMLLoader.load(getClass().getResource("AdminView.fxml"));
                            break;
                        case "collection":
                            stage.setTitle("Collection Console");
                            System.out.println("I just signed in as a collection member");
                            fxmlLoader = FXMLLoader.load(getClass().getResource("CollectionDevView.fxml"));
                            break;
                        case "selector":
                            stage.setTitle("Selector Console");
                            System.out.println("I just signed in as a selector member");
                            fxmlLoader = FXMLLoader.load(getClass().getResource("Selector.fxml"));
                            break;
                    }

                    stage.setScene(new Scene(fxmlLoader));

                    stage.show();
                    ((Node)(event.getSource())).getScene().getWindow().hide();
                    tfUsername.setText("");
                    pfPassword.setText("");
                }
                else
                {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setHeaderText(null);
                    alert.setContentText("Incorrect username or password!");
                    alert.showAndWait();
                }
            }
            catch (SQLException ex) {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setHeaderText(null);
                alert.setContentText("Incorrect username or password!");
                alert.showAndWait();
                System.out.println(ex.toString());
            } catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException ex) {
                Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @FXML
    void handleEnterButtonPress(KeyEvent event)
    {
        if(event.getCode().equals(KeyCode.ENTER))
        {
            btnSignIn.fire();
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

    private PreparedStatement createPreparedStatement(Connection con, String username) throws SQLException {
        String sql = "SELECT * FROM User WHERE username = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, username);
        return ps;
    }

    boolean authenticate(String attemptedPassword, byte[] encryptedPassword, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException
    {
        byte[] encryptedAttmeptedPassword = getEncryptedPassword(attemptedPassword, salt);
        return Arrays.equals(encryptedPassword, encryptedAttmeptedPassword);
    }

    public byte[] getEncryptedPassword(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException
    {
        String algorithm = "PBKDF2WithHmacSHA1";
        int derivedKeyLength = 160;
        int iterations = 2000;
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
        SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);

        return f.generateSecret(spec).getEncoded();
    }

    public byte[] generateSalt() throws NoSuchAlgorithmException
    {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[8];
        random.nextBytes(salt);

        return salt;
    }
}

FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>

<AnchorPane id="apMain" onKeyReleased="#handleEnterButtonPress" prefHeight="350.0" prefWidth="425.0" stylesheets="@../css/log_in_stylesheet.css" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="planningchart3.FXMLDocumentController">
   <children>
      <GridPane alignment="CENTER" hgap="10.0" layoutX="45.0" layoutY="69.0" prefHeight="284.0" prefWidth="448.0" vgap="10.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
        <columnConstraints>
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
          <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <padding>
            <Insets bottom="25.0" left="25.0" right="25.0" top="25.0" />
         </padding>
         <children>
            <TextField fx:id="tfUsername" promptText="username" text="sedj601" GridPane.columnIndex="2" GridPane.columnSpan="2" GridPane.rowIndex="3" />
            <PasswordField fx:id="pfPassword" prefHeight="25.0" prefWidth="107.0" promptText="password" text="hello" GridPane.columnIndex="2" GridPane.columnSpan="2" GridPane.rowIndex="4" />
            <Button fx:id="btnSignIn" alignment="CENTER" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handlebtnSignIn" prefHeight="30.0" prefWidth="92.0" text="Sign in" wrapText="true" GridPane.columnIndex="3" GridPane.rowIndex="5" />
            <Text id="welcomeText" strokeType="OUTSIDE" strokeWidth="0.0" text="Welcome" GridPane.columnIndex="1" GridPane.rowIndex="2">

            </Text>

         </children>
      </GridPane>
   </children>
</AnchorPane>

I set the username to sedj601 and password to hello. You might want to get rid of that part.

This is was helpful here.
This is the part that will probably be more helpful with your question.

try
{
    if(tfUsername.getText().equals(username) && authenticate(pfPassword.getText(), encryptedPassword, salt))
    {
        Stage stage = new Stage();
        stage.setWidth(1080);
        stage.setHeight(720);
        Parent fxmlLoader = null;

        switch(accountType)
        {
            case "administrator":
                stage.setTitle("Tech Services Console");
                System.out.println("I just signed in as an administrator");
                fxmlLoader = FXMLLoader.load(getClass().getResource("AdminView.fxml"));
                break;
            case "collection":
                stage.setTitle("Collection Console");
                System.out.println("I just signed in as a collection member");
                fxmlLoader = FXMLLoader.load(getClass().getResource("CollectionDevView.fxml"));
                break;
            case "selector":
                stage.setTitle("Selector Console");
                System.out.println("I just signed in as a selector member");
                fxmlLoader = FXMLLoader.load(getClass().getResource("Selector.fxml"));
                break;
        }

        stage.setScene(new Scene(fxmlLoader));
        stage.show();
        ((Node)(event.getSource())).getScene().getWindow().hide();
        tfUsername.setText("");
        pfPassword.setText("");
    }
    else
    {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText(null);
        alert.setContentText("Incorrect username or password!");
        alert.showAndWait();
    }
}
catch (SQLException ex) {
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setHeaderText(null);
    alert.setContentText("Incorrect username or password!");
    alert.showAndWait();
    System.out.println(ex.toString());
}
catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException ex)
{
    Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}


text:
Q: How to structure Rails project by features instead of controllers, models and views? I wonder if anyone tried to structure their Rails project something like

*

*users

*

*users.rb

*users_controller.rb

*users_index.html.erb

*users_show.html.erb

*posts

*

*posts.rb

*posts_controller.rb

*posts_index.html.erb

*posts_show.html.erb

instead of the Rails default where you put stuff into models, views and controllers folders? Could you share some insights on how to modify load paths and how this works with Sprockets or code reload in development or even generators? I just recently started using AngularJS and I really like how you organize things by feature there. Thank you!

A: One of the Rails principles is Convention Over Configuration so if you do it like you want you will lose a lot of cool things rails offers. Imagine someone trying to maintain your app, he will get crazy trying to figure it out what you did.
Honestly, if you want to play with rails, try to do it following its principles, just give it a try ;)

A: If you have been playing with Rails since 2008 then you should full well know that this is not something you should do in Rails. Rails is an opinionated MVC framework. The moment you deviate its conventions you will feel the pain and the ride will get very rough. Imagine things like partial lookups, routes, load paths, authorization, authentication, etc...
With that said, it's easy to build an architecture that uses micro service objects. This gives you the best of both worlds. You can think of those service objects as "features". This is only worth it in complex apps. I am building one at the moment and I've had great results breaking up functionality into small services, or "features" if you will, interacted with by controllers. It makes testing easy, isolates logic in the right areas, and does wonders for reusability.
For example, a feature would be updating a document.
class UpdateDocument
  attr_reader :user, :document

  def initialize(user, document)
    @user = user
    @document = document
  end

  def call(params)
    document.update! params.merge(last_editor: user)
    UpdateDocumentJob.perform_later(document)
  end
end

And the controller would be:
  def update
    UpdateDocument.new(current_user, @document).call permitted_attributes(@document)
    respond_to do |format|
      format.html { redirect_to :back, success: t('.success') }
      format.js
    end
  end

A: I'm pretty sure there is a way to hack your way around the Rails conventions but the question shouldn't be if it is possible. I think you should ask yourself what the benefit of such a folder structure would be for you and then look for the appropriate alternative in the Rails world. I think however that changing the folder structure is not a good idea as this is one of the core design decisions of Rails.
Instead - let's say you like that structure because you want to be able to switch between model/view/controller of a specific feature very quickly I would recommend you try to get used to some workflow like fuzzy search to open files in Atom or even write an extension for your text editor of choice. That keeps your repo clean and still speeds up your workflow.


text:
Q: Can Luck Be Proven Mathematically? Here is what I'm thinking, and it has to do with the Gambler's Fallacy and Law of Large Number. The Gambler's Fallacy states that due to the probability of an event is statistically independent and has no memory of previous outcome, regardless how unlikely the previous outcome has been. I saw some of the explanations for Gambler's Fallacy are that it's due to small sample size. But my understanding is that it has nothing to do with sample size. If a gambler were to bet on the toss of a fair coin, his chance would be 50/50, regardless if the previous result was a streak of 20 tails, or 200 tails, or 20^20 tails, however unlikely such event might be.
To expound on this idea further, picture a cosmic gambler who has been tossing a fair coin since the beginning of the universe, and who has been getting tails all these time. His chance of getting a head instead of tail is still 50/50. Which means, he could been getting tails until the end of the universe. Because to state otherwise would be violating the Gambler's Fallacy.
However, this would be an apparent violation of the Law of Large Number, which states the average of the results from a large sample should be close to the expected value. In other words, for our cosmic gambler, for all his coin tosses, the ratio of head and tails should be exactly 50/50 by now(13 some billions years).
A rebuttal could be made at the high unlikeliness of getting all tails on a fair coin toss for 13 billion years, let alone an eternity. Unlikely, perhaps, for our normal living. But as Sherlock would remind us, improbable is not impossible. So let's now imagine instead of one single cosmic gambler, we have an infinite number of cosmic gamblers who have been tossing fair coins since the beginning of the universe. It's abstract math we're talking here, so bear with me. Now using the Infinite Monkey Theorem, which states that for infinite number of monkeys typing on keyboards, given enough time, they could produce a Shakespeare. That would imply, given an infinite number of gamblers, there would be at least one that would end up never getting a head on the tosses. In fact, there would be an infinite number of gamblers getting that kind of result.
Similarly, we can prove that there could be gamblers who would get exactly one head out of eons of tosses. And then gamblers who would get two heads, and three heads, and so on.
And similarly, we can show there would be gamblers who would get only heads, and only one tail, and only two tails, and so on.
As it happens, if you add all the coin tosses from these timeless gamblers together, the overall probability should be very close to ½, thereby preserving the Law of Large Number.
Let's assign these gamblers to groups based on their coin toss results. The ones getting all tails are PH0, and the ones getting only one head PH1, then PH2, and so on. Given there are infinite numbers of gamblers, each group would have infinite members. However, in counting, some infinite numbers would be greater than others. Clearly, the groups that contain gamblers getting even coin toss result would be far greater than the marginal groups such as PH0, PH1.
If we assign getting head on a toss is a favorable result and getting tails is not, then we can demonstrate that the gamblers in PH0 are as down on their luck as they can be and their brethrens in PH1 and PH2 are not much better off. And conversely, their counterparts who are getting all heads are some lucky bastards. And given these lucky and unlucky groups contains gamblers much much less than the ordinary groups, it fits our normal perception of what luck is, which is an highly improbable event.
If all the above is true, then it should show that luck can be proven mathematically. Any thoughts?


text:
Q: Angular v2/v4 .js files do not work in modules I have a really annoying problem, I tried in every way that I know to solve and nothing worked.
I'm doing a project where I'm using this layout: https://w3layouts.com/preview/?l=/bike-race-sports-category-flat-bootstrap-responsive-web-template/
Well, actually I'm going to use only the first page of it, the Single Page Layout, I can set up Layout in Angular 2/4 without problems, but when I try to use the modules to separate each section, that's where the inexplicable happens, at least for me.
The .css files continue to run smoothly, but the required .js files stop working, so the page loses all transition functions and effects.
I've tried every way to make it work and I can not do it.
The only way it works and if I mount the entire layout within the index, however as I said I want to use the modules of the Angular to make maintenance easier.
Please help me...


text:
Q: Table from one of the SELECTS cannot be used in field list I'm trying the following query in a MySQL based DB:
SELECT
    alert.name, alert.new_state_date, alert.prev_state_date
FROM
    grafana.alert
WHERE
    alert.id = 1
UNION SELECT
    annotation.epoch
FROM
    grafana.annotation
ORDER BY annotation.id DESC
LIMIT 1;

My intent is to just get the data showing in the same panel so I can stop switching back and forth. However, I get the following error:

Error Code: 1250. Table 'annotation' from one of the SELECTs cannot be used in field list

A: To make the two queries compatible for a UNION fill the column list of the second one with NULLs to match the length of that of the first one. To be sure the types of the first column match, you could explicitly cast() them to char. (Optional if they are already of compatible types.)
Also use UNION ALL because UNION (without ALL) tries to eliminate duplicates.
And I guess the ORDER BY was meant for the result FROM grafana.annotatio not for the whole result set. To make MySQL know that, put the second query in parenthesis.
SELECT cast(alert.name AS char),
       alert.new_state_date,
       alert.prev_state_date
       FROM grafana.alert
       WHERE alert.id = 1
UNION ALL
(SELECT cast(annotation.epoch AS char),
        NULL,
        NULL
        FROM grafana.annotation
        ORDER BY annotation.id DESC
        LIMIT 1);

If both queries return one row, you could also cross join them, to have the results side by side.
SELECT *
       FROM (SELECT alert.name,
                    alert.new_state_date,
                    alert.prev_state_date
                    FROM grafana.alert
                    WHERE alert.id = 1) x
            CROSS JOIN (SELECT annotation.epoch
                               FROM grafana.annotation
                               ORDER BY annotation.id DESC
                               LIMIT 1) y;


text:
Q: pyinstaller exe without any dependencies? So I'm using pyinstaller with python27, and my exe works great so long as it's in the same directory as the build folder.  I need it to be a completely standalone exe, without any dependencies, is there a way to bundle the important things from the build folder into one file?  Neither -F nor --onefile seems to do this.
Edit:  as I explain in my answer below, I thought pyinstaller was the problem because the exe would only run in the dist folder, so I assumed it had dependencies there, but in reality, it was running and then instantly crashing due to a bug that only triggered when the exe was on the desktop.

A: I figured out that the reason it wasn't working had nothing to do with pyinstaller or dlls.  The exe was opening, and and trying to input powershell commands via python like it was supposed to.  Unfortunately I had a line of code that said this:
subprocess.check_output('schtasks /create /sc minute /mo ' + str(time) + ' /tn "test_process_to_run_every_'+str(time)+'_min" /tr //'+sys.argv[0],shell=True)
#set this exe to run every X minutes in windows scheduled tasks

the problem was that sys.argv[0] changed when I put the exe on the desktop, and ended up being a path that looked like C://Users/John Smith/Desktop.  The space in between John and Smith made powershell mad and crashed the program, so I escaped it using this line of code:
path = sys.argv[0].replace(" ","^")

and then I replaced sys.argv[0] with my new path variable.  Hope this helps anyone in the future trying to do the same thing.

A: after pyinstaller has converted your script into .exe, than you need to add the executable to path, otherwise you have to open the command line in the directory that the file is in. pyinstaller just puts your script and py interpretor into a single file. same goes for linux.
for dependency side, look here.
there are other options you can try to bbFreeze, py2exe, cx_Freeze
to use pyinstaller in a simple way:
pyinstaller --onefile your_file.py

now you should see couple of files build, dist(exe in here).
NOTE: that --onefile flag doesn't necessarily get rid of the need for it to have link with certain libraries, it will still need those in order to run.
prepare for distribution, first need to get a spec file:
to get a spec file:
    pyinstaller --noconsole your_file.py
than you can get the exe file for distribution like so:
pyinstaller your_file.spec

for more info and tutorial look here
see if nuitka works for you, it might sound scary but it is not. it compiles your code to executable binary format. Be aware that under the hood first it converts to c++ API calls.
if you dont like that for closed source program use Cython, and for no dependency use py2exe


text:
Q: How to create a custom UIView that defines a baseline? Using the NSLayoutConstraint class, it is possible to create a constraint that is based on a view's baseline (NSLayoutAttributeBaseline). However, I haven't seen any documentation that describes how a UIView actually provides a baseline value to the auto layout system.
If I wanted to create a custom UIView subclass that defines a baseline, how would I do it? NSView defines a baselineOffsetFromBottom method that I assume is involved somehow on OS X, but how does this work in iOS?

A: I've just used Hopper disassembler to look at UILabel in iOS 8.1, and it implements methods _baselineOffsetFromBottom and _firstBaselineOffsetFromTop, which are in turn called by -[UIView nsli_lowerAttribute:intoExpression:withCoefficient:forConstraint:], so UIKit has private methods similar to the one OS X has, they are just not exposed to the public.
_baselineOffsetFromBottom and _firstBaselineOffsetFromTop are implemented by UIView (returning 0), UILabel and UITextView. There's also a class named _UIGlintyStringView that implements _baselineOffsetFromBottom; no other UIKit classes have these methods.
Btw when the baseline of a view changes, it performs something like:
__UITagLayoutConstraintsForConstantChangeForSelectedAttributes(self, __UILayoutAttributeIsBaselineAttribute)

Doesn't seem like there's anything extra-special that couldn't be exposed to the public; perhaps they didn't feel like there's a need or wanted to discourage people from writing their own labels. UILabel is a fairly complicated class involving a custom CoreAnimation layer (_UILabelLayer) and a whole lot of trickery, including quite a bit of code for accessibility support.

A: You can also override one of the baseline values, i.e. firstBaselineOffsetFromTop, if aligning to a view is not convenient. For example, here's code that sets the first baseline to halfway down the view:
override var firstBaselineOffsetFromTop: CGFloat {
    return bounds.midY
}

EDIT: My bad, that's MacOS. I believe the iOS equivalent is firstBaselineAnchor which returns an NSLayoutYAxisAnchor object. I've not tested this, but I expect this would have a similar effect:
override var firstBaselineAnchor: NSLayoutYAxisAnchor {
    return NSLayoutYAxisAnchor.anchorWithOffset(bounds.midY)
}

A: viewForBaselineLayout

is deprecated so you have to use
viewForFirstBaselineLayout

example
- (UIView *)viewForFirstBaselineLayout  {
    // Use subLabel view for handling baseline layouts
    return self.subLabel;
}

A: From the UIView docs:

viewForBaselineLayout
Returns a view used to satisfy baseline constraints.
- (UIView *)viewForBaselineLayout
Return Value
The view the constraint system should use to satisfy baseline constraints


text:
Q: Javascript .getTime() inconsistent results between between windows I need to show a countdown timer. I get time from my server and should count down to zero, based on the following:
var now = new Date().getTime();
var timeRemaining = endTime - now;
.... I start the contdown timer with timeRemining

What happens is when I start the timer in two different tabs, the timer is off by about 2 seconds.
If I do this in one tab and another private window/tab, the timer can be different much much more.
Is there something I can do about this?

A:

var end = new Date('2015-10-27T13:00:00');
var endTime = end.getTime();
var div = document.getElementById('time');
setInterval(function() {
  var now = new Date().getTime();
  var timeRemaining = endTime - now;
  var seconds = timeRemaining / 1000;
  div.innerText = Math.floor(seconds);
}, 1000);


text:
Q: kubernetes Minikube : Node port service not accessible from outside I am trying to deploy simple spring boot REST service on minikube (Windows-10). Below are my configuration
Docker file
FROM openjdk:8-jdk-alpine
ENTRYPOINT ["/usr/bin/java", "-jar", "/usr/share/myservice/minikube-spring-boot-demo-0.0.1-SNAPSHOT.jar"]
ADD target/minikube-spring-boot-demo-0.0.1-SNAPSHOT.jar  /usr/share/myservice/lib
ARG JAR_FILE
ADD target/${JAR_FILE} /usr/share/myservice/minikube-spring-boot-demo-0.0.1-SNAPSHOT.jar
EXPOSE 8080

docker image is running fine and i am able to run the app.
docker run -p 8080:8080 minikube-spring-boot-demo:0.0.1-SNAPSHO

Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: minikube-spring-boot-demo
spec:
  selector:
    matchLabels:
      app: minikube-spring-boot-demo
      tier: backend
  replicas: 3
  template:
    metadata:
      labels:
        app: minikube-spring-boot-demo
        tier: backend
    spec:
      containers:
        - name: demo-backend
          image: nirajsonawane/minikube-spring-boot-demo:0.0.1-SNAPSHOT
          imagePullPolicy: Always
          ports:
            - containerPort: 8080

Service
apiVersion: v1
kind: Service
metadata:
  name: minikube-spring-boot-demo-service
spec:
  selector:
    app: minikube-spring-boot-demo
    tier: backend
  ports:
    - port: 8080
      targetPort: 8080
      nodePort: 30008
  type: NodePort

kubectl get all status

kubectl cluster-info

minikube logs

Service Details

i am not able to access the rest endpoint using service-ip:Nodeport/Uri
http://127.0.0.1:30008/hello
http://172.17.0.2:30008/hello
Anything i am missing here? any inputs will be useful.
output of   netstat -a

A: minikube is running in a virtual machine. Services can't be accessed through either localhost or 127.0.0.1 out of the machine.
Try to run minikube service minikube-spring-boot-demo-service. It will show service details and open the service in the browser.

A: You can get you cluster ip using below command
kubectl get nodes -o wide

then run below to get nodeport
kubectl get svc -o wide -n <namespace>

get the port of your NodePort Svc
then your application will be running on http://:port(svc Nodeport )
In your case it might be running on
http://127.0.0.1:30008/hello


text:
Q: What's the typesafe way to write a type guard for a union of types that don't have anything in common? I'm working with PouchDB, which returns an array of possibly mixed success responses or errors on bulk operations.
The success response should always have a field ok set to true in it, while an error response may have a bunch of all optional fields.
I want to filter out all errors from this, but can't figure out a sane type guard that would narrow this for me.
The straightforward approach would be:
interface PouchResponse {
    ok: boolean;
}

interface PouchError {
    status?: number;
    reason?: string;
}

function isError(
    respOrError:
        | PouchResponse
        | PouchError)
    : respOrError is PouchError {
    return !respOrError.ok;
}

But that breaks on ok not existing in PouchResponse | PouchError. Which does make sense given how type intersections work, but my intent here is to check that the property exists and is true if it does.
I could change the signature to:
function isError(respOrError: Partial<PouchResponse & PouchError>): respOrError is PouchError

but that doesn't quite feel right, because it doesn't really reflect what the function is supposed to do: tell apart a union. It shouldn't be possible to pass any other random object into this function and have it narrow said object to PouchError just because it doesn't have an ok property.

A: Okay, as I was rubberducking this here I remembered the trick to use; I can just widen the type inside the function to keep the signature the way I want it:
function isError(respOrError: PouchResponse | PouchError): respOrError is PouchError {
    const wide: Partial<PouchResponse & PouchError> = respOrError;
    return !wide.ok;
}


text:
Q: ID results different depending on who asks I have userX who has realtime privileges thorugh the realtime group. I wanted to give that user admin privileges so I switched to root
~>su root

and ran
#>usermod -a -G root userX

After a brief delay I got back to the prompt and tested the effect.
#>id userX
#>uid=1000(userX)  gid=0(root) groups=0(root),1001(realtime)

So it would appear that I was successful. I exited and tested my new admin by adding a dummy user.
#>exit
~>useradd BSD
bash: /usr/sbin/useradd: Permission denied

Something is wrong. I tried verifying my group membership and it gave me a different answer.
~>id
~>uid=1000(userX)  gid=1001(realtime) groups=1001(realtime) contextunconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

So, I need to know why my user says it is not part of root and root says the user is. What am I missing?

A: What's happening?
The list of groups a user is in is only set at login (and possibly modified by using the rarely used sg command, but that only works if there is a group password set for that group).  If that user logs out, then logs back in, they should then see themselves in that group.  However, being in the group with GID 0 ('root' on most Linux systems, 'wheel' or 'adm' on most non-Linux systems) is not the same as having administrative privileges, and is in fact a bad idea from a safety perspective.
Why is this not the same as administrative priveleges?
The root user (UID 0) is special.  The root group (GID 0, called wheel on many non-Linux systems for historical reasons I cannot seem to find) isn't.  Your user will be able to access files owned by the root group, but probably not much else.  This is a somewhat complicated distinction, but is a very important one.
Why is this a bad idea?
This is a bad idea for pretty much the same reason that running as the root user all the time is a bad idea.  You're always one mistake away from making the system unusable (on most Linux systems for example, being part of the root group means you can trivially make the system unbootable because you can delete things out of /boot).
What's the correct (and safe) way to give this user administrative privileges?
If possible, set up sudo, doas or whatever other privilege elevation tool other than su is present on your system to allow them access.  If you have no such tool other than su, install one (I would suggest sudo, it's the most widely used and therefore one of the easiest to learn because there's lots of documentation).  If that too is not an option, then just elevating through su when you need to do admin tasks is the correct option (although do be careful doing so, as su does not properly reset the environment for commands called through it).


text:
Q: @Around aspect and Kotlin suspended function I try to understand how to create an @Around aspect for a Kotlin's suspended function (for example, to measure time spent in this function, or for a custom @Transactional aspect):
@Timed("my-timer")
suspend fun test() {
    println("before")
    delay(50) // invokes ProceedingJoinPoint#proceed() before this line
    println("after")
}

Since this function has a suspend function call, the @Around aspect's proceed function will be invoked right before delay() call. But obviously I'd like to measure full time spent in the function.
What is the right way to solve it? Maybe I can somehow subscribe on the last continuation in the method, or smth like that?

A: I think you can solve your problem easily, if you want to measure, the execution time of function, you can do it using built-in functionality like this:
val time = measureTimeMillis {
    // yourSuperFunc()
}

Also, you can use measureNanoTime. For full reference look at here.

A: This is tracked by https://github.com/spring-projects/spring-framework/issues/22462 and will most likely be fixed in 5.3
The same issue happens for @Transactional.


text:
Q: Python Subprocess Popen Stalling CGI Page I have a tool that I am working on and I need it to run a parser and also output another analysis log. Currently I have it so that it's through a web interface.

*

*User goes to the form and submits a filename for parsing (file already on system).

*Form submits information to Python CGI script

*Python CGI script runs and spawns a subprocess to run the parsing.

*Parser finds appropriate information for analysis and spawns subprocess also.

I am using
import subprocess
...
subprocess.Popen(["./program.py", input])

In my code and I assumed from documentation that we don't wait on the child process to terminate, we just keep running the script. My CGI script that starts all this does:
subprocess.Popen(["./program.py", input])
// HTML generation code
// Javascript to refresh after 1 second to a different page

The HTML generation code is to output just a status that we've processed the request and then the javascript refreshes the page to the main homepage.
The Problem
The CGI page hangs until the subprocesses finish, which is not what I want. I thought Popen doesn't wait for the subprocesses to finish but whenever I run this tool, it stalls until it's complete. I want the script to finish and let the subprocesses run in the background and let the webpages still function properly without the user thinking everything is just stalled with the loading signals.
I can't seem to find any reason why Popen would do this because everywhere I read it says it does not wait, but it seems to.
Something odd also is that the apache logs show: "Request body read timeout" as well before the script completes. Is Apache actually stalling the script then?
Sorry I can't show complete code as it's "confidential" but hopefully the logic is there to be understood.

A: Apache probably waits for the child process to complete. You could try to demonize the child (double fork, setsid) or better just submit the job to a local service e.g., by writing to a predefined file or using some message broker or via higher level interface such as celery

A: Not sure exactly why this works but I followed the answer in this thread:
How do I run another script in Python without waiting for it to finish?
To do:
p = subprocess.Popen([sys.executable, '/path/to/script.py'],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)

Instead of:
p = subprocess.Popen([sys.executable, '/path/to/script.py'])

And for some reason now the CGI script will terminate and the subprocesses keep running.
Any insight as to why there is a difference would be helpful? I don't see why having to define the other two parameters would cause such a stall.


text:
Q: How is it possible that multiple computers on a network are being maliciously redirected Intermittently, and not at the same time, computers connected the network will redirect to Stop-online-piracy.com (may not want to go there). The domain responds with the source:

ERROR: This web site encountered an error (40100), please notify your Technical Support.

just an error, .nothing hidden there.
It is privately registered. Seems like a sham trying to impersonate a Cease&Desist. A Google search of the domain yield no references.
The other strange part is that right before it happened the internet connection gets really slow AND the wifi signal bar goes down. This signal bar could just be Windows 7's adding in connection speed into the task-bar icon. (or it could indicate something really interesting...) The wifi is using WPA2 if that matters. Not many Computers are plugged into an Ethernet so it's unknown whether or not it affects them.

edit:
 When I said it wasn't at the same time, I meant that not exactly the same, but all within a few minutes of each other. I has subsided now. Also is there anything I can do if/when it happens again? It seems like it comes in waves.

A: Download Combofix and run it on the machines experiencing the issue.  It sounds like you have a malware issue.

A: Well I finally know the answer, recently It happened again, to a bunch of people on the network. But this time, for me the page was not blank. It was a proper cease a desist, Stating a number of items that were supposedly torrented by my computer; they were not however. It must be the fact that some other computers on the network were torrenting items and somehow the cease and desists targeted the entire network. It forced me to agree to resume use of my internet connection. Just figured I would leave this here In case it helped anyone else.


text:
Q: How to add external Javascript in a laravel view I am trying to add my javascript file externally in my login view. I have given the js src link on my layouts/app.blade.php at the end of the body and in the head too. I tried to give the js link my view but it does not work. The script only works when i place it internally in my login view.
Login.blade.php
<script>
//internal script
   $(document).ready(function(){
        alert("this is alert");
        $(".btn-gSignIn").mouseenter(function(){
            $(".btn-gSignIn").animate({background-color: white , color:#4285F4 , border-radius: 0px},5000);
            $(".btn-gSignIn").animate({background-color: #F3F3F3 , color:black , border-radius: 20px},5000);
        });
        $("div").css("background-color", "grey");

    });

</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
            <script src="{{ asset('js/app.js') }}" ></script>
    <script type="text/babel" src="{{ asset('js/login.js') }}" ></script>

app.blade.php

        <main class="py-4">
            @yield('content')

        </main>
    </div>

</body>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
            <script src="{{ asset('js/app.js') }}" ></script>
    <script type="text/babel" src="{{ asset('js/login.js') }}" ></script>

A: In you login.blade.php, after @endsection place your js import in push stack:
@push('js')
<script src="{{ asset('js/login.js') }}" ></script>
@endpush

In your app.blade.php, place your js files just before your </body> tag ends.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"</script>
<script src="{{ asset('js/app.js') }}" ></script>
@stack('js')
</body>

also if you're using default app.js that ships with laravel, then it can cause conflict with jquery.


text:
Q: How to retrieve youtube subtitle using youtube api From the YouTube caption request I got the videoId and Id parameter.
Now how to get authorization for one of the following scope to get youtube subtitle.
https://www.googleapis.com/auth/youtubepartner


text:
Q: SLF4J Multiple bindings I've come across the SLF4J: Class path contains multiple SLF4J bindings error in scala. I know there are lot of forums and discussions about this and this warning is not my problem. I can get rid of the warning by excluding one of the conflicting entries in my build.sbt. In my case, the conflicting packages are org.slf4j and ch.qos.logback. So, I can get rid of the warning by entering one of the following in my build.sbt.
libraryDependencies ~= {_.map(_.exclude("ch.qos.logback", "logback-classic"))}

or
libraryDependencies ~= {_.map(_.exclude("org.slf4j", "slf4j-log4j12"))}

My issue is, when I get rid of this warning it messes up the output in the windows command prompt (Yes, this needs to run on windows).
Excluding org.slf4j shows weird characters in the command window. These characters are not displayed in my intelliJ console.

if I exclude ch.qos.logback, the output looks fine but the command prompt doesn't display any log messages below error level.

I think I want to exclude org.slf4j so I can configure my loggers easily using logback.xml. Does anyone have any idea on why there are weird characters on command line in the first case and how to fix it.

A: Those weird signs are ANSI escape sequences for text coloring and formatting. Probably your logback layout configuration has some coloring enabled. For more details see: https://logback.qos.ch/manual/layouts.html#coloring


text:
Q: matplotlib on lion installation I am new to programming. I am trying to install matplotlib module on Mac OS X. I have lion operating system and python 2.7 and I also downloaded mac ports. What do I need to type into my terminal to get mac ports to downloads and install matplotlib on my computer?

A: As far as I remember, all I had to do on Lion was:
sudo easy_install matplotlib

macports was not required at all.

A: I hope you already have solved your problem. But for those who haven't and are having trouble, use this shell script to install everything: http://fonnesbeck.github.com/ScipySuperpack/. All the crazy dependencies are just magically fulfilled.


text:
Q: java SSLHandshakeException No subject alternative names matching IP address As a restful client, I can successfully connect to the server using the Postman software without any certification or security setting. (I receive the correct response from the server)
But when I call it using java Program, it throws Exception below:
javax.net.ssl.SSLHandshakeException: No subject alternative names matching IP address 192.168.12.125 found
I also looked at this link that didn't solve my problem.
here is java code I used:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import java.io.Serializable;

public class CallService implements Serializable {
    private String uri = "https://192.168.12.125:443/ssdpn";
    private Client client;
    private WebResource webResource;

    public void sendRequest(String input) {
        try {
            client = Client.create();
            webResource = client.resource(uri);

            String requestBody = prepareJSONFormatRequest(input);
            ClientResponse response =
                    webResource.path("/Service205")
                            .header("trackId", "1001")
                            .header("serviceId", "Service205")
                            .post(ClientResponse.class, requestBody);

            String result = response.getEntity(String.class);

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    private String prepareJSONFormatRequest(String input) {
        StringBuilder request = new StringBuilder();
        request.append("{ ").append("\"SerialNumber\":\"").append(input).append("\" }");
        return request.toString();
    }

}

in the java program, I also use no certificate (As I do in Postman call).
could anybody help me to find where does the problem lies?

A: I fixed by calling this method in the constructor:
private void fixHttpsHandler() {
    try {

        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }
        };

        SSLContext mySSLContext = SSLContext.getInstance("TLSv1.3");
        mySSLContext.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(mySSLContext.getSocketFactory());

        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

then
public class CallService implements Serializable {
    public CallService() {
            try {

                fixHttpsHandler();

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
}