text:
Q: Is cross-table indexing possible? Consider a structure where you have a many-to-one (or one-to-many) relationship with a condition (where, order by, etc.) on both tables.  For example:
CREATE TABLE tableTwo (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    eventTime DATETIME NOT NULL,
    INDEX (eventTime)
) ENGINE=InnoDB;

CREATE TABLE tableOne (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    tableTwoId INT UNSIGNED NOT NULL,
    objectId INT UNSIGNED NOT NULL,
    INDEX (objectID),
    FOREIGN KEY (tableTwoId) REFERENCES tableTwo (id)
) ENGINE=InnoDB;

and for an example query:
select * from tableOne t1
  inner join tableTwo t2 on t1.tableTwoId = t2.id
  where objectId = '..'
  order by eventTime;

Let's say you index tableOne.objectId and tableTwo.eventTime.  If you then explain on the above query, it will show "Using filesort".  Essentially, it first applies the tableOne.objectId index, but it can't apply the tableTwo.eventTime index because that index is for the entirety of tableTwo (not the limited result set), and thus it must do a manual sort.
Thus, is there a way to do a cross-table index so it wouldn't have to filesort each time results are retrieved?  Something like:
create index ind_t1oi_t2et on tableOne t1
  inner join tableTwo t2 on t1.tableTwoId = t2.id
  (t1.objectId, t2.eventTime);

Also, I've looked into creating a view and indexing that, but indexing is not supported for views.
The solution I've been leaning towards if cross-table indexing isn't possible is replicating the conditional data in one table.  In this case that means eventTime would be replicated in tableOne and a multi-column index would be set up on tableOne.objectId and tableOne.eventTime (essentially manually creating the index).  However, I thought I'd seek out other people's experience first to see if that was the best way.
Thanks much!
Update:
Here are some procedures for loading test data and comparing results:
drop procedure if exists populate_table_two;
delimiter #
create procedure populate_table_two(IN numRows int)
begin
declare v_counter int unsigned default 0;
  while v_counter < numRows do
    insert into tableTwo (eventTime)
    values (CURRENT_TIMESTAMP - interval 0 + floor(0 + rand()*1000) minute);
    set v_counter=v_counter+1;
  end while;
end #
delimiter ;

drop procedure if exists populate_table_one;
delimiter #
create procedure populate_table_one
   (IN numRows int, IN maxTableTwoId int, IN maxObjectId int)
begin
declare v_counter int unsigned default 0;
  while v_counter < numRows do
    insert into tableOne (tableTwoId, objectId)
      values (floor(1 +(rand() * maxTableTwoId)),
              floor(1 +(rand() * maxObjectId)));
    set v_counter=v_counter+1;
  end while;
end #
delimiter ;

You can use these as follows to populate 10,000 rows in tableTwo and 20,000 rows in tableOne (with random references to tableOne and random objectIds between 1 and 5), which took 26.2 and 70.77 seconds respectively to run for me:
call populate_table_two(10000);
call populate_table_one(20000, 10000, 5);

Update 2 (Tested Triggering SQL):
Below is the tried and tested SQL based on daniHp's triggering method.  This keeps the dateTime in sync on tableOne when tableOne is added or tableTwo is updated.  Also, this method should also work for many-to-many relationships if the condition columns are copied to the joining table.  In my testing of 300,000 rows in tableOne and 200,000 rows in tableTwo, the speed of the old query with similar limits was 0.12 sec and the speed of the new query still shows as 0.00 seconds.  Thus, there is a clear improvement, and this method should perform well into the millions of rows and farther.
alter table tableOne add column tableTwo_eventTime datetime;

create index ind_t1_oid_t2et on tableOne (objectId, tableTwo_eventTime);

drop TRIGGER if exists t1_copy_t2_eventTime;
delimiter #
CREATE TRIGGER t1_copy_t2_eventTime
   BEFORE INSERT ON tableOne
for each row
begin
  set NEW.tableTwo_eventTime = (select eventTime
       from tableTwo t2
       where t2.id = NEW.tableTwoId);
end #
delimiter ;

drop TRIGGER if exists upd_t1_copy_t2_eventTime;
delimiter #
CREATE TRIGGER upd_t1_copy_t2_eventTime
   BEFORE UPDATE ON tableTwo
for each row
begin
  update tableOne
    set tableTwo_eventTime = NEW.eventTime
    where tableTwoId = NEW.id;
end #
delimiter ;

And the updated query:
select * from tableOne t1
  inner join tableTwo t2 on t1.tableTwoId = t2.id
  where t1.objectId = 1
  order by t1.tableTwo_eventTime desc limit 0,10;

A: Cross-table indexing is not possible in MySQL except via the now-defunct Akiban(?) Engine.
I have a rule:  "Do not normalize 'continuous' values such as INTs, FLOATs, DATETIMEs, etc."  The cost of the JOIN when you need to sort or range-test on the continuous value will kill performance.
DATETIME takes 5 bytes; INT takes 4.  So any 'space' argument toward normalizing a datetime is rather poor.  It is rare that you would need to 'normalize' a datetime in the off chance that all uses of a particular value were to change.

A: As you know, SQLServer achieves this with indexed views:

indexed views provide additional performance benefits that cannot be
  achieved using standard indexes. Indexed views can increase query
  performance in the following ways:
Aggregations can be precomputed and stored in the index to minimize
  expensive computations during query execution.
Tables can be prejoined and the resulting data set stored.
Combinations of joins or aggregations can be stored.

In SQLServer, to take advantage of this technique, you must query over the view and not over the tables. That means that you should know about the view and indexes.
MySQL does not have indexed views, but you can simulate the behavior with table + triggers + indexes.
Instead of creating a view, you must create an indexed table, a trigger to keep the data table up to date, and then you must query your new table instead of your normalized tables.
You must evaluate if the overhead of write operations offsets the improvement in read operations.
Edited:
Note that it is not always necessary to create a new table. For example, in a 1:N relationship (master-detail) trigger, you can keep a copy of a field from the 'master' table into the 'detail' table. In your case:
CREATE TABLE tableOne (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    tableTwoId INT UNSIGNED NOT NULL,
    objectId INT UNSIGNED NOT NULL,
    desnormalized_eventTime DATETIME NOT NULL,
    INDEX (objectID),
    FOREIGN KEY (tableTwoId) REFERENCES tableTwo (id)
) ENGINE=InnoDB;

CREATE TRIGGER tableOne_desnormalized_eventTime
   BEFORE INSERT ON tableOne
for each row
begin
  DECLARE eventTime DATETIME;
  SET eventTime =
      (select eventTime
       from tableOne
       where tableOne.id = NEW.tableTwoId);
  NEW.desnormalized_eventTime = eventTime;
end;

Notice that this is a before insert trigger.
Now, the query is rewritten as follows:
select * from tableOne t1
  inner join tableTwo t2 on t1.tableTwoId = t2.id
  where t1.objectId = '..'
  order by t1.desnormalized_eventTime;

Disclaimer: not tested.

A: May be I'm wrong , but if this is my application I will not duplicate the data unless I need to order by 2 columns in 2 different tables and this is a hot query (it's required many times). But since there is no clear cut solution to avoid the filesort, what about this little trick (force the optimizer to use the index on the column in the order by clause eventTime)
select * from tableOne t1
inner join tableTwo t2 use index (eventTime)  on t1.tableTwoId = t2.id and t2.eventTime > 0
where t1.objectId = 1
order by t2.eventTime desc limit 0,10;

notice use index (eventTime) and t2.eventTime > 0
It's explain shows that the optimizer has used the index on eventTime instead of filesort
1   SIMPLE  t2  range   eventTime   eventTime   5       5000    Using where; Using index
1   SIMPLE  t1  ref objectId,tableTwoId tableTwoId  4   tests.t2.id 1   Using where


text:
Q: Transform multiple columns with a function that uses different arguments per column I write and review a fair amount of R code like this:
df <- data.frame(replicate(10, sample(0:5, 10, rep = TRUE)))
my.func <- function(col, y) {col %in% y}

df$X2 <- my.func(df$X2, c(1,2))
df$X3 <- my.func(df$X3, c(4,5))
df$X5 <- my.func(df$X5, c(1,2))
df$X6 <- my.func(df$X6, c(4,5))
df$X8 <- my.func(df$X8, c(4,5))
df$X9 <- my.func(df$X9, c(1,2))
df$X10 <- my.func(df$X10, c(1))

That is, certain columns in a data.frame (or data.table) are transformed using a function, where one argument is a column and the other is some arbitrary, somewhat-unique-to-that-column value.
What's a more concise way to make such transformations?
I've tried using data.table's set (:=) operator, which makes things slightly cleaner, but still each column name must appear twice and the function must appear once for each column.

A: A concise way would be Map with the input arguments as the dataset ('df') and a list of vector that would be passed as argument to my.func.  Here, each column of the data.frame is a unit and similarly the vector element from list.
df[] <- Map(my.func, df, list(1:2, 4:5, 3:4))

NOTE: The OP's function or a minimal reproducible example is not provided, so it is not tested
NOTE2: Here, the assumption is that the number of columns is 3.  If it is more than 3, increase the length of the list as well

The above can also be converted to data.table syntax
library(data.table)
setDT(df)[, names(df) := Map(my.func, .SD, list(1:2, 4:5, 3:4))]

If only a subset of columns needs to be changed, specify the columns in .SDcols, and also change the names(df) to the subset of names

Or with tidyverse
library(tidyverse)
map2_dfc(df, list(1:2, 4:5, 3:4), my.func)

A: OP's request from a comment:

make the association between column names and function argument(s) for those columns more explicit

Adjusting the Map approach seen in the other answers:
yL <- list(X2 = 1:2, X3 = 4:5, X5 = 3:4, X6 = 4:5, X8 = 4:5, X9 = 1:2, X10 = 1)
df[names(yL)] <-  Map(my.func, df[names(yL)], y = yL)

With data.table:
# this saves you from writing DT twice
DT[, names(yL) := Map(my.func, .SD, y = yL), .SDcols=names(yL)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I log in with other user's account? I would like to ask you about login command in bash shell Ubuntu.
I entered #login then it asks me about username and password. Is this a way to log in with other user's account?

A: login does exactly what the name says, it logs a user in and sets up the environment, but the login command is not intended for switching to another user account on the command line. For this you would either use su username to switch to another account, or sudo -u username to run just a single command as another user.


text:
Q: Fedora 37 reboot after update - Grub Out of Range Pointer and not able to rescue boot w/ USB After a regular Fedora 37 update last evening, I rebooted my home server (actually a Fedora Workstation 37 but with lots of extras). I went to log in this morning remotely and ... no connection. Upon checking the machine directly, it was giving a Grub Out of Range pointer error on the screen.
Hours of internet searches plus in-article link crawling later, I have concluded this grub issue (https://endeavouros.com/news/full-transparency-on-the-grub-issue/) is the most likely cause. However, I do have a unique situation, I think, and need some help. I am unable to follow the "I have already updated and my machine is broken, what should I do?" instructions for the reason(s) spelled out below, most importantly the inability to even get the USB to boot. I am able to identify the harddrive mount point, and the USB does also show up. But any attempts to insmod linux after setting the key environment variables results in the same out of range error as Grub.
It's an older I5 processor tower (from at least 2009 if not older), and I've never attempted to set up UEFI in the Bios. Attempts to enable UEFI just change the initial error to "No Boot Device available" - I suspect there's a whole list of other challenges I'd have to learn to go that route successfully. So... I'm focusing for now on the Grub related issue. Not only do I get the Grub Out of Range Pointer error from the Grub menu selection, I get it from the command line as well when I attempt to manually (again from the command line) set up and boot to a LiveOS USB or otherwise. I'm stuck for now, not sure what the next step ought to be. I do have physical access to all the hardware, but would prefer a command line solution even if it requires a bit of technical learning on my part.

A: After wrestling with this for a couple weeks on my system, reinstalling the grub bootloader and rebuild grub.conf fixed the problem on my computer, at least for now anyway.
https://docs.fedoraproject.org/en-US/quick-docs/bootloading-with-grub2/#restoring-bootloader-using-live-disk


text:
Q: First value is missing in list fragment I am trying to build a notes app and my arrayadapter is not taking the first value.
Main Activity :
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.FragmentTransaction;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;

import Models.Note;

public class MainActivity extends AppCompatActivity implements MainActivityFragment.Onqwertylistener{

    static ArrayList<Note> ar = new ArrayList<Note>();
    static arraylistclass newar = new arraylistclass();
    static ArrayAdapter adapter=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final MainActivity thisobject = this;
        FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.fab);

        SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
        Gson gson1 = new Gson();
        String json = mPrefs.getString("yaah", "");
        newar = gson1.fromJson(json, arraylistclass.class);
        if (newar != null)
            ar = newar.getAr();
        else {
            ar = new ArrayList<Note>();
        }
        adapter=new ArrayAdapter<Note>(this,android.R.layout.simple_list_item_1,ar);
        fab1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                //adapter.add(no);
                int pos;
                pos = ar.size();
                ar.add(new Note("", pos +1));
                adapter.notifyDataSetChanged();
                if (newar != null)
                    newar.setAr(ar);
                SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
                SharedPreferences.Editor prefseditor = mPrefs.edit();
                Gson gson = new Gson();
                String json = gson.toJson(newar);
                prefseditor.putString("yaah", json);
                prefseditor.apply();
                onNoteSelected(pos);
                Toast.makeText(thisobject,"Pos"+pos, Toast.LENGTH_SHORT).show();
            }
        });
        FragmentManager fragmentManager=getSupportFragmentManager();

        MainActivityFragment mainfragment=new MainActivityFragment();
        fragmentManager.beginTransaction().add(R.id.fragment_container,mainfragment).addToBackStack(null).commit();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void onPause() {
        super.onPause();

    }
    @Override
    public void onNoteSelected(int pos) {
        Intent intent = new Intent(MainActivity.this, opennote.class);
        intent.putExtra("opennote", pos);//ar.get(position).getId());
        startActivity(intent);
    }
}

opennote :
package com.example.dhrumil.notes;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;

import java.util.ArrayList;

import Models.Note;

public class opennote extends AppCompatActivity {

    int x;
    String val;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_opennote);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Intent intent = getIntent();
        x=intent.getIntExtra("opennote", 0);
        ArrayList<Note> ar;
        ar=MainActivityFragment.getar();
        val=ar.get(x).getNote();
        EditText e1= (EditText) findViewById(R.id.edt1);
        e1.setText(val);
    }
    public void onPause() {
        EditText s;
        super.onPause();
        s= (EditText) findViewById(R.id.edt1);
        ArrayList<Note> ar;
        ar=MainActivityFragment.getar();
        ar.get(x).setNote(s.getText().toString());

    }
}

Fragment :
package com.example.dhrumil.notes;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.view.WindowManager.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;
import Models.Note;
import static android.content.Context.MODE_PRIVATE;
import static com.example.dhrumil.notes.MainActivity.ar;
import static com.example.dhrumil.notes.MainActivity.adapter;
/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends ListFragment {
    Onqwertylistener Callback;
    boolean b=false;

    public interface Onqwertylistener
    {
        public void onNoteSelected(int pos);
    }
    static ArrayList getar()
    {
        return ar;
    }
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
    {
        setListAdapter(adapter);

        return super.onCreateView(inflater,container,savedInstanceState);
    }
    public void onAttach(Context context)
    {
        super.onAttach(context);
        Activity activity=(Activity) context;
        try {
            Callback = (Onqwertylistener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }

    }
    public void onResume()
    {
        super.onResume();
        adapter.notifyDataSetChanged();

    }
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
        Callback=(Onqwertylistener) getActivity();

        getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //adapter.remove(ar.get(position));
                final int pos=position;
                AlertDialog.Builder diabox=new AlertDialog.Builder(getActivity());
                diabox.setMessage("Do you want to delete this note ?").setTitle("ALERT");
                diabox.setCancelable(true);
                diabox.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        adapter.remove(ar.get(pos));
                        dialog.cancel();
                    }
                });
                diabox.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                AlertDialog deletedia=diabox.create();
                deletedia.show();
                return true;
            }
        });

    }
    /*@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            Callback = (Onqwertylistener) getActivity();
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString()
                    + " must implement OnHeadlineSelectedListener");
        }

        /*gridView = (GridView) getActivity().findViewById(R.id.gridv);;

        adapter = new ArrayAdapter<Note>(getActivity(), android.R.layout.simple_list_item_1, ar);
        //adapter = new ArrayAdapter<Note>(this, android.R.layout., ar);

        gridView.setAdapter(adapter);
        /*gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Callback.onNoteSelected(position);
            }
        });*/
        /*if (!b) {
            gridView.setNumColumns(1);
        } else {
            gridView.setNumColumns(3);
        }
        gridView.setLongClickable(true);
        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //adapter.remove(ar.get(position));
                final int pos = position;
                AlertDialog.Builder diabox = new AlertDialog.Builder(thisObject);
                diabox.setMessage("Do you want to delete this note ?").setTitle("ALERT");
                diabox.setCancelable(true);
                diabox.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        adapter.remove(ar.get(pos));
                        dialog.cancel();
                    }
                });
                diabox.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                AlertDialog deletedia = diabox.create();
                deletedia.show();
                return true;
            }
        });*/

            //}

    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        Callback.onNoteSelected(position);
        // Set the item as checked to be highlighted when in two-pane layout

        //getListView().setItemChecked(position, true);
    }

}

I am new to Android and application development so please suggest me any changes/improvements in the code.


text:
Q: centering an object so vertical constraints are always even I need to center a UIButton('Call') between a UIView(the dialpad) and the bottom layout guide.   The view is always align center x and align center y.
So, I'd like to have the vertical constraints between the view and the call button and the call button and the bottom layout guide always equal
The UIView ('DialPad') constraints

The UIButton ('Call') is currently constained to the bottom layout guide.  I want it to be spaced evenly between the UIView and the bottom layout guide

and the storyboard preview shows different sizes and how the Call button IS NOT centered between the UIView and the bottom layout guide.  Extremely obvious in the 4.7" layout

A: have you tried doing this at runtime also through constraints ? , the approach will be as follow :
you will have your constraints set as the current state then you need to outlet the button constraint (the one from the button to the bottom layout guide) to your viewController (you do so like you outlet any UIKit control)
and then in your viewWillAppear or viewDidAppear you can write the following code :
//here we get the end y point of the dial view .
CGFloat dialPadYEndPos = self.dialPad.frame.origin.y + self.dialPad.frame.size.height;
//here we get the space between the dial view and the bottom of the view
CGFloat spaceBetweenViews = self.view.frame.size.height - dialPadYEndPos ;
//here we get the half of the call button height .
CGFloat halfBtnHeight = self.Call.frame.size.height/2.0f ;
//then we set the outlet constraint .
self.bottomConstraint.constant = (spaceBetweenViews/2.0f)-halfBtnHeight ;
[self.view layoutIfNeeded] ;

i haven't tested the code but theoretically it should work .

A:
Are you want this?
i use proportional width/height for parent view.
width constraint of blue view

height constraint is same.
width and height constraint of buttons in blue view


text:
Q: Blank content is displayed when trying to open .pdf in another tab using React and Express I am trying to open a .pdf in another tab that is stored in the server's file system (I am using Express, React and MySQL).
When the user clicks the "See" button, the displayCV function is executed, and a new tab is open, but the .pdf content is blank even though the new tab shows the correct number of pages the .pdf contains.
The flow goes like this:
JobItem.jsx
const displayCV = async (e) => {
   e.preventDefault();
   await displayCurriculum();
};

JobContext.js
const displayCurriculum = async () => {
  const { id } = params;

  const response = await axios.get(`/api/jobs/${id}/cv`);
  // console.log(response);

  const file = new Blob([response.data], {
    type: "application/pdf",
  });

  const fileURL = URL.createObjectURL(file);
  const pdfWindow = window.open();
  pdfWindow.location.href = fileURL;
};

The backend looks like this:
jobRoutes.js
const express = require("express");
const router = express.Router();
const { displayCurriculum } = require("../controllers/jobController");
router.route("/:id/cv").get(displayCurriculum);

jobController.js
const displayCurriculum = asyncHandler(async (req, res) => {
  try {
    const { id } = req.params,
      q = `SELECT curriculum FROM jobs WHERE idjobs = ?`,
      doc = await pool.query(q, [id]);

    const fileName = doc[0].curriculum;

    // const data = fs.readFileSync(filesPath + "\\" + fileName);
    res.setHeader("Content-Type", "application/pdf");
    res.sendFile(fileName, { root: filesPath }, (err) => {
      if (err) console.log(err);
      else console.log("Sent: ", fileName);
    });
  } catch (error) {
    console.log(error);
  }
});

If I use Postman and hit the API's endpoint (/api/jobs/${id}/cv) the .pdf is displayed correctly in Postman. When hitting the endpoint from the frontend I get the following
Image with blank .pdf content
How can I display the .pdf content in the new tab?

A: In this case, it turns out that the responseType from Axios needs to be set to "blob" for the .pdf to be read.
JobContext.js
 const displayCurriculum = async () => {
    const { id } = params;
    const response = await axios.get(`/api/jobs/${id}/cv`, {
      method: "GET",
      responseType: "blob",
    });

    const file = new Blob([response.data], {
      type: "application/pdf",
    });

    const fileURL = URL.createObjectURL(file);
    window.open(fileURL);
 };

The .pdf is now opening in a new tab and is showing its content. However, the name of the file in the URL is set to the DOMString that is created by URL.createObjectURL(). If the user tries to download the .pdf, the default filename will be the DOMString generated.
Example URL:

blob:http://localhost:3000/c6430bc7-99b3-4dae-9caf-79997f801752


text:
Q: element.style loading whenever the page is loaded but it is supposed to function on window.onscroll I am trying to make a web page in which the top nav bar hides on scrolling down and shows up on scrolling up. I am using the code given below to do so.
<nav class="navbar navbar-expand-lg navbar-dark navbar-custom fixed-top" id='navHeader'>

<!-- all the elements of navbar like logo and menu goes here-->

    </nav> <!-- end of navbar -->
    <!-- end of navigation -->
    <script>
    var header=document.getElementById("navHeader");
    var prevScrollpos = window.pageYOffset;
    window.onscroll = function() {
    var currentScrollPos = window.pageYOffset;
    if (prevScrollpos > currentScrollPos) {
    navHeader.style.top = "0";
    } else {
    navHeader.style.top = "-50px";
    }
    prevScrollpos = currentScrollPos;
    }
    </script>

But the problem is the element.style should load on scrolling the web page sown. But it is loading initially when the web page is opened and the nav bar is not visible initially. When the web page is scrolled down and then up again at that time the nav bar is visible.
The Images Given below may also help you
Initally and on scrolling down
On scrolling up
But when the page loaded for first time and untill and unless it is scrolled there should not be any element.style I guess.
Then Why is this happening and how can is I solve it.
Thanks for any help in Advance.

A: I think this is quite simple: just add this code right before the scroll event

navHeader.style.top = "0";

some thing like this:
<script>
    var header=document.getElementById("navHeader");
    navHeader.style.top = "0";//Please add this new line
    var prevScrollpos = window.pageYOffset;
    window.onscroll = function() {
    var currentScrollPos = window.pageYOffset;
    if (prevScrollpos > currentScrollPos) {
    navHeader.style.top = "0";
    } else {
    navHeader.style.top = "-50px";
    }
    prevScrollpos = currentScrollPos;
    }
    </script>

A: The main problem I see is that you're setting the variable header to the element with the id navHeader, but then you're trying to set the style on the navHeader variable, which you haven't defined. Does it work if you change those references to header instead?


text:
Q: p-adic analogue of the Strong Law of Large Numbers Is there a $p$-adic analogue of the Strong Law of Large Numbers?  In particular, suppose that $f_i: \mathbb{Z}_p \longrightarrow \mathbb{Q}_p$ for $i = 1,2,\ldots$ is an sequence of random variables that is i.i.d. with respect to the $\mathbb{Q}_p$-valued normalized Haar measure $\mu$ on $\mathbb{Z}_p$.  Must one have $$\int_{\mathbb{Z}_p} f_1 d \mu  = \lim_{n \rightarrow \infty} \frac{f_1(x) + f_2(x) + \cdots + f_n(x)}{n}$$ for almost all $x \in \mathbb{Z}_p$? If not, is there a partial result in this direction?

A: I think this can't work. If you look at the simplest possible case, where the $f_i$ take values 0 and 1 with probabilities $1-1/p$ and $1/p$, say, then you are effectively looking at the average of the digit sums of $x$.
To make sense (since your $f_i(x)$ generally take values in $\mathbb Q_p$), you should look for a limit in $\mathbb Q_p$. But now, the numerator is an integer close to $n/p$. By standard random walk techniques, you know that the ratio will be exactly $1/p$ infinitely often (with $p$-valuation $-1$).
On the other hand, for $n$ not a multiple of $p$, the $p$-valuation of the ratio will be (at least) $0$. Hence there is no pointwise convergence.

A: There seems to be an extensive oeuvre of one A. Khrennikov on the subject. Here is one paper. It seems one can get interesting results (his interest comes from mathematical physics).


text:
Q: problem with displaying Excel files I am designing an Intranet workspace for my company.
The requirements are to display multiple Excel files(max 5) in a single page created. The design is displayed in my computer but when looking into others computer, I am getting the following error message,

"an error occurred during the execution of the requested action. try
  again"

Sometimes the webpage loses its connection and refreshing 3 to 4 times, I am getting back.
Sorry its In French but when you translate you will get the above error message

A: If You are using SharePoint 2013: Use the "Search Results Web Part". In the configuration You can point it to the Library (or libraries) You want to fetch the documents from and configure it to show only 5 elements.

A: Could you please tell us which permissions you gave to users, and which kind of account you use for?
I suppose that is a problem of permission if you can access to your page but not for the others.
http://blogs.technet.com/b/excel_services__powerpivot_for_sharepoint_support_blog/archive/2013/05/21/excel-services-the-workbook-cannot-be-opened.aspx
Bon Courage.


text:
Q: How does a zero in transfer function affect the bandwidth of a system Suppose we have a system with the closed-loop gain:
\$\displaystyle G(s) = \frac{\omega_n^2}{s^2 + 2\zeta\omega_n+\omega_n^2}\$
Which is the default two-pole system closed-loop gain. Let's also assume that bandwith \$\omega_0\$ is defined with \$|G(j\omega_0)| = \frac{1}{\sqrt{2}}|G(j0)|\$ (standard 3dB definition).
Through substitution of these two expressions we end up with:
\$ \omega_0 = \omega_n\sqrt{1-2\zeta^2+\sqrt{4\zeta^4 - 4\zeta^2 + 2}}\$.
-> My question is: If we add a finite zero to the transfer function, such as:
\$\displaystyle G(s) = \frac{(s+z)\omega_n^2}{s^2 + 2\zeta\omega_n+\omega_n^2}\$
what will happen to the bandwidth? Will it change? I know that the finite zero only affects the system in transient phase, and in stable phase (when t \$\rightarrow \infty\$) the zero doesn't affect it. However, I'm not sure about the bandwidth.
Of course, I could substitute G(s) into the bandwidth expression, but I won't get a normal result.
Help :)

A: What you have initially described is a 2nd order low pass filter then you've made a bit of a complication of things because the bandwidth is \$\omega_n\$ i.e. \$\omega_n\$ is the 3dB point when \$\zeta\$ is not causing the filter to peak i.e. has a value of \$\frac{1}{\sqrt2}\$: -

OK you may be trying to derive a general expression but that doesn't help much visualize the problem so for now I'm assuming \$\zeta\$ = \$\frac{1}{\sqrt2}\$.
Anyway, moving on and ignoring your expression for \$\omega_0\$, the bandwidth of the low-pass filter is from dc to \$\omega_n\$. Then you've modified the 2nd order low-pass filter expression with a 1st order high pass filter (\$s +z\$).
When s is very low, the low pass filter is unaffected other than having a "gain factor" of z. If z is unity then the low pass filter response is unaffected until jw approaches z in magnitude - this then marks a lower 3dB point and the net response climbs with increasing frequency until the original \$\omega_n\$ is reached then, because the low pass filter is a second order, the response starts to fall again.
What you have proposed is a band pass filter with finite gain at dc.

I'm not sure about the bandwidth

If the high pass filter (\$s +z\$) comes into play at significantly lower frequencies than \$\omega_n\$ then the net bandwidth reduces from \$\omega_n\$ to \$\omega_n - z\$.
That's how I see it anyway.


text:
Q: Exporting from ssrs 2008 report to multiple column in csv I have ssrs report. When I export that report to csv , and when I open that csv file in ms-excel, some data is coming in column A and some data is coming in column B .Can you help me in getting whole data to column A only ? In report, DataElementOutput property of each textbox is also set to 'Auto'.

A: Without more to go on it seems you have two columns and they are displayed as such.  If you just want a single column consider doing an expression like this in SSRS:(click the cell and choose 'Expression' in 2008 and higher)
=Fields!(FieldName).Value & " " & Fields!(FieldName2).Value

This would put two fields in one column but seperate them with a (space).


text:
Q: cnn-lstm autoencoder for multivariate time series Hello I'm new in deep learning,I have a multivariate time series dataset composed of 49 sensors .i'm trying to perform anomaly detection using cnn lstm autoencoder where  1d cnn is used to encode the intercorrelation between different features and lstm is used to support sequence prediction(time series) .below the implemented code .
input shape:(154369, 49)
Training input shape:  (154364, 5, 49)
model = Sequential()
model.add(Conv1D(filters=32, kernel_size=7, padding="same", strides=1, activation='relu',
input_shape=(x_train.shape[1], x_train.shape[2])))
model.add(Conv1D(filters=16, kernel_size=7, padding="same", strides=1, activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(RepeatVector(5))
model.add(LSTM(units=32, return_sequences=True))
model.add(Dropout(0.5))
model.add(TimeDistributed(Dense(5, activation='relu')))
model.add(Flatten())
model.add(Dense(25,activation='relu'))
model.add(Reshape((5,5)))
model.add(UpSampling1D(size=3))
model.add(TimeDistributed(Dense(15, activation='relu')))

model.add(Conv1DTranspose(filters=8, kernel_size=7, padding="same", strides=1,
 activation="relu"))
model.add(Conv1DTranspose(filters=16, kernel_size=7, padding="same", strides=1,
activation="relu"))
model.add(Conv1DTranspose(filters=32, kernel_size=7, padding="same", strides=1,
activation="relu"))
model.add(Dropout(0.2))
model.add(TimeDistributed(Dense( x_train.shape[2])))

model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.001), loss="mse",metrics=
 ['accuracy'])
model.summary()

however I'm not sure if it is useful to use cnn for feature extraction and dimension reduction in my case . what should be the input shape to deal with this task? Is it( batch size, time steps, features )or (batch size, features, time steps)?
i will be grateful if someone can help


text:
Q: Plot heatmaps of multiple data frames using a slider in R I have multiple data.frames and each one of them represent the pairwise interactions of individuals at different time points.
Here is an example of how my data.frames look.
df1 <- matrix(data = rexp(9, rate = 10), nrow = 3, ncol = 3)
df2 <- matrix(data = rexp(16, rate = 10), nrow = 4, ncol = 4)
df3 <- matrix(data = rexp(4, rate = 10), nrow = 2, ncol = 2)

I would like to plot them as it is pointed in this page (https://plotly.com/r/sliders/)
where with a slider I can move from one heatmap to the other.
I have tried so far with plotly but I have not succeeded. Any help is highly appreciated.
I am struggling for long with this issue. I might be a bit blind at this point so please forgive me if the question is stupid.

A: Following the Sine Wave Slider example on https://plotly.com/r/sliders/ this can be achieved like so. The first step of my approach involves converting the matrices to dataframes with columns x, y, z. Second instead of lines we plot heatmaps.
df1 <- matrix(data = rexp(9, rate = 10), nrow = 3, ncol = 3)
df2 <- matrix(data = rexp(16, rate = 10), nrow = 4, ncol = 4)
df3 <- matrix(data = rexp(4, rate = 10), nrow = 2, ncol = 2)

library(tibble)
library(tidyr)
library(plotly)

# Make dataframes
d <- lapply(list(df1, df2, df3), function(d) {
            d %>%
              as_tibble(.colnames = seq(ncol(.))) %>%
              rowid_to_column("x") %>%
              pivot_longer(-x, names_to = "y", values_to = "z") %>%
              mutate(y = stringr::str_extract(y, "\\d"),
                     y = as.numeric(y))
    })

aval <- list()
for(step in seq_along(d)){
  aval[[step]] <-list(visible = FALSE,
                      name = paste0('v = ', step),
                      x = d[[step]]$x,
                      y = d[[step]]$y,
                      z = d[[step]]$z)
}
aval[1][[1]]$visible = TRUE

steps <- list()
fig <- plot_ly()

for (i in seq_along(aval)) {
  fig <- add_trace(fig, x = aval[i][[1]]$x, y = aval[i][[1]]$y, z = aval[i][[1]]$z, visible = aval[i][[1]]$visible,
                   name = aval[i][[1]]$name, type = "heatmap")
  fig
  step <- list(args = list('visible', rep(FALSE, length(aval))), method = 'restyle')

  step$args[[2]][i] = TRUE
  steps[[i]] = step
}

fig <- fig %>%
  layout(sliders = list(list(active = 0,
                             currentvalue = list(prefix = "Heatmap: "),
                             steps = steps)))
fig


text:
Q: Mean distance between N equidistributed points in a circle I would like to calculate the mean distance depending on circle shape points,
This is a mean for calculating all possible distances between any two points
for $N=2$, line, there is only 1 distance.
for $N=3$, triangle, again, there is only 1 distance
for $N=4$, square, henceforth there are more than 1 distance..
in this case we would have four distances for sides and two distances in diagonal path, $\sqrt{2}$, then the mean distance would be
$D=(4+2\sqrt{2})/6=1.138..$
for $N=30$, it would be a "pixeled" circle .. and $N=\infty$ is a circle
How to calculate it for $N>4$ ? Is there any general formula or can it be derived?
Thanks!

A: The average distances among all points must be equal that the average distances from a given point. By geometry: we have that the distance is $d=2 \sin(\theta/2)$, so:
$$\bar d = \frac{2}{N-1} \sum_{k=1}^{N-1} \sin\left(\frac{\pi k}{N}\right)$$
On the limit, $N\to \infty$, you replace the sum by an integral and you get the limit by Christian Blatter: $\bar d \to 4/ \pi$
For example, for $N=30$:
 >>>  N=30;
 >>>  r = 2* sin(pi*[1:N-1]/(N));
 >>> sum(r)/(N-1)
 ans =  1.3159
 >>> 4/pi
 ans =  1.2732

Update: If instead of having a unit circle (radius 1) we have that the distance among nearest neighbours is 1 (the question is not clear about this, and the example for N=4 only makes sense in this later case), we just divide the above result by $2\; \sin(\pi/N)$. In the limit, $\sin(\pi/N) \to \pi/N$ and so $\bar d \to N \; 2/\pi^2$

A: When  two points $z_1$, $z_2$ are independently uniformly distributed on the unit circle $S^1$ then their mean distance $\bar d$ is ${4\over\pi}$. To prove this one may keep $z_1$ fixed and let $z_2$ have an angular distance $\phi\in[0,\pi]$ from $z_1$ which is uniformly distributed on $[0,\pi]$. The euclidean distance between these two points is given by $d(z_1,z_2)=2\sin{\phi\over2}$,whence
$$\bar d={1\over\pi}\int_0^\pi 2\sin{\phi\over2} \ d\phi={4\over\pi}\ .$$
This can be interpreted as follows: If you have a polygon $P$ with $N\gg 1$ vertices  independently and uniformly distributed on $S^1$ then the mean distance between these vertices will be approximately ${4\over\pi}$.


text:
Q: "have you ever gone to" to ask past experience is it correct to ask:
Have you ever gone to Spain?
if i want to know whether or not he had visited Spain in his life (experience)?

A: I don't know what you mean by "is it correct to ask", but a more idiomatic as well as more conventional way to ask someone if they have visited a particular place at least once in their live would be:

Have you ever been to Spain?
Have you ever been to London?

You would use been in this situation rather than gone.


text:
Q: Load page and run javascript I have an existing script (in a bookmarklet) that only works with the http:// version of the page. When I am on the https:// version of the page, I want to load the http:// version using:
add = window.location.href;
if(add.indexOf('https') == 0){
  window.location.href = 'http' + add.slice(5);
}

and then allow the bookmarklet to run on the new page. Is there a way to do this ?
Right now, I added the code above to the bookmarklet, and click it twice: the first click loads the http:// version of the page and the second click runs the original bookmarklet.
Thanks !!


text:
Q: Getting PLS-00201 error while creating a type in oracle I have a table like this:
CREATE TABLE T_C_EVO_GAME_CONFIG_CHANGE_LOG(
F_TABLE_MODIFIED        VARCHAR2(40),
F_OPERATION_PERFORMED   VARCHAR2(30),
F_ROWS_ALTERED          INTEGER,
F_LAST_UPDATED_BY       VARCHAR2(200),
F_LAST_UPDATED_DATE     TIMESTAMP);

I am trying to build a type with the same structure:
create or replace type TYPE_EVOL_CONFIG_CHANGE_LOG as object
(
F_TABLE_MODIFIED        T_C_EVO_GAME_CONFIG_CHANGE_LOG.TABLE_MODIFIED%TYPE ,
F_OPERATION_PERFORMED   T_C_EVO_GAME_CONFIG_CHANGE_LOG.OPERATION_PERFORMED%TYPE,
F_ROWS_ALTERED          T_C_EVO_GAME_CONFIG_CHANGE_LOG.ROWS_ALTERED%TYPE ,
F_LAST_UPDATED_BY       T_C_EVO_GAME_CONFIG_CHANGE_LOG.LAST_UPDATED_BY%TYPE ,
F_LAST_UPDATED_DATE     T_C_EVO_GAME_CONFIG_CHANGE_LOG.LAST_UPDATED_DATE%TYPE
);

Getting the below error message in creating the Type :

Error(3,25): PLS-00201: identifier 'T_C_EVO_GAME_CONFIG_CHANGE_LOG.TABLE_MODIFIED' must be declared.

Previously I tried to create the Type without using %TYPE and just simply copying the parameter definition and it worked.
But I don't want to make any changes in Type when I make any changes in Table.

A: The %TYPE syntax is for use in PL/SQL declarations. Unfortunately we cannot use it when creating SQL objects. Same goes for %rowtype.
It would be highly neat if we could, because one common use of create or replace type would be to build table APIs as you want to do. However, it would be too complicated to manage referencing constructs in the data dictionary; bear in mind that Types can be used to define other objects including Table columns.
So alas, you need to declare the Type with explicit datatypes for its attributes:
create or replace type TYPE_EVOL_CONFIG_CHANGE_LOG as object
    (
    F_TABLE_MODIFIED        VARCHAR2(40) ,
    F_OPERATION_PERFORMED   VARCHAR2(30),
    F_ROWS_ALTERED          INTEGER ,
    F_LAST_UPDATED_BY       VARCHAR2(20) ,
    F_LAST_UPDATED_DATE     DATE
);

Obviously you also need to sync it manually whenever the structure of any  T_C_EVO_GAME_CONFIG_CHANGE_LOG column changes. But you would have to do this anyway if you added or dropped a column.
Alternatively you can define the type as a PL/SQL record in a package. That would allow you to use the referencing syntax.
create or replace package game_config as

    TYPE_EVOL_CONFIG_CHANGE_LOG is record
    (
        F_TABLE_MODIFIED        T_C_EVO_GAME_CONFIG_CHANGE_LOG.F_TABLE_MODIFIED%TYPE ,
        F_OPERATION_PERFORMED   T_C_EVO_GAME_CONFIG_CHANGE_LOG.F_OPERATION_PERFORMED%TYPE,
        F_ROWS_ALTERED          T_C_EVO_GAME_CONFIG_CHANGE_LOG.F_ROWS_ALTERED%TYPE ,
        F_LAST_UPDATED_BY       T_C_EVO_GAME_CONFIG_CHANGE_LOG.F_LAST_UPDATED_BY%TYPE ,
        F_LAST_UPDATED_DATE     T_C_EVO_GAME_CONFIG_CHANGE_LOG.F_LAST_UPDATED_DATE%TYPE
    );

    -- or even
    TYPE TAB_EVOL_CONFIG_CHANGE_LOG is table of T_C_EVO_GAME_CONFIG_CHANGE_LOG%rowtype;
end;

It depends how you want to use the Type in your broader application.


text:
Q: extract text from html mail odoo I want to get the email body but not in html format . I have used Beautifulsoup and
    data = re.sub(r'<.*?>', '', html2)
to remove the html tags but it didn't work I can't receieve email to applicant
def message_new(self, cr, uid, msg, custom_values=None, context=None):
""" Overrides mail_thread message_new that is called by the mailgateway
    through message_process.
    This override updates the document according to the email.
"""
if custom_values is None:
    custom_values = {}
val = msg.get('from').split('<')[0]
val1 = msg.get('from').split('<')[1]
val2 = val1.split('>')[0]
myString2 = msg.get('body') if msg.get('body') else ''
soup = BeautifulSoup(myString2)
data = soup.get_text()
defaults = {
    'name': msg.get('subject') or _("No Subject"),
    'partner_name': val,
    'email_from': val2,
    'email_cc': msg.get('cc'),
    'user_id': False,
    'partner_id': msg.get('author_id', False),
    'description': data,
}
if msg.get('priority'):
    defaults['priority'] = msg.get('priority')
defaults.update(custom_values)
return super(hr_applicant, self).message_new(cr, uid, msg,custom_values=defaults, context=context)

A: please try re library of python for remove html tags from text.
  import re
  text = re.compile('<.*?>')
  message = re.sub(text, '', self.body)

A: I've been using HTMLParser with good success for the exact same thing: stripping out the HTML tags but keep the data.
from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

strip_tags expects a string containing your HTML content.


text:
Q: Show that if $\sigma=(a_1,a_2,\dots,a_m)$ and $\tau$ is any element of $S_n$, then $\tau\sigma\tau^{-1}=(\tau a_1,\tau a_2,\dots,\tau a_m)$ Show that if $\sigma=(a_1,a_2,\dots,a_m)$ and $\tau$ is any element of $S_n$, then $\tau\sigma\tau^{-1}=(\tau a_1,\tau a_2,\dots,\tau a_m)$.
I'm not quite sure how to start this.
The solution starts off by saying that
$$\tau\sigma\tau^{-1}(\tau(a_i))=\tau\sigma(a_i)=\begin{cases}\tau(a_{i+1})&i<m\\\tau(a_1)&i=m\end{cases}$$
but I don't see why.


text:
Q: Change IP Address in VB.Net I am writing a Windows Forms App in VB.Net that will (among other things) change the IP Address, Default Gateway, Subnet Mask, and set the IP Address to Static on an image of Winfows 7 only. Sysprep is not being used. I have searched Google and only come up with 2 options. I don't believe the first solution will work for me because I do not necessarily know the name of the connection. It uses netsh to change IP settings. I was going to give a link to this example but I can't post more than 2 links...
The second solution is shown at this link (the VB.Net version) and the original code is here (the C# version). This solution uses WMI which I really don't know that much about.
When I debug the code and look at everything the code seems to be executing properly but the IP Address is still set to DHCP and all of the other setting are still the same. So, basically, what gives? Why does this code seem to not work?
Here is my code. I only made a few changes:
    'Changed the 3 IPs below
    Dim IPAddress As String = "192.168.1.105"
    Dim SubnetMask As String = "255.255.252.0"
    Dim Gateway As String = "192.168.1.100"

    Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
    Dim objMOC As ManagementObjectCollection = objMC.GetInstances()

    For Each objMO As ManagementObject In objMOC
        If (Not CBool(objMO("IPEnabled"))) Then
            Continue For
        End If

        Try
            Dim objNewIP As ManagementBaseObject = Nothing
            Dim objSetIP As ManagementBaseObject = Nothing
            Dim objNewGate As ManagementBaseObject = Nothing

            objNewIP = objMO.GetMethodParameters("EnableStatic")
            objNewGate = objMO.GetMethodParameters("SetGateways")

            'Set DefaultGateway
            objNewGate("DefaultIPGateway") = New String() {Gateway}
            objNewGate("GatewayCostMetric") = New Integer() {1}

            'Set IPAddress and Subnet Mask
            objNewIP("IPAddress") = New String() {IPAddress}
            objNewIP("SubnetMask") = New String() {SubnetMask}

            objSetIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
            objSetIP = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)

            'Changed this line so I could see if it was executing all of the way
            MessageBox.Show("Updated IPAddress, SubnetMask and Default Gateway!")

        Catch ex As Exception
            MessageBox.Show("Unable to Set IP : " & ex.Message)
        End Try
    Next objMO

A: I can answer my own question. I thought of it in the shower (how cliche right?). Because this is Windows 7, all I needed to was right-click and run the program as an administrator.


text:
Q: $_GET variables don't work my ec2 instance using cloudfront aws On my website, $_GET variables for php do not work (undefined index error). For my behavior settings, I have this set:

Is there another option I have to set?

A: The CloudFront settings would not be related at all to you not having $_GET unless it is related to query strings appended at the end.
If thats the case then you need to look either forwarding important keys, or all keys (although this will affect caching performance).

You can configure CloudFront do one of the following:

*

*Don't forward query strings to the origin at all. If you don't forward query strings, CloudFront doesn't cache based on query string parameters.

*Forward query strings to the origin, and cache based on all parameters in the query string.

*Forward query strings to the origin, and cache based on specified parameters in the query string.

Take a further read here: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/QueryStringParameters.html


text:
Q: Batch database results before processing next query The code executes before the last result set has been processed:
var rxQueryTimeOut = pollingPeriodInSeconds + dbQueryTimeoutInSeconds;
var scheduler = new EventLoopScheduler(ts => new Thread(ts) {Name = "DatabasePoller"});
query = Observable.Interval(rxQueryTimeOut, scheduler).ObserveOn(SynchronizationContext.Current)
    .Select(_ => dbQuery.LoadItemsFromDB(LastFetchedRecord)).Do((x) => DoSomething(x, itemsMgr))
    .Retry() //Loop on errors
    .Repeat(); //Loop on success

query.Subscribe();

private void DoSomething(List<ItemDBData> theoDataDbs, IItemsMgr itemsMgr)
{
    foreach(var theoData in theoDataDbs)
    {

    }
}

Before DoSomething finishes executing, Observable.Interval fires again.
I tried:
private void DoSomething(List<ItemDBData> items, IItemsMgr itemsMgr)
{
    if(items.Count> 0)
        LastFetchedRecord = items[items.Count-1].TimeStamp;

    foreach(var itemData in items)
    {

    }
}

But I think each interval discards the last query request because I'm losing data.  How do  I solve this?

A: Are you trying to process the new rows in the database table every X seconds?
It will lose data when it cannot process all the rows in one query before the timer runs out.
Without more detail it's difficult to see the problem.
Consider looking how many blocking operations are done while processing the rows returned by the database query.  A common problem is to get lots of rows back and then foreach loop on them and do one or more database round trips for each row of data.


text:
Q: Regression that is continuous and differentiable at every value of X? I'm currently enrolled in a statistics course and we are studying regression models. What does it mean to develop a regression model that contains both a straight line in the regressor, as well as a quadratic model outside of the range for x where the model is continuous and differentiable at every value of x?
I'm not looking for an answer, but more of what is this question even asking? Should I create a value for $x_1$ = 1, for example, and then $x_2$ is both a quadratic that can take on any value besides 1?

A: This regression model is piecewise defined.
$$y_i=\begin{cases} b_0+b_1x_i+\epsilon_i \ \ \forall \ x_i\leq x^* \\  \\b_2+b_3x_i+b_4x_i^2+\epsilon_i  \ \ \forall \ x_i> x^*,\end{cases}$$
where $\epsilon_i$ is the error term.
Next the intersection of the two functions has to be calculated in order to find $x^*$. This can be done with the quadratic formula.


text:
Q: WebView, проигрываем видео с sd карты Пытаюсь проиграть видео в WebView с sd карты:
  WebView browser = (WebView) findViewById(R.id.webView);

    WebSettings webSettings = browser.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setSupportZoom(false);
    webSettings.setAllowFileAccess(true);
    webSettings.setLoadsImagesAutomatically(true);
    webSettings.setSaveFormData(false);

    browser.setWebChromeClient(new WebChromeClient());

    String videoPath="file:///storage/emulated/0/Pictures/AnySign/tt.mp4";
    String html =   "" +
                        "" +
                        "" +
                        "" +
                            "<video width=\"365\" height=\"200\" src=\""+videoPath+"\" controls autobuffer>" +
                            "</video>" +
                        "" +
                    "";
    browser.loadDataWithBaseURL("", html, "text/html","utf-8", "");

но видео не проигрываеться.... В чем могут быть проблемы? Если попытаться обратиться к картинке таким же способом(но заменить тег video на img), то картинка показываться без проблем.


text:
Q: How to hide currency symbol in angular currency pipe I'm trying to use Angular currency pipe and I wanted to remove the currency symbol all together from the formatted number, but it seems there is no option to do that. So is there any easy way to achieve this without writing a custom pipe for it?

A: Just send the arguments empty:
price | currency:'':''

A: As @R.Richards mentioned, I ended up using the number pipe:
{{ 50000 | number }} <!-- output: 50,000 -->

A: Hope this example could help.
{{ 0001234.012 | currency:' ':'symbol':'0.0-1' }}  <!-- 1,234 -->
{{ 0001234.012 | currency:' ':'symbol':'0.1-1' }}  <!-- 1,234.0 -->
{{ 0001234.012 | currency:' ':'symbol':'0.0-2' }}  <!-- 1,234.01 -->
{{ 0001234.012 | currency:' ':'symbol':'0.2-2' }}  <!-- 1,234.01 -->

{{ 123 | currency:' ':'symbol':'5.0-0' }}          <!-- 00,123 -->
{{ 123 | currency:' ':'symbol':'4.0-0' }}          <!-- 0,123 -->
{{ 123 | currency:' ':'symbol':'3.0-0' }}          <!-- 123 -->

A: Another option is to set this globally:
import { DEFAULT_CURRENCY_CODE, NgModule } from '@angular/core';

@NgModule({
  ...
  providers: [
    { provide: DEFAULT_CURRENCY_CODE, useValue: '' },
  ],
  ...
})

Example:
<div>{{ 20124.56789 | currency }}</div>   <!-- output: 20,124.57 -->


text:
Q: Force LinearLayout child to use all available space but at least enough to fit its content I'm struggling with getting LinearLayout to behave like I want it. Unfortunately, both dimension modes MATCH_PARENT and WRAP_CONTENT don't seem to fit for my purposes.
Here's why: I want the child that is added to the LinearLayout to be completely visible. Nothing should be cut off. So normally, I should use WRAP_CONTENT to achieve this behaviour.
But, if there's more space in the LinearLayout than the child really needs, I also want it to fill that space. This is of course what MATCH_PARENT is for.
However, I can't use MATCH_PARENT because in case there is less space in the LinearLayout than my child needs, using MATCH_PARENT will cut off the child which I don't want.
So this leaves me somewhat puzzled as to how I can achieve what I want: How can I allow a child to fill additional space in the LinearLayout (if available) while at the same time forcing the LinearLayout to be at least as big as the child needs in order to be completely visible?

A: Put your child view inside a ScrollView with width MATCH_PARENT, height MATCH_PARENTand set both the child's dimensions MATCH_PARENT

A: Instead of using MATCH_PARENT for your child, use WRAP_CONTENT and set your child's weight to 1,So it will take all the empty space in your LinearLayout. Suppose your LinearLayout's height is 128dp, and your child 's height is 56dp, your child will be 128dp . If you set WRAP_CONTENT on your LinearLayout, it will be 56dp, and it child will still take all the place it needs.
If you want your LinearLayout to have a minimum width or height, and not match_parent, you can do setMinimumWidth() or setMinimumHeight() in your xml layout or in your code programmatycally depending your childs default height and width.


text:
Q: Python telebot script (take picture every minute and send to telegram) Hi I have been struggling with this script for a while and the last line is starting to drive me crazy. I want to take a picture every minute and send it to telegram.
import telebot
import picamera

# Set token
token = "PLACE TOKEN HERE"

# Connect to our bot
bot = telebot.TeleBot(token)

# Sets the id for the active chat
chat_id=PLACE CHAT ID HERE

# Get the photo
camera=picamera.PiCamera()
camera.capture('./capture.jpg')
camera.close()

# Sends a message to the chat
bot.send_photo(chat_id, photo=open('./capture.jpg', 'rb'))

ERROR: TypeError: send_photo() got an unexpected keyword argument 'photo'
Help would be greatly appreciated.

A: I have improved the script. If it helps anyone here is the code im currently using:
import time
import requests
import telebot
import picamera
from time import sleep

# Set token
token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Connect to our bot
bot = telebot.TeleBot(token)

# Sets the id for the active chat
chat_id="xxxxxxxxx"

# Repeat function
def repeat():
    # Set camera
    camera=picamera.PiCamera()
    # Take picture
    camera.capture('./capture.jpg')
    # Camera close
    camera.close()
    # Send photo to telegram
    bot.send_photo(chat_id=chat_id, photo=open('capture.jpg', 'rb'))
    # Sleep 60 seconds
    time.sleep(60)
while True:
  repeat()

It works but sometimes the script will crash with one of these errors:
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))
requests.exceptions.ConnectionError: ('Connection aborted.', timeout())
Any idea how to solve those errors?


text:
Q: include statement not working in Google script The official documentation for HTML best practices says that files can be included with <?!= include(myFile); ?>. However, when I go to try it myself, it prints literally on my page. WHY!?
My actual HTML code:
<!DOCTYPE html>

    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css>
    <?!= include('stylesheet'); ?>

Pothole sheet generator

      <form style="margin: 10px 10px 10px 10px;">

Initial measurements

      </form>

stylesheet.html


text:
Q: React Native stuck on white screen IOS My app is working fine on the web but stuck on the XCode Simulator upon running the initiating cmd expo start

List of files

Tried removing node_modules , package-lock etc but nothing seems to work
App has been reloaded numerous times but only works on web.

A: I found where the problem was, having expo-splash-screen was causing this issue. I was using this in a useEffect to load my project font but having removed this package resolved the issue.


text:
Q: Is differentiability a necessary or sufficient condition for a critical point $c$ of a function $f$? I do understand that the gradient of $f$ should be zero. This is for the purpose of classifying local extrema.

A: It is neither necessary nor sufficient. By definition a critical point of $f$ is point $x$ where either $f'(x)=0$ or $f'(x)$ does not exist. So differentiability is not necessary. If $f$ is differentiable at $x$ and $f'(x)\neq 0$ then $x$ is not a critical point, so differentiability is not sufficient.


text:
Q: Toolbar Secondary order is not working in IOS Xamarin.Forms Toolbar secondary order is not working in IOS Xamarin forms, I want to achieve toolbar secondary order like android in ios. My toolbar code is like this,
ToolbarItem tbi = new ToolbarItem()
{
    Text = "Logout",
    Order = ToolbarItemOrder.Secondary,
    Priority = 0,
};

tbi.Clicked += tbi_Clicked;
this.ToolbarItems.Add(tbi);


text:
Q: MySql - How to ORDER BY conditionally based on number of rows returned? Lets suppose I have USERS table, and I want to return 10 USERS whose status is not equal to ACTIVATED. But I want to sort output based on number of rows returned e.g. if number of rows returned is greater than 10, then I want to order by id, else I want to order by date created:
SELECT * FROM USERS
WHERE status != 'ACTIVATED'
ORDER BY
    CASE
      WHEN (SELECT COUNT(ID) FROM USERS WHERE status != 'ACTIVATED') > 10 THEN id
      ELSE created
    END
ASC
LIMIT 10

Note that we need to cast id to INT in CASE statement, otherwise it sorts id like string.

A: Create a view and then use it in your count statement:
CREATE VIEW result AS
SELECT * FROM USERS
WHERE status != 'ACTIVATED'
ORDER BY
  CASE
    WHEN (SELECT COUNT(*) FROM result) > 10 THEN id
    ELSE created
  END
ASC
LIMIT 10

A: There was a syntax error on your part, so I quickly corrected your query, to limit the hassle. Notice the CASE condition and its extra brackets:
SELECT
    *
FROM USERS
WHERE
    status != 'ACTIVATED'
ORDER BY
    CASE
        WHEN ((select count(ID) FROM USERS WHERE status != 'ACTIVATED') > 10) then id
        ELSE created
    END
    ASC
LIMIT 10

EDIT: also agree on practice of creating a separate view for every read action that can be combined in other (sub)queries.
I.e. a separate view:
CREATE VIEW 'my_view' as
SELECT *
FROM USERS
WHERE
    status != 'ACTIVATED'

By utilizing views, you can further optimize the sql execution and make it somewhat simpler overall. This is especially important when you need to combine such views to other, more complex views.
I quickly added an example of a view syntax, so it's not production ready or a desired template to utilize when creating views. Most views that you'll create also define security definer, invokers, in older mysql versions (and mariadb and other mysql forks) people also signify whether to utilize sql_cache or not, etc.


text:
Q: Web App SPA & OIDC: How to properly authenticate before accessing the front? I have a regular web app, composed as usual of a frontend SPA (angular) and a backend.
The server calls are protected from unauthorized calls through authentication provided by OpenID Connect.
My web app is accessible from the internet, and though the front by itself does not contain any user data (which is saved in a database in the backend), I still want to prevent non-users from accessing my front code, because it would leak features that I don't want non-users to know about.
Similarly, I also want to prevent regular users from being able to see admin features (/admin part of my website).
I know the whole point of SPA is to download everything in a single page load and then make dynamic changes, but I still want users to only download code for which they have appropriate rights (for example, you can download the 3 tabs of the main menu in one go if you have access rights for these 3 tabs, but the admin page can only be downloaded if you have admin rights).
What options do I have to make sure the user is authenticated and authorized before downloading front code, and what are their advantages / drawbacks ?

A: You could use the CanLoad guard to check user permissions.
This guard will not only determine if users can navigate to a given route, it will also prevent the download of the module code when not authorized.

A: HMTL
Usually in an SPA there is a single index.html file, as in this online SPA of mine. So when following a pure SPA architecture the HMTL reveals no information.
<!DOCTYPE html>

        <meta charset='utf-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>

        <base href='/spa/' />
        <title>OAuth Demo App</title>

        <link rel='stylesheet' href='bootstrap.min.css?t=1651226315563' integrity='sha256-YvdLHPgkqJ8DVUxjjnGVlMMJtNimJ6dYkowFFvp4kKs='>
        <link rel='stylesheet' href='app.css?t=1651226315563' integrity='sha256-B7pu+gcFspulW4zXfgczVtPcEuZ81tZRFYeRciEzWro='>

If multiple HTML files are returned, this is more of a website approach, and website stacks tend to protect HTML files using cookies to prevent any disclosure.
JAVASCRIPT
Javascript has traditionally not been secured in either SPAs or website tech stacks, since you need to allow Javascript to download in order to render an initial page, eg with a login button.
My deployed Javascript application code is not secured and is available in this bundle file. It is minified, so also does not reveal much. Of course, there should be nothing really secret in UI logic, and APIs should be making all security decisions for the SPA.
My SPA could use a package such as Javascript Obfuscator to further hide Javascript logic. The reason I have not done this is that exception stack trace lookup from source maps no longer works, but I would use obfuscation if I could find a solution where this was supported.
MULTIPLE JAVASCRIPT RESOURCES
If you need to secure Javascript you will need to build the SPA into multiple bundles such as these. Some website stacks provide this type of option, by hosting secured assets in a different folder. The web backend then checks that requests for those assets have an auth cookie:
- /unsecured/app-unauthenticated.bundle.js
- /secured/app-area1.bundle.js
- /secured/app-area2.bundle.js

You would need to look into code splitting and lazy loading. In your app you can control when dynamic inports occur, so your code would never request secured bundles when the user is unauthenticated.
AUTHORIZATION CHECKS
If you are concerned about a hacker accessing your JS bundles outside of your own code, as for my bundle above, then you could secure access to bundle files by checking for cookies, or even going so far as checking claims in underlying OAuth access tokens, though I would not do any of this.
My web host is the AWS Cloudfront Content Delivery Network (CDN), where Lambda Edge Extensions can run code before assets are served. Currently the only role of my lambda edge code is to serve a default document and issue recommended web security headers.
This code could be updated to make the same cookie checks as API gateway code, eg to return a 401 JSON response if it a valid cookie was not supplied. It would add considerable complexity though, and it is more standard to ensure at design time that UI code does not need securing.
SUMMARY
SPA security architecture is done best by separating web and API concerns. Personally I would put all my security efforts into securing APIs, and stick to obfuscation for Javascript.


text:
Q: Get names and values from WordPress options In my functions.php file I've created an options page for WordPress admin which is working fine.
I've got a bunch of fields and I can retrieve the values that are saved and display them on my options page, like this one for example:
$options = get_option( 'flight_settings' );
<input name="passenger_name" value="<?php if($options['passenger_name']) { echo esc_attr_e( $options['passenger_name'] ); } ?>" />

But now I need to take it further and I've hit a road block.
Using this method I can now create additional fields, which can be spawned like...
<input name="passenger_name_1" id="passenger_name_1" value="" />
<input name="passenger_name_2" id="passenger_name_2" value="" />
<input name="passenger_name_3" id="passenger_name_3" value="" />

...and so on, which no limit to how many additional fields you can spawn. This works perfectly fine and when I save the settings the data is being stored in the database (in "flight_settings" option_name with all the correct option values.)
The Actual Problem
The problem I now have is how do I retrieve the stored values without knowing exactly what I'm looking for? With just a single field it's easy because I know the exact name of what I'm looking for (passenger_name for example as mentioned above).
But if 20 fields were spawned and saved, then ideally I would see all 20 fields displayed on my options page.
I'm guessing the answer is something along the lines of a custom loop that looks for all option field names that are similar to passenger_name. But maybe I'm nowhere near on the right track?
Thanks in advance.

A: Use an array. If you use the name passenger_name[] for each of your fields, you will get a $_REQUEST['passenger_name'] variable in the backend that is an array. Simply loop through this array.
This will both simplify what you need to do to spawn an endless amount of such fields, and make it trivial to retrieve their values.


text:
Q: Importing textscan I have a large CSV data and I tried to import using textscan. The data has some letters NA in the inside the data. I used the following script, however out of 215842 rows only 11 are recognized. The data importing stopped at row where it encouter the NA text.
How could I convert this data to NaN before importing to matlab or other alternative to that might work?
field=fopen ('wt01.csv');

  wt_data= textscan (field,' %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f ','delimiter',',');

fclose (field);

A: You can do this using the TreatAsEmpty option, like wt_data= textscan(fid,' %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f ','delimiter',',','TreatAsEmpty',{'NA','na'});
See http://de.mathworks.com/help/matlab/ref/textscan.html
Or use uiimport as it will give you nice buttons to press, including what to do with data that doesn't match the ideal format, and later allow you to generate a script from it, so that you can reuse it.


text:
Q: error: class HackerRank is public, should be declared in a file named HackerRank.java While submitting code on HackerRank, I am getting this compilation error:

error: class HackerRank is public, should be declared in a file named HackerRank.java

How can I get rid of it? I have tried changing the name of the class to main, but still it gives me the same compilation error.
import java.io.IOException;
import java.util.Scanner;

public class HackerRank {
    public static void main(String a[]) throws IOException, Exception {
        Scanner in = new Scanner (System.in);
        int test = in.nextInt();
        Scanner in1 = new Scanner(System.in);
        if (test < 1 || test > 10) {
            throw new Exception("Illegal test cases");
        }
        while (test-- > 0) {
            // System.out.println("Enter patient dna");
            String patient = in1.nextLine().toLowerCase();
            // System.out.println("Enter virus dna");
            String virus = in1.nextLine().toLowerCase();
            int l = virus.length();
            int i = 0;
            int count = 0;
            if (patient.length() > 100000 || virus.length() > 100000) {
                throw new Exception("Input length out of bounds");
            }
            for (i = 0; i < patient.length() - virus.length(); i++) {
                String sub = patient.substring(i, i + l);
                count = 0;
                for (int j = 0; j < sub.length(); j++) {
                    if (virus.charAt(j) != sub.charAt(j)) {
                        count++;
                    }
                }
                if (count == 0 || count == 1) {
                    System.out.print(i + " ");
                }
            }
            System.out.println();
        }
    }
}

A: Only one class can be declared public within a file and his name must coincide with the file name ( without the extension ).
Try renaming your file to HackerRank.java.
Alternatively, you can change your public class' name:
public class YourFileName{
    ...
}

A: Java requires that each public class have its own file, and that the name of the file match the name of the public class it contains. If your file is not called "HackerRank.java", try renaming it to that and see if your error goes away.

A: The problem you are facing may be for this two reasons

*

*Your class HackerRank is public so may be your file name is not the same as your class name. Your file name must be HackerRank.java

*Or may be you have two classes in the same file and both are public.

A: Name your class as Solution, hackerrank provides an environment as specified in this link.
import java.io.IOException;
import java.util.Scanner;

public class Solution {
    ...
}


text:
Q: how to solve value error x must be 1d pie chart Using fifa 2018 data to plot a preferred foot pie chart. initialized left and right, getting error when calling them in plt.
left = fifa.loc[fifa['Preferred Foot'] == 'Left'].count(0)
right = fifa.loc[fifa['Preferred Foot'] == 'Right'].count(0)
print(left[0])
print(right[0])

plt.pie(x=[left,right])
plt.show()


text:
Q: jquery increment var name (think vars are getting overwritten) I think i know why I'm getting my problem but i don't know enough about jquery to fix it.
I'm connecting to database for a list of products and if there's more than one with the same itemid, i call a javascript function.  It is the same function but i added some bits to make it unique so i can get the right prices etc, but this one javascript variable/array is always the same and i think it's overwriting the previously declared var.
The link to my page is http://www.operationbraveheart.org.uk/jcart/testshop.php
I think it's to do with this line or could it be to do with a lot of the vars getting overwitten?
var price = item_prices_by_size[size].Price,

I had a theory that if i increment the varname so instead of var form, i get var form1
Here is my jquery function
<script type="text/javascript">
    var item_prices_by_size = <?php
    $blah=1;
    echo '{ ';
    foreach($subitem AS $subsubitem) {
        if($subsubitem['size'] != 'X-Large') {
            echo '"'.$subsubitem['size'].'": { "Price": "'.$subsubitem['price'].'", "ItemId": "'.$subsubitem['itemid'].'-'.$blah.'" },';
        }
        else {
            echo '"'.$subsubitem['size'].'": { "Price": "'.$subsubitem['price'].'", "ItemId": "'.$subsubitem['itemid'].'-'.$blah.'" }';
        }
        $blah++;
    }
    echo'};';
    ?>

    $(function() {

        $('#foo<?php echo $subitem[0]["prodid"] ?>').change(function() {

        var form = $(this).parents('form');

        // Size is whatever the value the user has selected
        var size = $(this).val();

        // Determine the correct price and item ID based on the selected size
        var price = item_prices_by_size[size].Price,
        itemId = item_prices_by_size[size].ItemId;

        form.find('#price<?php echo $subitem[0]['prodid'] ?>').text(price);

        form.find('[name=my-item-price]').val(price);

        // Update the item ID
        form.find('[name=my-item-id]').val(itemId);

        });
    });
</script>

A: I just had to change some of the var names using php as expected the var values were getting replaced by the next form being displayed.
There was no way of finding which var belonged to which form.
Working code now.
<script type="text/javascript">
                    var item_prices_by_size<?php echo $subitem[0]["prodid"] ?> = <?php
                        $blah=1;
                        echo '{ ';
                        foreach($subitem AS $subsubitem) {
                            if($subsubitem['size'] != 'X-Large') {
                                echo '"'.$subsubitem['size'].'": { "Price": "'.$subsubitem['price'].'", "ItemId": "'.$subsubitem['itemid'].'-'.$blah.'" },';
                            }
                            else {
                                echo '"'.$subsubitem['size'].'": { "Price": "'.$subsubitem['price'].'", "ItemId": "'.$subsubitem['itemid'].'-'.$blah.'" }';
                            }
                            $blah++;
                        }
                        echo'};';
                        ?>

        $(function() {

            $('#foo<?php echo $subitem[0]["prodid"] ?>').change(function() {

              var form = $(this).parents('form');

                // Size is whatever the value the user has selected
                var size = $(this).val();

                // Determine the correct price and item ID based on the selected size
                var price<?php echo $subitem[0]["prodid"] ?>  = item_prices_by_size<?php echo $subitem[0]["prodid"] ?>[size].Price,
                    itemId = item_prices_by_size<?php echo $subitem[0]["prodid"] ?>[size].ItemId;

                form.find('#price<?php echo $subitem[0]['prodid'] ?>').text(price<?php echo $subitem[0]["prodid"] ?>);

                form.find('[name=my-item-price]').val(price<?php echo $subitem[0]["prodid"] ?>);

              // Update the item ID
              form.find('[name=my-item-id]').val(itemId);

            });
        });
            </script>


text:
Q: Field at symmetrical axis Whenever we calculate field due to a wire with uniform charge density $\lambda$, we take a point in the middle and choose two elements. We take the field elements and find their components. One of the components cancel each other. Then we add all $x$-components by integration. It comes as $$E=\left(\frac14\pi\epsilon_0\right)\frac{2\lambda}{R^2}$$
I want to ask: Will the value of $E$ still be the same if we measure it somewhere else not at a point of symmetry. I know we do things like this to make the math easier. Will the value of $E$ be same everywhere if we calculate it?

Like this diagram will help. Why have we chosen a point p like that. We can also take a point anywhere else and try to find it. So why always in the middle? A point somewhere above the P. Will $E$ still be the same?

A: Yes,  the field had different values (and directions) in different points around the wire.  In points off the symmetry axis the field has y component too.  The integral will be more tedious to calculate so the introductory textbooks use the symmetric case as an example.

A: You might be misunderstanding why two points are chosen.
I presume this is calculating the E field from a charged wire.
To calculate the field from the wire, you have to add up (integrate) contributions from all parts of the wire, not just A and B. You can add them up one by one and calculate the vector E field from each. If you do, you will add many vectors pointing in many directions. You can do the sum. You will find the sum points directly away from the wire.
Adding pairs of elements just makes the calculation easier. Look at all the pieces of wire in the bottom half. Each piece has a similar piece in the top half. For example, given A, you can find B that is symmetrically placed.
If you calculate the E field from A, you will find the E field from B has the same magnitude because it has the same charge and distance. You will find it is at the same angle as the field from A. From this, you can conclude that the upward component from A is the same size as the downward component from B, and these components cancel.
By the same argument, the upward/downward components from every pair of pieces of wire cancel. You don't have to go to the trouble of calculating these components and adding them to find they are $0$. You know it from this symmetry argument. You conclude the total E field is the of components that point directly away from the wire. The total field must point directly away from the wire.
It doesn't matter where you choose your point P. You can still choose wire pieces in pairs and make the same argument. The field everywhere points directly away from the wire.
If you choose points P$_1$ and P$_2$ the same distance from the wire, you can do the calculation for both. The calculations would be identical at every step. You would get the same answer. This is another symmetry argument. It shows the E field has the same strength at every point the same distance from the wire.
Symmetry arguments are very useful in physics.

A: By "wire", do you mean a line of charge?
If yes, this should help. And if that is the case, your formula for $E$ looks sus.
As you can see in the link, it is not necessary to take the middle point and it is possible to take any point.


text:
Q: Rails better way to get item by field from has_many association Forgive me if this is a basic question; I'm learning Rails (using 3.2) as I go.
My Event model has_many images. Each image has an is_primary boolean field. Event should have a cover_image method, which returns the image with is_primary set to true, or the first image otherwise. This is my code:
def cover_image
    imgs = self.images
    imgs.each { |i| return i if i.is_primary }
    # If no primary
    return imgs.first
  end

I can't help feeling like there's a better way to do it, one that doesn't involve looping through all the elements just to find one.

A: You could do this with a scope quite easily:
Image model
scope :primary, where(:is_primary => true)

Event model
def cover_image
  images.primary.first
end

This is a really basic example that should get you started at least, you'll want to build on it to handle a missing primary image gracefully, for example.
For completeness, you don't have to do this as a scope, if you'd prefer you can use where statements directly. Scopes are just really nice for staying DRY:
Event model
def cover_image
  images.where(:is_primary => true).first
end


text:
Q: printing columns from all queries into one i have 2 groupby queries,each counts rows for each compnay_id, both grouped by company_id.
i need to output one query that will print column qty1, qty2, company_id
union doesnt work for me:
select count(*) as qty1
from T_MISSION
where datepart(month, [mdatetime])=12
group by  company_id

union all

select count(*) as qty2
from T_CUSTSK
where datepart(month, [sdate])=12
group by  company_id

A: I'm not a expert in SQL but would LEFT JOIN work for you?
https://www.w3schools.com/sql/sql_join_left.asp

A: A simple solution would be:
select sum(qty1), sum(qty2), company_id
from
(
 select count(*) as qty1, 0 as qty2, company_id
 from T_MISSION
 where datepart(month, [mdatetime])=12
 group by  company_id

 union all

 select 0 as qty1, count(*) as qty2, company_id
 from T_CUSTSK
 where datepart(month, [sdate])=12
 group by  company_id
) as combined
group by company_id

The idea: Use a separate column for each value. Set all other columns to 0 per each data collection so they do not mix up strangely. Finally sum them all up (per customer) so there is exactly one value per column and customer, as all others are 0 by definition.
This little trick allows for mixing otherwise unrelated data.


text:
Q: Access changes table Relationships by itself I am struggling with an issue in designing my Access database.
I am a caregiver, and part of my job is taking clients out into the community. I am attempting to build a catalog of outings to help the employees at our company come up with and store ideas for these. I want to store information for each of up to 5 types of events that clients can do at a location. That information includes the event type, when it runs and doesn't, and how much it'll cost, all of which would be user-selectable. (Separately in the same table, I want to include contact information and information that helps the user search for event locations, such as the ZIP code.) I have attempted to normalize the database by spreading event information across fields in the main table, linked to lookup tables. I am aware that Access has a limit of 32 relationships per table.
To help staff find event types, I am trying to set up a method for categorizing them. That requires setting up nested lookup tables, as shown in the first picture.
 If I understand correctly, the additional "copies" of those lookup tables are aliases. When I save the setup for the relationships between those aliased lookup tables, close the Relationships window, and open it again, I find Access has changed them, as shown in the second picture.  This happens whether I delete the lookup table information for each field in Datasheet View. I don't understand why it does this or how to fix it.

A: To answer your question:
In the object browser I see that you have only one table: t_OutingType. Therefore, the "tables" t_OutingType_2, t_OutingType_3 are just aliases; "pointers" to the same table (like a shortcut to a document). When you save the relationships and close the window, the relationship information is written to the metadata of the database. When you re-open the Relationships window Access re-builds the relationship diagram from the metadata, and it does not include the redundant aliases.
Additional advice:
Whenever you find yourself duplicating columns in a table, e.g., Event_1, Event_2, ... a little voice in your head should start shouting "Are you sure that's a good idea?" Imagine if you want to search the database for events that fall on a certain date. With the table layout described above you would need to ...
SELECT ... WHERE EventDate_1 = [theDate] OR EventDate_2 = [theDate] OR EventDate_3 = [theDate] ...

It's almost always better to split the Event information into a separate child table and maintain an association table between the child table and its parent.


text:
Q: Get text from inside custom component tag I'm trying to get the text (with html-tags and all) that gets added in a custom component in the component itself. That way I can show it in the correct spot.
I'm not sure if it can be done, but I don't see an alternative.
Page
<detail [content]="content" [image]="'animals.jpg'">

Item 1

Item 2

Item 3

.ts-file of component
export class DetailComponent
{
  @Input() content: Content;
  @Input() image:   string;

  constructor()
  {

  }
}

How can I get the 'ul' and it's children in the code of the component so I can show it in a specific spot?
Passing text through a property would make it lose it's structure.
I've tried via ElementRef, but I only get the detail-tag through nativeElement, not it's children.

A: @proti's answer was on the right track. However, since the template you need is inside (assuming there is the closing tag of </detail> after the
 tag) the
`<detail><!-- Content Needed --></detail>`

you have to use @ContentChild instead of @ViewChild.
Then you can capture the 'contents' in your component in the ngAfterContentInit() life-cycle hook.
The template,
<detail [content]="content" [image]="'animals.jpg'">

Item 1

Item 2

Item 3

</detail>

In the component class,
@ContentChild('content') elemRef: ElementRef;

ngAfterContentInit() {
 // treat this.elemRef as a ElementRef type variable and do whatever you want to do with it
}

ElementRef is imported from @angular/core

A: You can do that like that:
Set variable in HTML template for
 e.g. #myUlVar
Get it in TS using @ViewChild
<detail [content]="content" [image]="'animals.jpg'">

Item 1

Item 2

Item 3

export class DetailComponent
{
  @Input() content: Content;
  @Input() image:   string;
  @ViewChild('myUlVar') ul: HTMLElement;
  constructor()
  {

  }
}

or read more here:
http://learnangular2.com/viewChild/


text:
Q: mathematica package new style: a few beginner questions I have got a code made of several .m files, and I would like to turn it into a package. I have a few beginner questions

*

*Can I force the loading order of the files by adding all of them in the init.m file?

*How can I access global variables from the package? For example, I could like to define a couple of variables that are settings used by the package. I usually do it in my main notebook, before loading the .m files with all functions. But as far as I understand, if I define it in the notebook variables will be in namespace global, and using the same variable in the package will instead search for the local variable. If I prepend Global`  to the variable in the package, will it be able to find it?

*I have a very long settings file where I store most settings that I change very rarely. Now, these are  one of the few things that actually needs to get shared in between all of the package fragments. As far as I understood one needs to write
PackageScope[variable]

for each variable one wants to share. Is there any way to automatise this for all variables in the file?

A: Here are some answers

*

*That's a bad idea, and here is why: what will actually happen if you do
Get["YourPackage`FirstFragment`"]
...
Get["YourPackage`LastFragment`"]

is that the loader will effectively (re)load all fragments as many times, as there are fragments. That's just how it works.
The better options are:

*

*Pick one fragment, which will serve as the initialization fragment, and call Get on it in init.m - this will prompt all fragments to load, but this one will be guaranteed to load first. And restructure your code in such a way that the loading order of other fragments does not matter.
I think this is the best option, since in practice I have never seen the case where this could not be done, and OTOH, the dependence on the loading order for several files may indicate a fragile and insufficiently thought out design.

*Rename your fragments, adding letters A, B etc. at the beginning of fragment names, so that the alphabetical order of new names will be the loading order you want. This should work, since the loader loads fragments in alphabetical order, except the one that has been explicitly used in Get always loads first.

*You surely can access global variables by using the long symbol names, as you suggested, like Global`someGlobalVar. I would however strongly discourage that, apart possibly from a testing stage, since this would make your package not self-contained, and will pollute the Global`  namespace for no good reason.
Instead, why don't you simply declare those variables in your package's main context? You can do this in your initialization fragment, like e.g.
PackageExport["MyGlobalVar"]
PackageExport["MyOtherGlobalVar"]
...

And then assign them some initial values there, and use them both from within your package, and from the outside. This is what I've been doing all the time.

*Unfortunately, I don't know of a good way to do this, given that directives like PackageScope are not normal WL symbols or functions, but rather tokens for the parser / loader. So they have to be present verbatim, and before the code loading actually happens, since they are processed in a separate pass, before any code is evaluated.
The only possible option I can imagine here would be to have some build step / build process for your app, where you could have a separate file containing those definitions, which would be automatically generated from a more concise spec.


text:
Q: Converting char into NSString I am having trouble converting arguments to NSString format for my Cocoa application. I start my application like so:
open my.app --args a1 a2

I try to access the arguments like so:
const char *h_path_char = [[[[NSProcessInfo processInfo] arguments] objectAtIndex:1] fileSystemRepresentation];
const char *s_path_char = [[[[NSProcessInfo processInfo] arguments] objectAtIndex:2] fileSystemRepresentation];

NSString *h_path = [NSString stringWithUTF8String:h_path_char];
NSString *s_path = [NSString stringWithUTF8String:s_path_char];

NSLog(@"%s", h_path);
NSLog(@"%s", s_path);

However, Xcode complains about the NSLog with the following warning:

Conversion specifies type "char" but the argument has type "NSString".

How can I overcome this?

A: %s is meant for C strings. You should use %@ instead of %s to output NSString (and other Foundation types) to NSLog.


text:
Q: MAUI WebView GeolocationEnabled I'm trying to use maui webView to load a map.
how to use  navigator.geolocation.getCurrentPosition to get location?
Android and kotlin has the same implementation。

A: You and use the code to get the location:
private CancellationTokenSource _cancelTokenSource;
private bool _isCheckingLocation;

public async Task GetCurrentLocation()
{
    try
    {
        _isCheckingLocation = true;

        GeolocationRequest request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));

        _cancelTokenSource = new CancellationTokenSource();

        Location location = await Geolocation.Default.GetLocationAsync(request, _cancelTokenSource.Token);

        if (location != null)
            Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
    }

    catch (Exception ex)
    {
        // Unable to get location
    }
    finally
    {
        _isCheckingLocation = false;
    }
}

public void CancelRequest()
{
    if (_isCheckingLocation && _cancelTokenSource != null && _cancelTokenSource.IsCancellationRequested == false)
        _cancelTokenSource.Cancel();
}

Here is the website which you can refer to: https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/device/geolocation?tabs=ios


text:
Q: Android TTS - ACTION_CHECK_TTS_DATA default engine In my app (Android API 10) I use the standard way to check if the TTS engine and voice are available:
Intent checkIntent = new Intent();
checkIntent.setAction( TextToSpeech.Engine.ACTION_CHECK_TTS_DATA );
startActivityForResult( checkIntent, CHECK_TTS_DATA );

In a device with more than a TTS engine Android asks to select one ("complete action using...")
Is there a way to check ACTION_CHECK_TTS_DATA using the default TTS engine (to avoid the engine selection dialog) ?
Or ... how do I get the user selected TTS engine (to use it with setEngineByPackageName() (API 10)) ?

A: There are a few ways you can do this. To get the default TTS Engine, check in the onInit Listener:
TextToSpeech tts = new TextToSpeech(context, onInitListener);

    @Override
        public void onInit(final int status) {

            switch (status) {

            case TextToSpeech.SUCCESS:

                try {

                    final String initEngine = tts.getDefaultEngine();

    // Check it's != null before doing anything with it.

                } catch (final Exception e) {

                }

        break;
    }
}

The try/catch block is there as I've had crashes for some IVONA and SVOX TTS engines.
Once you have the package name, you can then query the intent activities and if necessary use a custom chooser or limit the intent to just the package name you got from above.
    private void getEngines(String initEngine) {

        Intent ttsIntent = new Intent();
        ttsIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);

        PackageManager pm = getPackageManager();

        List<ResolveInfo> list = pm.queryIntentActivities(ttsIntent,
                PackageManager.GET_META_DATA);

        for (ResolveInfo appInfo : list) {

// Might want a null check in here

            if(appInfo.activityInfo.applicationInfo.packageName.matches(initEngine) {

            ttsIntent
                    .setPackage(appInfo.activityInfo.applicationInfo.packageName);
        }

            startActivityForResult(ttsIntent, 33);

        }
    }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 33 && data != null) {

       // do something
    }
}

I've not tested the above, but I'm sure you can build on it to get it to do what you want.