text:
Q: What is the FragmentManager that is passed into FragmentStatePagerAdapter for? I have been trying to figure out what the FragmentManager argument is actually for in FragmentStatePagerAdapter. In the documentation, no method actually utilizes it. Its purpose is also missing from the documentation.
http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html#FragmentStatePagerAdapter(android.support.v4.app.FragmentManager)
The description of the constructor is actually blank, and none of the implementations of any of its methods require use of the FragmentManager.
What is the FragmentManager for?
(I know what FragmentManager is used for in other contexts, just not in the context of this adapter)

A:
What is the FragmentManager for?

FragmentStatePagerAdapter deals with Fragments. As you would do in your Activity, where you would use the FragmentManager to beginTransaction() and commit it, the FragmentStatePagerAdapter does the same. At a certain point, it will call beginTransaction, using the FragmentManager you provided to the super constructor, will call getItem(), where you return the Fragments you want to show, and commit it. As pointed out by @CommonsWare, FragmentStatePagerAdapter takes care also to remove the Fragments.


text:
Q: I want to load data in R I am using readLines("file.txt") to read in R. I'm getting a character vector:
[1]"classLabel|UserName|2|1.857|Subejct|User Questio(text)n?|Answer(text).|text"

but I wanted to further process it as so i can have it as a dataframe
col1       col2      col3  col4  col5    col6     col7    col8
classLabel  usrName    2  1.857  Subject User Q   Answer   text

The file format is | delimited and there are 8 attributes.
classLabel|UserName|2|1.857|Subejct|User Questio(text)n?|Answer(text).|text

Also if you can share some tutorials or resources for loading Data in R would be really helpful

A: You may try read.table
read.table("file.txt",sep="|")

A: Like lokheart said, you'll want to use read.table. The documentation is pretty good... type ?read.table at the R command prompt to see help, there are examples at the end.
As for tutorials, there are a number of tutorials available online. You should check out this SO question for some excellent links, as well as the official R language introduction on the R website.

A: In R are several ways to load datasets in csv format, txt format or others formats, one way is using read.table for that you do the follow code:
setwd("Directorypath") ##remember use "//" if you are using a Windows OS
Will be something like that your directory path:
"C:\\firstfolder\\secondfolder"

If your database has a header, you can use the follow parameters to import your dataset:
dataset <- read.table("FileName", sep=",", header=T)

However, as I said, there are a bynch ways to import data in R.
Another exemple is using read.csv
read.csv("FileName", sep=",", header=T)

Or use the readxl package to read Excel files:
read_excel("FileName", sheet="nameofsheet")

Although, the last way take more time to load as increase your database size, being recommended you use csv formats to process your data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I make a table and insert variables into the rows? I am building an automated email system that will send an email when a specific columns is edited based on another columns value being true. Right now I have it so that the output if that column is updated will tell me some other values in that row on different columns.
I have a co-worker who has a similar working project in HTML where the variables are called into a daily digest form. However, I can't duplicate it and get it to work for some reason. I also tried several methods I found on here in java script such as arrayToDataTable. And building it in HTML in the HTML body. But when I try those the output is just the word of the variable but not the variable itself.
function sendNotification(e){

  var ss = e.source.getSheetByName('Datasheet');
  var cell = e.range.getA1Notation();
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var cellvalue = e.range.getValue();
  var subject = 'SUBJECT: '+ ss.getSheetName();
  var name = ss.getRange(row, 9).getValue();
  var control = ss.getRange(row, 2).getValue();
  var owner = ss.getRange(row, 8).getValue();
  var key = ss.getRange(row, 3).getValue();

  if (name === 'NAME' && (col === 2 || col === 3 || col === 23 || col ===
24 || col === 31 || col === 32) === true) {

   MailApp.sendEmail({
      to: "EMAIL",
      subject: subject,
      htmlBody:(

 Control ID	   Control Owner
	   Updated Cell

   control
owner  	   cellvalue

 +

      "

The following cell has been updated:

"+
      " CONTROL ID: " +
control + "
" +
      " OWNER: " + owner
+ "
" +
      " UPDATED CELL: " +
cellvalue + "
" +
      " SIGNIFICANCE: " + key
+ "
" +
      "

Thank you.

"
    )
    })
  }
}

I want the output instead of reading line by line be transferred into an output table. Just to clean it up and make it look nice and professional. I feel like this should be possible but I can't get it working. After I get this table working I am going to work on storing a full 24 hours worth of updates and inputting it into the table as a daily digest output.
Thanks for your help.


text:
Q: I get error when I setup react-alert with my react app Uncaught Error: Objects are not valid as a React child I got this error  :
react-dom.development.js:14748 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead.
    in Unknown (created by App)
    in Provider (created by App)
    in div (created by App)
    in App
    in Provider
    at throwOnInvalidObjectType

this is my Alerts component
import React, { Component , Fragment} from 'react'
import { withAlert } from "react-alert";
export class Alerts extends Component {

        componentDidMount(){
            this.props.alert.show("it worked");
        }

    render() {
        return (
            <Fragment>

            </Fragment>
        );
    }
}

export default withAlert(Alerts);

and this is my App.js
import React ,{ Component, Fragment }  from "react";
import { render } from "react-dom";
import {Provider as AlertProvider} from 'react-alert';
import AlertTemplate from 'react-alert-template-basic';
import Header from './components/Header';
import Leads from './components/leads';
import AddLead from './components/AddLead';
import  Alerts from './components/Alerts'
import { Provider } from 'react-redux';
import store from './store';
import { connect } from 'react-redux';

const alertOptions = {
    timeout:3000,
    position:"top center"
}

class App extends Component{
    render(){
        return(
            <div>
                <AlertProvider template={AlertTemplate} {...alertOptions}>
                <Fragment>
                    <Header/>
                    <Alerts/>
                    <Leads/>
                    <AddLead/>
                </Fragment>
                </AlertProvider>
            </div>

        )
    }
}

export default App;
render(<Provider store={store}><App/></Provider>, document.getElementById("app"));

my errors reducer :
import { GET_ERRORS } from '../actions/Types';

const initialState = {
    msg: {},
    status:null
}

export default function (state = initialState, action) {
    switch(action.type){
        case GET_ERRORS:
            return {
                msg:action.payload.msg,
                status:action.payload.status
            };
        default:
            return state;
    }
}

A: Change the last line of Alert component from export default withAlert(Alerts); to
export default withAlert()(Alerts); according to react-alert docs.


text:
Q: group by same partial string of pandas dataframe column I have several csv files and each one contains one stock price in one month and has millions of data.
The raw csv data data is like:
AA_Candy.csv
Index   CompanyName      Time       Price
  1      AA Candy    030101090355   1.78
  2      AA Candy    030101091533   1.79
  .......
333498   AA Candy    031231145556   2.18

BB_Cookie.csv
   1     BB Cookie   030101090225   3.20
   2     BB Cookie   030101090845   3.14
  .......
391373   BB Cookie   031231145958   3.88

I use python and pandas to process the data, after I load and combine some of the datafiles, now I have a dataframe like:
frame:
Index   CompanyName      Time       Price
  1      AA Candy    030101090355   1.78
  2      AA Candy    030101091533   1.79
  .......
333498   AA Candy    031231145556   2.18
333499   BB Cookie   030101090225   3.20
333500   BB Cookie   030101090845   3.14
  .......
712871   BB Cookie   031231145958   3.88

The time 031231145958 represent 2013-12-31 14:59:58
now I want to get the highest price and final price in every one hour of each company, and get an output file like:
range_start   AA Candy/Max    AA Candy/Close    BB Cookie/Max     BB Cookie/Close
0301010900     1.79              1.77            3.20              3.10
........
0312311400     2.24              2.18            3.88              3.88

Therefore I want to groupby the CompanyName and first 8 character of Time to get the data of same company in one hour, then do the calculation to find the max price value and final price value of each company and output the outcome with same start hour in one row; let companyName/Max or Close be the new column name.
Because I am really new in pandas and dataframe, I have the following questions:

*

*How to group the data by the first 8 character of Time Column(Object) and then get my expected value?

*How to form a new output dataframe/matrix as my expected output?

Thanks!!

A: Perform a groupby on the company name and first 8 characters of your string timestamp (i.e. date plus hour).  Then use agg on the price to get custom functions for each (first, max, min and last).  Unstack the company names, swap the levels of the company names and open/high/low/close and optionally sort your symbols.
gb = (df.groupby(['CompanyName', df.Time.str[:8]])
        .Price
        .agg({'open': 'first',
              'high': np.max,
              'low': np.min,
              'close': 'last'})[['open', 'high', 'low', 'close']]
        .unstack('CompanyName'))
gb.columns = gb.columns.swaplevel(0, 1)
>>> gb.sortlevel(level=0, axis=1)
CompanyName AA Candy                   BB Cookie
                open  high   low close      open  high   low close
Time
03010109        1.78  1.79  1.78  1.79      3.20  3.20  3.14  3.14
03123114        2.18  2.18  2.18  2.18      3.88  3.88  3.88  3.88

A: For your first question, you can use
df.groupby(df.Time.str[0:8])

For your second question, unstack should be what you want:
df.groupby(df.Time.str[0:8]).unstack()


text:
Q: Graphic not showing in GUI - Java I don't want to make a repeat question as I have found many things similar, but nothing that is working for me. This is my first time using JFrame and I have followed a tutorial, word for word, and in my program, my line does not appear on the screen. I am not sure what I am doing incorrectly. Could someone please take a look and let me know what I need to change? Again, I am completely new to this.
Here is the code, thank you :)
package simplepaint;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SimplePaint extends JFrame {

public void Paint(Graphics g) {
    g.setColor(Color.BLUE);
    g.drawLine(0, 480, 960, 480);
    g.drawLine(342, 283, 384, 238);
}

public static void main(String[] args) {

    JFrame window = new JFrame("Let's Paint!");
    window.setSize(960,960); //600, 480
    window.setLocation(100,100);
    window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    window.setVisible(true);

   }

}


text:
Q: Am I not supposed update right away with Antegros? I installed Antergos yesterday with the Cinnamon DE. After using it for a while, I got a notification for updates to some core packages, and I thought "hey, being up to date is good right? Why not" and updated everything.
Today, I found that I'm unable to login. Luckily I was able to get a tty prompt and install Xfce4 from where I could go hunting on the internet for the solution.
It turns out that those updates I did included upgrading readline from 6.3 which I had to 7.0. cinnamon-desktop apparently relies on 6, so I started getting errors like:
cinnamon: error while loading shared libraries: libreadline.so.6: cannot open shared object file: No such file or directory

Of course just finding this error message in the first place took some hunting.
Indeed, I had only /lib/libreadline.so.7, so that explains the problem. I then assumed the easy solution is to just install the old version as /lib/readline.so.6 and that's that, but I had trouble figuring out how to do it in pacman and it turns out this isn't something encouraged in Arch.
Eventually I followed the advise from a thread about this problem and simply downgraded my readline to 6.3 from the pacman cache, and also bash since it depends on readline. Now cinnamon works as before. I see these two packages in the update notifier and I know that if I install them it will break my system.
My question is this: Is this sort of thing (updates suddenly breaking everything) expected behavior with Arch and/or Antergos? Is there some sort of "stable" channel that I could use instead, to receive updates only after they've been out for a while and tested in the real world?
I was planning to spend my morning doing work, but instead I spent it fixing a bug caused by an update. What did I do wrong? How do experienced Arch users handle this?

*

*Should I have just not installed updates unless I absolutely needed them? (but what about security and vulnerabilities?)

*Should I have only installed updates on a regular schedule, and made time for inevitable troubleshooting afterwards?

*Should I have configured my repositories/update settings differently to not get the latest updates?

*Is this expected behavior and you're supposed to just get used to rolling back from the cache?

Addendum: The issue with Cinnamon is included only as an example, but to await confusion from future readers, I should not that it is apparently now been fixed (7 hours after bug was opened) by rebuilding cinnamon. Looks like I got very "lucky" - I updated just when readline 7 was pushed out, but before the Cinnamon maintainers could catch and fix it.

A: This question is probably better directed at the Antergos forums, but I can share from personal experience with Arch:

*

*It's generally better to upgrade frequently than to upgrade infrequently.  You catch any issues as they come up and deal with them one-at-a-time rather than letting them pile up.

*Update as you see fit.  There's no particular reason to stick to any particular upgrade schedule; it depends on your system and your needs.  I've found, for instance, that Arch systems that have fewer packages installed generally don't need to be updated as frequently. On the 4 Arch systems that I use regularly, I update every time I log in (as much as once a day), which seems to work pretty well.

*Stick with the latest updates from the latest repos.  Generally speaking, this will get you the latest security updates, get you packages that have a better chance of working with the other software you have on your system, and keep everything running smoothly.

*Personally, I only rarely have to roll back from cache.  When there is an issue with upgrading, it's usually due to maintainers failing to build or test their packages properly, not due to me upgrading overzealously.
The issue you have with Cinnamon seems likely to do with a poor packaging job on the part of the package maintainers, and not a failure of the Arch-style bleeding-edge, rolling updates.  Personally, I've had some issues with Cinnamon on Arch, and it's never worked quite as well as the other DEs (I've used Gnome, MATE, and i3 with much less hassle).
One final thing that I would like to share is that, if you know you have problematic packages that break on upgrade, you can add them to an IgnorePkg directive in /etc/pacman.conf.  I only have to do this rarely, and it's almost always an AUR package that I'm ignoring (I like to use an AUR helper).  Once I had to blacklist the kernel in IgnorePkg on a laptop because the proprietary driver for the backlight did not work on recent kernel versions (luckily this got fixed upstream eventually and I could go back to receiving kernel updates). I would not recommend taking this approach unless absolutely necessary.

A: ArchLinux is a rolling release distribution as opposed to point release distributions. That means you will never have to reinstall ArchLinux to get the latest and greatest software. It slowly transforms into the newest software. This is great, most of the time. Sometimes, larger transitions need to be done and this can cause problems. To be aware of larger transitions, you should subscribe to announce@archlinux.org.
ArchLinux is also somewhat bleeding-edge. That means you get the latest software fairly on time. There are testing repositories in ArchLinux as well, that you could enable in /etc/pacman.conf. I don't know how long packages stay in testing, but it is not too long. This is great, most of the time. Sometimes you will get packages that are not tested well enough.
When updating ArchLinux (which you should do), you can follow two strategies:

*

*Update often. You will run into several small problems. But they usually don't break too many things. You can also more easily understand what package might have caused the problem.

*Update rarely. You will run into less problems, simply because most of them have been fixed by time. However, it might be that upgrading your system is a rather large task and updating it will take a while.
The tips above are rather pessimistic. There are problems here and there (more if you don't run widely used software), but generally, ArchLinux is very stable.
To answer your question: you should definitely update! ArchLinux is known to roll out security patches fairly quickly, and you would miss that. However, do not update 10 minutes before giving a presentation with your laptop.
If you run into problems, then

*

*check /var/log/pacman.log, for a history what has changed, try to understand what package is causing the problem.

*Use downgrade to downgrade the specific package.

*Use the ArchLinux Roll Back Machine as a last resort.


text:
Q: What 'language' is this written in? (from 1994) - Is it Fortran? I'm trying to replicate something like this in Matlab and I don't understand how it's written. I'm just trying to check some documentation, but idk what to search.
For example, I'm guessing the line: "If (L.LE.M)  Then" --> means if L is less than or equal to M, then.., but I can't be certain about anything.
Part 1:

Part 2:


text:
Q: Text combo box factory call For my project in Java FX, I have a list of strings and I need to add them to a combo box with the requirement that only one of them (the first) be coloured in red.
I thought about encapsulating the strings in a Text and adding them to the combo box with appropriate setStyle("fx-text-fill: Color.xxx"). This calls for a setCellFactory() method and I don't know how to set up it correctly.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Callback;

public class Mainu extends Application
{
    final ObservableList<Text> SAMPUNITFRONT = FXCollections.observableArrayList(
            new Text("complete"), new Text("seconds"), new Text("minutes"), new Text("hours"), new Text("days"));
    @Override
    public void start(Stage stage) throws Exception
    {
        ComboBox<Text> cb = new ComboBox<Text>();
        for(int j = 0; j < SAMPUNITFRONT.size(); j++) // cycle over the list and generate a line with dashing defined by list
            {
                Text text = SAMPUNITFRONT.get(j);
                if(text.getText().equals("complete"))
                    text.setStyle("-fx-text-fill: RED");
                else
                    text.setStyle("-fx-text-fill: BLACK");
                cb.getItems().add(text);
            }

        cb.setCellFactory(new Callback<ListView<Text>, ListCell<Text>>()
        {
            @Override public ListCell<Text> call(ListView<Text> p)
            {
                return new ListCell<Text>()
                {
                    private final Text text;
                        {
                            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                            text = new Text();
                        } // end Text
                    @Override protected void updateItem(Text item, boolean empty)
                        {
                            super.updateItem(item, empty);
                            if (item == null || empty)
                                {
                                    setGraphic(null);
                                }
                            else
                                {
                                    text.setStyle(item.getStyle());
                                    setGraphic(text);
                                    setItem(text);
                                }
                        }  // end updateItem()
                }; // end ListCell return
            }
        });

        cb.getSelectionModel().selectFirst();
        Pane root = new Pane();
        root.getChildren().add(cb);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }
    public static void main(String[] args) {launch(args);}
}

At the moment, the drop down list of the combo is empty.

A: Several recommendations to make here:

*

*Do not use a type of Node as item type. Instead store the data needed to determine the look of the ListCell in the items and let the ListCell implementations deal with the rest. You could simply use String as item type, if you the coloration should be done based on the text or index only or you could create a class containing 2 properties.

*Do not call setItem yourself. Let the ComboBox/ListView deal with this.

*For Text you need to use the -fx-fill css property instead of -fx-text-fill. The latter one would work, if you use the text property of the ListCell itself.

*If you do not use the functionality of ObservableList, it's pointless to create one. You could simply have used List and Arrays.asList instead of ObservableList and FXCollections.observableArrayList for SAMPUNITFRONT
final ObservableList<String> SAMPUNITFRONT = FXCollections.observableArrayList("complete",
        "seconds", "minutes", "hours", "days");

@Override
public void start(Stage stage) throws Exception {
    ComboBox<String> cb = new ComboBox<String>(SAMPUNITFRONT);

    cb.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
        @Override
        public ListCell<String> call(ListView<String> p) {
            return new ListCell<String>() {
                private final Text text;

                {
                    setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                    text = new Text();
                }

                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null || empty) {
                        setGraphic(null);
                    } else {
                        text.setStyle(item.equals("complete") ? "-fx-fill: red" : "-fx-fill: black");
                        text.setText(item);
                        setGraphic(text);
                    }
                }
            };
        }
    });

    cb.getSelectionModel().selectFirst();
    Pane root = new Pane();
    root.getChildren().add(cb);
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}

Alternatively without using a Text as graphic:
return new ListCell<String>() {

    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        setText(item);
        if (item != null) {
            setStyle(item.equals("complete") ? "-fx-text-fill: red" : "-fx-text-fill: black");
        }
    }
};

A: The problem is that you set style to Text objects. Try set the same style to cells. And you don't need encapsulating the strings in a Text.
Here is your code with fixes:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Main extends Application
{
    final ObservableList<String> SAMPUNITFRONT = FXCollections.observableArrayList("complete", "seconds", "minutes", "hours", "days");

    @Override
    public void start(Stage stage)
    {
        ComboBox<String> cb = new ComboBox<>();

        cb.setCellFactory(cell -> new ListCell<String>()
        {
            @Override
            protected void updateItem(String item, boolean empty)
            {
                super.updateItem(item, empty);
                if (item == null || empty)
                {
                    setGraphic(null);
                    setText("");
                }
                else
                {
                    if (item.equals("complete"))
                    {
                        setStyle("-fx-text-fill: RED");
                    }
                    setText(item);
                }
            }
        });

        cb.getItems().addAll(SAMPUNITFRONT);
        cb.getSelectionModel().selectFirst();
        Pane root = new Pane();
        root.getChildren().add(cb);
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args)
    {
        launch(args);
    }
}

And result:

I hope I understood you ritghtly and could help.


text:
Q: Rails 6 Active Storage image_processing gem issue Using Rails 6.0 and 'image_processing', '~> 1.9.3'
When trying to show a cropped variant of an image with:
url_for(user.avatar.variant(crop: crop_geometry)&.processed)

I get an error:

You must have ImageMagick or GraphicsMagick installed

I thought that image_processing gem included any dependencies relatives to this. Should I install some missing dependencies or what? Thanks

A: It's in the docs, first step, you need to instal dependencies:
https://github.com/janko/image_processing
1. Install ImageMagick and/or libvips:
> $ brew install imagemagick vips

I highly recommend using vips, it's much faster.

A: You have to install library first.
For Mac user:
brew install imagemagick vips

For debian/ubuntu user:
sudo apt update
sudo apt install imagemagick libvips


text:
Q: Armadillo: efficient RAM sparse batch insertion I know that Sparse matrix in armadillo is still in preliminary support.
I'm using armadillo lib in my quantum systems research and I have problem to construct sparse mat in  effective RAM way.
So far I was using my own implementation of sparse matrixes, but I want to have an optimized matrix class.
I'm filling elements in batch mode:
umat loc(2,size);
cx_vec val(size);

// calculate loc and val
...
//

sp_cx_mat Hamiltonian(loc, val);

This kind of action copy values from loc,val to constructor of Hamiltonian and for some few seconds require 2x RAM. I calculate huge matrix (size is about 2**L, where L=22, 24, ...) so I wish I had well optimised code in memory.
For comparison, matrix size: 705432x705432 - RAM and "filling time":

*

*my implementation (COO format): time 7.95s, memory  317668kB

*armadillo (CSC format):  time 5.32s, memory 715000kB
Is it possible to deallocate fragments of vectors: loc, val on the fly to save memory, element by element?

A: The answer here will be to use the other sparse matrix constructor that takes the CSC format, so you will need to modify your // calculate loc and val code, instead filling the following three arrays:

*

*values (length equal to number of points)

*row_indices (length equal to number of points)

*col_ptrs (length equal to number of columns plus one)

The points should be arranged in column-major ordering in the values and row_indices vectors, and the col_ptrs vector contains the number of nonzero elements before the beginning of the column.  That is, col_ptrs[0] will always contain 0, col_ptrs[1] will contain the number of nonzero elements in the first column, col_ptrs[2] will contain the number of nonzero elements in the first and second columns, and col_ptrs[n_cols + 1] will contain the number of nonzero elements in the matrix.
For more documentation on this constructor, see the "Batch constructors" section of http://arma.sourceforge.net/docs.html#SpMat ; this is the fourth entry in that list.
If you cannot easily modify your calculation code to adhere to that format, then you might be better off trying to specify sort_locations = false to the constructor you are using, if you are not already doing that.


text:
Q: Copy Paste Columns from one sheet to another sheet based on Autofilter I am trying to copy data from sheet to another sheet based on a filter.
Based on Column Q where autofilter criteria is "P", I need to copy column T & U from sheet ORD_CS to sheet Namechk.
Here is my code. No error but the entire column is getting copied.
Sub Macro26()
'
'Match Personal Names
'

'

    Dim i As Long, LR As Long
    Dim sht, sht1 As Worksheet

    Set sht = ActiveWorkbook.Worksheets("ORD_CS")
    Set sht1 = ActiveWorkbook.Worksheets("Namechk")

    sht.Range("A7:AC7").AutoFilter Field:=17, Criteria1:="P"
    sht.Range("T7:U99999").Copy
    sht1.Range("A1").PasteSpecial
    Application.CutCopyMode = False
End Sub

A: Try this:
sht.Range("T7:U99999").SpecialCells(xlCellTypeVisible).Copy sht1.Range("A1")

instead of
sht.Range("T7:U99999").Copy
sht1.Range("A1").PasteSpecial

A: Sub filter_paste()

Dim sht, sht1 As Worksheet

Set sht = ActiveWorkbook.Worksheets("ORD_CS")
Set sht1 = ActiveWorkbook.Worksheets("Namechk")

sht.Range("A:AC").AutoFilter Field:=17, Criteria1:="P"
sht.Range("T7:U99999").Copy sht1.Range("A1")

End Sub


text:
Q: Force member initialization in static const struct in c I am using a structs for storing different configurations and I would like to force the initialization of all members. I mean not let the compiler do it (to zero), but the progammer explizitly.
A compiler error would be best but a warning would be fine as well. I am using Segger clang for arm.
Any tips about how to achieve this?
Since I would like to use designated initializers, -Wmissing-field-initializers does not work in this case. See: Docs
typedef struct{
    int option_1,
    int option_2,
    ....
} config_t;

// this is fine
const config_t config_1 = {
    .option_1 = 10,
    .option_2 = 20,
};

// this should generate a warning
const config_t config_1 = {
    .option_2 = 20,
};

A: There's no particularly elegant way to do this programmatically. Best bet is to use a static initializer tool. (There's for example a MISRA-C:2012 rule that can be checked for, requiring that all elements of a struct must be initialized explicitly.)
With pure standard C, well...
Since this struct won't have any padding, I suppose you could cook up something fairly ugly like this:
#define CONFIG_INIT_LIST1 10, 20
#define CONFIG_INIT_LIST2 10

_Static_assert(sizeof (int[]){CONFIG_INIT_LIST1} == sizeof (config_t),
               "CONFIG_INIT_LIST1 wrong number of initializers.");
_Static_assert(sizeof (int[]){CONFIG_INIT_LIST2} == sizeof (config_t),
               "CONFIG_INIT_LIST2 wrong number of initializers.");

// this is fine
const config_t config_1 = {
    CONFIG_INIT_LIST1
};

const config_t config_2 = {
    CONFIG_INIT_LIST2
};

This gives the compiler error

error: static assertion failed: "CONFIG_INIT_LIST2 wrong number of initializers."


text:
Q: preg_match to domain.tld How can i get the strings that only contains domain.tld?
if (preg_match('^(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6}$', $domain))
echo "domain.tld found!";

but for the regex ^(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6}$, sub domains are also okay. But i just want to check "domain.tld". What regex should i use for it?
Thank you.

A: if (preg_match('/^[-a-z0-9]+\.[a-z]{2,6}$/', strtolower($domain)))
  echo "domain.tld found!";

would be the obvious answer.  You could always be more specific on the tld part if you wanted to remove false positives:
if (preg_match('/^[-a-z0-9]+\.[a-z][a-z]|biz|cat|com|edu|gov|int|mil|net|org|pro|tel|aero|arpa|asia|coop|info|jobs|mobi|name|museum|travel$/', strtolower($domain)))
  echo "domain.tld found!";

If you wanted to spell out the ccTLDs also, here's the current list:
if (preg_match('/^[-a-z0-9]+\.a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|t[cdfghjklmnoprtvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]|biz|cat|com|edu|gov|int|mil|net|org|pro|tel|aero|arpa|asia|coop|info|jobs|mobi|name|museum|travel$/', strtolower($domain)))
  echo "domain.tld found!";

I'd also accept the internationalized TLDs
xn--p1ai|xn--fiqs8s|xn--fiqz9s|xn--o3cw4h|xn--wgbh1c|xn--zckzah|xn--0zwm56d|xn--deba0ad|xn--g6w251d|xn--j6w193g|xn--kprw13d|xn--kpry57d|xn--pgbs0dh|xn--jxalpdlp|xn--kgbechtv|xn--fzc2c9e2c|xn--ygbi2ammx|xn--9t4b11yi5a|xn--mgbaam7a8h|xn--mgbayh7gpa|xn--80akhbyknj4f|xn--xkc2al3hye2a|xn--11b5bs3a9aj6g|xn--mgberp4a5d4ar|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a

or at least xn--[a-z0-9]+.
So those plus .arpa give
if (preg_match('^[-a-z0-9]+\.a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|t[cdfghjklmnoprtvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]|biz|cat|com|edu|gov|int|mil|net|org|pro|tel|aero|arpa|asia|coop|info|jobs|mobi|name|museum|travel|arpa|xn--[a-z0-9]+$', strtolower($domain)))

A: You want to find a specific text domain.tld while the regex with combination of A-Za-z0-9 character classes will match just about any text. Why don't you simply do:
if (strpos('domain.tld', $domain) !== false) {
  echo "domain.tld found!";
}

A: to extract http://www.example.com from
something http://www.example.com/page/blabla.html some thingggggg
<?php
preg_match('/((http:||https:)\/\/.*?)[\/||\n||\s]/s', $f,$n);
echo $n[1];
?>


text:
Q: Are Periodic Orbit all Iterations? We have,
If $x$ is a periodic point of a continuous function $f:\mathbb{R}\rightarrow\mathbb{R}$ and the period is $k$ i.e. $f^k(x)=x$ but $f^n(x)\not=x, \forall n: 0<n<k$.
(The statement up to this is slightly different in the text. This is my generalization but the main idea is same.)
Next the text says,
The periodic orbit of $x$ is $O(x)=\{x,f(x),f^1(x),f^2(x),\dots,f^{k-1}(x)\}$.
My question is, does it not have to be true that $f(x)=x$ to be periodic orbit? if $f^1(x)\not=x$ is it still in the periodic orbit?

A: I am guessing $f^k(x)$ means that you are iterating the function $f$ $k$ times. If that is the case, and $k=1$, then the function is of period one, actually the fundamental or the minimum period is one, then it is also 2,3,... periodic. Nothing would be wrong with the definition (saying that if $x=f(x)$ and you say is 1-periodic).
Next $O(x)$ refers precisely to the orbit, this is, the points in one fundamental period, that's why it says: $O(x)=\left\{x,f(x),f1(x),f^2(x),…,f^{k−1}(x)\right\}$, these are all the points within one period, and since, by definition, $x=f^k(x)$, then $f^k(x)$ is not included in the orbit.
Hope it helps.


text:
Q: Adding class to group of span tags one by one I got html structure like this:

My current goal is to add every 1s class "done" (its some kind of simple loading bar) to spans one by one and when last span got "done" class everything restart and loop over and over. Can someone help me how to write this in vanilla JavaScript?

A: You could do it like this:

var blocks = document.getElementsByClassName('block');

(function animateProgress(n) {
  for (var i = 0; i < blocks.length; i++) {
    blocks[i].classList[i < n ? 'add' : 'remove']('done');
  }
  setTimeout(function() {
    animateProgress((n + 1) % (blocks.length + 1));
  }, 400);
})(0);
.block {
  float: left;
  background: #eceded;
  padding: 1em;
  margin: 1px;
}
.block.done {
  background: #7be47b;
}


text:
Q: How to display WordPress category meta fields on the single post page? I need to display custom category meta fields (stored in wp_options table) on the single post page (single.php).
I have this code which doesn't work on the single post page (single.php):
$cat_id = get_query_var('cat');
$cat_data = get_option("category_$cat_id");
echo $cat_data['custom_field'];

This works only on the category.php/archive.php page but not on the single post page (single.php). The post belongs to only one category and I need custom fields of that category without using any plugins.
Is there any way to do this?

A: Maybe this is your answer (if you do with wordpress code):
http://codex.wordpress.org/Function_Reference/get_post_custom_keys


text:
Q: convert xml to sorted dictionary i have an xml file similar to this:
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <resource key="123">foo</resource>
    <resource key="456">bar</resource>
    <resource key="789">bar</resource>

</data>

i want to put this into a Dictionary (sorted) as key value pairs.
i.e:
123:foo,
456:bar...etc
the keys are unknown.
how can i do this?

A: This looks like a job for Linq to Xml
    static void Main(string[] args)
    {
        XDocument yourDoc = XDocument.Load("the.xml");
        var q = from c in yourDoc.Descendants("resource")
                orderby (int) c.Attribute("key")
                select c.Attribute("key").Value + ":" + c.Value;

        foreach (string s in q)
            Console.WriteLine(s);
        Console.ReadLine();
    }

A: Try this,
string s = "<data><resource key=\"123\">foo</resource><resource key=\"456\">bar</resource><resource key=\"789\">bar</resource></data>";
XmlDocument xml = new XmlDocument();
xml.LoadXml(s);
XmlNodeList resources = xml.SelectNodes("data/resource");
SortedDictionary<string,string> dictionary = new SortedDictionary<string,string>();
foreach (XmlNode node in resources){
   dictionary.Add(node.Attributes["key"].Value, node.InnerText);
}

A: This is actually easier without using Linq and just using an XmlDocument:
SortedDictionary<string, string> myDict = new SortedDictionary<string, string>();
foreach (XmlElement e in myXmlDocument.SelectNodes("/data/resource"))
{
   myDict.Add(e.GetAttribute("key"), e.Value);
}

A: Use LINQ:
Load the document XDocument.Load or XDocument.Parse:
var xml = XDocument.Load(...);

Iterate through the ordered sequence:
var sequence = from e in xml.Root.Elements()
               let key = (string)e.Attribute("key")
               order by key
               select new {
                 Key = key,
                 Value = (string)e
               };

A: I would do this with XSLT transformation. Do you need to do the job with C#? If not you can simply make a XSLT document which parses through all resource tags and outputs key:value sorted out for you. Very easy accomplished. Is this a solution you want?


text:
Q: JFR ExecutionSample event with TraceID I want to be able to relate JFR ExecutionSample events to trace ID/transaction ID/HTTP request etc. Any way to be able to trace the REST call thru several microservices. All this WITHOUT changing the application code.
Any help will be appreciated.


text:
Q: What's a sub-buffer object in OpenCL for? The align requirement seems to render at least the region part of this functionality almost completely useless.
Could anyone give me an example of when to create a sub-buffer from a region of a buffer?
And am I right that I can create a readonly or writeonly sub-buffer from a read-write buffer? If I can, will I benefit from this read/writeonly reference to a actually read-write buffer?

A: The purpose is to allow different parts of a buffer to be independently updated. One example would be if you want different devices to update different parts of your data structure. Rather than copying regions into new buffers, passing to devices, getting data back and remerging you can create sub-buffers and pass those to the devices.
You can create a read-write sub-buffer though. clCreateSubBuffer allows CL_MEM_READ_WRITE.


text:
Q: Is it possible to make a discord bot write in a word document? (discord.js) So I'm trying to make a queue of people in discord and I got the bot to message me with the name of the person who joined the queue, but I don't know where to go from here. I'd like to make a list of the people who joined the queue, possibly in word. Does anyone know how I could do this?
I only started coding yesterday so I don't really know all the ins and outs. This is the code I currently have:
client.on('message', message => {
    if(!message.content.startsWith(prefix)|| message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        client.commands.get('ping').execute(message, args);
    }
    if(command === 'clear'){
        client.commands.get('clear').execute(message, args);
    }
    if(command === 'embed'){
        client.commands.get('embed').execute(message, args, Discord);
    }
    if(message.content === `${prefix}joinqueue`){
        message.author.send('You have joined the queue!');
        console.log(`${message.author.username} joined the queue.`);
         client.users.fetch('518160902835666946').then(user => {
            user.send(`${message.author.username} joined the queue!`)
        })
    }
});

There are a few other commands, but the one I use for this is the last one. If you use the command it sends you a private message saying who joined and a private message to me saying that  joined the queue. I'd like the code to also add this persons name to a document so that I can see the order of the queue. I really don't care too much about the format, as long as I can see the order.

A: I assume that you would like to have a live-updated list. That means: If your Bot adds someone to queue you will see it immediately without having to reload.
Doing this with Word is misappropriate and very very difficult because word blocks the file from writing when you open it.
A few suggestions how you can archieve this:
1. Firebase Realtime Database and companion App
To get Started with the Realtime Datatbase: https://firebase.google.com/docs/database/web/start.
As companion App I would suggest Electron because you stay in the same programming language: https://www.electronjs.org/docs/tutorial/quick-start.
In this companion App you can show a live updated List.
In my opinion that is the best solution because here you are device undepended: You can recieve your queue on your mobile phone if you want to.
2. IPC and Electron
If you want to stay offline you can use a IPC (Internprocess Communication) connection to update an Electron app from your Discord Bot. This libary could be helpful: https://www.npmjs.com/package/node-ipc
Thats the best solution if you want to stay offline and be independent of your internet connection.
3. Simple-File and Notepad++
Here you would save the queue proper formatted into a file and open it with notepad++ (download here: https://notepad-plus-plus.org/downloads/). Note to enable update silenty. Scroll to the last line after update can prevent the coursor from jumping around.

This is not a long-term solution because your disks speed may impact you and your disks service time will shrink extraordinary. (I have done that once and i have broken my ssd after a month) However if you want to start quickly this is a very error-resistant way of doing it.
I hope I have helped you,
if that wasn't the thing you wanted try to edit your question.
Happy coding,
BierDav


text:
Q: monitor service for "failure" I'm developing a script which monitors a service for failure and launches another a different action depending on if failure is present or not.
I require a python script to monitor the output from a python program "monitor-services" and parsing the output search for an occurance of the word "failure". If present, the script should return with a true value, and run for a maxiumum of 30 seconds returning false if no occurance of "failure" occurs.
Sample output returned from "monitor-services":

{Device} [/device/xxx] Networks = dbus.Array([dbus.ObjectPath('/device/xxx/xxx'), dbus.ObjectPath('/device/00242b2e41b6/hidden')], signature=dbus.Signature('o'), variant_level=1)
{Service} [/profile/default/wifi_xxx_managed_wep] State = association
{Profile} [/profile/default] Services = dbus.Array([dbus.ObjectPath('/profile/default/wifi_xxx_managed_wep'), dbus.ObjectPath('/profile/default/wifi_xxx_managed_rsn')], signature=dbus.Signature('o'), variant_level=1)
{Manager} [/] Services = dbus.Array([dbus.ObjectPath('/profile/default/wifi_xxx_managed_wep'), dbus.ObjectPath('/profile/default/wifi_xxx_managed_rsn')], signature=dbus.Signature('o'), variant_level=1)
{Service} [/profile/default/wifi_xxx_managed_wep] **failure**
{Service} [/profile/default/wifi_xxx_managed_wep] State = idle

Any help would be appreciated.
[edit] A failure is likely to occur with 30 seconds or so of the action triggering the script, hence the script is required to terminate after 30 seconds. [/edit]

A: #!/usr/bin/python
from subprocess import Popen, PIPE
import sys

data = Popen(["monitor-services"], stdout=PIPE).communicate()[0]

sys.exit("failure" in data)

This does everything you want, except for the 30s wait (which I don't understand). Notice that it returns 0 if failure is not found, 1 if it is found, according to the shell conventions (i.e. 0 is success, non-zero is failure).


text:
Q: How to Copy a link in a website via ajax call? I would like to copy the first link in another website without loading the website.
I can copy text with the below code, what if i want to copy the first link or in a website without loading the website how can i achieve it? If i can achieve it without ajax call call please also post your method.
<!DOCTYPE html>

Click on the button to copy the text from the text field. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect.

<input type="text" value="Hello World" id="myInput">
<button onclick="myFunction()">Copy text</button>


text:
Q: JPA doesn't get OneToMany mapped entity I made a service which has saving function:
ClientService.java
@Transactional
public ClientDTO signUp(ClientSignupDTO clientSignupDTO) {

    Client client = Client.builder()
            .clientID(clientSignupDTO.getClientID())
            .clientPassword(passwordEncoder.encode(clientSignupDTO.getClientPassword()))
            .clientNickname(clientSignupDTO.getClientNickname())
            .clientActivated(true)
            .build();

    client = clientRepository.save(client);
    clientAuthorityRepository.save(new ClientAuthority(client, authorityRepository.getById("ROLE_CLIENT")));

    client = clientRepository.findOneWithAuthoritiesByClientID(client.getClientID()).orElseThrow(() -> new IllegalStateException("Client does not exist"));

    log.debug("{}", client.getAuthorities()); //This line throws NullPointerException

    return new ClientDTO(client);
}

I saved Client entity and ClientAuthority entity with saved Client's ID for M:N mapping.
But when I try to find Client in same function, JPA returns Client without ClientAuthority.
Client.java
@Entity
@Table(name = "client")
@Getter
@Setter
@Builder
@NoArgsConstructor
public class Client {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "client_id", length = 50)
    private String clientID;

    @Column(name = "client_password")
    private String clientPassword;

    @Column(name = "client_nickname", length = 50)
    private String clientNickname;

    @Column(name = "client_since", nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Date clientSince;

    @Column(name = "client_activated")
    private boolean clientActivated;

    @JsonIgnore
    @OneToMany(mappedBy = "client")
    private Set<ClientAuthority> clientAuthorities;

    @JsonProperty("authorities")
    public Set<Authority> getAuthorities() {
        return clientAuthorities.stream().map(ClientAuthority::getAuthority).collect(Collectors.toSet());
    }

    public Client(Long id, String clientID, String clientPassword, String clientNickname, Date clientSince, boolean clientActivated, Set<ClientAuthority> clientAuthorities) {
        this.id = id;
        this.clientID = clientID;
        this.clientPassword = clientPassword;
        this.clientNickname = clientNickname;
        this.clientSince = clientSince;
        this.clientActivated = clientActivated;
        this.clientAuthorities = clientAuthorities;
    }
}

ClientAuthority.java
@Entity
@Table(name = "client_authority")
@Getter
@Setter
@Builder
@NoArgsConstructor
public class ClientAuthority {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "client_authority_id")
    private Long clientAuthorityID;

    @ManyToOne
    @JoinColumn(name = "client_id")
    private Client client;

    @ManyToOne
    @JoinColumn(name = "authority_name")
    private Authority authority;

    public ClientAuthority(Long clientAuthorityID, Client client, Authority authority) {
        this.clientAuthorityID = clientAuthorityID;
        this.client = client;
        this.authority = authority;
    }

    public ClientAuthority(Client client, Authority authority) {
        this.client = client;
        this.authority = authority;
    }
}

Repository that I used to find client is Spring Data JPA repository.
ClientRepository.java
@Repository
public interface ClientRepository extends JpaRepository<Client, Long> {
    Optional<Client> findOneWithAuthoritiesByClientID(String clientID);
}

Since clientAuthorities inside Client that returned by findOneWithAuthoritiesByClientID is null, Client.getAuthorities returns NullPointerException.
Other properties such as clientID, clientNickname, etc. works fine but only clientAuthorities is null.
How can I get Client with Set<ClientAuthority> after save them?
Thanks.

Edit #1
Edited all save into saveAndFlush in function signUp.
But it keeps throwing NullPointerException.
@Transactional
public ClientDTO signUp(ClientSignupDTO clientSignupDTO) {

    Client client = clientRepository.saveAndFlush(Client.builder()
            .clientID(clientSignupDTO.getClientID())
            .clientPassword(passwordEncoder.encode(clientSignupDTO.getClientPassword()))
            .clientNickname(clientSignupDTO.getClientNickname())
            .clientActivated(true)
            .build());

    log.debug("{}, {}, {}, {}", client.getId(), client.getClientID(), client.getClientNickname(), client.getClientSince());

    clientAuthorityRepository.saveAndFlush(new ClientAuthority(client, authorityRepository.getById("ROLE_CLIENT")));

    client = clientRepository.findOneWithAuthoritiesByClientID(client.getClientID()).orElseThrow(() -> new IllegalStateException("Client does not exist"));

    log.debug("{}, {}, {}, {}", client.getClientID(), client.getClientNickname(), client.getClientSince(), client.getAuthorities());

    return new ClientDTO(client);
}

The log is:
Hibernate: insert into client (client_activated, client_id, client_nickname, client_password) values (?, ?, ?, ?)
2022-02-25 14:22:07.986 DEBUG 16684 --- [nio-8080-exec-3] c.d.s.service.ClientService              : 4, test, test, null
Hibernate: insert into client_authority (authority_name, client_id) values (?, ?)
Hibernate: select client0_.id as id1_1_, client0_.client_activated as client_a2_1_, client0_.client_id as client_i3_1_, client0_.client_nickname as client_n4_1_, client0_.client_password as client_p5_1_, client0_.client_since as client_s6_1_ from client client0_ where client0_.client_id=?
2022-02-25 14:22:08.071 ERROR 16684 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause

java.lang.NullPointerException: null
    at com.devjaewoo.springtest.entity.Client.getAuthorities(Client.java:46) ~[classes/:na]

When I test findOneWithAuthoritiesByClientID function with sample data (with data.sql file) outside of signUp function, It works fine.
Why doesn't it work properly only inside of signUp function?

A: you may need to saveAndFlush
but I would recommend
final var client = clientRepository
  .saveAndFlush(Client
    .builder()
    .clientID(clientSignupDTO.getClientID())
    ...
    .build());

So you immediately get the managed copy.


text:
Q: AWS Glue AccessDeniedException in SageMaker I am running the "Explain Credit Decisions" solution from Sagemaker Studio. I am following the instructions in the solution notebooks. The solution has been launched with my root user id. But when running 1_datasets.ipynb I am getting the below error when running the step
glue_run_id = glue.start_workflow(config.GLUE_WORKFLOW)
An error occurred (AccessDeniedException) when calling the GetJob operation: User: arn:aws:sts::myaccountid:assumed-role/rolecreatedbystack/GlueJobRunnerSession is not authorized to perform: glue:GetJob on resource: arn:aws:glue:us-east-1:myaccountid:job/sagemaker-soln-ecd-js-foccb4-job

The Cloud Formation stacks are created and the scripts should create the required roles and access which are needed to run this solution.
I have to run a POC with this solution with my custom data. So can you please help to solve the problem.

A: SageMaker is attempting to start a Glue Workflow but getting access denied. This is not a problem with SageMaker, it appears your CloudFormation stack is not assigning correct permissions.
Adding the permissions policy glue:GetJob to the role like this should fix this. If your role already has an appropriate Glue policy assigned, make sure your AWS environment does not have session policies preventing this.


text:
Q: What is a dedicated Linux box used for? So this is probably a very basic and obvious question for most people, but my google-fu is failing me and it just seems something is going over my head. I've heard numerous people refer to having a 'dedicated linux box' as a central part of a developer's setup.
I have been doing web-dev programming for about a year and understand the benefits of programming on a Unix/Linux system.  But I seem to be missing what role a 'dedicated linux box' plays in the development process.
I would assume that it is used as a server of some sort, but I am yet to run across any needs to have a computer dedicated to running a linux server.  Am I just being nieve and mistaking the commonality of programmers preferring to work in linux for a tool used by developers?  What do most developers use their 'dedicated linux box' for?

A: I do development targeted at hardware running Linux so a dedicated Linux box (i.e. not a Virtual machine) is essential for me to work.
We also have a dedicated linux build server that is used to ensure all our builds are built from a known system state.
But you can have dedicated database servers, web servers etc.  Depends entirely on what it is you're trying to do as to whether you need a dedicated box or whether a VM would do.

A: A dedicated linux machine is used for continuous development and is a machine that allows one or more users to customise all software according to their needs.
For example, if a linux box was used for web development, at the bare minimum, it would host a web server (e.g. Apache) with all required modules, access to a version control system, and provide remote access. This saves you having to run everything on your own computer and only being able to development when your computer is on.
As well as offering convenience, it also ensures the same environment as the production system. This removes any unintentional issues arising from tinkering with your computer.

A: The open nature of Linux allows you to do a variety of tasks.
It could act as:

*

*A personal webserver/code repository

*A testing platform for beta code before you upload it to the interwebs.

*A hardware firewall

*A torrent downloading box

*A glorified media player (running Boxee or XBMC)

*A code compiling station

*A box to run video game emulators while code is compiling on your 'work' machine.

*A place to try out new coding tools before you add them to your tool belt.
Because Linux is free and open source, if one of these use cases is no longer relevant to your needs, you can format the box and start again with a different goal in mind.  No harm, no foul.
Looking for more uses?  Try checking out Linux Journal, particularly their articles focusing on programming in Linux.

A: Dedicated Linux box is basically a machine which runs Linux and only Linux. In context of web development it probably means a test server, which emulates target environment.  In other words you would push your work to the Linux box, test it there and only then push it to production server.

A: Put simply a "dedicated" Linux box is whatever one decides to dedicate it to! :)

A: I've never heard this, but I would guess it means having a Linux box always available, as opposed to having a Windows machine with a Linux VM image.  This doesn't really make sense to me, but then where I work we have a handful of really big servers that just host VMs, so instead of four huge servers we have like seventeen +/- five virtual ones for various purposes and projects.  For all practical purposes, most are "dedicated" boxes, because they are always running.
I would guess what people really mean is that you should have a separate server (running whatever) available for test deployment, hosting large databases and other resource-intensive tasks that you don't want slowing down your development machine.

A: A dedicated Linux box is a box which runs Linux and is dedicated to a specific task.
Put in the context of your question this would be a machine (could be a VM could be physical) which is available to the developer and the developer only for developing and testing applications which are expected to run under Linux. The critical thing though is that it is used solely for this purpose and there will be no contention in terms of it being needed by other people or for other things.
The reason this is useful / necessary in some situations is that to maximise the developers productivity you shouldn't have to wait if you need to test something under Linux, or worry about your install or configuration changes causing problems for some other user or application. Basically you should be answerable to no-one for what happens on that box.
So the contrast with having access to a Linux box but having to arrange time to use it, agree changes that can be made and so on. This is workable (usually) but will result in wasted time while you try to get time on it and have to work around the constraints placed on you by others.
Is it necessary? It depends - do you develop anything that is expected to run on Linux? If not then no, it's completely irrelevant, if so then probably yes.
And there really shouldn't be a question of cost - you can run Linux perfectly fine on a $500 box and the license obviously costs nothing so that really shouldn't be an issue.

A: In the context of web development, "dedicated Linux box" usually refers to a server owned by someone else. You lease the hardware and usually some (often minimal) support services. You don't share the hardware with anyone else. You might or might not be allowed to pick the operating system and applications.
A dedicated server usually has more to do with deployment than with development.
Opposed to "shared server" or "shared virtual hosting environment", where multiple companies (commonly meaning multiple web sites) share the hardware, but are isolated by software. Sharing hardware means other people (whom you typically can't identify or contact) can really make life hard for you by monopolizing CPU, disk, etc.

A: If you don't like botched deployments, you want the closest copy of your production environment as possible. Usually it's a VM, and running such a VM on a e.g. notebook is usually not fun. (At least, you need to store the image for everyone to use.) Also, you'd like a common integration/testing environment for everyone in your team, e.g. with a common database, a central VCS repository (convenient even with a DVCS), store for all dependencies (of exact versions), etc.
This all could take a dedicated box, not necessarily Linux, while Linux is easiest of all.


text:
Q: How to obtain a new table after filtering only one column in an existing table in R? I have a data frame having 20 columns. I need to filter / remove noise from one column. After filtering using convolve function I get a new vector of values. Many values in the original column become NA due to filtering process. The problem is that I need the whole table (for later analysis) with only those rows where the filtered column has values but I can't bind the filtered column to original table as the number of rows for both are different. Let me illustrate using the 'age' column in 'Orange' data set in R:
> head(Orange)
  Tree  age circumference
1    1  118            30
2    1  484            58
3    1  664            87
4    1 1004           115
5    1 1231           120
6    1 1372           142

Convolve filter used
smooth <- function (x, D, delta){
z <- exp(-abs(-D:D/delta))
r <- convolve (x, z, type='filter')/convolve(rep(1, length(x)),z,type='filter')
r <- head(tail(r, -D), -D)
r
}

Filtering the 'age' column
age2 <- smooth(Orange$age, 5,10)
data.frame(age2)

The number of rows for age column and age2 column are 35 and 15 respectively. The original dataset has 2 more columns and I like to work with them also. Now, I only need 15 rows of each column corresponding to the 15 rows of age2 column. The filter here removed first and last ten values from age column. How can I apply the filter in a way that I get truncated dataset with all columns and filtered rows?

A: You would need to figure out how the variables line up. If you can add NA's to age2 and then do Orange$age2 <- age2 followed by na.omit(Orange) you should have what you want. Or, equivalently, perhaps this is what you are looking for?
df <- tail(head(Orange, -10), -10)    # chop off the first and last 10 observations
df$age2 <- age2
df

   Tree  age circumference      age2
11    2 1004           156  915.1678
12    2 1231           172  876.1048
13    2 1372           203  841.3156
14    2 1582           203  911.0914
15    3  118            30  948.2045
16    3  484            51 1008.0198
17    3  664            75  955.0961
18    3 1004           108  915.1678
19    3 1231           115  876.1048
20    3 1372           139  841.3156
21    3 1582           140  911.0914
22    4  118            32  948.2045
23    4  484            62 1008.0198
24    4  664           112  955.0961
25    4 1004           167  915.1678

Edit: If you know the first and last x observations will be removed then the following works:
x <- 2
df <- tail(head(Orange, -x), -x)     # chop off the first and last x observations
df$age2 <- age2


text:
Q: AppCompatActivity.onCreate can only be called from within the same library group After upgrading to appcompat 25.1.0 I've started getting weird errors.
In my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

I get lint error:
AppCompatActivity.onCreate can only be called from within the same library group (groupId=com.android.support)
How to prevent such behavior?

A: Disabling the warning in lintOptions doesn't look a good option it's better to suppress inspection at the statement level.
Add this comment above the line of code which gives the warning:
//noinspection RestrictedApi

A: As previous responses highlighted, it is bug. I recommend not to disable the specific lint warning project-wide, but for that method only. Annotate your method as follows:
@SuppressLint("RestrictedApi")
@Override
public void setupDialog(Dialog dialog, int style) {
    super.setupDialog(dialog, style);
    //your code here
}

A: As Felipe already pointed out in his comment this is a bug in the pre-release version of the tools.
You can workaround it for now, until Google release a fix, by adding the following into your project module's build.gradle file:
android {
  lintOptions {
    disable 'RestrictedApi'
  }
}

It's worth noting that this may hide true errors in your project as it suppresses all errors of that type, so the better option would be to downgrade the version of Android Studio and the tools used in the project.


text:
Q: scope is not getting the model from an input field in a directive and ng-if div container I think I'm missing something basic here.
I have a custom directive that have an input with ng-model on it. When I try to access the the value of the ng-model in the ng-change event the scope has no property of the ng-model. for exaple:
<input ng-model="myInput" ng-change="onChange()" />

and from the controller:
$scope.onChange = function() {
     console.log($scope.myInput);
}

and here is a plunkr I made with the issue: http://plnkr.co/edit/EnPE7p?p=info
Thanks,
e.

A: Or just pass the value into the function like this
<input type="text" ng-change="onChange(myInput)" ng-model="myInput" />

$scope.onChange = function(value) {
    console.log(value);
};

A: Oops! typo!
<input type="text" og-change="onChange()" ng-model="myInput" />

should be
<input type="text" ng-change="onChange()" ng-model="myInput" />

EDIT: update to address OP problem indicated in comment.
The issue is that you are using a surrounding ng-if, which sets up an isolated scope. This means that the controller's $scope.myInput is not the same as the model of the input since it is a literal.
So there are two solutions, you can either remove the ng-if, or your can change myInput to an object, which will be inherited correctly.
$scope.myInput = {
    val: ''
};

<input type="text" ng-change="onChange()" ng-model="myInput.val" />

Since I expect that you want the second solution (the ng-if is important) I updated the plnkr with this one.
Hope this helps!

A: I figured it out:
Since there is a ng-if on the div containing the input, the ng-if creates it's own inheriting scope. So in order to have the ng-model get bind in 2 way with the input value, the ng-model need to be assigned an object.
for example in the directive's controller:
$scope.myInput = {};

in the html:
<input ng-model="myInput.value"... />

and than we can access the myInput in onChange event.
here is an update plunk with the solution: http://plnkr.co/edit/Gwfl0y?p=preview
hope this helps anyone.


text:
Q: How to download CSV File form api response. (Response I am getting URL) In the response I am getting below data.
{
  "message": null,
  "data": {
    "fileName": "JUNE-Report",
    "uploadedBy": "Vasudha",
    "userType": "MANAGER",
    "dueDate": "2022-06-30",
    "uploadedDate": "2022-04-12T06:09:27.30413",
    "quarter": "Q2",
    "year": "2022",
    "url": "https://vlfreportdocuments.s3.amazonaws.com/JUNE-Report2022-04-12T06%3A09%3A25.797771?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20220412T060927Z&X-Amz-SignedHeaders=host&X-Amz-Expires=518399&X-Amz-Credential=AKIA4YA3RZN7I4FHHQ6R%2F20220412%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=7391170c548c4176eed83e645601e20b609d682686091f0d78dbe79bbe2a1e03",
    "jobFunction": null
  },
  "errorMessage": null
}


text:
Q: Bigquery convert string to datetime I'm trying to parse a string to a datetime format. I am posting here after exploring this answer
Here is my attempt at it, what am i missing?
select PARSE_TIMESTAMP('%Y-%M-%dT%H:%M:%S.000000', StartDate) AS parsedStartDate
This is the error I get: Failed to parse input string "2020-11-23T10:51:47.5533333"

A: Try the following in standard SQL:
with data as (
select '2020-11-23T10:51:47.5533333' as StartDate
)
select PARSE_TIMESTAMP('%Y-%m-%dT%H:%M:%E*S',StartDate) from data;


text:
Q: best way to clear all iptables rules I currently have this snippet:
# flush all chains
iptables -F
iptables -t nat -F
iptables -t mangle -F
# delete all chains
iptables -X

Is there a possibility that some impervious rule will stay alive after running this?
The idea is to have a completely clean iptables config, that can be easily replaced by new ruleset (nevermind routes/ifconfig's parameters).

A: This will correctly totally reset your iptables system to a very basic state:
iptables-save | awk '/^[*]/ { print $1 }
                     /^:[A-Z]+ [^-]/ { print $1 " ACCEPT" ; }
                     /COMMIT/ { print $0; }' | iptables-restore

All policies will be reset to ACCEPT as well as flushing every table in current use. All chains other than the built in chains will no longer exist.

A: One can do this in 1 or 2 commands:
 $ sudo iptables-save > iptables.bak
 $ sudo iptables -F

Result:
$ sudo iptables -nvL
Chain INPUT (policy ACCEPT 3138 packets, 5567K bytes)
pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 3602 packets, 6547K bytes)
pkts bytes target     prot opt in     out     source               destination

A: Backups configuration to iptables_backup.conf and clean all rules.
iptables-save | tee iptables_backup.conf | grep -v '\-A' | iptables-restore

To restore previous configuration:
iptables-restore < iptables_backup.conf

A: Whenever I need the firewall disabled is something like this:

*

*iptables-save > iptables.bak

*service iptables stop (i'm on fedora)

A: You can just unload iptables' modules from the kernel:
modprobe -r iptable_raw iptable_mangle iptable_security iptable_nat iptable_filter

UPD Unfortunately, too good to be true. As long as there's a rule or a user-defined chain in a table, corresponding module's reference count is 1, and modprobe -r fails. You might delete rules and user-defined chains like so:
echo $'*raw\nCOMMIT\n*mangle\nCOMMIT\n*security\nCOMMIT\n*nat\nCOMMIT\n*filter\nCOMMIT' | iptables-restore

or:
iptables-save | awk '/^[*]/ { print $1 "\nCOMMIT" }' | iptables-restore

Also, you might want to unload modules this way (no hardcoding module names):
lsmod | egrep ^iptable_ | awk '{print $1}' | xargs -rd\\n modprobe -r

On the bright side, after this iptables-save produces nice empty output :)

A: To answer your question succinctly, no: there would not be any "leftover" rules after flushing every table. In the interest of being thorough however, you may want to set the policy for the built-in INPUT and FORWARD chains to ACCEPT, as well:
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -t nat -F
iptables -t mangle -F
iptables -F
iptables -X

Clear ip6tables rules:
ip6tables -P INPUT ACCEPT
ip6tables -P FORWARD ACCEPT
ip6tables -P OUTPUT ACCEPT
ip6tables -t nat -F
ip6tables -t mangle -F
ip6tables -F
ip6tables -X

...and that should do it. iptables -nvL should produce this (or very similar) output:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

A: I've had to block all connections recently what I ended up doing was
iptables-policy INPUT DROP
iptables-policy OUTPUT DROP
iptables-policy FORWARD DROP

as for saving I'd recommend the following
Ubuntu:
/etc/init.d/iptables save
/sbin/service iptables save

RedHat/CentOS:
/etc/init.d/iptables save
/sbin/iptables-save

In addition to backup all current ufw rules Ive used this in the past
cp /lib/ufw/{user.rules,user6.rules} /<BACKUP LOCATION>
cp /lib/ufw/{user.rules,user6.rules} ./

I think this may be useful for future reference. Thought I would share.

A: This worked for me (on Ubuntu 18.04):
sudo bash -c "ufw -f reset && iptables -F && iptables -X && ufw allow 22 && ufw -f enable"

It resets (and disables) ufw and then resets iptables clearing and removing all chains. Then it enables the ufw again, but not before it allows port 22 for remote access. The two commands that require user confirmation are "forced" ensuring no input is required. I was able to run this over an active SSH connection.
(source)

A: Here is how I remove all DROP rules:
iptables -S |grep DROP| sed 's/-A/-D/' >rules  # -A becomes -D: delete
nano rules  # check that everything is correct
cat rules | while read line; do iptables $line; done
iptables-save

Done!

A: sudo iptables -t nat -F
sudo iptables -t mangle -F
sudo iptables -t filter -F
sudo iptables -t raw -F

sudo iptables -t nat -X
sudo iptables -t mangle -X
sudo iptables -t filter -X
sudo iptables -t raw -X

echo "=== NAT ==="; sudo iptables -t nat -S; echo "\n=== MANGLE ==="; sudo iptables -t mangle -S; echo "\n=== FILTER ==="; sudo iptables -t filter -S; echo "\n=== RAW ==="; sudo iptables -t raw -S

A: Newbie Necro-post:
Lately, I'm finding that nf/iptables reports it's busy so whatever --delete,
--flush,  or -X argument that was issued with the iptables command simply has no effect.  Thereby, I sometimes do end up with some mixture of new configuration rules, along with some unwanted artifact rules from a previous iptables configuration, getting saved with iptables-save.
While it's not a 100% cure, I suffix any iptables commands with --wait, along with whatever other arguments I intend, such as -X.
I think it's still worthwhile to augment
-X precautions with --flush, --delete and maybe make a null-firewall .rules file to restore with iptables-restore.
I can check in a bash shell script, using awk, if there's more than the default 38 lines resulting from an iptables --list command showing an empty configuration

EXITCOND1=0
iptables --list | awk '{ ++cnt; /
if (cnt < 40 ) exit level 1: /
print } '
EXITCOND1=$(echo $?)
if [ $EXITCOND1 == 0 ];
then
echo "There are firewall rules"
else
echo "There are no firewall rules"
fi

Obviously you all know to replace the "echo" statements with your own handling code.  You can also use similar code to check line length and --log-prefix content
in case you coincidentally do have only 38-40 lines of code in your iptables configuration.
(I'm typing this on my phone.  I hope spell check didn't help me screw this up.)
Great ideas in your posts folks.  Thanks.


text:
Q: Wp 8.1 xaml issue I have TemplatedControl defined as:
<Style TargetType="controls:HeaderedContentControl">
        <Setter Property="HintAlignment" Value="Center"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="controls:HeaderedContentControl">
                    <Grid Background="{TemplateBinding Background}">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                        <Border Background="Gray">
                            <TextBlock Text="{TemplateBinding Header}"
                                       FontSize="25"
                                       Foreground="White"
                                       TextWrapping="Wrap"
                                       Margin="0,10"
                                       HorizontalAlignment="Center"
                                       VerticalAlignment="Center"/>
                        </Border>
                        <ScrollViewer Grid.Row="1">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>
                                <TextBlock Visibility="{Binding Text, RelativeSource={RelativeSource Self}, Converter={StaticResource strConv}}"
                                   Text="{TemplateBinding Hint}"
                                   TextAlignment="{TemplateBinding HintAlignment}"
                                   TextWrapping="Wrap"
                                   Foreground="Gray"
                                   FontSize="17"
                                   Margin="10"/>
                                <ContentPresenter Content="{TemplateBinding Content}"
                                                  Grid.Row="1"/>
                            </Grid>
                        </ScrollViewer>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Sometimes after navigation to the page with this control I see
this
instead of
this
I think this occurs because of BottomAppBar on the page. How can I get round this issue?
Layout where this control is used:
<controls:HeaderedContentControl Header="Регистрация">
    <StackPanel Margin="10,40">
        <TextBlock Text="Номер телефона:"
                   FontSize="20"/>
        <Grid Margin="0,15">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="8"
                       Margin="10,0"
                       VerticalAlignment="Center"
                       FontSize="20"/>
            <controls:PhoneTextBox Value="{Binding PhoneNumber, Mode=TwoWay}"
                                   AddContactVisibility="Collapsed"
                                   Margin="0"
                                   Grid.Column="1"/>
        </Grid>
        <TextBlock Text="Номер вводится без 8-ки. Пример: (XXX)XXX-XX-XX"
                   FontSize="15"
                   Foreground="Gray"
                   TextWrapping="WrapWholeWords"/>
    </StackPanel>
</controls:HeaderedContentControl>

<Page.BottomAppBar>
    <CommandBar>
        <AppBarButton Label="Далее"
                      Icon="Accept"
                      Command="{Binding RegisterCommand}"/>
    </CommandBar>
</Page.BottomAppBar>


text:
Q: php sessions not storing data I'm currently having trouble with storing session data.
For some reason my sessions start and I can see it as a cookie but when I try to get my stored data from it it doesn't work.
Here is my code:
This is where I start the session and set the variables:
session_name("user");
session_start();
if ($groups != false) {
    $_SESSION['groups'] = $groups->fetch_all(MYSQLI_ASSOC);
}
if ($dateformat != false) {
    $_SESSION['dateformat'] = $dateformat;
}
$_SESSION['user_id'] = $row[0];
$_SESSION['user_firstname'] = $firstname;
$_SESSION['user_lastname'] = $lastname;

This is where I try to get my variables:
session_start();
if (isset($_SESSION['user_firstname'])) {
    echo $_SESSION['user_firstname'];
}

Note: The page where I try to get the session data is my navbar/header it is only used with an php include statement.

A: It could be that $firstname is failing to be set. Try changing $_SESSION['user_firstname'] = $firstname; for example, to $_SESSION['user_firstname'] = "TEST"; and see if it stores that. If so, you're not giving $firstname a value.


text:
Q: unit sphere in Q-dimensions and its relationship to volume and area of a sphere of any radius and dimension-Q I'm told that:
the surface Area of the unit sphere (r=1) in Q-dimensions is:
$$S_Q = \frac{2\pi^{Q/2}}{\Gamma(\frac{q}{2})}$$
and the volume of the unit sphere (r=1) in Q-dimensions is:
$$V_Q = \int_{0}^{1} S_Q~ r^{(Q-1)}~dr$$
$$V_Q = \frac{S_Q}{Q}$$
I'm trying to understand the formula for the general area, and general volume of Q-dimensional Sphere by multiply the unit volume ($V_Q$), and unit surface area ($S_Q$) by a function of radius. Specifically:
$$\tilde{S}_Q(r) = S_Q ~r^{Q-1}$$
$$\tilde{V}_Q(r) = V_Q ~r^Q$$
For instance, Why does multiplying the unit surface area $S_Q$ by $r^{Q-1}$ equal the Surface area for any sphere of radius r and dimension Q?
And, why does multiplying the unit volume by $r^Q$ equal the volume for any sphere of radius r and dimension Q?


text:
Q: no matching function for call to 'node::node()' I am creating and displaying an singly linked list.
However there is an error in the main function
no matching function for call to 'node::node()'
Following is my code:
#include <iostream.h>
 using namespace std;
 class node
 {
  node *next,*start,*ptr;
  int data;

  public:

  node(int d)
  {
    data=d;
    next=NULL;
    start=NULL;
    ptr=NULL;
  }
    void create();
    void display();

};
void node::create()
{
int d;
char ch;
node *temp;
do
{
cout<<"Enter data";
cin>>d;
temp=new node(d);
if(start==NULL)
{
    start=temp;
}
else
{
    ptr=start;
    while(ptr->next!=NULL)
    {
        ptr=ptr->next;
    }
    ptr->next=temp;
    temp->next=NULL;
}
cout<<"\nDo you want to enter more data?";
cin>>ch;
}while(ch=='y'||ch=='Y');
}
void node::display()
{
ptr=start;
while(ptr->next!=NULL)
{
    cout<<"\n"<<ptr->data;
    ptr=ptr->next;
}
cout<<"\n"<<ptr->data;
}
int main()
{
node n;
int c;
char a;
do
{
cout<<"*****MENU*****";
cout<<"\n1.Create \n2.Display";
cout<<"\nEnter your choice";
cin>>c;
switch(c)
{
case 1:
n.create();
break;
case 2:
    n.display();
break;
default:
    cout<<"\nInvalid choice";
    break;
}
cout<<"\nDo you want to continue?";
cin>>a;
}while(a=='y'||a=='Y');
    return 0;
}

When I write the same program using a friend class of node, the program executes successfully.
Why do we need to use more than one class?

A: For your class node you defined only one constructor, that accepts parameter type int, which means you can construct instances of this class with such parameter, what you do here:
temp=new node(d); // fine, you pass int d to construct node

but in main() you try to create instance of class node without any parameters:
int main()
{
    node n; // <---- problem

so either pass integer when you create n in main() or define another constructor without any parameters (aka default constructor) for class node.


text:
Q: Question on finding the relative error The question is as under:

Find the relative error in Z if

*

*Z= A/B

*Z= A(B^-1)
Relative error in A is ΔA/A and in B is ΔB/B

My solutions are :

*

*As A and B are being divided the relative error in Z is the sum of the relative errors in A and B.

  ΔZ/Z  = ΔA/A  +  ΔB/B

*B is raised to power -1. Then the relative error in Z will be  ΔZ/Z  = ΔA/A  -  ΔB/B

  I have written - ΔB/B because when a physical quantity is raised to a
  power then the relative error will be the product of power and the
  relative error in the original quantity.

Now the cases 1 and 2 give the same meaning but the relative errors are different. Why is this so.
Please give me the explanation.

A: This:

the relative error in Z is the sum of the relative errors in A and B.

is incorrect.
This:

when a physical quantity is raised to a power then the relative error will be the product of power and the relative error in the original quantity.

is also incorrect.
When you have a function $f(A,B)$ of two variables, then the uncertainty in $f$ (labeled $\sigma_f$) is related to the uncertainties $\sigma_A$ and $\sigma_B$ in $A$ and $B$ in the following way:
$$\sigma_f^2=\left(\frac{\partial f}{\partial A}\right)^2\sigma_A^2+\left(\frac{\partial f}{\partial B}\right)^2\sigma_B^2$$
Inserting $f(A,B)=A/B$ and $f(A,B)=AB^{-1}$ into the above formula will give you the same results for $\sigma_f$, and therefore will give you the same results for the relative error $\sigma_f/f$.


text:
Q: CSS: When flex row wraps, how to keep scrollable column from being pushed down below its container's fold? In a fixed-height container, I have a flexbox (.main) with flex-direction: row and flex-wrap: wrap. At a wide screen size, I'd like its children — an image (.image-column), and a long amount of text (.text-column) — to be columns, in which the image remains static and the text scrolls. So far, so good. When sized down past the columns' min widths, I'd like them to wrap and stack. This all works, but here's the problem: when they wrap and stack, the scrollable text is offset by the min-height of the .image-column above it, such that when you scroll down to the bottom of the text, the scrollbar disappears offscreen rather than remaining within its container. But if you adjust the height to account for this offset, the .text-column is squished in the unwrapped state.
The two conflicting elements seem to be:

*

*.image-column's min-height: 200px — but without this, the image doesn't show up at all when wrapped

*.text-column's height: 100% — but without this, the text doesn't scroll

I've tried .text-column with height: calc(100% - 200px) — this fixes the offset when stacked, but creates unnecessary whitespace when in columns, and I'd prefer to avoid such specificity anyway
I'd like to figure out a solution with CSS only and no media queries, since this container may be in a multi-column layout with other containers. I'm willing to use flex, grid, float, or any other arcane layout trick.
Has anyone else experienced this issue with flex row wrapping and scrolling?
(You can run the code snippet below to see the layout wrapped, and press Full Page to see the layout in its wide 2-column state.)

body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 40px;
    padding: 40px;
    background: #f6f6f6;
    font-family: sans-serif; font-size: 120%; line-height: 1.5; color: #111;
}

.container {
    height: 600px;
    min-width: 300px;
    max-width: 900px;
    width: 100%;
    display: flex;
    flex-direction: column;
    background-color: white;
    border-radius: 10px;
    overflow: hidden; /* don't scroll */
    border: 1px solid #ccc;
}
.header {
    border-bottom: 1px solid #ccc;
    padding: 20px;
}
.main {
    flex: 1 1 auto; /* fills remainder of height */
    display: flex;
    flex-direction: row;
    flex-wrap: wrap; /* wrap after elements reach min-width / flex-basis */
    overflow: hidden; /* don't scroll */
}
.image-column {
    min-height: 200px;
    flex: 1 1 300px; /* column width, min for wrapping */
    background-image: url('https://images.unsplash.com/photo-1641361784653-73767ccfdf60?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDM0fDZzTVZqVExTa2VRfHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=900&q=60');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}
.text-column {
    height: 100%;
    flex: 2 1 420px; /* column width, min for wrapping */
    overflow: auto; /* scroll */
    padding: 20px;
}
.footer {
    border-top: 1px solid #ccc;
    padding: 20px;
}

Header

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius enim eu justo posuere, a laoreet urna sodales. Mauris ac porta lorem, id malesuada ipsum. In ac ipsum sapien. Nunc nisi tellus, auctor vitae placerat sit amet, posuere id velit. In semper ex placerat purus sollicitudin, at aliquet metus viverra. Nam malesuada vel tellus malesuada fermentum. Curabitur iaculis vel lacus nec scelerisque. Praesent feugiat ac augue bibendum facilisis. Curabitur dapibus malesuada magna sit amet vehicula. Fusce ipsum eros, consectetur in sodales ac, lacinia at purus. Quisque laoreet justo et semper luctus. Nam ligula orci, ultricies et enim non, elementum rutrum massa. Aenean cursus lacus in magna hendrerit, in fermentum ex porttitor. Integer elementum, enim sit amet vehicula mollis, diam tortor congue massa, eget accumsan nulla arcu a leo. Maecenas convallis placerat magna, vitae lacinia mi ullamcorper quis. Etiam congue aliquet dolor eget dignissim. Donec malesuada laoreet nibh, sit amet tristique lacus facilisis nec. Quisque sit amet enim ac lectus bibendum laoreet. Pellentesque eleifend urna eget ultricies commodo. Nulla ex sapien, accumsan sit amet est vitae, pretium sollicitudin metus. Nullam finibus, ipsum id tincidunt tristique, diam tortor pellentesque orci, non rutrum turpis arcu ultricies eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius enim eu justo posuere, a laoreet urna sodales. Mauris ac porta lorem, id malesuada ipsum. In ac ipsum sapien. Nunc nisi tellus, auctor vitae placerat sit amet, posuere id velit. In semper ex placerat purus sollicitudin, at aliquet metus viverra. Nam malesuada vel tellus malesuada fermentum. Curabitur iaculis vel lacus nec scelerisque. Praesent feugiat ac augue bibendum facilisis. Curabitur dapibus malesuada magna sit amet vehicula. Fusce ipsum eros, consectetur in sodales ac, lacinia at purus. Quisque laoreet justo et semper luctus. Nam ligula orci, ultricies et enim non, elementum rutrum massa. Aenean cursus lacus in magna hendrerit, in fermentum ex porttitor. Integer elementum, enim sit amet vehicula mollis, diam tortor congue massa, eget accumsan nulla arcu a leo. Maecenas convallis placerat magna, vitae lacinia mi ullamcorper quis. Etiam congue aliquet dolor eget dignissim. Donec malesuada laoreet nibh, sit amet tristique lacus facilisis nec. Quisque sit amet enim ac lectus bibendum laoreet. Pellentesque eleifend urna eget ultricies commodo. Nulla ex sapien, accumsan sit amet est vitae, pretium sollicitudin metus. Nullam finibus, ipsum id tincidunt tristique, diam tortor pellentesque orci, non rutrum turpis arcu ultricies eros.

Footer

A: I've found a solution to my own question.
Grid has a similar way of wrapping columns, using repeat's auto-fit with a minmax for each column in which the min is a fixed width.
.main {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
    overflow: hidden; /* don't scroll */
}

Using this approach, when the columns wrap, the first column's min-height no longer offsets the second column and its scrollbar out of the container, as it did with flex row wrap.
The only small drawback is that the grid's two columns must be of equal width in order for the wrapping to work. For my uses, this is acceptable.

body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 40px;
    padding: 40px;
    background: #f6f6f6;
    font-family: sans-serif; font-size: 120%; line-height: 1.5; color: #111;
}

.container {
    height: 600px;
    min-width: 300px;
    max-width: 900px;
    width: 100%;
    display: flex;
    flex-direction: column;
    background-color: white;
    border-radius: 10px;
    overflow: hidden; /* don't scroll */
    border: 1px solid #ccc;
}
.header {
    border-bottom: 1px solid #ccc;
    padding: 20px;
}
.main {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
    overflow: hidden; /* don't scroll */
}
.image-column {
    min-height: 200px;
    background-image: url('https://images.unsplash.com/photo-1641361784653-73767ccfdf60?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDM0fDZzTVZqVExTa2VRfHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=900&q=60');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}
.text-column {
    overflow: auto; /* scroll */
    padding: 20px;
}
.footer {
    border-top: 1px solid #ccc;
    padding: 20px;
}

Header

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius enim eu justo posuere, a laoreet urna sodales. Mauris ac porta lorem, id malesuada ipsum. In ac ipsum sapien. Nunc nisi tellus, auctor vitae placerat sit amet, posuere id velit. In semper ex placerat purus sollicitudin, at aliquet metus viverra. Nam malesuada vel tellus malesuada fermentum. Curabitur iaculis vel lacus nec scelerisque. Praesent feugiat ac augue bibendum facilisis. Curabitur dapibus malesuada magna sit amet vehicula. Fusce ipsum eros, consectetur in sodales ac, lacinia at purus. Quisque laoreet justo et semper luctus. Nam ligula orci, ultricies et enim non, elementum rutrum massa. Aenean cursus lacus in magna hendrerit, in fermentum ex porttitor. Integer elementum, enim sit amet vehicula mollis, diam tortor congue massa, eget accumsan nulla arcu a leo. Maecenas convallis placerat magna, vitae lacinia mi ullamcorper quis. Etiam congue aliquet dolor eget dignissim. Donec malesuada laoreet nibh, sit amet tristique lacus facilisis nec. Quisque sit amet enim ac lectus bibendum laoreet. Pellentesque eleifend urna eget ultricies commodo. Nulla ex sapien, accumsan sit amet est vitae, pretium sollicitudin metus. Nullam finibus, ipsum id tincidunt tristique, diam tortor pellentesque orci, non rutrum turpis arcu ultricies eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla varius enim eu justo posuere, a laoreet urna sodales. Mauris ac porta lorem, id malesuada ipsum. In ac ipsum sapien. Nunc nisi tellus, auctor vitae placerat sit amet, posuere id velit. In semper ex placerat purus sollicitudin, at aliquet metus viverra. Nam malesuada vel tellus malesuada fermentum. Curabitur iaculis vel lacus nec scelerisque. Praesent feugiat ac augue bibendum facilisis. Curabitur dapibus malesuada magna sit amet vehicula. Fusce ipsum eros, consectetur in sodales ac, lacinia at purus. Quisque laoreet justo et semper luctus. Nam ligula orci, ultricies et enim non, elementum rutrum massa. Aenean cursus lacus in magna hendrerit, in fermentum ex porttitor. Integer elementum, enim sit amet vehicula mollis, diam tortor congue massa, eget accumsan nulla arcu a leo. Maecenas convallis placerat magna, vitae lacinia mi ullamcorper quis. Etiam congue aliquet dolor eget dignissim. Donec malesuada laoreet nibh, sit amet tristique lacus facilisis nec. Quisque sit amet enim ac lectus bibendum laoreet. Pellentesque eleifend urna eget ultricies commodo. Nulla ex sapien, accumsan sit amet est vitae, pretium sollicitudin metus. Nullam finibus, ipsum id tincidunt tristique, diam tortor pellentesque orci, non rutrum turpis arcu ultricies eros.

Footer

(You can run the code snippet below to see the layout wrapped, and press Full Page to see the layout in its wide 2-column state.)

A: try setting the height of .text-column to 260px
.text-column {
    height: 260px;
    flex: 2 1 420px; /* column width, min for wrapping */
    overflow: auto; /* don't scroll */
}


text:
Q: validate string to JavaScript Date format I'm having trouble validating the following string which comes from the new Date() Object.
"2020-10-06T14:23:43.964Z". In my case, I'll be expecting either this input format or a new Date(). I'm trying to write something to do this similar to
const isValidDate = (d: Date):boolean => {
 if (d instanceof Date || /* check if valid Date string here */) {
   return true
 }
 return false
}

A: Maybe this can help you.
Date.prototype.isValid = function () {
  // If the date object is invalid it
  // will return 'NaN' on getTime()
  // and NaN is never equal to itself.
     return this.getTime() === this.getTime();
};

A: Found the second half of my problem from this post which goes into more details javascript regex iso datetime
the function I came up with should check if the input is an instance of a Date object or a string that matches the output of the Date object.

function isValidDate (d) {
  if (d instanceof Date) {
    return true;
  }
  return /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/.test(d) ? true : false
}

const d1 = new Date(); // true
const d2 = '2020-10-05'; // false
const d3 = '2020-10-06T14:23:43.964Z'; // true

console.log(isValidDate(d1))
console.log(isValidDate(d2))
console.log(isValidDate(d3))


text:
Q: display data from 2 tables in excel from sql server I want to display 2 table data from SQL Server to Excel file. Each table has 2 columns.
I know that we can do this using Data tab. But what I could understand is we need to create 2 connections for the 2 tables.
Can we use a single connection and using this connection display the data from 2 tables?
Thanks in advance

A: Nope, you cannot connect two tables with one connection.
There is workaround to join tables in SQL query or use Union and index each table with column with name of the table.
Or if you do not want to use queries, try Microsoft Query from Excel, here is link to see how to use it.
https://help.acctivate.com/articles/3727/
Still I would suggest to do two connections.


text:
Q: Enable guest user not working I would like to activethe guest user in cmd or gpo:
Invité = Guest (I'm french), using Guest return an error.
CMD : net user Invité /active:yes
I've got "The command completed successfully" but my guest user is still off (I see it on the logon screen and into the Manage Account)...
The command succeedded if I've already activate the account into the Manage Account by myself...
GPO : I enable this one Accounts: Guest account status at Computer Configuration/Windows Settings/Security Settings/Local Policies/Security Options but it's not working too...
I'm missing something ?
EDIT : I also tried secpol.msc>security setting>security options>Guest account status but it's still disabled...


text:
Q: Is there a best practice for storing ReactJS hooks files? I've been through the ReactJS documentation regarding building custom hooks a few times, but I don't see a convention for where custom hooks should be stored within the project directory.
I'm trying to establish a convention for our developers and am wondering if the larger React community has solved this already.
For example, should they live within any of the following?
/hooks
/components/hooks
/utils
/use
My thought is that simply putting them within /hooks is best as they aren't really React components. Any thoughts? Thanks.

A: Typically I put ours in a helpers folder if it's shared across routes, or directly in the route folder if only needed there.
A flatter directory structure is simpler especially when you can just do a Ctrl P in VScode to find the file you're looking for.
React isn't opinionated on this, however the man himself has a take on it https://twitter.com/dan_abramov/status/1145354949871767552