text:
Q: How to format SQL statements in perl (code-style) I'd like to please perlcritic and have easy to read SQL queries in my code. Currently this is how I do it:
if (defined $dbh) {
    $sth = $dbh->prepare(<<'SQL'
SELECT firstname, lastname, email, country
FROM Person
JOIN Country ON Person.countryID = Country.ID
WHERE age = ?
  AND sex = ?
LIMIT 100
SQL
    );
}

The statement is not indented at all which makes it pop if the context is indented. I find this nice since it makes it easy to spot the statement and they're split into several lines to make them easy to read.
However, if the context is not indented this looks really messy. And if possible I don't like to introduce newlines or unnecessary white spaces in my stmt. Also SQL at the end of the stmt and the dangling ); is not nice either.
Please suggest a good style guide on this matter that I can adopt.

A: I'd recommend removing all SQL from your program completely by switching to DBIx::Class. If that's a little scary, then perhaps a halfway house like Data::Phrasebook::SQL.
In general, having raw SQL statements in your Perl code is a pretty bad idea.


text:
Q: Multiple paamayim nekudotayims in PHP, why not? In PHP 5.3.6, I've noticed that the following won't work:
class Foo{
    public static $class = 'Bar';
}

class Bar{
    public static function sayHello(){
        echo 'Hello World';
    }
}

Foo::$class::sayHello();

Issuing an unexpected T_PAAMAYIM_NEKUDOTAYIM. Using a temporary variable however, results in the expected:
$class = Foo::$class;
$class::sayHello(); // Hello World

Does anyone know if this is by design, or an unintended result of how the scope resolution operator is tokenized or something? Any cleaner workarounds than the latter, temporary variable example?

A: Unfortunately there is no way to do it in one line. I thought you might be able to do it with call_user_func(), but no go:
call_user_func(Foo::$class.'::sayHello()');
// Warning: call_user_func() expects parameter 1 to be a valid callback, class 'Bar' does not have a method 'sayHello()'

Also, why would you want to do something like this in the first place? I'm sure there must be a better way to do what you're trying to do - there usually is if you're using variable variables or class names.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Modify a Text inside a composite in Java SWT To choose a file and save the filepath I have the following code:
case FILE :
      final Composite fileBaseComposite = new Composite(table, SWT.BORDER);
      fileBaseComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
      final GridLayout fileBaseCompositeGridLayout = new GridLayout(2, false);
      fileBaseCompositeGridLayout.marginHeight = 0;
      fileBaseCompositeGridLayout.marginWidth = 0;
      fileBaseComposite.setLayout(fileBaseCompositeGridLayout);

      final Text selectFiletext = new Text(fileBaseComposite, SWT.SINGLE);
      selectFiletext.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
      selectFiletext.setText(aCurrentContent);
      selectFiletext.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent e)
        {
          Text text = (Text)tableEditor.getEditor();
          tableEditor.getItem().setText(ARGUMENT_VALUE_COLUMN, text.getText());
        }
      });

      final Button selectFileButton = new Button(fileBaseComposite, SWT.NONE);
      selectFileButton.setText("Browse");
    selectFileButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true));
    selectFileButton.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e)
      {
        FileDialog fileSelectDialog = new FileDialog(fileBaseComposite.getShell(), SWT.OPEN);
        fileSelectDialog.setText("Select File");

        // String is saved separately because otherwise it opens twice
        String filePath = fileSelectDialog.open();
        if (filePath != null) {
          selectFiletext.setText(filePath);
          tableEditor.getItem().setText(ARGUMENT_VALUE_COLUMN, filePath);
        }
      }
    });
    return fileBaseComposite;

when I try to modify the text manually, I've got a problem with the following error message:
java.lang.ClassCastException: org.eclipse.swt.widgets.Composite cannot be cast to org.eclipse.swt.widgets.Text

I understand the issue but cant find a solution. Is there a possibility to get the text inside the composite?
I want a text and a button in one table cell. The text should be editable manually and readable to safe it.

A: selectDirectoryText.addModifyListener(new ModifyListener() {
      @Override
      public void modifyText(ModifyEvent e)
      {
        Composite comp = (Composite)tableEditor.getEditor();
        Text text = (Text)comp.getChildren()[0];
        tableEditor.getItem().setText(ARGUMENT_VALUE_COLUMN, text.getText());
      }
    });

thats the solution..
I wanted to cast the Composite directly to a Text.


text:
Q: How to find DISTINCT Combinations? There are 3 tables :
CREATE TABLE Employee(
  EID mediumint PRIMARY KEY AUTO_INCREMENT,
  EName varchar(100) DEFAULT NULL,
  EPincode mediumint unsigned NULL
);

EID is the Employee-Id of each Employee which is unique;
CREATE TABLE Project(
  PID mediumint PRIMARY KEY AUTO_INCREMENT,
  PName varchar(30) DEFAULT NULL,
  MID mediumint UNIQUE NOT NULL,
  FOREIGN KEY (MID) REFERENCES Employee(EID)
);

MID is the Manager-Id of an Employee who is heading the Project.
CREATE TABLE Works_On(
  EID mediumint NOT NULL,
  PID mediumint NOT NULL,
  FOREIGN KEY (EID) REFERENCES Employee(EID),
  FOREIGN KEY (PID) REFERENCES Project(PID)
);

This table consist of all the Employees and Their Associated Project.

An Employee can work on multiple Projects. A Project can be done by
  multiple Employees. Each Project has a Manager. A Manager can have one
  or more employees under him.

I want to find a table consisting of Employee Name, Project Name and Manager Name. Please help.
This is the query I have written so far but its not working :
SELECT DISTINCT A.EName AS "Employee Name"
               ,A.PName AS "Project Name"
               ,B.EName AS "Manager Name"
FROM (SELECT P.PName
            ,E.EName
      from Works_On W
      NATURAL JOIN Project P
      NATURAL JOIN Employee E) A,
(SELECT E.EName
 from Project P
 INNER JOIN Employee E ON P.MID = E.EID) B

A: SELECT P.PName AS ProjectName,
       M.EName AS ManagerName,
       E.EName AS EmployeeName
FROM Project P
     LEFT JOIN Employee M ON (P.MID=M.EID)
     LEFT JOIN Works_On WO on (P.PID=WO.PID)
     LEFT JOIN Employee E on (E.EID=WO.EID);

It worked.

A: You can try below query -
SELECT
    E.EName,
    P.PName,
    M.EName
FROM Employee E
    INNER JOIN Employee M ON M.EID = E.EID
    INNER JOIN Project P ON E.EID = P.MID
    INNER JOIN Works_On W ON W.EID = E.EID AND W.PID = P.PID

This might help you.

A: select A.Employee_name,
       A.project_name,
       B.manager_name  from
      (
        SELECT
        P.PName AS project_name,
        E.EName AS Employee_name,
        E.EID,P.PID
        FROM Works_On W
        INNER JOIN Project P ON W.PID = P.PID
        INNER JOIN Employee E ON W.EID = E.EID

        ) as A

       left join
       (

        SELECT
        E.EName AS manager_name,
        E.EID,P.PID
        FROM Project P
        INNER JOIN Employee E ON P.MID = E.EID

        ) B on A.PID=B.PID


text:
Q: How to merge sqlite3 session extension sessions? I'm using the c API of the sqlite3 session extension and wondering if the session extension can be used to merge sqlite3 sessions that already have been written to file.
Following the tutorial referenced above I was able to register sqlite3 sessions by writing them to file one by one, e.g. for an UPDATE call I end up with a session file, and with another INSERT call I get another file, and so on. These transactions are triggered by UI button callbacks. I wonder if the session files could be somehow merged afterwards into one single session file, so that calling sqlite3changeset_apply() with this merged session file as its parameter I could end up with the same result as if I called sqlite3changeset_apply() on a list of session files. The reason I would like to do this is that I'd like to transfer only one session file instead of a folder of session files.
I tried iterating over a session list calling subsequent sqlite3changeset_apply() on a copy of the original database while registering the session, but in that I case I eventually get a session file with zero size (although the copy database would contain all the expected changes).
I could not find anything on this in the official documentation nor on the web.

A: ♀♂ necromancy alert ♂♀
You're probably looking for the sqlite3changeset_concat function:

This function is used to concatenate two changesets, A and B, into a single changeset. The result is a changeset equivalent to applying changeset A followed by changeset B.

There is also a streaming version, sqlite3changeset_concat_strm.
If you need to combine many changesets, you can use the type sqlite3_changegroup and its associated functions.


text:
Q: Join keys and values from Dictionary Is there a way to quickly (i.e. without using foreach) concat the following Dictionary:
Dictionary<string, string> g = new Dictionary<string, string>();
g.Add("K", "k1");
g.Add("L", "l1");

into
"K=@K,L=@L"

and what about getting this result: "K=k1,L=l1" ?
I am playing a little with String.Join, but that doesn't seem to do what I want.
Some background: I have a list of key/value pairs I want to either INSERT in my database (...keys...) VALUES (...values...) or UPDATE a records ...,key=value, ....

A: You can do this fairly easily with LINQ, it still is using foreach under the covers so it won't be any "faster" but it should be easy to read.
Dictionary<string, string> g = new Dictionary<string, string>();
g.Add("K", "k1");
g.Add("L", "l1");

var keys1 = g.Select(x=>String.Format("{0}=@{0}", x.Key));
var result1 = String.Join(",", keys1);
Console.WriteLine(result1);

var keys2 = g.Select(x=>String.Format("{0}={1}", x.Key, x.Value));
var result2 = String.Join(",", keys2);
Console.WriteLine(result2);

Run Code
The first thing we do is we make a IEnumerable<String> of the items we want, we then use string.Join to combine that IEnumerable in to a single string.
EDIT:
If you are updating in to a database I recommend dropping this approach and try out some ORM libraries like Entity Framework or NHibernate. They do all this work for you and make it much easier to work with objects and not worry about generating dynamic queries.

A: The shortest code I can think of is
string res = string.Join("\n", g.Select(p => "K=" + p.Key + ",L=" + p.Value));

This results in
K=K,L=k1
K=L,L=l1

A: You could use an extension class on the dictionary as well.  This runs the same but then lets you do something simple like
g.ToKeyValueString("{0}=@{1}", ",");

The Helper class
internal static class DictionaryHelper
{
    /// <summary>
    /// Returns a string of key value pairs in the format k1=v1,k2=v2,...
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="dictionary"></param>
    /// <returns></returns>
    public static string ToKeyValueString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary)
    {
        return ToKeyValueString(dictionary, "{0}={1}", ",");
    }

    /// <summary>
    /// Returns a string of key value paris in the format k1=v1{separator}kk2=v2...
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="dictionary"></param>
    /// <param name="seperator">The string separator for the pairs</param>
    /// <returns></returns>
    public static string ToKeyValueString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string seperator)
    {
        return ToKeyValueString(dictionary, "{0}={1}", seperator);
    }

    /// <summary>
    /// Returns a string of key value pairs in the specified format with the specified separator
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="dictionary"></param>
    /// <param name="format">The format string for the key value pairs</param>
    /// <param name="separator">The string separator for the pairs</param>
    /// <returns></returns>
    public static string ToKeyValueString<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, string format, string separator)
    {
        var pairs = dictionary.Select(c => string.Format(format, c.Key, c.Value));
        return string.Join(separator, pairs);
    }
}


text:
Q: handleInputChange - React Redux File Upload I am trying to upload a file and update the state with the file object that was uploaded.
The console logs after setState show the state has not been updated.
Anytime I try to console.log the event for the file upload onChange I get a circular JSON reference and if I try to log event.target I get undefined.
How do I write the uploaded file to the state?
import React, { Component } from "react";
import { connect } from "react-redux";
import Button from "@material-ui/core/Button";

class FileUpload extends Component {

  state = {
    myPicture: {}
  };

  handleInputChange = (event) => {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });

    console.log(JSON.stringify(this.state))
    console.log(JSON.stringify(this.props))

  }

  render() {
    const {myPicture} = this.props;

    return (
      <div>

        {JSON.stringify(this.state.myPicture)}

        <input
          accept="image/*"
          className={"fileInput"}
          id="myPicture"
          multiple
          type="file"
          onChange={this.handleInputChange}
        />
        <label htmlFor="myPicture">
          <Button variant="contained" color="primary" component="span">
            Upload Picture
          </Button>
        </label>
        </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    myPicture: state.auth.myPicture,
  };
}

export default connect(mapStateToProps)(FileUpload);

A: You cannot directly reference the array of files or the file itself.
You must reference specific keys from the event.target.files[0].
Example after file upload:

*

*Ex: JSON.stringify(event.target.files[0]) === {}

*Ex:    JSON.stringify(event.target.files[0].name ===
'myFileNameHere'


text:
Q: PHP8.1 FPM Crashes everyday after 12AM From the last two to three days I noticed that my PHP8.1-FPM process crashes after around 12:00 AM-12:30 AM at night.
My server has highest traffic in morning and lowest in night. But FPM process runs fine for whole day and crashes on night. This is very strange.
Here is what I found in logs:
DAY 1
[05-Dec-2022 00:19:47] NOTICE: [pool www] child 10868 started
[05-Dec-2022 00:25:02] NOTICE: [pool www] child 9967 exited with code 0 after 7446.963850 seconds from start
[05-Dec-2022 00:25:02] NOTICE: [pool www] child 10871 started
[05-Dec-2022 00:27:37] NOTICE: [pool www] child 9969 exited with code 0 after 7433.300005 seconds from start
[05-Dec-2022 00:27:37] NOTICE: [pool www] child 10872 started
[05-Dec-2022 00:32:41] WARNING: [pool www] child 10194 exited on signal 9 (SIGKILL) after 5713.957769 seconds from start
[05-Dec-2022 00:32:41] NOTICE: [pool www] child 10876 started
[05-Dec-2022 00:32:41] NOTICE: Terminating ...
[05-Dec-2022 00:32:41] NOTICE: exiting, bye-bye!

DAY 2
[05-Dec-2022 22:42:26] NOTICE: [pool www] child 23687 started
[05-Dec-2022 22:42:26] NOTICE: [pool www] child 21662 exited with code 0 after 11118.073861 seconds from start
[05-Dec-2022 22:42:26] NOTICE: [pool www] child 23688 started
[05-Dec-2022 22:42:31] NOTICE: [pool www] child 21663 exited with code 0 after 11071.941161 seconds from start
[05-Dec-2022 22:42:31] NOTICE: [pool www] child 23689 started
[05-Dec-2022 22:42:41] NOTICE: [pool www] child 21664 exited with code 0 after 11046.438863 seconds from start
[05-Dec-2022 22:42:41] NOTICE: [pool www] child 23690 started
[05-Dec-2022 23:31:34] NOTICE: [pool www] child 22058 exited with code 0 after 11163.770384 seconds from start
[05-Dec-2022 23:31:34] NOTICE: [pool www] child 24124 started
[06-Dec-2022 00:09:32] WARNING: [pool www] child 23076 exited on signal 9 (SIGKILL) after 8637.063701 seconds from start
[06-Dec-2022 00:09:32] NOTICE: [pool www] child 24580 started
[06-Dec-2022 00:09:32] WARNING: [pool www] child 23080 exited on signal 9 (SIGKILL) after 8607.986722 seconds from start
[06-Dec-2022 00:09:33] NOTICE: [pool www] child 24581 started
[06-Dec-2022 00:09:33] WARNING: [pool www] child 23089 exited on signal 9 (SIGKILL) after 8507.937877 seconds from start
[06-Dec-2022 00:09:33] NOTICE: [pool www] child 24582 started
[06-Dec-2022 00:09:33] WARNING: [pool www] child 23380 exited on signal 9 (SIGKILL) after 6752.142496 seconds from start
[06-Dec-2022 00:09:33] NOTICE: [pool www] child 24583 started
[06-Dec-2022 00:09:33] WARNING: [pool www] child 23403 exited on signal 9 (SIGKILL) after 6643.858307 seconds from start
[06-Dec-2022 00:09:33] NOTICE: [pool www] child 24584 started
[06-Dec-2022 00:09:33] WARNING: [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers), spawning 8 children, there are 0 idle, and 147 total children
[06-Dec-2022 00:09:33] NOTICE: Terminating ...
[06-Dec-2022 00:09:33] NOTICE: exiting, bye-bye!
[06-Dec-2022 00:23:49] NOTICE: fpm is running, pid 24611
[06-Dec-2022 00:23:49] NOTICE: ready to handle connections
[06-Dec-2022 00:23:49] NOTICE: systemd monitor interval set to 10000ms
[06-Dec-2022 00:23:53] WARNING: [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers), spawning 8 children, there are 59 idle, and 63 total children

Server Configuration
Digitalocean 4 Core AMD CPU 8GB RAM $54 USD basic droplet.
PHP8.1 FPM Settings
pm = dynamic
pm.max_children = 241
pm.start_servers = 60
pm.min_spare_servers = 60
pm.max_spare_servers = 180
pm.max_requests = 500

-- UPDATE
This application is a image server. It serves dynamically resized images from object storage or images from another server. It has very small php script which resizes images and serve them. Nginx is used for caching processed images.
-- UPDATE
dmesg output
[147949.035475] 0 pages in swap cache
[147949.035475] Swap cache stats: add 0, delete 0, find 0/0
[147949.035476] Free swap  = 0kB
[147949.035477] Total swap = 0kB
[147949.035478] 2097014 pages RAM
[147949.035478] 0 pages HighMem/MovableOnly
[147949.035479] 61947 pages reserved
[147949.035480] 0 pages hwpoisoned
[147949.035480] Tasks state (memory values in pages):
[147949.035481] [  pid  ]   uid  tgid total_vm      rss pgtables_bytes swapents oom_score_adj name
[147949.035485] [    380]     0   380     9935      864   106496        0          -250 systemd-journal
[147949.035489] [    417]     0   417    72328     6775   114688        0         -1000 multipathd
[147949.035496] [    539]   103   539    22338      415    73728        0             0 systemd-timesyn
[147949.035498] [    606]   100   606     4029      626    73728        0             0 systemd-network
[147949.035500] [    625]   101   625     6378     1681    94208        0             0 systemd-resolve
[147949.035502] [    650]     0   650     2880     1060    69632        0         -1000 systemd-udevd
[147949.035505] [    747]     0   747     1821      618    57344        0             0 cron
[147949.035506] [    749]   102   749     2191      891    57344        0          -900 dbus-daemon
[147949.035508] [    752]   998   752   345261     1828   208896        0          -900 do-agent
[147949.035511] [    757]     0   757    20699      669    61440        0             0 irqbalance
[147949.035513] [    758]     0   758     8249     2870   102400        0             0 networkd-dispat
[147949.035515] [    767]     0   767    58621      410    81920        0             0 polkitd
[147949.035517] [    768]   104   768    55600     1093    77824        0             0 rsyslogd
[147949.035522] [    771]     0   771   292597     4332   307200        0          -900 snapd
[147949.035524] [    776]     0   776     3873      574    69632        0             0 systemd-logind
[147949.035526] [    778]     0   778    98136     1305   122880        0             0 udisksd
[147949.035529] [    786]     0   786    79236      954   118784        0             0 ModemManager
[147949.035531] [    787]     0   787     1554      192    49152        0             0 agetty
[147949.035534] [    798]     0   798     1543      214    53248        0             0 agetty
[147949.035535] [    826]     0   826     3855     1169    73728        0         -1000 sshd
[147949.035538] [    863]     0   863    27523     2822   114688        0             0 unattended-upgr
[147949.035540] [    904]     0   904    40076     1619   110592        0             0 nginx
[147949.035541] [   1373]     0  1373    73985     1009   163840        0             0 packagekitd
[147949.035544] [   1712]     0  1712   343392      174   180224        0          -900 droplet-agent
[147949.035547] [  12216]     0 12216    53067     2645   151552        0             0 php-fpm8.1
[147949.035549] [  12743]    33 12743    50015    15472   225280        0             0 nginx
[147949.035552] [  12744]    33 12744    51002    16135   233472        0             0 nginx
[147949.035554] [  12745]    33 12745    50614    16019   233472        0             0 nginx
[147949.035556] [  12746]    33 12746    50765    16062   233472        0             0 nginx
[147949.035558] [  12747]    33 12747    40214     5403   147456        0             0 nginx
[147949.035560] [  23025]    33 23025    81250    26391   356352        0             0 php-fpm8.1
[147949.035562] [  23027]    33 23027    63171    13406   245760        0             0 php-fpm8.1
[147949.035564] [  23028]    33 23028    66013    15875   266240        0             0 php-fpm8.1
[147949.035566] [  23029]    33 23029    81755    23040   335872        0             0 php-fpm8.1
[147949.035568] [  23030]    33 23030    81289    25643   352256        0             0 php-fpm8.1
[147949.035570] [  23031]    33 23031    65772    15814   266240        0             0 php-fpm8.1
[147949.035572] [  23032]    33 23032    60680    10956   225280        0             0 php-fpm8.1
[147949.035574] [  23033]    33 23033    81290    22731   327680        0             0 php-fpm8.1
[147949.035576] [  23034]    33 23034    79989    22259   327680        0             0 php-fpm8.1
[147949.035578] [  23035]    33 23035    62802    12404   241664        0             0 php-fpm8.1
[147949.035579] [  23036]    33 23036    81250    22808   327680        0             0 php-fpm8.1
[147949.035581] [  23037]    33 23037    81760    23549   331776        0             0 php-fpm8.1
[147949.035584] [  23038]    33 23038    63141    12398   237568        0             0 php-fpm8.1
[147949.035585] [  23040]    33 23040    65876    16118   266240        0             0 php-fpm8.1
[147949.035588] [  23041]    33 23041    54628     5099   176128        0             0 php-fpm8.1
[147949.035593] [  23042]    33 23042    80737    22410   323584        0             0 php-fpm8.1
[147949.035595] [  23043]    33 23043    63388    12852   245760        0             0 php-fpm8.1
[147949.035596] [  23044]    33 23044    79976    26488   364544        0             0 php-fpm8.1
[147949.035599] [  23045]    33 23045    81353    25677   352256        0             0 php-fpm8.1
[147949.035601] [  23046]    33 23046    64263    14482   253952        0             0 php-fpm8.1
[147949.035603] [  23048]    33 23048    81247    28102   368640        0             0 php-fpm8.1
[147949.035604] [  23049]    33 23049    81763    17517   286720        0             0 php-fpm8.1
[147949.035606] [  23050]    33 23050    54633     5260   176128        0             0 php-fpm8.1
[147949.035608] [  23051]    33 23051    81745    27413   368640        0             0 php-fpm8.1
[147949.035610] [  23052]    33 23052    81250    20292   307200        0             0 php-fpm8.1
[147949.035612] [  23053]    33 23053    62492    12051   237568        0             0 php-fpm8.1
[147949.035614] [  23054]    33 23054    79479    19786   311296        0             0 php-fpm8.1
[147949.035616] [  23055]    33 23055    82274    24380   339968        0             0 php-fpm8.1
[147949.035618] [  23056]    33 23056    81762    23765   335872        0             0 php-fpm8.1
[147949.035619] [  23057]    33 23057    60234    10616   221184        0             0 php-fpm8.1
[147949.035624] [  23058]    33 23058    62266    12114   237568        0             0 php-fpm8.1
[147949.035626] [  23059]    33 23059    64558    15277   253952        0             0 php-fpm8.1
[147949.035628] [  23060]    33 23060    81670    17767   286720        0             0 php-fpm8.1
[147949.035630] [  23061]    33 23061    81740    23569   335872        0             0 php-fpm8.1
[147949.035632] [  23062]    33 23062    81765    27157   364544        0             0 php-fpm8.1
[147949.035634] [  23063]    33 23063    55149     5538   180224        0             0 php-fpm8.1
[147949.035636] [  23064]    33 23064    53607     4475   167936        0             0 php-fpm8.1
[147949.035638] [  23065]    33 23065    81251    26365   356352        0             0 php-fpm8.1
[147949.035640] [  23066]    33 23066    79991    19315   303104        0             0 php-fpm8.1
[147949.035642] [  23067]    33 23067    79803    20677   315392        0             0 php-fpm8.1
[147949.035643] [  23068]    33 23068    65398    16096   262144        0             0 php-fpm8.1
[147949.035645] [  23069]    33 23069    62633    12246   233472        0             0 php-fpm8.1
[147949.035647] [  23070]    33 23070    79262    19484   299008        0             0 php-fpm8.1
[147949.035649] [  23071]    33 23071    79788    30080   376832        0             0 php-fpm8.1
[147949.035651] [  23072]    33 23072    62276    12389   237568        0             0 php-fpm8.1
[147949.035653] [  23073]    33 23073    79974    21148   323584        0             0 php-fpm8.1
[147949.035655] [  23074]    33 23074    81250    20299   307200        0             0 php-fpm8.1
[147949.035656] [  23075]    33 23075    63702    13680   249856        0             0 php-fpm8.1
[147949.035658] [  23077]    33 23077    80732    17341   282624        0             0 php-fpm8.1
[147949.035660] [  23078]    33 23078    79772    20834   303104        0             0 php-fpm8.1
[147949.035662] [  23079]    33 23079    65346    15686   262144        0             0 php-fpm8.1
[147949.035664] [  23081]    33 23081    63206    13763   245760        0             0 php-fpm8.1
[147949.035666] [  23082]    33 23082    81761    24195   339968        0             0 php-fpm8.1
[147949.035667] [  23083]    33 23083    64690    15490   258048        0             0 php-fpm8.1
[147949.035669] [  23084]    33 23084    54811     5039   176128        0             0 php-fpm8.1
[147949.035674] [  23085]    33 23085    63144    12510   237568        0             0 php-fpm8.1
[147949.035676] [  23086]    33 23086    62481    12562   237568        0             0 php-fpm8.1
[147949.035680] [  23087]    33 23087    65662    15683   262144        0             0 php-fpm8.1
[147949.035682] [  23088]    33 23088    81757    27232   364544        0             0 php-fpm8.1
[147949.035684] [  23090]    33 23090    81762    18209   290816        0             0 php-fpm8.1
[147949.035686] [  23091]    33 23091    65152    15280   258048        0             0 php-fpm8.1
[147949.035688] [  23092]    33 23092    79988    21290   327680        0             0 php-fpm8.1
[147949.035690] [  23171]    33 23171    81760    18679   294912        0             0 php-fpm8.1
[147949.035692] [  23173]    33 23173    79410    17029   286720        0             0 php-fpm8.1
[147949.035694] [  23175]    33 23175    65824    16263   266240        0             0 php-fpm8.1
[147949.035696] [  23185]    33 23185    65365    16180   262144        0             0 php-fpm8.1
[147949.035698] [  23186]    33 23186    65231    15066   262144        0             0 php-fpm8.1
[147949.035699] [  23187]    33 23187    79988    20002   315392        0             0 php-fpm8.1
[147949.035701] [  23375]    33 23375    68209    18499   282624        0             0 php-fpm8.1
[147949.035703] [  23378]    33 23378    60998    11722   225280        0             0 php-fpm8.1
[147949.035705] [  23379]    33 23379    79435    18467   286720        0             0 php-fpm8.1
[147949.035707] [  23388]    33 23388    79258    21188   319488        0             0 php-fpm8.1
[147949.035709] [  23389]    33 23389    79453    20039   311296        0             0 php-fpm8.1
[147949.035711] [  23390]    33 23390    61517    11708   229376        0             0 php-fpm8.1
[147949.035713] [  23391]    33 23391    55516     5670   184320        0             0 php-fpm8.1
[147949.035715] [  23392]    33 23392    63335    12141   237568        0             0 php-fpm8.1
[147949.035717] [  23393]    33 23393    81245    19769   303104        0             0 php-fpm8.1
[147949.035721] [  23394]    33 23394    80731    18069   290816        0             0 php-fpm8.1
[147949.035723] [  23395]    33 23395    81229    17634   290816        0             0 php-fpm8.1
[147949.035725] [  23396]    33 23396    62102    11782   233472        0             0 php-fpm8.1
[147949.035727] [  23397]    33 23397    61251    11551   229376        0             0 php-fpm8.1
[147949.035729] [  23398]    33 23398    65025    15476   258048        0             0 php-fpm8.1
[147949.035731] [  23399]    33 23399    56609     6542   192512        0             0 php-fpm8.1
[147949.035733] [  23400]    33 23400    61918    11956   233472        0             0 php-fpm8.1
[147949.035735] [  23401]    33 23401    78978    25135   352256        0             0 php-fpm8.1
[147949.035736] [  23402]    33 23402    61182    11420   229376        0             0 php-fpm8.1
[147949.035738] [  23404]    33 23404    65174    15748   262144        0             0 php-fpm8.1
[147949.035740] [  23405]    33 23405    81247    22004   319488        0             0 php-fpm8.1
[147949.035742] [  23406]    33 23406    53598     4420   167936        0             0 php-fpm8.1
[147949.035744] [  23407]    33 23407    61984    11988   233472        0             0 php-fpm8.1
[147949.035746] [  23408]    33 23408    63977    14485   249856        0             0 php-fpm8.1
[147949.035748] [  23409]    33 23409    81247    25246   348160        0             0 php-fpm8.1
[147949.035749] [  23410]    33 23410    64153    14631   253952        0             0 php-fpm8.1
[147949.035751] [  23411]    33 23411    81279    23444   331776        0             0 php-fpm8.1
[147949.035753] [  23412]    33 23412    65221    15610   262144        0             0 php-fpm8.1
[147949.035755] [  23413]    33 23413    81753    27004   360448        0             0 php-fpm8.1
[147949.035757] [  23414]    33 23414    63471    14123   245760        0             0 php-fpm8.1
[147949.035759] [  23415]    33 23415    63396    14222   245760        0             0 php-fpm8.1
[147949.035761] [  23467]    33 23467    80729    15421   266240        0             0 php-fpm8.1
[147949.035763] [  23469]    33 23469    65609    15655   262144        0             0 php-fpm8.1
[147949.035767] [  23470]    33 23470    63897    14733   249856        0             0 php-fpm8.1
[147949.035769] [  23472]    33 23472    81239    22790   327680        0             0 php-fpm8.1
[147949.035771] [  23473]    33 23473    62872    13170   241664        0             0 php-fpm8.1
[147949.035773] [  23474]    33 23474    64835    15560   258048        0             0 php-fpm8.1
[147949.035775] [  23475]    33 23475    65215    15739   262144        0             0 php-fpm8.1
[147949.035777] [  23476]    33 23476    63137    12595   237568        0             0 php-fpm8.1
[147949.035778] [  23477]    33 23477    78749    17139   282624        0             0 php-fpm8.1
[147949.035780] [  23478]    33 23478    81236    22468   323584        0             0 php-fpm8.1
[147949.035783] [  23479]    33 23479    81238    22144   319488        0             0 php-fpm8.1
[147949.035784] [  23480]    33 23480    61533    12097   229376        0             0 php-fpm8.1
[147949.035786] [  23481]    33 23481    61742    12461   233472        0             0 php-fpm8.1
[147949.035788] [  23668]    33 23668    81120    27387   364544        0             0 php-fpm8.1
[147949.035790] [  23669]    33 23669    81281    25762   352256        0             0 php-fpm8.1
[147949.035792] [  23670]    33 23670    80711    22075   323584        0             0 php-fpm8.1
[147949.035794] [  23671]    33 23671    81629    21215   311296        0             0 php-fpm8.1
[147949.035796] [  23672]    33 23672    54106     4783   172032        0             0 php-fpm8.1
[147949.035798] [  23673]    33 23673    80732    20166   303104        0             0 php-fpm8.1
[147949.035800] [  23674]    33 23674    62566    13115   237568        0             0 php-fpm8.1
[147949.035802] [  23675]    33 23675    62266    11933   237568        0             0 php-fpm8.1
[147949.035804] [  23676]    33 23676    62778    12260   237568        0             0 php-fpm8.1
[147949.035805] [  23677]    33 23677    93296    27104   364544        0             0 php-fpm8.1
[147949.035807] [  23678]    33 23678    79960    26685   364544        0             0 php-fpm8.1
[147949.035809] [  23679]    33 23679    79235    17993   286720        0             0 php-fpm8.1
[147949.035814] [  23680]    33 23680    63334    13892   245760        0             0 php-fpm8.1
[147949.035816] [  23681]    33 23681    82264    22326   323584        0             0 php-fpm8.1
[147949.035817] [  23682]    33 23682    62045    12131   233472        0             0 php-fpm8.1
[147949.035819] [  23683]    33 23683    81649    24578   344064        0             0 php-fpm8.1
[147949.035821] [  23684]    33 23684    81755    25202   348160        0             0 php-fpm8.1
[147949.035823] [  23685]    33 23685    56617     6875   192512        0             0 php-fpm8.1
[147949.035825] [  23686]    33 23686    55403     5763   180224        0             0 php-fpm8.1
[147949.035827] [  23687]    33 23687    78956    21007   319488        0             0 php-fpm8.1
[147949.035829] [  23688]    33 23688    58896     9008   208896        0             0 php-fpm8.1
[147949.035830] [  23689]    33 23689    61751    11976   233472        0             0 php-fpm8.1
[147949.035832] [  23690]    33 23690    79253    29982   372736        0             0 php-fpm8.1
[147949.035834] [  23803]     0 23803     4285      846    73728        0             0 sshd
[147949.035836] [  23806]     0 23806     4260      971    73728        0             0 systemd
[147949.035838] [  23807]     0 23807    42651     1255    90112        0             0 (sd-pam)
[147949.035840] [  23863]     0 23863     2287      943    53248        0             0 bash
[147949.035842] [  23878]     0 23878     2152      868    53248        0             0 htop
[147949.035843] [  24124]    33 24124    63362    13980   245760        0             0 php-fpm8.1
[147949.035846] [  24573]    33 24573    54409     4318   176128        0             0 php-fpm8.1
[147949.035848] [  24574]     0 24574    53067     1478   126976        0             0 php-fpm8.1
[147949.035850] [  24575]     0 24575    53150     1663   126976        0             0 php-fpm8.1
[147949.035854] [  24576]     0 24576    53067     1235   122880        0             0 php-fpm8.1
[147949.035856] [  24577]     0 24577    53067     1589   122880        0             0 php-fpm8.1
[147949.035857] [  24578]     0 24578    53067     1591   122880        0             0 php-fpm8.1
[147949.035859] [  24579]     0 24579    53067     1572   122880        0             0 php-fpm8.1
[147949.035861] [  24580]     0 24580    53067     1615   122880        0             0 php-fpm8.1
[147949.035863] oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=systemd-resolved.service,mems_allowed=0,global_oom,task_memcg=/system.slice/php8.1-fpm.service,task=php-fpm8.1,pid=23071,uid=33
[147949.035882] Out of memory: Killed process 23071 (php-fpm8.1) total-vm:319152kB, anon-rss:112388kB, file-rss:1824kB, shmem-rss:6108kB, UID:33 pgtables:368kB oom_score_adj:0

A: Your server runs out of memory at this point.
Maybe there is some scheduled task that launches multiple long-lasting and memory-intensive operations. This then triggers the Linux kernel out of memory killer, that terminates the processes that consume most memory.
You need to increase either memory or swap space. Or look into the memory usage of your application and see if it can be reduced.


text:
Q: In R, how to create a loop to divide columns in a data frame In R, I would like to create a loop which takes the first 3000 columns of my data frame and writes them into one file, the  next 3000 columns into another file, and so on and so forth until all columns have been divided as such. What would be the best way to do this?  I understand there are the isplit and iterators functions available now via CRAN, but I am really unsure how to go about this.  Any suggestions please?

A: You could try something like:
library(plyr)
max.col <- ncol(x)
l_ply(seq(1, max.col, by=3000), function(i)
    write.table(x[,i:min(i+2999, max.col)], file=paste("i", i, sep="-"))
)

A: Not sure why you'd bother loading plyr... assuming your data frame is df... (stole the wise use of min() from Shane's answer)
maxCol <- ncol(df)
for (i in seq(1, maxCol, by 3000)) {
     write.table(df[,i:min(i+2999, maxCol)], "i")
}

You may want to edit the write.table command above to add in your preferred formatting.


text:
Q: Symfony\Component\Translation\TranslatorInterface is not instantiable I am working on a Laravel package, trying to inject "Illuminate\Validation\Factory" to __construct():
namespace Extensions\Tpp\Forms;

   use Illuminate\Validation\Validator as ValidatorInstance;
   use Illuminate\Validation\Factory as Validator;

   abstract class FormValidator {

    /**
     * @var Validator
     */
    protected $validator;

    /**
     * @var ValidatorInstance
     */
    protected $validation;

    function __construct(Validator $validator)
    {
        $this->validator = $validator;
    }

But got following error:
    Illuminate \ Container \ BindingResolutionException
Target [Symfony\Component\Translation\TranslatorInterface] is not instantiable.

I understand it means Laravel doesn't know which implementation of Symfony\Component\Translation\TranslatorInterface is. My question is why in normal Laravel application Symfony\Component\Translation\TranslatorInterface can be bound, however in a Laravel package, it's not.
Thank you

A:
My question is why in normal Laravel application
  Symfony\Component\Translation\TranslatorInterface can be bound

It is because Laravel exclusively uses Symfony components and the Validator class has dependencies on following Symfony components (check the Illuminate\Validation\Validator) along with other Illuminate components:
Symfony\Component\HttpFoundation\File\File;
Symfony\Component\Translation\TranslatorInterface;
Symfony\Component\HttpFoundation\File\UploadedFile;

You will be ab;e to use this (Remove the use statements):
function __construct(\Validator $validator)
{
    $this->validator = $validator;
}


text:
Q: Find missing element by comparing 2 2D-Arrays in Javascript A few days ago I posted a thread asking on how to find the missing element when passing a method 2 JS arrays. As you can see here. I've been trying to figure out now how to modify the method so that instead of passing it 2 Arrays you pass it 2 2D-Arrays... Having some trouble though:
/*var sml = new Array();
sml[0] = new Array("dean","22");
sml[1] = new Array("james","31");
sml[2] = new Array("ludwig","35");

var lrg = new Array();
lrg[0] = new Array("dean","22");
lrg[1] = new Array("james","31");
lrg[2] = new Array("ludwig","35");
lrg[3] = new Array("kevin","23");
lrg[4] = new Array("elton","40");*/

var sml = new Array();
sml[0] = "dean";
sml[1] = "james";
sml[2] = "ludwig";

var lrg = new Array();
lrg[0] = "dean";
lrg[1] = "james";
lrg[2] = "ludwig";
lrg[3] = "kevin";
lrg[4] = "elton";

var deselected = findDeselectedItem(sml, lrg);

alert("Deselected Items: " + deselected[0]+", "+ deselected[1]);

// -------------------------------------------------------------- //

function findDeselectedItem(CurrentArray, PreviousArray) {

var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
var deselectedItems = new Array();

// loop through previous array
for (var j = 0; j < PreviousArrSize; j++) {

    // look for same thing in new array
    if (CurrentArray.indexOf(PreviousArray[j]) == -1)

    deselectedItems.push(PreviousArray[j]);

}

if (deselectedItems.length != 0) {
    return deselectedItems;
} else {
    return null;
}

}

Now if you run the above code it works perfectly, but if you go and uncomment the variable declarations on top that that pushes arrays ontop of the array, and then comment out the simple strings that get pushed on top of the array, it doesn't work as well... For instance:
var sml = new Array();
sml[0] = new Array("dean","22");
sml[1] = new Array("james","31");
sml[2] = new Array("ludwig","35");

var lrg = new Array();
lrg[0] = new Array("dean","22");
lrg[1] = new Array("james","31");
lrg[2] = new Array("ludwig","35");
lrg[3] = new Array("kevin","23");
lrg[4] = new Array("elton","40");

/*var sml = new Array();
sml[0] = "dean";
sml[1] = "james";
sml[2] = "ludwig";

var lrg = new Array();
lrg[0] = "dean";
lrg[1] = "james";
lrg[2] = "ludwig";
lrg[3] = "kevin";
lrg[4] = "elton";*/

var deselected = findDeselectedItem(sml, lrg);

alert("Deselected Items: " + deselected[0]+", "+ deselected[1]);

// -------------------------------------------------------------- //

function findDeselectedItem(CurrentArray, PreviousArray) {

var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
var deselectedItems = new Array();

// loop through previous array
for (var j = 0; j < PreviousArrSize; j++) {

    // look for same thing in new array
    if (CurrentArray.indexOf(PreviousArray[j][0]) == -1)

    deselectedItems.push(PreviousArray[j][0]);

}

if (deselectedItems.length != 0) {
    return deselectedItems;
} else {
    return null;
}

}

The method returns 2 completely wrong values. PS - I'm not interested in the "numbers" just yet, just the "names" for now...

A: Your CurrentArray is 2-dimensional and indexOf compares Arrays but not first elements of that Arrays. So you need to use:
for ( var i = 0; i < CurrentArray.length; ++i){
    if (CurrentArray[i][0] == PreviousArray[j][0]){
        deselectedItems.push(PreviousArray[j][0]);
        break;
    }
}

Instead of
if (CurrentArray.indexOf(PreviousArray[j][0]) == -1)
    deselectedItems.push(PreviousArray[j][0]);

A: indexOf function will check object equality in this case; to make it return something else than -1 you've to pass same 2D array instances to sml and lrg.
new Array("dean","22") === new Array("dean","22") //false

Keep the same instances (e.g. http://jsfiddle.net/3TQYz/) in both arrays or use your own indexOf test that would recursively check values of the array to make your case working.

A: You could also rearrange the array like this:
var sml = {};
sml["dean"] = 22;
sml["james"] = 31;
sml["ludwig"] = 35;

var lrg = {};
lrg["dean"] = 22;
lrg["james"] = 31;
lrg["ludwig"] = 35;
lrg["kevin"] = 23;
lrg["elton"] = 40;

and use:
function findDeselectedItem(c,p){
    ret=[];
    for (var i in p){
        if (p.hasOwnProperty(i)){
            if ('undefined'===typeof c[i]) {
                ret.push(i);
            }
        }
    }
    return ret;
}

alert(findDeselectedItem(sml, lrg));

Demo: http://jsfiddle.net/LsrCj/


text:
Q: DNS Resolver for Windows over TCP I know that DNS uses UDP with Port 53 for DNS queries.
However, at my place sometimes UDP requests are blocked and DNS fails.
I know that there is protocol for DNS over TCP and many public DNS servers (such as Google's 8.8.8.8 ) supports it.
Is there a way or a DNS resolver that could make DNS requests over TCP for windows.

A: Configure the windows Adapter Interface for localhost 127.0.0.1
UDP to TCP Socks Proxy Server For UDP DNS Packets
DNS2SOCKS.exe /la:socks.log 127.0.0.1:1080 8.8.8.8:53 127.0.0.1:53

Further Reading
https://stackoverflow.com/questions/32082423/dns-through-socks-proxy-how-do-i-change-windows-settings-for-domain-resolution
http://dns2socks.sourceforge.net

A: If port 53 requests are being block by a firewall, there is a reason for it.  Viruses and Malware often use directed DNS queries to find their command-and-control servers, so that's a very good reason for an ISP to block port 53 except to their own servers or select public DNS services.  They can catch this garbage and inform users they are infected.
You need to contact your network administrator and ask for their DNS servers and use those.  (Especially since you're running Windoze.)


text:
Q: Can't connect to MySQL installed via Homebrew on Mac Monterey I ma using M1 MacBook Air, and managing my tools with Homebrew.
I've installed Mysql, and it was working fine for a while, but when I've rebooted my device it just stopped working.
I don't get any errors when running brew services start mysql, but when I try brew services list MySQL is marked as stopped.
When I try to enter mysql with mysql -u user -p password I get following error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
When I run mysql.server start (as some answers suggest) I get following error:
. ERROR! The server quit without updating PID file (/opt/homebrew/var/mysql/MacBook-Air.local.pid).
I've tried many solutions, but non of them worked.

A: i fixed this error The server quit without updating PID on mysql version 8.0.18
try sudo chown -R mysql:mysql xx/mysql, and sudo chmod 775 xx/mysql
'xx/mysql' is your mysql home dir


text:
Q: How to parse the XML with mixed nodes and text in Java? I have a xml of the format -
<root>
      <sentence>
           first part of the text

           second part of the text

      </sentence>
</root>

Essentially, the <sentence> tag represents a sentence and the child tags  are the interpolated parts in the sentence.
The XPath expression String sentence = xPath.evaluate("sentence", transUnitElement); gives the text as - first part of the text second part of the text i.e. it omits the interpolation.
The XPath expression -
NodeList aList = (NodeList) xPath.evaluate("/sentence/a", transUnitElement, XPathConstants.NODESET); gives the list of the  elements.
How can I parse them to get the text of the <sentence> element as well as the  element without losing the order and positions of the  element?
The expected output -
the first part of the sentence {interpolation_1} second part of the text {interpolation_2}

A: The result you are looking for may be achieved by iterating on children nodes of sentence and building the target string progressively. For example:
// retrieve <sentence> as Node, not as text
Node sentence = (Node) xPath.evaluate("sentence", transUnitElement, XPathConstants.NODE);

StringBuilder resultBuilder = new StringBuilder();
NodeList children = sentence.getChildNodes();

for (int i = 0; i < children.getLength(); i++) {
  Node child = children.item(i);
  short nodeType = child.getNodeType();
  switch (nodeType) {
    case Node.TEXT_NODE:
      String text = child.getTextContent().trim();
      resultBuilder.append(text);
      break;
    case Node.ELEMENT_NODE:
      String id = ((Element) child).getAttribute("id");
      resultBuilder.append(" {").append(id).append("} ");
      break;
    default:
      throw new IllegalStateException("Unexpected node type: " + nodeType);
  }
}
// outputs "first part of the text {interpolation_1} second part of the text {interpolation_2}"
System.out.println(resultBuilder.toString());

A: Have you thought of doing this with a little XSLT transformation? In XSLT 3.0 it's simply
<xsl:template match="sentence">
  <xsl:apply-templates/>
</xsl:template>
<xsl:template match="a">{<xsl:value-of select="."}</xsl:template>


text:
Q: Rename multiple files according using a names-list I'm trying to rename multiple numbered files according to a list of names.
Example:
1.pdf, 2.pdf, …, n.pdf

And a file called names.txt, with a value per line:
Fabio
Joao
n-name

So we will have

*

*1.pdf → Fabio.pdf

*2.pdf → Joao.pdf

*n.pdf → n-name.pdf
Any ideas on how to accomplish this?

A: If the files are really just "lineNumber.pdf", then this is very easy to do. In the shell:
c=0
while IFS= read -r name; do
    ((c++))
    echo mv -- $c.pdf "$name.pdf"
done < names.txt

Once you're sure that works as you want it, remove the echo from the mv command.
If you have very many files, you might want to consider doing it in Perl instead which will be much faster:
perl -lne 'rename("$..pdf","$_.pdf")' names.txt


text:
Q: django admin list_display from two tables, no relations like foreign key or manytomany relation available i have two tables, one is MeasuredController and MeasuredGrid, and there is no relation like foreign key or manytoman etc , and in admin i have to show two fields of MeasuredGrid i.e power and status, where MeasuredController's senddate = MeasuredGrid's senddate, in two different column, i have wrote code like below, but in the current code , the database will be hit two time for each object, so is there a way like select related or use cache concept ?
list_display = ("grid_status", "grid_power")

def grid_status(self, obj):
    STATUS_CHOICES = {0:"Outage", 1:"No Outage" }
    mobj = MeasuredGrid.objects.filter(senddate=obj.senddate).latest("senddate")

    try:
        return STATUS_CHOICES[int(mobj.status)], 2
    except:
        pass
grid_status.short_description = 'Grid Status'

def grid_power(self, obj):
    mobj = MeasuredGrid.objects.filter(senddate=obj.senddate).latest("senddate")
    return mobj.power

grid_power.short_description = 'Grid Power[W]'

A: You can use Cache Framework. It is very easy:
# coding: utf-8
from django.core.cache import cache
from django.contrib import admin

from .models import MeasuredController, MeasuredGrid

class MeasuredControllerAdmin(admin.ModelAdmin):
    list_display = ("grid_status", "grid_power")

    STATUS_CHOICES = {
        0: "Outage",
        1: "No Outage",
    }

    def grid_status(self, obj):
        mobj = self._get_mobj_data(obj)
        return mobj['status']
    grid_status.short_description = 'Grid Status'

    def grid_power(self, obj):
        mobj = self._get_mobj_data(obj)
        return mobj['power']
    grid_power.short_description = 'Grid Power[W]'

    def _get_mobj_data(self, obj):
        """Get a relevant MeasuredGrid object for a given MeasuredController"""

        data = cache.get('mobj_%s' % obj.pk)
        if data is not None:
            return data

        mobj = MeasuredGrid.objects.filter(senddate=obj.senddate).latest("senddate")

        status = None
        try:
            status = self.STATUS_CHOICES[int(mobj.status)], 2
        except: # <---------- Not the best decision. You probably need ValueError or KeyError
            pass

        data = {
            "id": mobj.pk,
            "power": mobj.power,
            "status": status,
        }

        cache.set('mobj_%s' % obj.pk, data) # the default timeout is 300 seconds

        return data

NB: the default cache backend is django.core.cache.backends.locmem.LocMemCache, so the cache will work even in dev environment (ie. DEBUG = True).


text:
Q: Gmail Ignore HTML email table widths and styles So, saw a bunch of posts of how gmail handles html emails ... I saw that I needed to use inline styles, and also saw a post about using spaces after ";" and ":" in my inline styles ... but I'm still running into issues. My issue is that I am designating table cell widths (30-70), but my table is still not showing the correct widths (more like 90-10 in gmail). This is mainly a gmail issue -- The styles still show in other mail clients. I've done some homework, but can't find any solutions...
Styling HTML email for Gmail
Table cell width in HTML email does not correspond to width set in HTML or CSS
Below is how I am creating the message for the form (in PHP) ...  note the width="30%" and the inline styles (width:30%).  Still, this gets ignored in gmail. Below is a snippet of the code...
$to_email[] = "
";
        $to_email[] = "
";
            $to_email[] = "Column 1	";
            $to_email[] = "Column 2	";
        $to_email[] = "
"; // Then more code to finish the page

When I look at the page in google, the left width looks like it is around 90% and the right is about 10%.  Note: There are no images in the email, that would force a larger width.
When I "inspect element" and view the code in google to see the email, the code looks like this...

Column 1	Column2>

Anyone know what is wrong? As I said, the styles and everything else show up in other mail clients, so the form works fine. It's just gmail...
Note: When I save the .eml file from gmail and open it in notepad, all of the widths are there... Not sure what is going on.
Let me know. Thanks.

A: Couldn't find a good answer, so I completely restructured the form, using new headers and now the form works in google. So, check your headers...


text:
Q: Automatizado de vencimientos de pagos Hola este estoy haciendo un control de pagos pero quiero automatizar
el mensaje que ha se ha vencido, pero lo malo que con este método solo me actualiza el primer registro que tengo y ya los demás no e intentado con un ciclo FOR o no se que estaré haciendo mal.
El ciclo los estoy llamada con un document.ready para que se ejecute el método cuando se abre la pagina.
    public function revisarFecha() {
        $user = Session::getSession("User");
        if (null !== $user) {
            if ("Admin" == $user["Roles"]) {
       //Obtengo todos los registros de la tabla pagos para detectar la fecha d
       del vencimiento
                //A qui tendría que enviar el dato de Id_cliente
                //Pero el problema es que solo me evalúa un registro y
                //quiero que me evalué todos los registros de la tablas pagos
                $array = array(
                        1,
                     );
                $data = $this->model->getPago2($array);

               print_r($data);

                //    $array = $data["results"];
                //   $data2 = $this->model->getPago($array[0]["Id_cliente"]);

                if(is_array($data)) {
                    //Guardamos los results
                    $array = $data["results"];
                    $fecha = date("d-m-Y");
                    //Si la fecha es la misma que tenemos en la tabla pagos e insertaremos
                    //En la tabla cliente vencido
                    //Tendria que hacer un ciclo for para que cada registro se evaluara
                    //Cada ID_cliente y compare fechas para anotar vencidos
                    if ($array[0]["Fecha_pago"] == $fecha) {

                         $array = array(
                            $array[0]["Id_cliente"],
                            "Vencido",
                      );
                       print_r($this->model->insertarVencido($array));
                    } else {
                       echo 'Funciona correctamente';
                    }
                }
            } else {
                echo "No tiene permitido";
            }
        }
}


text:
Q: get the last picture taken by user hey I want to get the last picture captured by user through any camera application.
I have no idea how to do that
can any one help me?
further I want to send that image as an attachment to an email or MMS..
thanks

A: // Find the last picture
String[] projection = new String[]{
    MediaStore.Images.ImageColumns._ID,
    MediaStore.Images.ImageColumns.DATA,
    MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
    MediaStore.Images.ImageColumns.DATE_TAKEN,
    MediaStore.Images.ImageColumns.MIME_TYPE
    };
final Cursor cursor = getContext().getContentResolver()
        .query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
               null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");

// Put it in the image view
if (cursor.moveToFirst()) {
    final ImageView imageView = (ImageView) findViewById(R.id.pictureView);
    String imageLocation = cursor.getString(1);
    File imageFile = new File(imageLocation);
    if (imageFile.exists()) {   // TODO: is there a better way to do this?
        Bitmap bm = BitmapFactory.decodeFile(imageLocation);
        imageView.setImageBitmap(bm);
    }
}

I'm still working on the MMS sending part.

A: Inspired by https://stackoverflow.com/a/20065920/763459
So the main concern in that answer was not all the devices are using "DCIM" as the camera folder. Then I found out that if a file is located inside a app-specified folder, it will be indexed by ContentResolver but the other app doesn't have access to it, which means canRead=false.  So here I come up with another solution:
    while (cursor.moveToNext()) {
        String imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
        File imageFile = new File(imagePath);
        if (imageFile.canRead() && imageFile.exists()) {
           // we have found the latest picture in the public folder, do whatever you want
            break;
        }
    }

A: Here it is in Kotlin. I have used Glide library to load the last image into an imageview
private fun getLastImageFromGallery(){
        val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI

        val projection = arrayOf(
            MediaStore.Images.ImageColumns._ID,
            MediaStore.Images.Media._ID,
            MediaStore.Images.ImageColumns.DATE_ADDED,
            MediaStore.Images.ImageColumns.MIME_TYPE
        )
        val cursor: Cursor = applicationContext.contentResolver.query(uriExternal, projection, null,
            null, MediaStore.Images.ImageColumns.DATE_ADDED + " DESC"
        )!!

        Log.i("Cursor Last", cursor.moveToLast().toString())
        if (cursor.moveToFirst()) {
            val columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
            val imageId: Long = cursor.getLong(columnIndexID)
            val imageURI = Uri.withAppendedPath(uriExternal, "" + imageId)

            Glide.with(applicationContext)
                .load(imageURI)
                .transform(CenterCrop(), RoundedCorners(12))
                .into(imageView)

        }

        cursor.close()
}


text:
Q: Looping through UIImageViews to see if any view overlap the other view in the array With an NSArray of UIImageViews, how do I check to see if any of the views intersect. My attempt is below. The error reads, "Property 'frame' not found on object type 'id'".
- (BOOL)isOverlapping:(UIImageView*)image
{
    for (int x = 0; x < objectsArray.count; x++)
    {
        if([objectsArray[x] isEqual:image])continue;
        if([objectsArray[x] isKindOfClass:[UIImageView class]])
            if(CGRectIntersectsRect(image.frame, (UIImageView)objectsArray[x].frame))
                return true;
    }
    return false;
}

A: Try wrapping the cast around parenthesis:
((UIImageView *)objectsArray[x]).frame


text:
Q: How can I create a function that check boolean field in array of object javascript The final goal: if all the field are true the last object.field must change to true
const badges = [

  { name: "peter", given : true, points: 10 },
    { name: "Alice", given : true,  points: 100 },
    { name: "Hugo", given: true,  points: 100 },
    { name: "Salah", given: false,  points: 500 },
    { name: "Rui", given: false, points: 1000 },
    { name: "Jimena", given: false,  points: 10000 }

]

My code:

const badges = [
    { name: "peter", given : true, points: 10 },
    { name: "Alice", given : true,  points: 100 },
    { name: "Hugo", given: true,  points: 100 },
    { name: "Salah", given: false,  points: 500 },
    { name: "Rui", given: false, points: 1000 },
    { name: "Jimena", given: false,  points: 10000 }
]

let count = 0
badges.forEach((ele, index) => {
  const l = badges.length
  ele.given === true ? count = count + 1 : count
  count == l - 1 ? badges[l - 1].given = true : badges[l - 1].given
})

console.log(badges)

What I would like to achieve: is a more generic function that can works anywhere but I could not find the way or maybe a simplest way.

A: This will work so long as the field provided is a boolean. Makes use of slice to get everything but the last element and every to check all those conform to a condition.

const badges = [

  { name: "peter", given : true, points: 10 },
    { name: "Alice", given : true,  points: 100 },
    { name: "Hugo", given: true,  points: 100 },
    { name: "Salah", given: true,  points: 500 },
    { name: "Rui", given: true, points: 1000 },
    { name: "Jimena", given: false,  points: 10000 }

]

function check(input, field) {
  var result = input.slice(0,input.length-1).every(x => x[field]);
  if(result) {
    badges[input.length-1][field] = true;
  }
}

check(badges,"given");
console.log(badges)


text:
Q: PHP - Insert into table with name of previous select statement result I am trying to insert into a mySql table, the tables name is the result of a sql select query, the first query returns the correct result but the second query is where the error seems to lie, any help would be very very much appreciated
$query = mysql_query("SELECT council from users where username = '$username'");

 $x = mysql_result($query,0, "council");
 $councilArea = (string)$x;

// mysql inserting a new row
    $result = mysql_query("INSERT INTO '$councilArea' ('barcode', 'productname', 'bin', 'info', 'addedby') VALUES('$barcode', '$productname', '$bin', '$info', '$username')");

A: You get the error because a table name must not be quoted by single quotes, but by backticks.
There is also a fundamental problem with your database design.
You save data in different tables, that really should be stored in one table.
Add a field counselArea in the table to distinguish the data, instead of storing it in different tables.


text:
Q: Is foreach with reference faster than without in PHP? Please consider these 2 codes:
Key lookup:
foreach ($array as $key => $value){
   $array[$key] = "New Value";
}

Reference:
foreach ($array as $key => &$value){
    $value = "New Value";
}
// Make sure no unwanted changes are committed through this reference
unset($value)

My understanding of this is, that the first example with key lookup will be slower due to additional hash table lookup operation. Is this correct? Is using reference better option?


text:
Q: useContext working not working with nested component I am trying to refactor an app to use useContext but have hit a snag and cannot figure out what is happening.
Using the latest version of everything, running Next.js.
The way things are structured is that every page is wrapped in <Layout> and some pages are also wrapped in <Fund>, nested under <Layout>.
I have global context that is set in _app.js and passed to Layout where it is rendered.  This works fine, the aTest context variable that I define in pages/_app.js renders on Layout and shows on all pages.
Then I have fund-specific context that is set in components/Fund.js and loaded in on pages/fund/index.js (and subsequent other pages).
This does not work.  The anotherTest context variable that I define in /components/Fund.js is not showing in /pages/fund/index.js even though the return statement there is wrapped in the <Fund> component (which I assume should hold and pass on the context).
I think I have maybe got my child/parent order mixed up for the non-working scenario but by brain is fried.  Any tips?
Stripped back, the basic code is:
/components/
   - UserContext.js
   - FundContext.js
   - Layout.js
   - Fund.js

/pages/
   - _app.js
   - index.js
   - /fund/
      - index.js

Both the /components/*Context.js files are the same bar the names declared in them:
import { createContext } from 'react';
const FundContext = createContext();
export default FundContext;

and
import { createContext } from 'react';
const UserContext = createContext();
export default UserContext;

In /pages/_app.js I am doing:
import React, { useState } from "react";
import UserContext from '../components/UserContext';
...

function MyApp({ Component, pageProps }) {
   ...
   return (
      <UserContext.Provider value={{
         aTest: "This is a test"
    }}>
      <Component {...pageProps} />
    </UserContext.Provider>
   )
}

export default MyApp

In /components/Layout.js I am doing:
import React, { useState, useContext } from "react";
import UserContext from './UserContext';
const Layout = ({children}) => {

   let {aTest} = useContext(UserContext);

   return (

{aTest}

         {children}

    )
}

export default Layout

In /components/Fund.js I am doing:
import React, { useState, useContext } from "react";
import UserContext from './FundContext';
const Fund = ({children}) => {

   return (

{aTest}

            <FundContext.Provider value={{ anotherTest: "Just another test" }}>
            {children}
         </FundContext.Provider>

    )
}

export default Layout

In /pages/fund/index.js I am doing:
import React, { useState, useContext } from "react";
import FundContext from '../../components/FundContext';
...

export default function App () {

   let {anotherTest} = useContext(FundContext);

   return (
      <Fund>
         {anotherTest}
      </Fund>
   )
}

A: Your useContext hook is called in the global scope on /pages/fund/index.js. Moving the hook to the scope of the component should fix the issue.
import React, { useState, useContext } from "react";
import FundContext from '../../components/FundContext';
...

export default function App () {
   let {anotherTest} = useContext(FundContext);

   return (
      <Fund>
         {anotherTest}
      </Fund>
   )

Also, I do not see a FundContext.Provider anywhere in the provided code, which means that calls to useContext(FundContext) will not work as intended. If it is not present, make sure a wrap the consumers of FundContext with it.
EDIT (OP updated the question):
useContext(FundContext) is being used above FundContext.Provider in the component tree.
  |_App (useContext(FundContext))
     |_Fund
         |_FundContext.Provider
                    |_{anotherTest}

Consider moving FundContext.Provider above the App component, or pass a component similar to the following one as a child to Fund:
const AnotherTest = () => {
  let {anotherTest} = useContext(FundContext);

  return (
      <>
         {anotherTest}
      </>
   )
}

/pages/fund/index.js:
import React, { useState, useContext } from "react";
import FundContext from '../../components/FundContext';
...
export default function App () {
   return (
      <Fund>
         <AnotherTest />
      </Fund>
   )
}


text:
Q: How to write custom validation error on mongoose schema? Any idea how can I provide custom validation error on mongoose schema for unique values(unique:true).
I found here https://mongoosejs.com/docs/validation.html
but in that they did not mention for unique values(unique:true)
I have tried so far. here for unique value it does't work.
departmentId: {
        type: String,
        required: [true, 'cannot be empty'],
        unique: [true, 'already exist']
},

A: In Mongoose, the unique option for schemas is not a validator. It's a convenient helper for building MongoDB unique indexes.  Please check this link for more info.
Also, you can use mongoose-unique-validator for your operation.


text:
Q: Battery holder for protected 18650 battery When placing a 18650 Li-Ion rechargeable battery in its battery holder, everything is fine. The problem is with protected 18650 Li-Ion battery. There are protection circuits attached into them and they are longer in size. Hardly can they go into the battery holder or come out and in most of case they are damaged.
What battery holders should I use for protected 18650 Li-Ion rechargeable batteries?

A: This is the normal situation, the 65mm is the internal length of the cell and the protection circuitry adds to it. If it was 65mm I'd worry about the protection circuitry not being there.
Buy a holder that can handle a ~67mm or ~69mm cell (depending if the button is there or not).
Do not measure the battery length as shown below.


text:
Q: Activity ShortCut is not create in Vivo devices I want to create the Activity shortcut on the home screen, so a user can open the activity screen directly .
I have used this code
if(ShortcutManagerCompat.isRequestPinShortcutSupported
    (getApplicationContext()))
    {
        ShortcutInfoCompat shortcut = new ShortcutInfoCompat.Builder(getApplicationContext(), id)
         .setIntent(new Intent(getApplicationContext(),
           TranslateActivity.class).setAction(Intent.ACTION_MAIN))
         .setShortLabel(label)
         .setIcon(icon)
         .build();
        return
         ShortcutManagerCompat.requestPinShortcut(getApplicationContext(),
         shortcut, startHomeScreen());
    }
    else
    {
        // Shortcut is not supported by your launcher
        Intent shortcutIntent = new Intent(getApplicationContext(), TranslateActivity.class);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        Intent addIntent = new Intent();
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Test");
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher));
        addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        getApplicationContext().sendBroadcast(addIntent);
    }

A: It's because of default launcher in vivo devices. When I changed default launcher to some other launcher It's let me create desktop shortcut. So as far I did R&d I found below solution it's not complete solution but you can redirect to allow Desktop shortcuts screen.
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.component = ComponentName("com.bbk.launcher2", "com.bbk.launcher2.installshortcut.PurviewActivity")
activity.startActivity(intent)

I tried to get result if user allowed or not but it's not work for all vivo devices.
var uri = Uri.parse("content://com.bbk.launcher2.settings/favorites")
            var query = activity.contentResolver.query(uri, null, " itemType = ?", arrayOf("30"), null);
            if (query != null && query.count > 0) {
                var idIndex = query.getColumnIndexOrThrow("_id");
                var intentIndex = query.getColumnIndexOrThrow("intent");
                var shortcutPermissionIndex = query.getColumnIndexOrThrow("shortcutPermission");
                while (query.moveToNext()) {
                    val long = query.getLong(idIndex)
                    val intent = query.getString(intentIndex)
                    val shortcutPermission = query.getInt(shortcutPermissionIndex)
                    var unflattenFromString = ComponentName.unflattenFromString(intent)
                    Log.e("bhavin->", "initView: getShortcutPerBtn id=$long packageName= ${unflattenFromString!!.packageName} shortcutPermission= $shortcutPermission")
                    if (unflattenFromString!!.packageName == activity.packageName && shortcutPermission != 0 && shortcutPermission != 16){
                        val intent = Intent()
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        intent.component = ComponentName("com.bbk.launcher2", "com.bbk.launcher2.installshortcut.PurviewActivity")
                        activity.startActivity(intent)
                        query.close()
                        return@ensureBackgroundThread
                    }
                    else{
                        Log.e("bhavin->","abcd")
                    }
                }
                query.close()
            }

For more details you can check this I found this git
Note: I found exception some devices vivo 1902 and Z3
java.lang.SecurityException: Permission Denial: opening provider com.bbk.launcher2.data.LauncherProvider from ProcessRecord{f8f30af 16137:com.qiutinghe.change/u0a172} (pid=16137, uid=10172)
requires com.bbk.launcher2.permission.READ_SETTINGS or com.bbk.launcher2.permission.WRITE_SETTINGS


text:
Q: How to add and run an additional manifest in a VSTO Add-in I have a VSTO Add-in in C# for Excel in Visual Studio 2017.
I also have a manifest which references a Web Add-in for Excel.
I'd like to add the manifest to the VS project so that when the user installs the VSTO add-in, the web add-in will be installed as well.
I have found several ways to add a manifest to a VS project:
1. Create the manifest through New File -> Add Manifest Application File
2. Add a Web Add-in to a solution
However, these 2 ways aren't enough to achieve what I'm trying to do.
With the first method, the manifest is added to the project, but nothing reads it so it is never loaded.
Moreover, I thought I could specify it as an additional manifest, but VS doesn't let me embed it:

With the second method, I successfully added a Web add-in project to my solution.
When set as additional start up project, it loads and runs correctly on debug mode.
However, when I build my solution, the web add-in doesn't generate anything,  so it isn't embeded in my installer (I'm using Wix 3.11 to generate a .msi installer), and thus, it is never run when I install the add-in.
How can I add and read the manifest in my solution so it will run upon installation?
EDIT:
I have also found this to use AdditionalManifestFile in (I believe) the .csproj of a project, however this doesn't work either.


text:
Q: Cordova/phonegap in android div contenteditable can't delete image Use Cordova/Phonegap to build an android app which contains the following simple html file index.html

1234

Run this android apps using any android mobile phone, place the cursor at the end of the div(i.e. behind image 2.jpg), the soft keyboard will be opened automatically.  Then, press the "BACKSPACE" button on the soft keyboard.
Expected Result: the image 2.jpg is removed.
Actual Result: the letter "4" is removed.  AND, it is not possible to remove the 2 images inside the div.
If I run this simple html using any desktop browsers or any browsers in mobile phone, this result is as expected.  The problem only appears when it is run inside a webview of an android apps.
I'm sorry that I created this new question; I asked an old one but no one response, may be my last question is too complicated, so I create this one which is easier to understand.

A: I try in a new cordova application and it works perfectly, i think that the problem is only releated to your html formatting, you miss two enclosing tags in the img and one single quotes in contenteditable="true, follow the correct html:

            12  34

Maybe android chrome version that you have installed on phone have a more pedant management of the html formatting and not recognize the image tags.


text:
Q: Load data to amazon RDS/SQL from S3 I know this is not a programming question but I would really appreciate for the help.
I am trying to transfer files from s3 bucket to the Amazon RDS mysql database particularly to table say 'test'. I am doing this first time and don't know how to approach to it.
I tried in the following way:
aws rds restore-db-instance-from-s3 ^
--allocated-storage 250 ^
--db-instance-identifier myidentifier ^
--db-instance-class db.m4.large ^
--engine mysql ^
--master-user-name masterawsuser ^
--master-user-password masteruserpassword ^
--s3-bucket-name mybucket ^
--s3-ingestion-role-arn arn:aws:iam::account-number:role/rolename ^
--s3-prefix bucketprefix ^
--source-engine mysql ^
--source-engine-version 5.6.27

The AWS Console is showing "incompatible restore" for "myidentifier". I don't know how to resolve it.
And I am wondering by the above code, will the data gets load in the desired table("test")?
Thanks

A: You are trying to restore SQL as an RDS instance.
RDS instances are managed database servers which you then create databases within.
You should create an RDS instance then load your SQL code using MySQL command line tools.
If you are migrating from an existing database server also have a look at AWS DMS.