text:
Q: SQLite Compare Orders Let's say I have a table with two columns a1 and a2.
I need to check if the sequence order of this table is the same, when I order it by a1 and if I order it by a2.
Select a1, a2 from Test order by a1

a1
a2

1
2

2
1

3
3

Select a1, a2 from Test order by a2

a1
a2

2
1

1
2

3
3

Is it somehow possible to check if both results are actually the same, respecting the order of each output?
I tried something like:
With order_1 as (Select * from Test order by a1),
     order_2 as (Select * from Test order by a2)

Select * from order_1 except Select * from order_2

This should yield something like:

a1
a2

2
1

1
2

But this doesn't work, as it apparently doesn't respect the order.

A: We can use ROW_NUMBER() OVER ( ORDER BY in a CTE to find the entries which are not in the same position when we use the 2 different keys to sort.
Here we have inversed 3 and 4.

create table sorter (
a1 int, a2 int);

insert into sorter values
(1,100),(2,200),(3,400),(4,300),(5,500);

with cte as (
select
  a1,
  a2,
  row_number() over (order by a1) rna1,
  row_number() over (order by a2) rna2
from sorter)
select
  a1,
  a2
from cte where rna1 <> rna2;

a1 |  a2
-: | --:
 3 | 400
 4 | 300

db<>fiddle here

A: Use ROW_NUMBER() window function twice for each of the columns a1 and a2 in a cte and then a self join of the cte to filter out the matching rows:
WITH cte AS (
  SELECT *,
         ROW_NUMBER() OVER (ORDER BY a1) rn_a1,
         ROW_NUMBER() OVER (ORDER BY a2) rn_a2
  FROM Test
)
SELECT c1.a1, c1.a2
FROM cte c1 INNER JOIN cte c2
ON c1.rn_a1 = c2.rn_a2 AND (c1.a1, c1.a2) <> (c2.a1, c2.a2)
ORDER BY c1.a1;

See the demo.
Results:

a1
a2

1
2

2
1


text:
Q: Text above whole window I have a C# Application with WPF.
I want a text above my whole main window. It should look like this:
http://s2.postimg.org/uqad6sosp/Capture.png
The window should keeping interactive and the user should work with the application. So the text is only a watermark on the window.
Have anyone a idea how can i do this with xaml?

A: Just place a Label on top inside the applicationWindow. Then set IsHitTestVisible=False. This should do the trick. Of course you can start using Adorners, but that's maybe too much right now...
 <Grid>
        <Your Stuff here />
        <TextBlock Text="My Watermark" IsHitTestVisible="False" FontSize="45pt" VerticalAlignment="Center" HorizontalAlignment="Center" DoSomeRotation... />
    </Grid>

A: Here you go,
Add a resource like this,
<Window.Resources>
               <Style x:Key="MyStyle" TargetType="{x:Type TextBox}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TextBox}">
                        <Grid>
                            <Border Background="White" BorderBrush="#FF7D8683" BorderThickness="1"/>
                            <ScrollViewer x:Name="scrollhost" Margin="5,0,0,0" VerticalAlignment="Center" />
                            <Label Margin="5,0,0,0" x:Name="lblwatermark" Content="{TemplateBinding Tag}" VerticalAlignment="Center"
                           Visibility="Collapsed" Foreground="Gray" FontFamily="Arial"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="Text" Value=""/>
                                </MultiTrigger.Conditions>
                            <Setter Property="Visibility" TargetName="lblwatermark" Value="Visible"/>
                            </MultiTrigger>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter Property="Foreground" Value="DimGray"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

XAML:
     <Grid >
    <TextBox  Style="{StaticResource MyStyle}" Height="50" FontSize="43"  Tag="OFFLINE">
        <TextBox.LayoutTransform>
            <RotateTransform Angle="-43" />
        </TextBox.LayoutTransform>
    </TextBox>
    </Grid>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Chrome: doesn't print javascript content ( This is through Grease/Tampermonkey ).
Here's a print function for a kiosk using the Chrome beta browser:
$("#autoCheckOrder button").click ( function () {
    var newWin      = window.open ("");
    newWin.document.write ( "<!DOCTYPE html>" );
    newWin.document.write( "" );
    newWin.document.write( "" );
    newWin.document.write( "<title>" );
    newWin.document.write( "</title>" );
    newWin.document.write( "" );
    newWin.document.write( "" );
    newWin.document.write( "" );
    newWin.document.write ( loanHTML );
    newWin.document.write( "" );
    newWin.document.write( "" );
    if(newWin.print()) {
        newWin.close();
    } else {
        newWin.close();
    }
});

It grabs a table from the a page listing all items, then creates a
'receipt'. The receipt is then printed. This worked perfectly for a while, now it only prints the first item.
I have tried the following with absolutely no results:

*

*Using page-break-after: always

*Placing receipt in div with the above CSS rule

*Reinstalling the printer

*Paper reduction settings for printer

The crazy thing is that it used to print all items flawlessly and now it doesn't. I even re-installed the script from a backup just to be sure.
No idea where to go from here. All content shows in print preview, but only the first item prints. 'Header and footer' setting only makes things worse, not better.
UPDATE
I changed the HTML sent to the printer and it works. Still not sure if it's entirely valid but it's printing. I'll know what to fix if it stops printing. Thanks for the input!

A: The only plausible explanation I can see is that your loanHTML variable is empty or undefined.
Demo: http://jsfiddle.net/waitinforatrain/bMzUt/2/
Comment out the var loanHTML line and run again, and you'll see what I mean.


text:
Q: MongoDB - Compound group I have cities collection of documents, where my document is as follow:
{
    "_id" : ObjectId("52fe1d364b5ab856eea75ebc"),
    "elevation" : 1855,
    "name" : "Kud",
    "country" : "India",
    "lon" : 75.28,
    "lat" : 33.08,
    "isPartOf" : [
        "Jammu and Kashmir",
        "Udhampur district"
    ],
    "timeZone" : [
        "Indian Standard Time"
    ],
    "population" : 1140
}

I am interested to find the "the average regional city population for all countries in the cities collection".  My aggregation pipeline command is as follow:
pipeline = [
            {"$match": {"isPartOf":{"$exists":1}, "country":{"$exists":1}}},
            {"$unwind": "$isPartOf"},
            {"$group":{"_id": {"isPartOf": "$isPartOf", "country": "$country"}, "avgRegionalPopulation": {"$avg":"$population"}}},
            {"$sort": {"avgRegionalPopulation":-1}}
            ]

But it seems I am missing something. Since 'avgRegionalPopulation' for 'Lithuania' should be 14750.784447977203. What do I missing in my pipeline command?

A: you missed the average population for each country step.  This is a correct aggregate pipeline command:
pipeline = [
            {"$match": {"isPartOf":{"$exists":1}, "country":{"$exists":1}}},
            {"$unwind": "$isPartOf"},
            {"$group" : {"_id": {"isPartOf": "$isPartOf", "country": "$country"}, "avgregion":{"$avg":"$population"}}},
            {"$group": {"_id": "$_id.country", "avgRegionalPopulation": {"$avg":"$avgregion"}}},
            {"$sort": {"country":-1}}
            ]


text:
Q: Ground attached to negative terminal - where do the electrons come from? My question pertains to this circuit:

Not considering conventional current direction, but rather considering actual electron flow: if the negative terminal is connected to the ground, where do the electrons from the other two grounds come from? The three grounds here are not connected to earth ground, so what is exactly happening for this circuit to function? Where do the electrons from the negative terminal actually go?

A: All three are connected together. You can just remove the ground symbols and draw a wire between them if that is easier to grasp.

A:
Not considering conventional current direction, but rather considering actual electron flow:

It won't help you much. They are equal and opposite.

if the negative terminal is connected to the ground, where do the electrons from the other two grounds come from?

All the grounds are connected. It's a shorthand way of showing the points that are connected to some reference point. This may be the actual Earth or some other convenient common in the circuit.

The three grounds here are not connected to earth ground, so what is exactly happening for this circuit to function?

The symbol they've chosen was originally designed to represent the plates buried underground for an "earth" connection. It still does but is also used (confusingly in my opinion) for other systems such as auto chassis which provides the common negative conductor for all the vehicle electrics.

Where do the electrons from the negative terminal actually go?

Stop worrying about electrons. Just think of current. All the earth points are connected together so current flows as required to or from the battery.
I have written more on the topic in Ground, earth and chassis explained and this may be of help.

A: In an actual circuit you would have what is referred as a "common" ground, creating a loop for energy to flow through.
Although, even without this loop, current flows due to a difference in potential (voltage), so from some battery to a ground reference (potential difference 5V-0V ideally) there is voltage for current to flow.


text:
Q: javascript good way to create or design Singleton class I think in javascript it could create Singleton class like below
test.js
class Container {
    constructor() {
      this.map = new Map;
    }

    set(key, value) {
      this.map.set(key, value);
    }

    get(key) {
      return this.map.get(key);
    }
  }
module.exports.Container = new Container();

so that
I could use that other files like  in index.js
import container from './test'

However  the constructor of Container need some other parameters so that it could do better.  And the Container also need to be Singleton class  ,
because it is a common class . And i do not know how to create it?
constructor(servie) {
      this.map = new Map;
      this.servie = servie;
    }

by the way  the service variable is created when application starts

A: EDIT: I've realised my naming is slightly confusing, as I've used Container to represent the IoC container, and then realised you've used that name to represent your Singleton.
Providing you are able to instantiate your singleton at a central point of code (entry point file for example, while setting up server). You can achieve a Singleton in a number of ways. For example:
let instance = null;
class Singleton {
  constructor(arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;
  }
}

module.exports = (...args) => {
  return instance || (instance = new Singleton(...args));
}

You could do this any multitude of ways e.g. with static functions instead of the anonymous function. However, with all of these I think it becomes slightly confused as to whether you're init'ing the instance or just trying to retrieve it.
IoC container patterns (often used in C# projects) are a little cleaner in my opinion. Where you might have a single container class that keeps track of your singletons and provides separate access and initiation functions.
class Container {
  constructor() {
    this.instances = {};
  }

  add(name, instance) {
    this.instances[name] = instance; // depends if you want overwrite or not
  }

  get(name) {
    if (!this.instances[name]) {
      throw new Error('some appropriate error messaging for your app');
    }
    return this.instances[name];
  }

  remove(name) {
    delete this.instances[name];
  }
}

module.exports = new Container(); // this has to be a no-param constructor

Then in your app init code, you initialise the singletons and register them with your container:
const Container = require('<path_to_Container>');
const Singleton = require('<path_to_Singleton>');
...
Container.add('mySingleton', new Singleton(arg1, arg2));

and access it at any time with:
Container.get('mySingleton');

Couple notes:

*

*You could use Singleton.name instead of a string name ('mySingleton' in the example)

*This is just a personal preference. But I like it because it feels more declarative, you register (add) an instance to the container at app start-up and don't blur the lines between initialisation and usage. And it means that if you add more of these singletons going forward, you have a single pattern for it already in place.


text:
Q: How do I find the minimum and maximum values of a function of two variable with constraints? The question is find the minima and maxima of the function
$$f(x,y)= x^2+5y^2+11x-12y+30$$
on $(x^2)/81+(y^2)/49 \leq 1.$
I've been trying to use FindMaxValue and FindMaximum like this without success:
FindMaxValue[2 x^2 + 3 y^2 + 8 x - 18 y + 11, {x^2/81 + y^2/49 <= 1}]
FindMaximum[2 x^2 + 3 y^2 + 8 x - 18 y + 11, {x^2/81 + y^2/49 <= 1}]

A: $Version

(* "13.0.1 for Mac OS X x86 (64-bit) (January 28, 2022)" *)

Clear["Global`*"]

f[x_, y_] := x^2 + 5 y^2 + 11 x - 12 y + 30

Note that the objective and the constraint go in the same list and the variables must be specified.
{min, max} = #[{f[x, y], x^2/81 + y^2/49 <= 1}, {x, y}] & /@
  {MinValue, MaxValue} // RootReduce

(* {-(149/20), Root[
 24631233979464 - 6866750384574 # + 83692030225 #^2 - 335820832 #^3 +
  430336 #^4& , 4, 0]} *)

{min, max} // N

(* {-7.45, 370.859} *)

{minN, maxN} = #[{f[x, y], x^2/81 + y^2/49 <= 1}, {x, y}] & /@
  {FindMinValue, FindMaxValue}

(* {-7.45002, 370.859} *)

NMaxValue fails to find the global maximum
{minN2, maxN2} = #[{f[x, y], x^2/81 + y^2/49 <= 1}, {x, y}] & /@
  {NMinValue, NMaxValue}

(* {-7.45002, 211.418} *)

A: f = x^2 + 5 y^2 + 11 x - 12 y + 30;
cons = (x^2)/81 + (y^2)/49 <= 1;

max = Maximize[{f, cons}, {x, y}] // N

{370.859, {x -> 2.14956, y -> -6.79741}}

min = Minimize[{f, cons}, {x, y}] // N

{-7.45, {x -> -5.5, y -> 1.2}}

For visualizing:
r = ImplicitRegion[x^2/81 + y^2/49 <= 1, {x, y}]

Show[
 Plot3D[f, {x, y} \[Element] r]
 , Graphics3D[{
   AbsolutePointSize[12], Red
   , Point[{x, y, max[[1]]} /. max[[2]]]
   , Point[{x, y, min[[1]]} /. min[[2]]]
   }]
 ]


text:
Q: CheckBox not Toggling on Click in RecycleView Android I have created a Recycle View which has a list of records having a checkBox in each Row. Corresponding to each checkBox there is a flag in list of records. I have implemented a Adapter and a custom listener for the same. But On clicking value is not getting changing and reflecting on the screen.
public class RecycleStudentsAdapter
        extends RecyclerView.Adapter<RecycleStudentsAdapter.ViewHolder> {

    private final TypedValue mTypedValue = new TypedValue();
    private int mBackground;
    private List<Student> mValues;
    Student template;

    public Student getValueAt(int position) {
        return mValues.get(position);
    }

    public RecycleStudentsAdapter(Context context, List<Student> items) {
        context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
        mBackground = mTypedValue.resourceId;
        mValues = items;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_student, parent, false);
        view.setBackgroundResource(mBackground);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        template = null;
        template = (Student) mValues.get(position);

        holder.studentId.setText(template.getStudent_disp_id());
        holder.studentName.setText(template.getStudent_name());

        holder.studentCheckBox.setChecked(template.isCheckFlag());
        holder.studentCheckBox.setTag(position);

        holder.studentCheckBox.setOnClickListener(new   CheckBoxListener(position));
        holder.studentCheckBox.setClickable(true);
    }

    public void updateData(List<Student> studentList){

        mValues  = studentList;
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public final View mView;
        public final TextView studentId;
        public final TextView studentName;
        public final CheckBox studentCheckBox;

        public ViewHolder(View view) {
            super(view);
            mView = view;

            studentId = (TextView) view.findViewById(R.id.studentId);
            studentName = (TextView) view.findViewById(R.id.studentName);
            studentCheckBox = (CheckBox) view.findViewById(R.id.check);

        }
    }

    class CheckBoxListener implements View.OnClickListener {

        int position;
        CheckBoxListener(int position) {
          this.position = position;
        }

        public void onClick(View v) {

            boolean isChecked = ((CheckBox) v).isChecked();

           ((CheckBox) v).setChecked(!isChecked);

            if (((CheckBox) v).isChecked()) {
                studentList.get(position).setCheckFlag(true);
            } else {
                studentList.get(position).setCheckFlag(false);
            }

            notifyDataSetChanged();
        }

    }
}

A: instead of holder.studentCheckBox.setOnClickListener(); write holder.studentCheckBox.setOnCheckedChangeListener(); and make a custom listener extending view.oncheckchangelistener.
Remove holder.studentCheckBox.setClickable(true); line that is not required.

A: make a listener as below for your checkbox:
public class CheckBoxListener implements CompoundButton.OnCheckedChangeListener {
    int position;
    CheckBoxListener(int position) {
      this.position = position;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {
        // TODO Auto-generated method stub
           studentList.get(position).setCheckFlag(true);
           notifyDataSetChanged();
    }

}


text:
Q: Partition $Z_2^n \setminus \{0\}$ into disjoint sets. Does one contain a maximal subspace? Let $n \geq 1$. $V=Z_2^n \setminus \{0\}$. $A \cup B = V$. $A \cap B = \Phi$.
Is it true that either A or B contains a sub-space of dimension $n-1$ (without the zero element)?
(I reduced a homework question to this one).

A: This is not true. For $n=4$ let
$$A=\{(0,1,0,0), (0,0,1,0), (0,0,0,1), (1,1,0,0), (1,1,1,0), (1,1,0,1), (1,0,1,1), (0,1,1,1)\}$$
$$B=\{(1,0,0,0), (1,0,1,0), (1,0,0,1), (0,1,1,0), (0,1,0,1), (0,0,1,1), (1,1,1,1) \}$$
$B \cup \{0\}$ is not a subspace, and its size (with the zero vector) is $2^3$, so it doesn't contain a subspace of dimension 4-1=3.
Notice that if you remove one vector from A, then it will not be a subspace (with the zero vector) so again $A\cup \{0\}$ doesn't contain a 3 dimensional subspace.


text:
Q: Unable to SSH into server I'm trying to SSH into a server and I'm receiving a Connection closed message every time. I've tried changing MTU settings on both server and client side without success.
Here are the server side logs:
-> /usr/sbin/sshd -e -p 27 -D -d -e   -o StrictModes=no -o SyslogFacility=DAEMON -o PermitRootLogin=prohibit-password

debug1: sshd version OpenSSH_8.4, OpenSSL 1.1.1j  16 Feb 2021
debug1: private host key #0: ssh-rsa SHA256:Q76xVI+MO2LQky0e582943UWrAYfdTh0Q5hj9YpAMPY
debug1: private host key #1: ssh-dss SHA256:Lnp91+XIE3NVI4KLmk8Ara28s9qwX3+k4PY0iVYIgXY
debug1: private host key #2: ecdsa-sha2-nistp521 SHA256:QHUFHadquHxJYJ7qB4F2K+aJEoIysOJda2vY8lP5mVY
debug1: private host key #3: ssh-ed25519 SHA256:Y2YjbYM14maKA+09EvCfq+oJ5nfqQ5RAxo9xUJ6ByFM
debug1: rexec_argv[0]='/usr/sbin/sshd'
debug1: rexec_argv[1]='-e'
debug1: rexec_argv[2]='-p'
debug1: rexec_argv[3]='27'
debug1: rexec_argv[4]='-D'
debug1: rexec_argv[5]='-d'
debug1: rexec_argv[6]='-e'
debug1: rexec_argv[7]='-o'
debug1: rexec_argv[8]='StrictModes=no'
debug1: rexec_argv[9]='-o'
debug1: rexec_argv[10]='SyslogFacility=DAEMON'
debug1: rexec_argv[11]='-o'
debug1: rexec_argv[12]='PermitRootLogin=prohibit-password'
debug1: Set /proc/self/oom_score_adj from 0 to -1000
debug1: Bind to port 27 on 0.0.0.0.
Server listening on 0.0.0.0 port 27.
debug1: Bind to port 27 on ::.
Server listening on :: port 27.
debug1: Server will not fork when running in debugging mode.
debug1: rexec start in 5 out 5 newsock 5 pipe -1 sock 8
debug1: sshd version OpenSSH_8.4, OpenSSL 1.1.1j  16 Feb 2021
debug1: private host key #0: ssh-rsa SHA256:Q76xVI+MO2LQky0e582943UWrAYfdTh0Q5hj9YpAMPY
debug1: private host key #1: ssh-dss SHA256:Lnp91+XIE3NVI4KLmk8Ara28s9qwX3+k4PY0iVYIgXY
debug1: private host key #2: ecdsa-sha2-nistp521 SHA256:QHUFHadquHxJYJ7qB4F2K+aJEoIysOJda2vY8lP5mVY
debug1: private host key #3: ssh-ed25519 SHA256:Y2YjbYM14maKA+09EvCfq+oJ5nfqQ5RAxo9xUJ6ByFM
debug1: inetd sockets after dupping: 3, 3
Connection from 192.168.1.172 port 54044 on 192.168.1.227 port 27
debug1: Local version string SSH-2.0-OpenSSH_8.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_8.5
debug1: match: OpenSSH_8.5 pat OpenSSH* compat 0x04000000
debug1: permanently_set_uid: 1001/1001 [preauth]
debug1: list_hostkey_types: rsa-sha2-512,rsa-sha2-256,ssh-rsa,ecdsa-sha2-nistp521,ssh-ed25519 [preauth]
debug1: SSH2_MSG_KEXINIT sent [preauth]
debug1: SSH2_MSG_KEXINIT received [preauth]
debug1: kex: algorithm: curve25519-sha256 [preauth]
debug1: kex: host key algorithm: ssh-ed25519 [preauth]
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none [preauth]
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none [preauth]
debug1: expecting SSH2_MSG_KEX_ECDH_INIT [preauth]
debug1: rekey out after 134217728 blocks [preauth]
debug1: monitor_read_log: child log fd closed
debug1: do_cleanup
debug1: Killing privsep child 404
255
iex(48)> Toolshed.cmd("/usr/sbin/sshd -e -p 27 -D -d -e   -o StrictModes=no -o SyslogFacility=DAEMON -o PermitRootLogin=prohibit-password")
debug1: sshd version OpenSSH_8.4, OpenSSL 1.1.1j  16 Feb 2021
debug1: private host key #0: ssh-rsa SHA256:Q76xVI+MO2LQky0e582943UWrAYfdTh0Q5hj9YpAMPY
debug1: private host key #1: ssh-dss SHA256:Lnp91+XIE3NVI4KLmk8Ara28s9qwX3+k4PY0iVYIgXY
debug1: private host key #2: ecdsa-sha2-nistp521 SHA256:QHUFHadquHxJYJ7qB4F2K+aJEoIysOJda2vY8lP5mVY
debug1: private host key #3: ssh-ed25519 SHA256:Y2YjbYM14maKA+09EvCfq+oJ5nfqQ5RAxo9xUJ6ByFM
debug1: rexec_argv[0]='/usr/sbin/sshd'
debug1: rexec_argv[1]='-e'
debug1: rexec_argv[2]='-p'
debug1: rexec_argv[3]='27'
debug1: rexec_argv[4]='-D'
debug1: rexec_argv[5]='-d'
debug1: rexec_argv[6]='-e'
debug1: rexec_argv[7]='-o'
debug1: rexec_argv[8]='StrictModes=no'
debug1: rexec_argv[9]='-o'
debug1: rexec_argv[10]='SyslogFacility=DAEMON'
debug1: rexec_argv[11]='-o'
debug1: rexec_argv[12]='PermitRootLogin=prohibit-password'
debug1: Set /proc/self/oom_score_adj from 0 to -1000
debug1: Bind to port 27 on 0.0.0.0.
Server listening on 0.0.0.0 port 27.
debug1: Bind to port 27 on ::.
Server listening on :: port 27.
debug1: Server will not fork when running in debugging mode.
debug1: rexec start in 5 out 5 newsock 5 pipe -1 sock 8
debug1: sshd version OpenSSH_8.4, OpenSSL 1.1.1j  16 Feb 2021
debug1: private host key #0: ssh-rsa SHA256:Q76xVI+MO2LQky0e582943UWrAYfdTh0Q5hj9YpAMPY
debug1: private host key #1: ssh-dss SHA256:Lnp91+XIE3NVI4KLmk8Ara28s9qwX3+k4PY0iVYIgXY
debug1: private host key #2: ecdsa-sha2-nistp521 SHA256:QHUFHadquHxJYJ7qB4F2K+aJEoIysOJda2vY8lP5mVY
debug1: private host key #3: ssh-ed25519 SHA256:Y2YjbYM14maKA+09EvCfq+oJ5nfqQ5RAxo9xUJ6ByFM
debug1: inetd sockets after dupping: 3, 3
Connection from 192.168.1.172 port 54250 on 192.168.1.227 port 27
debug1: Local version string SSH-2.0-OpenSSH_8.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_8.5
debug1: match: OpenSSH_8.5 pat OpenSSH* compat 0x04000000
debug1: permanently_set_uid: 1001/1001 [preauth]
debug1: list_hostkey_types: rsa-sha2-512,rsa-sha2-256,ssh-rsa,ecdsa-sha2-nistp521,ssh-ed25519 [preauth]
debug1: SSH2_MSG_KEXINIT sent [preauth]
debug1: SSH2_MSG_KEXINIT received [preauth]
debug1: kex: algorithm: curve25519-sha256 [preauth]
debug1: kex: host key algorithm: ssh-ed25519 [preauth]
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none [preauth]
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none [preauth]
debug1: expecting SSH2_MSG_KEX_ECDH_INIT [preauth]
debug1: rekey out after 134217728 blocks [preauth]
debug1: monitor_read_log: child log fd closed
debug1: do_cleanup
debug1: Killing privsep child 409

Here are the client side logs:
✗ ssh -p 27   root@192.168.1.227 -v

OpenSSH_8.5p1, OpenSSL 1.1.1k  25 Mar 2021
debug1: Reading configuration data /home/eric/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to 192.168.1.227 [192.168.1.227] port 27.
debug1: Connection established.
debug1: identity file /home/eric/.ssh/id_rsa type -1
debug1: identity file /home/eric/.ssh/id_rsa-cert type -1
debug1: identity file /home/eric/.ssh/id_dsa type -1
debug1: identity file /home/eric/.ssh/id_dsa-cert type -1
debug1: identity file /home/eric/.ssh/id_ecdsa type -1
debug1: identity file /home/eric/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/eric/.ssh/id_ecdsa_sk type -1
debug1: identity file /home/eric/.ssh/id_ecdsa_sk-cert type -1
debug1: identity file /home/eric/.ssh/id_ed25519 type 3
debug1: identity file /home/eric/.ssh/id_ed25519-cert type -1
debug1: identity file /home/eric/.ssh/id_ed25519_sk type -1
debug1: identity file /home/eric/.ssh/id_ed25519_sk-cert type -1
debug1: identity file /home/eric/.ssh/id_xmss type -1
debug1: identity file /home/eric/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_8.5
debug1: Remote protocol version 2.0, remote software version OpenSSH_8.4
debug1: compat_banner: match: OpenSSH_8.4 pat OpenSSH* compat 0x04000000
debug1: Authenticating to 192.168.1.227:27 as 'root'
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ssh-ed25519
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
Connection closed by 192.168.1.227 port 27

Any additional flags that would help in debugging? I've verified that I'm able to ssh to other servers.
Thanks

A: Your main issue can like be identified by the line where it says expecting SSH2_MSG_KEY_ECDH_REPLY. A similar issue happened to someone a while ago from the post found here.
The accepted solution by @shgnInc was to perform one of the following commands:
sudo ip li set mtu 1200 dev wlan0

or
sudo ifconfig wlan0 mtu 1200

An alternative solution if those didn't work can be found in the next answer here or to try any of the later ones to see if they work for you


text:
Q: ActiveRecord finding "best effort" results? So I have a bunch of users who are stored in a Redis scoreboard style thing. But, sometimes those users get deleted, and they don't get deleted in Redis. This is non crucial for my app, so I don't mind. However, Rails, when trying to get the results using a query like so:
User.find([1,2,3,4,244])

Rails can't find one of the users so it returns this really helpful error:
ActiveRecord::RecordNotFound: Couldn't find all Users with IDs (1, 2, 3, 4, 244) (found 4 results, but was looking for 5)

(Kudos to rails for human readable errors!)
I'm wondering though, is there a way to do a best effort find to get all the results that exist in that array, and not care if all the results aren't returned?

A: If you use where instead, you'll be good:
User.where(id: [1, 2, 3, 4, 244])

Rails will translate this to "id" IN (1, 2, 3, 4, 244) in SQL, which is exactly the same sql as your find statement would execute, but Rails will not require the exact number of records be returned using where, unlike find.

A: Use SQL in command. This will return all existing values on your database and ignore the others.
User.where('id in ?', [1,2,3,4,244])
User.where(id => [1, 2, 3, 4, 244])


text:
Q: Do diffeomorphisms preserve dimension of subsets in the following sense? Suppose that $\phi:H^{n} \cap V \rightarrow M$ is a diffeomorphism between a relatively open subspace of the half-space $H^{n}$ and a set $M$, so that the set $M$ is an $n$-manifold with boundary (I'm doing the "with boundary" case for generality). Suppose that $C \subseteq M$ is such that the subset $\phi^{-1}(C) \subseteq H^{n} \cap V$ is an $m-$ manifold with boundary. That is, there exists a diffeomorphism  $\phi':H^{m} \cap V' \rightarrow \phi^{-1}(C)$.
Because the compositions of diffeomorphisms is a diffeomorphism, it should then follow that
$$\phi \circ \phi' : H^{m}\cap V' \rightarrow C$$
is a diffeomorphism, so that $C$ is also an $m-$ manifold (with boundary). Is this correct?
Putting this all together, we'd have that if $\phi:H^{n} \cap V \rightarrow M$ is an $n-$manifold with boundary and $S \subseteq H^{n} \cap V$ is an $m-$dimensional subspace (in the manifold sense), then $\phi(S)$ is an $m-$dimensional subspace as well. So, "diffeomorphisms preserve the dimension of subsets".
I thank you all in advance!

A: *

*The claim that "an −manifold (with boundary), by definition, it is diffeomorphic to $H^m$" is quite false. What is true is that every point of an $m$-dimensional manifold with boundary has a neighborhood which is diffeomorphic to an open subset of $H^m$.

*Other than that, yes, $C$ is an $m$-dimensional submanifold with boundary, simply because diffeomorphisms (such as $\phi^{-1}$) send submanifolds (with boundary) to submanifolds with boundary, and dimension is preserved. (Saying that something is an $m$-dimensional subspace in a manifold is weaker. The notion of dimension, say, the covering dimension, is defined for arbitrary topological spaces, not just for manifolds. For manifolds with boundary, it equals the dimension in the sense of the definition of a manifold.)  Incidentally, I suggest you avoid saying that a subset of a manifold is a manifold, since it is ambiguous; instead, use the terminology "submanifold."


text:
Q: How do "you" pronounce eczema? /ˈɛɡzɪmə/, /ˈɛksɪmə/, /ˈɛksmə/
As I no longer live in the UK I don't usually hear how eczema is pronounced, so I've always pronounced it as ig-zee-muh but recently my English boyfriend told me that the only correct pronunciation is ˈɛksmə (the second e- is silent), and he's quite adamant about it!  He considers my pronunciation as nothing short of an abomination. Listen to the first British speaker on Forvo to  hear the "correct" pronunciation of eczema.
However, when I checked online I saw that there are three ways of pronouncing this term.
I would like to know which pronunciation is most dominant in British English and in American English. And why the second e- is sometimes silent in eckz(e)ma.

A: I just took an unscientific poll of North American professional actors (read: searched the web for eczema commercial), and "egzema" /ˈɛɡzɪmə/ was the most common, followed by the similar "eksema" /ˈɛksɪmə/. I hadn't heard "egzeema" /ɪɡˈzi:mə/ until today.

*

*A TV ad for Elidel (pimecrolimus) cream 1% calls it a prescription drug to treat "egzema".

*Another Elidel ad with an animated character also says "egzema".

*A commercial for Gold Bond opens with a woman talking about "an eksema flareup" but it's kind of close. The voiceover says "egzema relief cream".

*"There are better ways to soothe egzeema" than spreading ice cream all over your skin. "Try Polysporin egzeema essentials".

*"Cortizone-10 intensive healing egzema lotion"

*Neosporin because "Americans suffer from eksema"

The "egzema" and "eksema" pronunciations represent a common phonological process called voicing assimilation: "egzema" and "egzeema" are anticipatory while "eksema" is lag.

A: You may want to check here: http://youglish.com/search/eczema
The cons: it doesn't indicate the location of the speakers.
The pros: they are professional speakers.
They added accent support.

A: I'm a lifelong US resident and the daughter of a dermatologist.  I grew up hearing my father pronounce it ig-zee-muh.  He grew up in Chicago and did his residency at the Mayo Clinic in Minnesota.  However, he moved us to North Carolina when I was a baby.  So though I always said "ig-zee-muh" (accent on second syllable, long e) I recall most locals saying "egg-ze-muh" (accent on first syllable, pronounced like the word "egg", second e more of a schwa).  I've never, ever heard the word spoken as only two syllables.

A: ˈɛksɪmə.  I am a U.S. native (Chicago).  I have also commonly heard ˈɛɡzɪmə, but never ˈɛksmə, as far as I can recall.
These were the only pronunciations I was familiar with till I was surprised years ago to learn that the skin cream Noxzema, pronounced nɒkˈsiːmə (nok-SEE-ma) and sold under that name for nearly a century, was so named because it was advertised as a treatment for eczema.  That is, the name of the cream assumes a pronunciation of ɛkˈsiːmə (ek-SEE-ma) or ɛɡˈziːmə (eg-ZEE-ma) for the word eczema.  Prior to hearing this bit of information, I had never heard this pronunciation for eczema.
https://en.wikipedia.org/wiki/Noxzema

A: Merriam-Webster and my own personal experience with American English suggest pronouncing it ˈeg-zə-mə
Cambridge Dictionary Online lists the pronunciation as ˈek.sɪ.mə and provides audio of English and American pronunciation.


text:
Q: Angular selector returns me word object instead of value [object] I have this selector that pulls data from a services.
When I select any of the options that appear, it appears in the console:
{enterprises: '[object Object],[object Object],[object Object],[object Object]', warehouses: ''}
enterprises
:
"[object Object],[object Object],[object Object],[object Object]"
warehouses
:
""
Enterprises are the companies that I can select and warehouses are the warehouses that I can select.

Does anyone know why?
My html:
            <select class="form-select" formControlName="enterprises" (change)="updateSelectValues()">
              <option value="" disabled selected="selected">SELECCIONA LA EMPRESA</option>
              <option [value]="enterprises" *ngFor="let item of enterprises">{{item.name}}</option>
            </select>

            <select class="form-select" aria-label="Default select example" formControlName="warehouses"
              (change)="updateSelectValues()">
              <option value="" disabled selected="selected">SELECCIONA EL TALLER</option>
              <option [value]="item" *ngFor="let item of warehouses">{{item.name}}</option>
            </select>

My ts:
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { DatosService, EmpresaTaller } from '../services/datos.service';
import { ApiService } from '../services/api.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  token = "";
  userName = "";
  error = "";

  enterprise=-1;
  warehouse=-1;

  enterprises = [];
  warehouses = [];

  seleccionado;

  selectForm: FormGroup;

  cargaCount = 0;
  cargaTrasiego = 0;
  descargaCount = 0;
  descargaTrasiego = 0;

  constructor(
    private datosService: DatosService,
    private fb: FormBuilder,
    private api:ApiService,
  ) { }

  ngOnInit() {
    this.token=sessionStorage.getItem('authToken');
    this.userName=sessionStorage.getItem('userName');

    this.api.getEnterprises(this.token, this.userName).subscribe(responseEnterprises=>{
      const {result, value} = responseEnterprises;
      if(result !== 0 || !value || !value.Rows || value.Rows.length === 0){
        this.error='Error, usuario sin empresas';
        return;
      }
      this.enterprises=value.Rows.map(enterprise=>{
        const {CODIGO: code, EMPRESA: name} = enterprise;
        return {code, name};
      });
      this.enterprise = this.enterprises[0].code;

      this.api.getWarehouses(this.token, this.userName, this.enterprise).subscribe(responseWarehouses=>{
        const {result, value} = responseWarehouses;
        if(result !== 0 || !value || !value.Rows || value.Rows.length === 0){
          this.error='Error, usuario sin almacenes';
          return;
        }
        this.warehouses=value.Rows.map(warehouse=>{
          const {CODIGO: code, ALMACEN: name} = warehouse;
          return {code, name};
        });
        this.warehouse = this.warehouses[0].code;

        this.api.getDashboard(this.token, this.userName, this.enterprise, this.warehouse).subscribe(responseDashboard=>{
          const {result, value} = responseDashboard;
          if(result !== 0 || !value || !value.Rows || value.Rows.length === 0){
            this.error='Error, no ha devuelto dashboard';
            return;
          }
          this.cargaCount = value.Rows[0].orden_carga_count;
          this.cargaTrasiego = value.Rows[0].orden_carga_trasiego_count;
          this.descargaCount = value.Rows[0].orden_descarga_count;
          this.descargaTrasiego = value.Rows[0].orden_descarga_trasiego_count;
        });

      });

    });

    this.selectForm = this.fb.group({
      enterprises: [''],
      warehouses: ['']
    });
  }

  updateSelectValues() {
    this.datosService.updateEmpresaTaller(this.selectForm.value as EmpresaTaller);
  }

}

Then, once selected, I want what is selected to appear at the top of another page, but this appears:

My html:

{{(datosEmpresaTaller | async).enterprises}}

{{(datosEmpresaTaller | async).warehouses}}

      <form class="d-flex">
        <button class="btn btn-outline" type="submit" routerLink='/dashboard'> </button>
      </form>

My ts:
import { Component, OnInit } from '@angular/core';
import { DatosService, EmpresaTaller } from '../services/datos.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnInit {
  datosEmpresaTaller: Observable<EmpresaTaller>;

  constructor(private datosService: DatosService) {}

  ngOnInit(): void {
    this.datosEmpresaTaller = this.datosService.getEmpresaTaller();
  }

}

My service:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

export interface EmpresaTaller {
  enterprises: string,
  warehouses: string
}

@Injectable({
  providedIn: 'root'
})
export class DatosService {
  private selectValues = new BehaviorSubject<EmpresaTaller>({enterprises: '', warehouses: ''});

  constructor() { }

  updateEmpresaTaller(values: EmpresaTaller) {
    this.selectValues.next(values);
    console.log(values)
  }

  getEmpresaTaller() {
    return this.selectValues.asObservable();
  }
}

A: you have set all enterprises as mat-option value.
Change this:
<option [value]="enterprises" *ngFor="let item of enterprises">{{item.name}}</option>

to:
<option [value]="item" *ngFor="let item of enterprises">{{item.name}}</option>


text:
Q: How to use grep match string then look for other string Is it possible to look for 'string1' if its true then look for 'string2' using grep.
Here is my situation. i have many txt report files in that i need to search for 'FAIL' based on test path 'Test path: path/to/test'
sample report file:
     Test path:          path/to_tests/t1
     Host name:                   testpc1
                  AMEND_1/Sec3/E30012.c,          ;               PASS;     ;              ;             ;          ;
                  AMEND_1/Sec3/E30013.c,          ;               FAIL;     ;              ;             ;          ;
                  AMEND_1/Sec3/E30014.c,          ;               PASS;     ;              ;             ;          ;
                  AMEND_1/Sec3/E30015.c,          ;               FAIL;     ;              ;             ;          ;

I'm trying following command, but it prints only FAIL lines but not test path, also i want to remove ';' in the lines.
 find . -name "*concat.txt" | xargs grep -E 'Test path: path/to_tests/t1' grep -e 'FAIL'

Please guide me how can i achieve this using one line command.
desire output:
 Test path:          path/to_tests/t1   AMEND_1/Sec3/E30013.c  FAIL
 Test path:          path/to_tests/t1   AMEND_1/Sec3/E30015.c  FAIL

A: Simple with Awk.
awk '/Test path:/ { t=$0; next }
    $3 == "FAIL;" ( print t, $2, $3 }' **/*concat.txt

If your shell is too old to support the ** wildcard, or you genuinely have matches on this wildcard which are not plain files, you might want to keep your find command, and pipe that to Awk.
This will retain the semicolon after FAIL. It's easy to get rid of before printing if that's a problem; sub(";", "", $3):
The regex on the first line just looks for "Test path:" -- if you want to look for a specific path, you'll need to escape the backslashes.

A: Use this:
find . -name "*concat.txt" | (read file && egrep 'Test path:[ \t]*path/to_tests/t1' $file && grep 'FAIL' $file)

I'm not sure about the whitespace in the line Test path; (...), so I added the pattern [ \t]* to match any whitespace you might encounter there.
This will print:
Test path: (whitespace) path/to_tests/t1
AMEND_1/Sec3/E30013.c,          ;               FAIL;     ;
AMEND_1/Sec3/E30015.c,          ;               FAIL;     ;

If you need exactly the output as stated in your question, you will need more than one line, to do it eloquently and probably need to use other commands, like sed, awk or perl regexps.
A version with some sed to better format the output.
find . -name "*concat.txt" | (read file && egrep 'Test path:[ \t]*path/to_tests/t1' $file | sed 's/^[ \t]*//' && grep 'FAIL' $file | sed 's/^[ \t]*//' | sed 's/[ \t]*;[ \t]*//' | sed 's/,\(FAIL\).*/ \1/')


text:
Q: Why can't we simply write a script to collect all visible/lit pixels and create it into image? As you know Netflix and Prime Video and others don't allow screenshots. But I'm having a hard time understanding why can't we write a script, maybe in JavaScript (and run in browser console) which reads the screen and the light intensity/color of each pixel of screen and then combine them to create an image i.e., screenshot?
After all, what we see in the video is basically pixels with some amount of light and colors. Isn't it possible?
Note: I know it's not legal to do this, but I'm just curious if it is possible or not. If possible, why people don't do it?

A: The amount of work to try and do this is completely beyond what is really "feasible". It also requires cooperation from the hardware that is processing the video.
You need to individually check upwards of 2 million individual pixels (1080p), then construct and format an image, then temporarily store that, then gather the next frame 33 milliseconds (30fps) later and repeat over and over again using JavaScript. JavaScript is already a relatively inefficient programming language and is working in a browser that is attempting to protect the user from webpages overstepping their boundaries.
Then there's the fact that the video is (most likely) being played in hardware on your graphics card using what is known as an "overlay". What that means is that your browser itself draws a black, or white, or green area and then simply tells the graphics card "here's some video data, decode it and display it over this space". The graphics card does the work and then overlays the video as one of the final steps before pushing the data out to the display.
Due to video protections that final step may potentially be at a point where your browser can't even request a true representative copy of that pixel at the point of display. It may well be that the video is only merged into the data stream as the part of the final display output that is protected by encryption.
As a result all that the JavaScript might see is a single solid colour painted over the area. Not entirely useful to capture.


text:
Q: google apps script doGet I'm having problems with this code.  Google deprecated several pieces that were working. Now when making a new sheet and trying to use the old code, I get errors and can't find the way to make changes with the documentation at google.
function doGet(e) {

    //This is not working?

    if (typeof e.parameter.id  == 'undefined'){
        return no_id(e) // The URL doesn't have an ?id=345 on the end!
    }

    var id = parseInt( e.parameter.id ) // This is the id of the row in the spreadsheet.

    //Script properties is changed and I think it is now: PropertyService.getScriptProperties() // Get the data from the spreadsheet and get the row that matches the id

    var this_spreadsheet_id = ScriptProperties.getProperty('this_spreadsheet_id')
    var ss = SpreadsheetApp.openById(this_spreadsheet_id)
    var sheet = ss.getSheetByName("Sheet1")
    var range = sheet.getDataRange()
    var last_row = range.getLastRow()
    var last_column = range.getLastColumn()

    for(i = 2; i <= last_row ; i++){

        var this_row = sheet.getRange(i,1 , 1, last_column)
        var values = this_row.getValues()[0]
        var row_id = parseInt( values[0] )

        //row id == id is not working either

        if ( row_id == id){
            var title = values[5]
            var details = values[8]
            var status_txt = values[7]

            Logger.log( "STATUS: " + status )

            var image_url = values[4]
        }
    }
}

Any idea's would be great!
Thanks,

A: "ReferenceError: "id" is not defined. (line 23, file "Code")"
You  have a return in an if statement before the id is defined. So if it is not being defined then the if statement is being triggered. Move your  variable definitions to the top.
var id = parseInt( e.parameter.id ) // This is the id of the row in the spreadsheet.

//Script properties is changed and I think it is now: PropertyService.getScriptProperties() // Get the data from the spreadsheet and get the row that matches the id

var this_spreadsheet_id = ScriptProperties.getProperty('this_spreadsheet_id')
var ss = SpreadsheetApp.openById(this_spreadsheet_id)
var sheet = ss.getSheetByName("Sheet1")
var range = sheet.getDataRange()
var last_row = range.getLastRow()
var last_column = range.getLastColumn()

if (typeof e.parameter.id  == 'undefined'){
    return no_id(e) // The URL doesn't have an ?id=345 on the end!
}


text:
Q: UNIX- How to cut specific characters in the particular sentence How to cut specific characters in the particular sentence?
Input String:
7,717   http-16502-2    INFO    com.****.mxxdctm.cscxscxs**-    new name:/opt/docu/fs1_1/fs_cache/09vvadadaca.mghyyysss.excel12book
7,717   http-16502-2    INFO    com.****.mxxdctm.cscxscxs**-    new name:/opt/docu/fs1_1/fs_cache/09vvadadaca.bcdvsxsas.pdf
7,717   http-16502-2    INFO    com.****.mxxdctm.cscxscxs**-    new name:/opt/docu/fs1_1/fs_cache/09vvadadaca.nmncdvsxsas.pdf

I want to cut the string which is before the file extension of the above sample sentence.
Below output I am looking for:
bcdvsxsas
mghyyysss
nmncdvsxsas

A: awk -F. '{print $(NF-1)}' inFile.txt


text:
Q: Getting extra rufus-scheduler thread with each delayed_job rake jobs:work Am trying to use rufus-scheduler to check every minute or so to see if
there are jobs ready to be placed in the delayed_job queue.
Have an initializer script in #{RAILS_ROOT}/config/initializers that
starts the scheduler.   Unfortunately the rake jobs:work also runs the
rails initialization process so another gets started for each
jobs:work started.
How can I prevent this?
Running ruby 1.8.6.26, rails 2.3.5, dj 1.8.5, rufus-scheduler 2.0.6 on
XP pro sp3

A: In your initializer, find a way not to run the schedule if the rails initialization process is invoked via Rake.
For sure there is a more railsy way, but you could do
  unless defined?(Rake)
    # do the scheduling...
  end

The block 'do the scheduling' won't get called if the constant Rake is defined (for a Rake task it is defined).


text:
Q: How to open file with gz extendion in spyder? I have got a file whith gz extension. Basically it was just a python file with py extension. After some manipulaition with that file It bacome file with gz ext. How to get it back?
Thanks in advance?

A: You did one of two things.

*

*You compressed the file using a command like zip, winzip, gzip etc

*You renamed the file with .gz as the extension
A file extension is just an indicator of the expected file contents.  I can have a text file with python code and a gz extension.
To fix your problem, open the file in a text editor.  If the contents look like garbage, you've opened a compressed file and will need to uncompressed it using   appropriate software.
Most likely, you will find that the file contains readable python code.  In that case simply save the file with the correct extension.
An pay closer attention to how you are manipulating your files in the future.


text:
Q: How to make an Ubuntu live USB stick in Fedora? I have Fedora installed on my desktop and I want to make a live USB stick with Ubuntu to install it on a laptop. What's the easiest way to do it?

A: My way on Fedora 21:

*

*On Fedora, ensure the nautilus and gnome-disk-utility packages are installed.

*Download Ubuntu image.

*Right-click on the Ubuntu image, and select Open With -> Disk Image Writer.

*Select your USB stick as the Destination, and click Start Restoring...
Note: your data on USB stick will lost, so, back up your USB stick data.

A: Update: Sorry for providing a tutorial for Unetbootin, but it might be helpful if you're having problem with the dependencies.
Command Line - using dd
You can make a live USB using command line.

*

*Download the ISO.

*Insert USB stick with at least 4GB capacity (it will be wiped).

*Run sudo fdisk -l and note down the device name of the flash drive. You would be able to find it somewhere near the bottom lines. For example, let the name is /dev/sdb1.

*Use the following command to write the ISO on the flash drive:
sudo dd if=/path-to-the-iso/ubuntu-18.04.1-desktop-amd64.iso of=/dev/sdb bs=8M

You'll need to enter your password to run this and previous commands as root with sudo. To have the ability to run programs as root, you'll need to be a member of the group wheel.
Important Points:

*

*The name of the device should be used i.e. of=/dev/sdb and NOT /dev/sdb1. It is because sdb1 is the name of the partition, not the device.

*path-to-the-iso should be replaced with the path where the ISO is. For example, if it is located in /home/user/Downloads, it should be like if=/home/user/Downloads/ubuntu-18.04.1-desktop-amd64.iso.

*The name of the ISO file should be changed according to the version downloaded.

*dd would format the flash drive, so make sure to take a backup, if you've any files you don't want to lose.

Command Line - using live-iso-to-disk tool
You can find the tutorial here:

*

*http://fedoraproject.org/wiki/How_to_create_and_use_Live_USB#Using_the_livecd-iso-to-disk_tool

Using Unetbootin
Edit: Although the screenshots are from Ubuntu, they won't differ much in Fedora (except for the look, ofcourse). They are given just for reference.

*

*Install unetbootin.
sudo yum install unetbootin

OR you can get it from their website.

*Install syslinux and p7zip
sudo yum install syslinux syslinux-extlinux
sudo yum install p7zip p7zip-plugins

*Execute unetbootin
You should access it this way if you've downloaded it manually, from the website.
sudo /<path-to-the-executable>/unetbootin

If you've installed it from the repository.
sudo unetbootin

*If you've already downloaded the ISO, select the iso and the flash drive and click OK.

You can also select the distribution and the version, if you don't have the ISO. Although the list may not be updated, so it is recommended that you download it directly from the distro website.

A: The best way is to use Unetbootin tool, which is available from Unetbootin web site. You will need Ubuntu ISO image.
Best wishes.

A: There are a number of ways of doing this. Two of the simplist use tools already included on Fedora as standard.

*

*You can use dd to write an image file to a device from the command line. This method should work on almost any Unix based system.

*Alternatively you can use GNOME's gnome-disk-utility GUI tool (in the menus as "Disks"). This should work on any stem running GNOME (You also get a pretty progress bar).
Command line (dd)
This method is pretty simple if you're used to the command shell, it can be confusing to newer users which device they are writing to. Plus there is always the danger of typos and dd does not waste time showing you any progress information.
Step 1. Find your stuff
First of all, you want to establish where your image file (ISO) you want to write is located. Usually it'll be in ~/Downloads.
Secondly you want to establish which device is your USB Stick. You can check using sudo fdisk -l.
This will print out lines like
Disk /dev/sda: 298.1 GiB, 320072933376 bytes, 625142448 sectors

and
Disk /dev/sdb: 7.5 GiB, 8019509248 bytes, 15663104 sectors

You want a device that is not there when it is unplugged, but is there when it's plugged in. It should also be the correct size. Mine is the 8GB (7.5GiB) /dev/sdb. Note you want the device (sdb) not the partition (sdb1).
Step 2. Run the scary command
Finally run dd and wait for it to finish (you wont get any progress indication until it finishes):
dd if=/path/to/your.iso of=/your/device bs=8M

Of course, you should replace /path/to/your.iso with the path to your image (ISO) file and /your/device with the /dev/ location of your USB device that you found using fdisk (e.g. /dev/sdb).
Alternatively, using GNOME's "Disks" GUI
I personally prefer this method, you get a nice progress bar and it is easier to identify the correct disk. It is also nice and simple to take a backup image of the device if you so choose.
Step 1.

Open gnome-disk-utility by Going to "Activities" and searching for "Disks".
Step 2.

Select the correct device from the left hand menu and then choose "Restore Disk Image..." from the menu drop down at the top.
Step 3.

Use the file selector to find the image (ISO file) you want to write to the USB stick. Click "Start Restoring..." and then "Restore" at the confirmation.
Step 4.

Enter your password to grant root permissions to Disks and hit ENTER on your keyboard.
Step 5.

Wait. Patiently. (At least you get a progress bar! Those poor dd users...)
Step 6.

Done! Enjoy your new bootable USB. Perhaps take a moment to check it looks somewhat like the screen above and ensure you didn't get any errors before continuing.

A: The easiest way is to use Fedora Media Writer (dnf install mediawriter), formerly known as Live USB Creator. Run it (as root / via sudo), pick the ISO, pick your drive, and go.
You can also consult the Fedora documentation for alternate methods.
I looked at Unetbootin, but it wanted to install to a tiny partition of my previously-partitioned thumb drive, rather than using the entire drive.


text:
Q: Python returns JSON with line breaks in RGBA coordinates I'm working with python to produce json for semanticnet/OpenGraphiti. I've inserted RGBA coordinates as a list within a json object.
The result is that each RGBA point is printed on a separate line, which I've been fixing manually, as it can't be interpreted by OpenGraphiti in this format.
How do I return the coordinates on a single line within the object? (I don't need to have the entire object printed on one line, just the coordinates.)
Here's a sample of the code, along with the result I'm getting:
color = []
for i in range(len(hostname)):
    color.append([1.0, 1.0, 6.0, 1.0])

edges = zip(origin, hostname, connection, shortname, color)

Result:
    {
     "src": "oddjob",
     "dst": "runloop",
     "og:space:color": [
      1.0,
      1.0,
      6.0,
      1.0
     ],
     "type": "connection",
     "id": "oddjob-runloop"
    }

Here's the result I need:
{
 "src": "oddjob",
 "dst": "runloop",
 "og:space:color": [1.0, 1.0, 6.0, 1.0],
 "type": "connection",
 "id": "oddjob-runloop"
}

Any help would be much appreciated!

A: The Python json module doesn't give you this level of control, but you can construct the JSON semi-manually:
import json

result = {
    "src": "oddjob",
    "dst": "runloop",
    "og:space:color": [
        1.0,
        1.0,
        6.0,
        1.0
    ],
    "type": "connection",
    "id": "oddjob-runloop"
}

result = {k: json.dumps(v) for k, v in result.items()}
result = """{{
 "src": {src},
 "dst": {dst},
 "og:space:color": {color},
 "type": {type},
 "id": {id}
}}""".format(color=result["og:space:color"], **result)

print(result)

Output:
{
 "src": "oddjob",
 "dst": "runloop",
 "og:space:color": [1.0, 1.0, 6.0, 1.0],
 "type": "connection",
 "id": "oddjob-runloop"
}

Or you could use a regex to find and replace the array of numbers.


text:
Q: Pandas how to compare two csv file for delete duplicate? Assume I have two csv file csv1 and csv2.  Now I will to delete all record from csv2 if any record match with csv1. Both csv have unique identifier sku.
csv1:
sku    name
Gk125  Jhone
GK126  Mike

csv2:
sku    name
   Gk127  Doe
   GK128  Hock
   GK126  Mike #this is the duplicate record which already in csv1

my expected result for csv2 will be
  sku    name
   Gk127  Doe
   GK128  Hock

I tried this but didn't work:
old_file = list(old['sku'])
updated = new[~new['sku'].isin(old)]
updated.to_csv('...my path/updated.csv')

A: Works fine for me:
df1 = pd.DataFrame(data={'sku':['Gk125', 'GK126'], 'name':['Jhone', 'Mike']})
df2 = pd.DataFrame(data={'sku':['Gk127', 'GK128', 'GK126'], 'name':['Doe', 'Hock', 'Mike']})

print(df2[~df2['sku'].isin(df1['sku'])])

Output:
     sku  name
0  Gk127   Doe
1  GK128  Hock


text:
Q: Using jQuery to remove class from a select field when it has an option selected I have combed through multiple StackOverflow posts and haven't found the right syntax for what I'm looking for. I think I'm close, but need some help. Here's the situation:
I have a form with regular text and select fields that are styled differently based on whether the field has been filled out or not.
I've purposely not added something like Chosen or jQuery UI to rip apart the select field and rebuild with normal elements. Trying to keep things clean and small. All styling is done with CSS.
Currently I am adding a class to my select fields on load and then removing that class when someone interacts with the select field:
$(".infield select").addClass('default-value');

$("select").bind("focus", function () {
$(this).removeClass('default-value');
});

This works great, but my issue is that we are using cookies to prepopulate some of the form fields if they've filled out a form on the site previously. The above code only kicks in if they interact with the field.
I need something to remove my "default-value" class if the page loads and the select field has something selected. Here's my latest try, but it's not working.
$("select option:selected").on(function() {
    $(this).parent().removeClass("default-value");
});

Also for reference here's the basic select field code:

$(".infield select").addClass('default-value');

$(".infield select option:selected").on(function() {
 $(this).parent().removeClass("default-value");
});

$(".infield select").bind("focus", function () {
  $(this).children('option[value="defaultValue"]').remove();
  $(this).removeClass('default-value');
});
form {
  background-color: #EFF2F4;
  padding: 5%;
  }

.infield select {
 font: bold 1.1em "source-sans-pro", Helvetica, Helvetica;
 border: none;
 border-left: 4px solid #BCC2C8;
 padding: .5em;
 width: 100%;
 color: #808080;
 -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
           box-sizing: border-box;
 border-radius: 0px;
 border-radius: 0px !important;
 background: url(/images/uploads/design-assets/select-arrow.png) right center no-repeat;
 background-size: 21px;
 -webkit-border-radius: 0px;
 -webkit-appearance: none;
 background-color: #fff;
 -webkit-border-radius: 0px;
 -webkit-appearance: none;
 -moz-appearance: none;
   appearance: none;
 border-right: 10px solid #fff;
}

.infield select.default-value {
 color: #99acb9;
 font-weight: normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="infield">

<select id="billing_state" name="billing_state">
       <option value="">State</option>
       <option selected="selected" value="AL">AL</option>
       <option value="AK">AK</option>
    </select>

 </form>

What am I missing?

A: You need to filter selects with selected value not equal to defaultValue. Something like this:
$(".infield select").filter(function () {
    return $(this).val() !== "";
}).removeClass("default-value");

But better to add default-value class only to those selects which has defaultValue option selected in the first place.
Check the demo below.

$(".infield select").filter(function () {
    return $(this).val() === "";
}).addClass("default-value");

$(".infield select").bind("focus", function () {
    $(this).children('option[value="defaultValue"]').remove();
    $(this).removeClass('default-value');
});
form {
    background-color: #EFF2F4;
    padding: 5%;
}
.infield select {
    font: bold 1.1em"source-sans-pro", Helvetica, Helvetica;
    border: none;
    border-left: 4px solid #BCC2C8;
    padding: .5em;
    width: 100%;
    color: #808080;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    border-radius: 0px;
    border-radius: 0px !important;
    background: url(/images/uploads/design-assets/select-arrow.png) right center no-repeat;
    background-size: 21px;
    -webkit-border-radius: 0px;
    -webkit-appearance: none;
    background-color: #fff;
    -webkit-border-radius: 0px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border-right: 10px solid #fff;
}
.infield select.default-value {
    color: #99acb9;
    font-weight: normal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<form action="" class="infield">
    <select id="billing_state" name="billing_state">
        <option value="">State</option>
        <option selected="selected" value="AL">AL</option>
        <option value="AK">AK</option>
    </select>
</form>

A:
$(".infield select option:selected").on(function() {

This statement isn't doing anything.  For .on you need to specify an event.

.on( events [, selector ] [, data ], handler )  ~ http://api.jquery.com/on/

Can't you do something like the following:
$(document).ready(function(){
    if($(".infield select option:selected").length > 0){
      $(".infield select").removeClass("default-value");
    }
});

The code above would check if any options are selected after the document has loaded and if at least one is selected, it will remove the class.

A: In case someone having a similar problem, in my case the problem was the ', check this out:
Don't work select field, but work's on textboxes!
$('#<?echo $campo_logradouros;?>').removeClass('hidden');

It work's on select fields:
$('#<?echo $campo_logradouros;?>').removeClass("hidden");

I mean, how crazy is that?


text:
Q: Are bitwise operations going to help me to serialize some bools? I'm not used to binary files, and I'm trying to get the hang of it. I managed to store some integers and unsigned char, and read them without too much pain. Now, when I'm trying to save some booleans, I see that each of my bool takes exactly 1 octet in my file, which seems logical since a lone bool is stored in a char-sized data (correct me if I'm wrong!).
But since I'm going to have 3 or 4 bools to serialize, I figure it is a waste to store them like this : 00000001 00000001 00000000, for instance, when I could have 00000110. I guess to obtain this I should use bitwise operation, but I'm not very good with them... so could somebody tell me:

*

*How to store up to 8 bools in a single octet using bitwise manipulations?

*How to give proper values to (up to 8 bools) from a single octet using bitwise manipulation?

*(And, bonus question, does anybody can recommend a simple, non-mathematical-oriented-mind like mine, bit manipulation tutorial if this exists? Everything I found I understood but could not put into practice...)

I'm using C++ but I guess most C-syntaxic languages will use the same kind of operation.

A: The easy way is to use std::bitset which allows you to use indexing to access individual bits (bools), then get the resulting value as an integer.  It also allows the reverse.
int main() {
  std::bitset<8> s;
  s[1] = s[2] = true;  // 0b_0000_0110
  cout << s.to_ulong() << '\n';
}

A: To store bools in a byte:
bool flag; // value to store
unsigned char b = 0; // all false
int position; // ranges from 0..7
b = b | (flag << position);

To read it back:
flag = (b & (1 << position));

A: Without wrapping in fancy template/pre-processor machinery:

*

*Set bit 3 in var:var |= (1 << 3)

*Set bit n in var:var |= (1 << n)

*Clear bit n in var:var &= ~(1 << n)

*Test bit n in var: (the !! ensures the result is 0 or 1)!!(var & (1 << n))

A: Try reading this in order.

*

*http://www.cprogramming.com/tutorial/bitwise_operators.html

*http://www-graphics.stanford.edu/~seander/bithacks.html#ConditionalSetOrClearBitsWithoutBranching
Some people willthink that 2nd link is way too hardcore, but once you will master simple manipulation, it will come handy.

A: Basic stuff first:

*

*The only combination of bits that means false is 00000000 all the others mean true i.e: 00001000,01010101

*00000000 =  0(decimal), 00000001 = 2^0, 00000010 = 2^1, 00000100 = 2^2, …. ,10000000 = 2^7

*There is a big difference between the operands (&&, ||) and (&,|) the first ones give the result of the logic operation between the two numbers, for example:
00000000 && 00000000 = false,
01010101 && 10101010 = true
00001100 || 00000000 = true,
00000000 || 00000000 = false
The second pair makes a bitwise operation (the logic operation between each bit of the numbers):
00000000 & 00000000 = 00000000 = false
00001111 & 11110000 = 00000000 = false
01010101 & 10101001 = 00000001 = true
00001111 | 11110000 = 11111111 = true
00001100 | 00000011 =  00001111 = true

To work with this and play with the bits, you only need to know some basic tricks:

*

*To set a bit to 1 you make the operation | with an octet that has a 1 in that position and ceros in the rest.

For example: we want the first bit of the octet A to be 1 we make: A|00000001

*

*To set a bit to 0 you make the operation & with an octet that has a 0 in that position and ones in the rest.

For example: we want the last bit of the octet A to be 0 we make: A&01111111

*

*To get the Boolean value that holds a bit you make the operation & with an octet that has a 1 in that position and ceros in the rest.

For example: we want to see the value of the third bit of the octet A, we make: A&00000100, if A was XXXXX1XX we get 00000100 = true and if A was XXXXX0XX we get 00000000 = false;

A: You can always serialize bitfields. Something like:
struct bools
{
    bool a:1;
    bool b:1;
    bool c:1;
    bool d:1;
};

has a sizeof 1


text:
Q: JQuery select() is not working inside fabric canvas event When some object in canvas selects I want to select input text. But it is not working.
canvas.on({
 'object:selected': function() {
     document.getElementById('text_input').select();
  }
});


text:
Q: PIT Coverage generation minion exited abnormally i see the following stacktrace when running the pitest gradle task in my project after adding all the required configurations in build.gradle. Can you please help me on this ? I'm using 1.5.1 version of the plugin.
The changes have been done in build.gradle as per the instructions in https://github.com/szpak/gradle-pitest-plugin
7:00:32 PM PIT >> INFO : Verbose logging is disabled. If you encounter a problem, please enable it before reporting an issue.
    7:00:33 PM PIT >> INFO : Sending 46 test classes to minion
    7:00:33 PM PIT >> INFO : Sent tests to minion
    7:00:33 PM PIT >> SEVERE : Error generating coverage. Please check that your classpath contains modern JUnit 4 or PIT test plugin for other test tool (JUnit 5, TestNG, ...) is enabled.
    Exception in thread "main" org.pitest.util.PitError: Coverage generation minion exited abnormally. Please check the classpath and/or enable test plugin for used test tool.

Please copy and paste the information and the complete stacktrace below when reporting an issue
VM : OpenJDK 64-Bit Server VM
Vendor : Private Build
Version : 25.252-b09
Uptime : 1723
Input ->
 1 : -Dfile.encoding=UTF-8
 2 : -Duser.country=US
 3 : -Duser.language=en
 4 : -Duser.variant
BootClassPathSupported : true

Please copy and paste the information and the complete stacktrace below when reporting an issue
VM : OpenJDK 64-Bit Server VM
Vendor : Private Build
Version : 25.252-b09
Uptime : 1724
Input ->
 1 : -Dfile.encoding=UTF-8
 2 : -Duser.country=US
 3 : -Duser.language=en
 4 : -Duser.variant
BootClassPathSupported : true

        at org.pitest.util.Unchecked.translateCheckedException(Unchecked.java:20)
        at org.pitest.coverage.execute.DefaultCoverageGenerator.calculateCoverage(DefaultCoverageGenerator.java:105)
        at org.pitest.coverage.execute.DefaultCoverageGenerator.calculateCoverage(DefaultCoverageGenerator.java:51)
        at org.pitest.mutationtest.tooling.MutationCoverage.runReport(MutationCoverage.java:115)
        at org.pitest.mutationtest.tooling.EntryPoint.execute(EntryPoint.java:121)
        at org.pitest.mutationtest.tooling.EntryPoint.execute(EntryPoint.java:51)
        at org.pitest.mutationtest.commandline.MutationCoverageReport.runReport(MutationCoverageReport.java:87)
        at org.pitest.mutationtest.commandline.MutationCoverageReport.main(MutationCoverageReport.java:45)
Caused by: org.pitest.util.PitError: Coverage generation minion exited abnormally. Please check the classpath and/or enable test plugin for used test tool.

Please copy and paste the information and the complete stacktrace below when reporting an issue
VM : OpenJDK 64-Bit Server VM
Vendor : Private Build
Version : 25.252-b09
Uptime : 1723
Input ->
 1 : -Dfile.encoding=UTF-8
 2 : -Duser.country=US
 3 : -Duser.language=en
 4 : -Duser.variant
BootClassPathSupported : true

        at org.pitest.coverage.execute.DefaultCoverageGenerator.gatherCoverageData(DefaultCoverageGenerator.java:143)
        at org.pitest.coverage.execute.DefaultCoverageGenerator.calculateCoverage(DefaultCoverageGenerator.java:89)
        ... 6 more

FAILURE: Build failed with an exception.

A: As per the error message, you do not have the pitest junit 5 plugin enabled.
If you add
junit5PluginVersion = '0.12'
To the configuration the plugin will be enabled and the tests should be picked up.

A: The thing is that the latest version of PIT uses JUnit5, and I was using JUnit4. So, I solved it by migrating to JUnit5
if you are using maven, add the following lines to your pom file:
  <properties>
    <junit.jupiter.version>5.8.1</junit.jupiter.version>
    <junit.platform.version>1.8.1</junit.platform.version>
  </properties>

  <dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.jupiter.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${junit.jupiter.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-params</artifactId>
        <version>${junit.jupiter.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-suite</artifactId>
        <version>${junit.platform.version}</version>
        <scope>test</scope>
    </dependency>

</dependencies>


text:
Q: Проверять значение при нажатии на "Back" Есть два activity MainActivity и WordActivity. Мне нужно чтобы при закрытии WordActivity (т.е. при отображении MainActivity) в MainActivity делать что-то. Подскажите есть ли какой-нибудь метод для этого?

A: Вам необходимо запускать WordActivity с
startActivityForResult
static final int SOME_REQUEST = 123; //поле Mainactivity
...
//в методе где открываете WordActivity
Intent intent = new Intent(Mainactivity.this, WordActivity.class);
startActivityForResult(intent, SOME_REQUEST);

и обрабатывать результат в
onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == SOME_REQUEST) {
        //здесь Вы вернулись с WordActivity
        //в зависимости от результата можете обработать действия
        //из Intent data можете доставать данные, если Вы туда их сложили в WordActivity
    }
}

Подробная документация с примерами


text:
Q: How can I detect a "long touch" gesture with the Hololens 2? (Unity3D with MRTK) In my Hololens 2 app I want to add a context menu to each hologram that the user can open by touching the hologram for 2 seconds. It should basically look like this:
https://learn.microsoft.com/en-us/dynamics365/mixed-reality/guides/media/touch-dwell-animation.gif
(Source: https://learn.microsoft.com/en-us/dynamics365/mixed-reality/guides/authoring-gestures-hl2)
But I cannot find any code examples for this. Do you have any ideas what I need to add for this or any piece of documentation?

A: The Interactable component can meet your request, it will catch input actions and funnel these interactions into events to responsive. To make this possible, the Interactable component provides different types of out-of-box event receivers to respond to different types of input. Among them, InteractableOnHoldReceiver is used to trigger after pressing Interactable for a period. For how to add the event receiver into the Interactable please see Events


text:
Q: Query Custom Post Type by Taxonomy Meta Value I need to filter my custom post type "events" by Taxonomy Meta Field "city". But I can't make it work and need some help?
This is what I already have. But no results...
function aa_pre_get_posts($query)   {
    if (is_admin() || $query->get('post_type') != 'my-events') return;

    if(isset($_GET['city']) and trim($_GET['city']))
    {
        $query->set(
            'tax_query',
            array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'my_location',
                    'orderby' => 'meta_value',
                        'meta_query' => [[
                        'key' => 'city',
                        'value' => sanitize_text_field($_GET['city']),
                        'compare' => 'LIKE'
                    ]],
                )
            )
        );
    }
}
add_action('pre_get_posts', 'aa_pre_get_posts');

So, what's wrong?

A: This isn't possible via WP_Query, but more importantly, this would be stupendously expensive. Taxonomy queries are expensive. Post meta queries are super super expensive. Like queries are also expensive.
Finding all posts that have a term that has a meta that is like X, is an astoundingly expensive/slow query. Writing this out as a custom SQL query is the only option, and I would be surprised if the query finished in under 10 seconds. It could easily bring down a database server if your site gets a moderate or higher level of concurrent traffic.
Would it not be orders of magnitude faster and simpler to have a city taxonomy? If you need to filter or search for posts by something, use taxonomy terms. Meta is not for searching


text:
Q: How can I determine what application is asking "Where is GrowlHelperApp.App?" I recently upgraded to OS X 10.9 Mavericks and am now seeing a "Choose Application" dialog pop up every minute or two asking: "Where is the GrowlHelperApp.app?". I don't particularly want to buy the new version of Growl, so how can I determine which application is looking for it so that I can change it's preferences or remove it?

Update: It turns out that it was an old Dashboard widget that was looking for Growl. I found this out by deleting all of my Dashboard widgets since I haven't used it in a while, but I'd still be interested in finding out how one would discover what is launching this dialog.

A: You could have used sudo opensnoop to see what files are being opened or fseventer to see what files are being modified.
Those dialogs are often shown by AppleScripts that have reference a missing application. You could also have tried running mdfind GrowlHelperApp, but it doesn't search the contents of compiled scripts or scripts saved as applications.

A: Helped me solve this problem I am having an awful lot of time. The mdfind GrowlHelperApp with combo of deleteting the resource files found helped me to remove the annoying popup window. In my case, Firefox was the rooting problem app.


text:
Q: Birt report - hidden cross tab cells showing in excel I have a cross tab. I hide an entire column by setting the style to one containing "display: none". This looks great in html and pdf.
But when exporting to Excel, the column appears with empty values.
How do I force the excel export to not show the column?

A: Have you tried using the visibility expression for the column instead of the style display:none?

A: I think setting width to 0 only hide the column (when exporting to excel) when the report Layout is "Fixed Layout".
Unfortunately "Fixed Layout" is a pain to use when you have a crosstab with lots of columns, as Excel starts throwing errors if the width gets too big.


text:
Q: Make a popover over a table I want to make a popover that covers a table
<!DOCTYPE html>

  <title>JS Bin</title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

  4

    abcdefghi:

        alongtitleisverylong
        linked to event3
        100 lines

        Jill
        Smith
        50

JSBin
There are two problems:
1) the width of the popover cannot cover the width of the table
2) I don't want to bold the first row of the table, but I don't know how to do it
Could anyone help?

A: You can use the following code

<!DOCTYPE html>

  <title>JS Bin</title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

  4

    abcdefghi:

        alongtitleisverylong
        linked to event3
        100 lines

        Jill
        Smith
        50

The  tag will always bold the text within it so i have replaced it with  tag.
The max-width in the popover class has been given as 276px in the bootstrap.css so i have overridden that by replacing it with max-width:50%.


text:
Q: fgetcsv() ignores special characters when they are at the beginning of line! I have a simple script that accepts a CSV file and reads every row into an array. I then cycle through each column of the first row (in my case it holds the questions of a survey) and I print them out. The survey is in french and whenever the first character of a question is a special character (é,ê,ç, etc) fgetcsv simply omits it.
Special characters in the middle of the value are not affected only when they are the first character.
I tried to debug this but I am baffled. I did a var_dump with the content of the file and the characters are definitely there:
var_dump(utf8_encode(file_get_contents($_FILES['csv_file']['tmp_name'])));

And here's my code:
if(file_exists($_FILES['csv_file']['tmp_name']) && $csv = fopen($_FILES['csv_file']['tmp_name'], "r"))
    {
        $csv_arr = array();

        //Populate an array with all the cells of the CSV file
        while(!feof($csv))
        {
            $csv_arr[] = fgetcsv($csv);
        }

        //Close the file, no longer needed
        fclose($csv);

        // This should cycle through the cells of the first row (questions)
        foreach($csv_arr[0] as $question)
        {
            echo utf8_encode($question) . "<br />";
        }

    }

A: Are you setting your locale correctly before calling fgetcsv()?
setlocale(LC_ALL, 'fr_FR.UTF-8');

Otherwise, fgetcsv() is not multi-byte safe.
Make sure that you set it to something that appears in your list of available locales. On linux (certainly on debian) you can see this by doing
locale -a

You should get something like...
C
en_US.utf8
POSIX

For UTF8 support pick an encoding with utf8 on the end. If your input is encoded with something else you'll need to use the appropriate locale - but make sure your OS supports it first.
If you set the locale to a locale which isn't available on your system it won't help you.

A: This behaviour has a bug report filed for it, but apparently it isn't a bug.

A: Have you already checked out the manual page on fgetcsv? There is nothing talking about that specific problem offhand, but a number of contributions maybe worth looking through if nothing comes up here.
There's this, for example:

Note: Locale setting is taken into account by this function. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.

Also, seeing as it's always in the beginning of the line, could it be that this is really a hidden line break problem? There's this:

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

You may also want to try saving the file with different line endings.

A: We saw the same result with LANG set to C, and worked around it by ensuring that such values were wrapped in quotation marks.  For example, the line
a,"a",é,"é",óú,"óú",ó&ú,"ó&ú"

generates the following array when passed through fgetcsv():
array (
  0 => 'a',
  1 => 'a',
  2 => '',
  3 => 'é',
  4 => '',
  5 => 'óú',
  6 => '&ú',
  7 => 'ó&ú',
)

Of course, you'll have to escape any quotation marks in the value by doubling them, but that's much less hassle than repairing the missing characters.
Oddly, this happens with both UTF-8 and cp1252 encodings for the input file.


text:
Q: Magento 2: Dependency Injection: Optional class as parameter We are developing a Magento 2 extension and we need to inject a class from a third party extension that the user may or may not have installed.
We thought about injecting the class via the di.xml file and set as an optional parameter in the class constructor.
When we run 'bin/magento setup:di:compile' no errors are thrown, however when refreshing the pages, a class not found exception is thrown.
How can we check that the class exists before injecting in the di.xml?
I have something like this in my di.xml:
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="My\Custom\Class\Builder">
        <arguments>
            <argument name="thirdPartyHelper" xsi:type="object">Third\Party\Helper</argument>
        </arguments>
    </type>
</config>

And something like this in the class that i'm trying to inject:
    class Builder
    {
        private $dependency1;
        private $thidPartyHelper;

        public function __construct(
            Dependency1 $dependency1,
            ThidPartyHelper $thidPartyHelper = null
        ) {
            $this->dependency1 = $dependency1;
            $this->thidPartyHelper = $thidPartyHelper;
        }
    }

A: You could inject a factory in the constructor that returns the optional object when it's available and a null object otherwise.
You could use ModuleList to see if the class/module is available.

A: First Approach:
The cleanest way is to not take decisions in the constructor.
Let the di.xml do that for you.
Let's say the core class you are using if a module is not present is Some\Core\ClassName.
And the class that should use this core class us My\Custom\ClassName.
And the class that might not exist is MyExtension\PerhapsNotInstalled\ClassThatMightNotExist
Make your class constructor like this:
public function __construct(
    \Some\Core\ClassName $object
) {
    $this->_object = $object;
}

Now, in your module MyExtension_PerhapsNotInstalled di.xml file add this:
<type name="My\Custom\ClassName">
    <arguments>
        <argument name="object" xsi:type="object">MyExtension\PerhapsNotInstalled\ClassThatMightNotExist</argument>
    </arguments>
</type>

just make sure that MyExtension\PerhapsNotInstalled\ClassThatMightNotExist extends the core class Some\Core\ClassName.
This way, if the module MyExtension_PerhapsNotInstalled is not installed, the original core class Some\Core\ClassName will be used, otherwise MyExtension\PerhapsNotInstalled\ClassThatMightNotExist will be used.
Second Approach:
If your extension that might not exist, is a third party extension that you cannot control, and you want your code to work with it and without it, you can do this (using the same notations as above):
Create your own class that acts as a factory:
Let's call it My\Module\Factory
<?php

namespace My\Module;
class Factory
{
    protected $moduleManager;
    protected $objectManager;
    public function __construct(
        \Magento\Framework\Module\Manager $moduleManager,
        \Magento\Framework\ObjectManagerInterface $objectManager $objectManager
    ) {
        $this->moduleManager = $moduleManager;
        $this->objectManager = $objectManager;
    }
    public function create(array $data = array())
    {
        if ($this->_moduleManager->isEnabled('ThirdPartyExtension_PerhapsNotInstalled')) {
            $instanceName =  'MyExtension\PerhapsNotInstalled\ClassThatMightNotExist';
        } else {
            $instanceName = 'Some\Core\ClassName';
        }
        return $this->objectManager->create($instanceName, $data);
    }
}

You should inject this new class in the constructor of your My\Custom\ClassName class and call  the create method from it to determine the class instance you need.
public function __construct(
    \My\Module\Factory $factory
) {
    $this->_object = $factory->create();
}

Note: This second approach is not really clean, because in theory your dependencies should be explicit and the composition should be done via di.xml but I certainly understand the need.
Second Note: You are not violating any guidelines of not using the object manager, because OM is allowed in factories and you just created a factory.
And your class does not depend on the OM directly.
I didn't test the code, so watch out for syntax errors.
Ref : Magento2: Checking if a module exists, after being injected via class constructor

A: I needed a quick way to do this for a private script, without messing around with factories and other nonsense.
You can just check in the constructor:
public function __construct(
    \Magento\Framework\Module\Manager            $moduleManager,
    \Magento\Framework\ObjectManagerInterface    $objectManager
) {
    $this->moduleManager = $moduleManager;
    $this->objectManager = $objectManager;

    if ($moduleManager->isEnabled("MyOptionalModule_MyModule")) {
        $this->optionalModule = $objectManager->get("\My\Optional\Module");
    }
}


text:
Q: How to stub a line of code inside a method called from another method using mockito I have a class below
class MyClass{
    void setX(){
        statement1;
        statement2;
        obj.setY();
    }

    void setY(){
        statement3;
        anotherObj.setZ();
    }
}

I would like to stub the line  anotherObj.setZ() using mockito. How do I do that.

A: It depends where anotherObj is initialised. If it is initialised in the constructor of MyClass then it's easy:
AnotherObj anotherObjMock = Mockito.mock(AnotherObj.class);
MyClass classToTest = new MyClass(anotherObjMock);
Mockito.when(anotherObjMock.setZ()).thenReturn(whatever);

If it's local to the setY() method then its probably possible with PowerMock but honestly it's probably more an indicator that your code is not written well for testing and you should consider refactoring.


text:
Q: Disconnect image cache from opencart 3 image manager When i upload any image for my Opencart 3 website, it takes close to 10 minutes for the image to appear in the image manager.
I discovered that the images are stuck in the cache before they upload to the main directory.
I have increased the values of my php.ini  and the sizes of my images are between 25kb to 50kb and deployed many speed optimization apps and  yet I still have the same delays.
Presently, I want to disconnect the cache from the image manager so all images gets loaded directly to the image manager
Please I need help

A: A simple way to do this is to change how the Model returns files to the front-end in \catalog\model\tool\image.php right at the bottom of the file you'll find this code:
if ($this->request->server['HTTPS']) {
    return $this->config->get('config_ssl') . 'image/' . $image_new;
} else {
    return $this->config->get('config_url') . 'image/' . $image_new;
}

You can change it to:
if ($this->request->server['HTTPS']) {
    return $this->config->get('config_ssl') . 'image/' . $image_old;
} else {
    return $this->config->get('config_url') . 'image/' . $image_old;
}


text:
Q: Fazer meu site abrir no aplicativo automaticamente quando acesso pelo Navegador eu tenho um aplicativo para Android feito no Android Studio, e simples um webview, oque devo fazer no app para reconhecer o site e abrir ele no app ?

A: Tente usar o Firebase Indexing.
Com o Firebase Indexing você pode criar URLs que ao serem acessadas encaminham o usuário para dentro do seu aplicativo. Além disso você pode criar caminhos como url/configuracoes para que o Aplicativo abra na tela de Configuração por exemplo.
O serviço é gratuito e de fácil implementação, basta abrir uma conta no Firebase, cria um Projeto, e seguir a documentação. Aproveite para descobrir outros serviços gratuitos do Firebase para otimizar o seu app.


text: Q: How can I upload duplicate files in remote location using java ftpclient I am trying to upload files to remote server using java FTPSClient. If I try to upload duplicate files I am getting error response with reply code as 550. Is there anyway to upload duplicate files using FTPSClient.


text:
Q: Missing $ inserted with apacite? \documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[natbibapa]{apacite}

\title{For testing}

\begin{document}

Information about natbib in \citeauthor{sharelatex}.

\bibliographystyle{apacite}
\bibliography{bibli.bib}

\end{document}

This gives the error "Missing $ inserted". What has mathmode to do with apacite or citeauthor?

A: The problem is the _ in the url, which can normally only be used in math mode. In order to use them in a url, either use the url or the hyperref package.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[natbibapa]{apacite}

\usepackage{url}

\usepackage{filecontents}
\begin{filecontents*}{\jobname.bib}
@misc{sharelatex,
    title={ShareLaTeX, the Online LaTeX Editor},
    url={nl.sharelatex.com/learn/Natbib_citation_styles},
    journal={ShareLaTeX, Online LaTeX-verwerker}
}
\end{filecontents*}

\title{For testing}

\begin{document}

Information about natbib in \citeauthor{sharelatex}.

\bibliographystyle{apacite}
\bibliography{\jobname}

\end{document}


text:
Q: Hide escapes in wxPropertyGrid LongStringProperty in wxPython I'm using wxPython and wxPropertyGrid to create a UI and am having trouble getting a LongStringProperty to behave as I want it to.  The default behaviour is to show line returns tabs etc as they're respective escape sequences in the grid view, which is not what I want...
Looking at the documentation here: http://docs.wxwidgets.org/2.9.2/classwx_p_g_property.html#wxLongStringProperty I can see that it is supposedly possible to override this behaviour.  The problem is that firstly PG_PROP_NO_ESCAPE doesn't seem to be defined in wxPython, and secondly it requires subclassing.  If my understanding is correct you can't directly subclass in wxPython but rather has to be done using propertygrid.PyProperty which would basically mean creating the whole class again from scratch!  Now I'm not sure if I believe that last statement or if I've just made it up, but either way if PG_PROP_NO_ESCAPE isn't defined I can't set it so it's a moot point.
So my question is:  Is it possible to hide escape sequences in LongStringProperties in wxPython without creating the whole class again from scratch, and if so how do you do it?


text:
Q: Fancybox is displaying a blank page with IE7 I'm trying to load a YouTube video with Fancybox. It's working with all the browsers but it seems to have problem with IE7, it only shows a blank white page. I don't know what I've done wrong here, I tested there example online and it work with IE7, http://fancybox.net/blog. I also took my code from them.
So here's my markup on the homepage (where the video is located):

The Problem

and, this is my script for the video:
SetupVideos = function(){
    $("#homevideo1").click(function() {
        $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : this.title,
            'width'     : 740,
            'height'        : 495,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'          : 'swf',
            'swf'           : {
                 'wmode'        : 'transparent',
                'allowfullscreen'   : 'true'
            }
        });
        return false;
    });
}

It might be something to do with CSS, I'm not too sure... But I haven't touch the .css that comes with the plug-in at all
Any ideas?
Thanks.

A: You need to put your jquery click event in document ready, like this
$(document).ready(function(){
    $("#homevideo1").click(function() {
        $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : this.title,
            'width'         : 740,
            'height'        : 495,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type'          : 'swf',
            'swf'           : {'wmode':'transparent','allowfullscreen':'true'}
        });
        return false;
    });
});

Try it live here (jsfiddle)

A: Synotte,
I too had problems with IE7 (not YouTube, but video embedding).
Removing the padding from the map worked for me, for some reason it was reducing the width of the video to zero.
May not be your issue, but worth a try.
Adam


text:
Q: Mutate column of dataframe using values stored in different dataframe I have created two dataframes, with df.1 containing my main data.
ID  A_ratio   B_ratio  C_ratio
1    0.9       7.6      3.5
2    3.1       4.4      0.7
3    6.3       8.2      1.2

The dataframe cut only contains one row.
A_cut  B_cut  C_cut
 4.5    5.3    2.0

I now want to use the values stored in cut to binarize df, turning X_ratio <= X_cut to 1 and X_ratio > X_cut to 0. The new column could be called X_bin.  I've tried the following dplyr approach:
df.2 <- df.1 %>%
  mutate(across(ends_with("ratio"), ~if_else(. <= get(cut[str_replace(cur_column(),"ratio","cut")]), 1, 0)
            .names = "{.col}_bin"))%>%
  rename_with(~str_replace(.,"_ratio",""),contains("_ratio_"))
  select(ID, ends_with("bin"))

But I'm unfortunately  getting an Error: unexpected symbol. Could someone point out my mistake? The desired output in df.2 would be
ID A_bin B_bin C_bin
1   1     0     0
2   1     1     1
3   0     0     1

Thanks a lot in advance!

A: There is a , missing before the .names and if we are extracting the column from cut, we don't need any get along with the fact that instead of mutate, use transmute to return only those columns needed so that the last step with select can be removed
library(dplyr)
library(stringr)
df.1 %>%
  transmute(ID, across(ends_with("ratio"),
      ~if_else(. <=  cut[[str_replace(cur_column(),"ratio","cut")]],
            1, 0),
        .names = "{.col}_bin")) %>%
   rename_with(~str_replace(.,"_ratio",""),contains("_ratio_"))

-output
#  ID A_bin B_bin C_bin
#1  1     1     0     0
#2  2     1     1     1
#3  3     0     0     1

As we are returning binary columns, if_else is not really needed.  The logical vector can be coerced to binary with as.integer or wrapped with +(
df.1 %>%
  transmute(ID, across(ends_with("ratio"),
      ~as.integer(. <=  cut[[str_replace(cur_column(),"ratio","cut")]]),
        .names = "{.col}_bin")) %>%
   rename_with(~str_replace(.,"_ratio",""),contains("_ratio_"))

Note: cut is a function name, so it is better not to name objects with function names
data
df.1 <- structure(list(ID = 1:3, A_ratio = c(0.9, 3.1, 6.3), B_ratio = c(7.6,
4.4, 8.2), C_ratio = c(3.5, 0.7, 1.2)), class = "data.frame", row.names = c(NA,
-3L))

cut <- structure(list(A_cut = 4.5, B_cut = 5.3, C_cut = 2), class = "data.frame",
row.names = c(NA,
-1L))

A: Base R answer :
df.1[-1] <- +(sweep(df.1[-1], 2, unlist(cut), `<=`))
df.1

#  ID A_ratio B_ratio C_ratio
#1  1       1       0       0
#2  2       1       1       1
#3  3       0       0       1

A: purrr
df <- structure(list(ID = 1:3, A_ratio = c(0.9, 3.1, 6.3), B_ratio = c(7.6,
                                                                         4.4, 8.2), C_ratio = c(3.5, 0.7, 1.2)), class = "data.frame", row.names = c(NA,
                                                                                -3L))

cut <- structure(list(A_cut = 4.5, B_cut = 5.3, C_cut = 2), class = "data.frame",
                 row.names = c(NA,
                               -1L))
library(purrr)
df[-1] <- +map2_dfc(df[-1], cut, ~.x <= .y)
df
#>   ID A_ratio B_ratio C_ratio
#> 1  1       1       0       0
#> 2  2       1       1       1
#> 3  3       0       0       1

Created on 2021-04-02 by the reprex package (v1.0.0)