text:
Q: Are font names on Windows English-only? Just curious, do font names on Windows always have English face names, or are they localizable depending on a user selected UI language?
In other words, is Times New Roman called that as well on Chinese installation of Windows?

A: Font names are localized if the font creator chooses to publish metadata for a specific locale, but all fonts have a system-known name, usually the PostScript name, that ensures that the same font can be referenced and retrieved with a reasonable amount of reliability.
For OpenType and TrueType fonts, you can find localized names in the name record of an OpenType file.
The Naming Table (OpenType Spec 1.6) @ Microsoft Typography
Font Names Table (TrueType Spec) @ Apple
For PostScript Type 1 fonts, you can locate the assigned names by their FontName declarations.
Adobe Type 1 Font Format @ Adobe (PDF)
Update:
I checked to see whether the PostScript name can be used to instantiate a font, and unfortunately it doesn't work. However, using the localized name (as retrieved from Mark Ransom's link in his comment) does work. This sample is in C#.
using System.Drawing;

namespace FontNameCheckApplication
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Font TimesNewRomanByPSName = new Font("TimesNewRomanPSMT", 16f);
            Console.WriteLine("TimesNewRomanPSMT = {0}", TimesNewRomanByPSName.Name);

            Font TimesNewRomanByName = new Font("Times New Roman", 16f);
            Console.WriteLine("Times New Roman = {0}", TimesNewRomanByName.Name);

            Font ArialByPSName = new Font("ArialMT", 16f);
            Console.WriteLine("ArialMT = {0}", ArialByPSName.Name);

            Font ArialByName = new Font("Arial", 16f);
            Console.WriteLine("Arial = {0}", ArialByName.Name);

            Font GulimByEnglishName = new Font("Gulim", 16f);
            Console.WriteLine("Gulim = {0}", GulimByEnglishName.Name);

            Font GulimByKoreanName = new Font("굴림", 16f);
            Console.WriteLine("굴림 = {0}", GulimByKoreanName.Name);

            Console.ReadKey();
        }
    }
}

Unfortunately we've butted heads with Font substitution, as "Microsoft Sans Serif" is definitely not Times New Roman nor Arial. This indicates that the PostScript name can't be used reliably to reference the same font.
Here's the output:
TimesNewRomanPSMT = Microsoft Sans Serif
Times New Roman = Times New Roman
ArialMT = Microsoft Sans Serif
Arial = Arial
Gulim = Gulim
?? = Gulim

Update #2:
Here's a sample for Win32.
One thing to note is that CreateFontIndirect() is subject to substitution. When running this sample, I never got an empty handle, even for PostScript names. To see whether we can get an unsubstituted match, we should use EnumFontFamiliesEx() to scan the available system font list. We get the same results as the C#, but without substitutions. For some fonts the results may depending on the graphics mode setting (see SetGraphicsMode() / GM_ADVANCED).
LOGFONT structure (Windows) @ MSDN
CreateFontIndirect function (Windows) @ MSDN
SetGraphicsMode function (Windows) @ MSDN
EnumFontFamiliesEx function (Windows) @ MSDN
EnumFontFamExProc callback function (Windows) @ MSDN
#include "stdafx.h"
#include <Windows.h>

void TestCreateFont(LPCTSTR lpczFontName, BYTE bCharSet)
{
  LOGFONT lf;
  lf.lfHeight = 0;
  lf.lfWidth = 0;
  lf.lfEscapement = 0;
  lf.lfOrientation = 0;
  lf.lfWeight = FW_DONTCARE;
  lf.lfItalic = FALSE;
  lf.lfUnderline = FALSE;
  lf.lfStrikeOut = FALSE;
  lf.lfCharSet = bCharSet;
  lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  lf.lfQuality = DEFAULT_QUALITY;
  lf.lfPitchAndFamily = DEFAULT_PITCH;
  // NOTE: LF_FACESIZE = 32, WinGdi.h
  _tcsncpy_s(lf.lfFaceName, 32, lpczFontName, _tcsnlen(lpczFontName, 32));

  HFONT hf = ::CreateFontIndirect(&lf);

  // NOTE: LF_FACESIZE = 32, WinGdi.h
  _tprintf_s(_T("TestCreateFont:\r\n%.32s = %.32s, bCharSet=%d, HFONT=0x%8.8x\r\n\r\n"), lpczFontName, lf.lfFaceName, bCharSet, hf);

  ::DeleteObject(hf);
}

int CALLBACK MyEnumFontFamExProc(const LOGFONT *lpelfe, const TEXTMETRIC *lpntme, DWORD FontType, LPARAM lParam)
{
  _tprintf_s(_T("  Found: %.32s, bCharSet=%d\r\n"), lpelfe->lfFaceName, lpelfe->lfCharSet);

  return 1;
}

void TestEnumFontFamiliesEx(LPCTSTR lpczFontName, BYTE bCharSet)
{
  LOGFONT lf;
  lf.lfHeight = 0;
  lf.lfWidth = 0;
  lf.lfEscapement = 0;
  lf.lfOrientation = 0;
  lf.lfWeight = FW_DONTCARE;
  lf.lfItalic = FALSE;
  lf.lfUnderline = FALSE;
  lf.lfStrikeOut = FALSE;
  lf.lfCharSet = bCharSet;
  lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  lf.lfQuality = DEFAULT_QUALITY;
  lf.lfPitchAndFamily = DEFAULT_PITCH; // NOTE: DEFAULT_PITCH = 0, WinGdi.h
  // NOTE: LF_FACESIZE = 32, WinGdi.h
  _tcsncpy_s(lf.lfFaceName, 32, lpczFontName, _tcsnlen(lpczFontName, 32));

  _tprintf_s(_T("TestEnumFontFamiliesEx: %.32s, bCharSet=%d\r\n"), lpczFontName, bCharSet);

  HDC hdcAll = GetDC(NULL);

  ::EnumFontFamiliesEx(hdcAll, &lf, &MyEnumFontFamExProc, 0, 0);
}

int _tmain(int argc, _TCHAR* argv[])
{
  TestCreateFont(_T("TimesNewRomanPSMT"), DEFAULT_CHARSET);
  TestCreateFont(_T("Times New Roman"), DEFAULT_CHARSET);

  TestCreateFont(_T("ArialMT"), DEFAULT_CHARSET);
  TestCreateFont(_T("Arial"), DEFAULT_CHARSET);

  TestCreateFont(_T("Gulim"), DEFAULT_CHARSET);

  TestCreateFont(_T("굴림"), DEFAULT_CHARSET);

  TestEnumFontFamiliesEx(_T("TimesNewRomanPSMT"), DEFAULT_CHARSET);
  TestEnumFontFamiliesEx(_T("Times New Roman"), DEFAULT_CHARSET);

  TestEnumFontFamiliesEx(_T("ArialMT"), DEFAULT_CHARSET);
  TestEnumFontFamiliesEx(_T("Arial"), DEFAULT_CHARSET);

  TestEnumFontFamiliesEx(_T("Gulim"), DEFAULT_CHARSET);

  TestEnumFontFamiliesEx(_T("굴림"), DEFAULT_CHARSET);

  return 0;
}

And here are the results:
TestCreateFont:
TimesNewRomanPSMT = TimesNewRomanPSMT, bCharSet=1, HFONT=0xda0a117c

TestCreateFont:
Times New Roman = Times New Roman, bCharSet=1, HFONT=0xdb0a117c

TestCreateFont:
ArialMT = ArialMT, bCharSet=1, HFONT=0xdc0a117c

TestCreateFont:
Arial = Arial, bCharSet=1, HFONT=0xdd0a117c

TestCreateFont:
Gulim = Gulim, bCharSet=1, HFONT=0xde0a117c

TestCreateFont:
?? = ??, bCharSet=1, HFONT=0xdf0a117c

TestEnumFontFamiliesEx: TimesNewRomanPSMT, bCharSet=1
TestEnumFontFamiliesEx: Times New Roman, bCharSet=1
  Found: Times New Roman, bCharSet=0
  Found: Times New Roman, bCharSet=177
  Found: Times New Roman, bCharSet=178
  Found: Times New Roman, bCharSet=161
  Found: Times New Roman, bCharSet=162
  Found: Times New Roman, bCharSet=186
  Found: Times New Roman, bCharSet=238
  Found: Times New Roman, bCharSet=204
  Found: Times New Roman, bCharSet=163
  Found: Times New Roman, bCharSet=0
  Found: Times New Roman, bCharSet=177
  Found: Times New Roman, bCharSet=161
  Found: Times New Roman, bCharSet=162
  Found: Times New Roman, bCharSet=186
  Found: Times New Roman, bCharSet=238
  Found: Times New Roman, bCharSet=204
  Found: Times New Roman, bCharSet=163
  Found: Times New Roman, bCharSet=0
  Found: Times New Roman, bCharSet=177
  Found: Times New Roman, bCharSet=178
  Found: Times New Roman, bCharSet=161
  Found: Times New Roman, bCharSet=162
  Found: Times New Roman, bCharSet=186
  Found: Times New Roman, bCharSet=238
  Found: Times New Roman, bCharSet=204
  Found: Times New Roman, bCharSet=163
  Found: Times New Roman, bCharSet=0
  Found: Times New Roman, bCharSet=177
  Found: Times New Roman, bCharSet=161
  Found: Times New Roman, bCharSet=162
  Found: Times New Roman, bCharSet=186
  Found: Times New Roman, bCharSet=238
  Found: Times New Roman, bCharSet=204
  Found: Times New Roman, bCharSet=163
TestEnumFontFamiliesEx: ArialMT, bCharSet=1
TestEnumFontFamiliesEx: Arial, bCharSet=1
  Found: Arial, bCharSet=0
  Found: Arial, bCharSet=177
  Found: Arial, bCharSet=178
  Found: Arial, bCharSet=161
  Found: Arial, bCharSet=162
  Found: Arial, bCharSet=186
  Found: Arial, bCharSet=238
  Found: Arial, bCharSet=204
  Found: Arial, bCharSet=163
  Found: Arial, bCharSet=0
  Found: Arial, bCharSet=177
  Found: Arial, bCharSet=161
  Found: Arial, bCharSet=162
  Found: Arial, bCharSet=186
  Found: Arial, bCharSet=238
  Found: Arial, bCharSet=204
  Found: Arial, bCharSet=163
  Found: Arial, bCharSet=0
  Found: Arial, bCharSet=177
  Found: Arial, bCharSet=178
  Found: Arial, bCharSet=161
  Found: Arial, bCharSet=162
  Found: Arial, bCharSet=186
  Found: Arial, bCharSet=238
  Found: Arial, bCharSet=204
  Found: Arial, bCharSet=163
  Found: Arial, bCharSet=0
  Found: Arial, bCharSet=177
  Found: Arial, bCharSet=161
  Found: Arial, bCharSet=162
  Found: Arial, bCharSet=186
  Found: Arial, bCharSet=238
  Found: Arial, bCharSet=204
  Found: Arial, bCharSet=163
TestEnumFontFamiliesEx: Gulim, bCharSet=1
  Found: Gulim, bCharSet=0
  Found: Gulim, bCharSet=129
  Found: Gulim, bCharSet=161
  Found: Gulim, bCharSet=162
  Found: Gulim, bCharSet=186
  Found: Gulim, bCharSet=238
  Found: Gulim, bCharSet=204
TestEnumFontFamiliesEx: ??, bCharSet=1
  Found: Gulim, bCharSet=0
  Found: Gulim, bCharSet=129
  Found: Gulim, bCharSet=161
  Found: Gulim, bCharSet=162
  Found: Gulim, bCharSet=186
  Found: Gulim, bCharSet=238
  Found: Gulim, bCharSet=204

Here's a snippet from wingdi.h for the CharSet values.
#define ANSI_CHARSET            0
#define DEFAULT_CHARSET         1
#define SYMBOL_CHARSET          2
#define SHIFTJIS_CHARSET        128
#define HANGEUL_CHARSET         129
#define HANGUL_CHARSET          129
#define GB2312_CHARSET          134
#define CHINESEBIG5_CHARSET     136
#define OEM_CHARSET             255

#define JOHAB_CHARSET           130
#define HEBREW_CHARSET          177
#define ARABIC_CHARSET          178
#define GREEK_CHARSET           161
#define TURKISH_CHARSET         162
#define VIETNAMESE_CHARSET      163
#define THAI_CHARSET            222
#define EASTEUROPE_CHARSET      238
#define RUSSIAN_CHARSET         204

#define MAC_CHARSET             77
#define BALTIC_CHARSET          186


text:
Q: How to put a List View in an Alert Dialog when i click an banner? I am newbie, when I click a banner, i need an AlertDialog with a ListView with 2 choices spanish and english  to appear. And when I click one I need go to a website, and the option to back or cancel of dialog.
If this help, all that I have (is not with ListView)
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final AdView adView = (AdView) findViewById(R.id.adView);
    adView.loadAd(new AdRequest());

     // Internet Connection detector
    ConnectionDetector cd;

    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();

    final ImageView Banner = (ImageView) findViewById(R.id.imageView2);
    Banner.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {

            // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.custom);
            dialog.setTitle("Title...");

            // set the custom dialog components - text, image and button
            TextView text = (TextView) dialog.findViewById(R.id.text);
            text.setText("Android custom dialog example!");
            ImageView image = (ImageView) dialog.findViewById(R.id.image);
            image.setImageResource(R.drawable.ic_launcher);

            Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
            // if button is clicked, close the custom dialog
            dialogButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

            dialog.show();
          }
        });
    }
}

            //al apretar click en el banner abre el browser con la pág: las.leagueoflegends.com

            //Intent browserIntent =
            //  new Intent(Intent.ACTION_VIEW,
                //  Uri.parse("http://www.facebook.com"));
        //   startActivity(browserIntent);
        }});

PD: i tried different codes from people but i get different errors D:

A: Try this..
Banner.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {

                String[] MenuItems = {"spanish", "english"};
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Activity.this);
                // set title
                alertDialogBuilder.setTitle("Select");
                // set dialog message
                alertDialogBuilder
                    .setCancelable(true)
                    .setSingleChoiceItems(MenuItems, 0, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog1, int pos) {
                            // TODO Auto-generated method stub

                            if(pos == 0) {
                                 // Do Your choice
                            } else if(pos == 1) {
                                 // Do Your choice
                            }
                            dialog1.cancel();
                        }
                    })
                    .setPositiveButton("Cancel",new DialogInterface.OnClickListener() {
                        @SuppressLint("NewApi")
                        public void onClick(DialogInterface dialog1,int id) {
                            dialog1.cancel();
                        }
                      });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    // show it
                    alertDialog.show();
            }
        });

A: Its perfectly achieveble what is mentioned by Tamilan and Vipul but in future if you need better control overr alert dialog its bette r to use customAlertDialog,
just Create Layput as usual; you do it in your Activity .
AlertDialog dialog;
public void myDialog(){

AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Dialog Demo");
LayoutInflater inflater=getLAyoutInflater();
final View dialogView=inflater.inflate(R.layout.cutomdialog,null);
builder.setView(dialogView);
dialog=builder.create();
dialog.show();
}

cutomdialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="+@id/myLayout
android:layout_width="match_parent"
android:layout_hight="match_parent"
android:orientation="vertical">

<ListView
android:id="+@id=myListView'
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<Button
android:id="+@id/myOkButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="OK"/>

</LinearLayout>

A: final CharSequence[] items = {"Foo", "Bar", "Baz"};

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Make your selection");
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
         // Do something with the selection
    }
});
AlertDialog alert = builder.create();
alert.show();

Source:
ListView in AlertDialog

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nodejs child process for deleting 6 hours older files on a directory I am working on NodeJs Child process for deleting all files on a directory which are 6 hours older. I have already done : delete all files on a directory without directory delete. But can do whose files are 6 hours olders.
My code :
var exec = require('child_process').exec;
var path = '../tmp/uploads';

exec('rm '+ path+"/*", function(err,stdout,stderr){
  if(err)
     console.log('Directory Empty', err);
  else
     console.log("Files Deleted");
});

So I need help on deleting those files which are older then 6 hours

A: If you want to do this using exec with linux command you can use
find /path/to/files* -mmin +360 -exec rm {} \;

exec('find /path/to/files* -mmin +360 -exec rm {} \;', function(err,stdout,stderr){
 if(err)
 console.log('Directory Empty', err);
 else
 console.log("Files Deleted");
});

Otherwise you can use File System Package
https://nodejs.org/api/fs.html#fs_class_fs_stats

A: Use the fs package:
https://nodejs.org/api/fs.html#fs_class_fs_stats
You should be able to get a files age from that
You can use the fact package to delete files too instead of using child_process.
Here is a link to how to do it using exec and shell command:
Shellscript - check a folder and delete files within that folder older than an hour


text:
Q: Mysql query to sum a column from a table where another two columns are unique when combined together I have a Mysql table where it combines three tables. This table stores some statistics for each combination of the three foreign keys.
eg:
1)A Files table
columns-
id - primary key
name
number_of_lines_of_text - the stats field

2)A Folders table has a one to many relationship with files table
columns-
id - primary key
name

3)A Folder_Groups table has a many to many relationship with the folders table
columns-
id - primary key
name

Finally the combination table ordered_file_stats
columns-
folder_group_id - foreign key from 3 above(can repeat multiple times)
folder_id - foreign key from from 2 above(can repeat muliple times)
file_id - foreign key from 1 above, unique but only a subset of the records from 1

I need to select and sum the number_of_lines_of_text field of the Files table for each unique combination of the folder_group_id and the folder_id in the ordered_file_stats table.
Which may look like
folder_group_id   folder_id  file_id
     1                2         1
     1                2         2
     1                3         9
     2                1         7
     2                1         8

How do I write the select statement to obtain the stats?

A: select ofs.folder_group_id, ofs.folder_id, sum( Files.number_of_line_of_text)
from ordered_file_stats ofs
join Files on Files.id = ofs.file_id
group by folder_group_id, folder_id


text:
Q: Passing worksheet object to another sub getting "object doesn't support this property or method" I'm writing a macro that along other things formats a bunch of much sheets, one subroutine I've written needs to accept a worksheet object I've defined and used earlier. When i try and call the subroutine with the worksheet object as a parameter i get an "object doesn't not support this property or method"
Option Explicit

Public wb As Workbook

Public data, summary_month, summary_item, summary_charge, summary_pro As Worksheet

Public i, n, x, y, z As Variant

Public libName(), itype(), tcharge(), tprofile() As Variant

Public profile, pay_lib, item_auth, total_paid, month, item_type, chr_type As Variant

Public Sub main()

Set wb = ThisWorkbook
Set data = wb.Sheets(1)
Set summary_month = wb.Sheets(2)
Set summary_item = wb.Sheets(3)
Set summary_charge = wb.Sheets(4)
Set summary_pro = wb.Sheets(5)

With data
    Set pay_lib = .Range( _
                    .Cells(2, 2), _
                    .Cells(2, 2).End(xlDown))
    Set item_auth = .Range( _
                    .Cells(2, 4), _
                    .Cells(2, 4).End(xlDown))
    Set month = .Range( _
                    .Cells(2, 3), _
                    .Cells(2, 3).End(xlDown))
    Set total_paid = .Range( _
                    .Cells(2, 10), _
                    .Cells(2, 10).End(xlDown))
    Set item_type = .Range( _
                    .Cells(2, 5), _
                    .Cells(2, 5).End(xlDown))
    Set chr_type = .Range( _
                    .Cells(2, 6), _
                    .Cells(2, 6).End(xlDown))
    Set profile = .Range( _
                    .Cells(2, 8), _
                    .Cells(2, 8).End(xlDown))

End With

'''''''''''''''''''''''''''''''''''''''''''''
''''''''''some other stuff'''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''

change_colors (summary_month)

End Sub

Sub change_colors(wksheet As Worksheet)

With wksheet
    For Each i In .Range(.Cells(2, 1), .Cells(2, 1).End(xlDown))
        If i.Row Mod 2 = 0 Then
            .Range(.Cells(i.Row, i.Column), .Cells(i.Row, i.Column).End(xlToRight)).Interior.ColorIndex = 31
        Else
            .Range(.Cells(i.Row, i.Column), .Cells(i.Row, i.Column).End(xlToRight)).Interior.ColorIndex = 2
        End If
    Next i
End With

when the subroutine is called the 'with' statement should alternate colors based on row, and from my testing there doesn't seem to be anything round with that, i get the error when the subroutine is being called. both subs are in the same module.
Clearly there is something i'm not fully understanding with how worksheet objects work any help would be greatly appreciated

A: declared worksheets separately rather than inline
Option Explicit

Public wb As Workbook

Public i, n, x, y, z As Variant

Public libName(), itype(), tcharge(), tprofile() As Variant

Public profile, pay_lib, item_auth, total_paid, month,
item_type, chr_type As Variant

Public Sub main()

Dim data As Worksheet
Dim summary_month As Worksheet
Dim summary_item As Worksheet
Dim summary_charge As Worksheet
Dim summary_pro As Worksheet

Set wb = ThisWorkbook
Set data = wb.Sheets(1)
Set summary_month = wb.Sheets(2)
Set summary_item = wb.Sheets(3)
Set summary_charge = wb.Sheets(4)
Set summary_pro = wb.Sheets(5)

and also made sure the subroutine was called as below rather than in parenthesis
change_colors summary_month


text:
Q: Should we keep the detrended time series when predicting? I am learning about exploring traditional TS. According to this notebook, detrending is necessary for time series predicting models

When a time series is stationary, it can be easier to model. Statistical modeling methods assume or require the time series to be stationary.

Yet when I want to predict the next move with SARIMAX, do I need to keep the detrended time series or the original time series?
Here is the tail of the original time series:
>>> df_settle.tail()

Date
2020-10-01    211.905228
2020-11-01    201.941315
2020-12-01    216.210007
2021-01-01    222.419998
2021-02-01    239.649994
Freq: MS, Name: Close, dtype: float64

If I keep the detrended the prediction doesn't make much sense:
df_log = np.log(df_settle)
df_log_ma = df_log.rolling(2).mean()
df_detrend = df_log - df_log_ma
df_detrend.dropna(inplace = True)

import itertools
import warnings
from statsmodels.tsa.statespace.sarimax import SARIMAX

warnings.filterwarnings("ignore")

def arima_grid_search(dataframe, s):
  p = d = q = range(2)
  param_combinations = list(itertools.product(p, d, q))

  lowest_aic, pdq, pdqs = None, None, None

  total_iterations = 0
  for order in param_combinations:
    for (p, d, q) in param_combinations:
      seasonal_order = (p, d, q, s)
      total_iterations +=1
      try:
        model = SARIMAX(df_settle, order=order,
                        seasonal_order = seasonal_order,
                        enforce_stationarity=False,
                        enforce_invertibility=False,
                        disp=False
                      )
        model_result = model.fit(maxiter=200, disp=False)

        if not lowest_aic or model_result.aic < lowest_aic:
          lowest_aic = model_result.aic
          pdq, pdqs = order, seasonal_order

      except Exception as ex:
        continue

  return lowest_aic, pdq, pdqs

lowest_aic, order, seasonal_order = arima_grid_search(df_detrend, 12)

model = SARIMAX(
    df_detrend,
    order=order,
    seasonal_order = seasonal_order,
    enforce_stationarity=False,
    enforce_invertibility=False,
    disp=False
)

model_results = model.fit(maxiter=200, disp=False)

n = len(df_detrend.index)
prediction = model_results.get_prediction(
    start=n-14*5, #changed from 12
    end=n+5
)

prediction_ci = prediction.conf_int()

Indeed, I get:
>>> prediction_ci.head(3)

    lower Close upper Close
2020-04-01  -0.090269   0.051201
2020-05-01  -0.071606   0.069863
2020-06-01  -0.042065   0.099405

Which doesn't make much sense compared to the last value of the original dataframe: 239.649994 for 2021-02-01

A: 'd' in SARIMAX is coming from integrated. For example if a process is integrated of order 1 it means it becomes stationary if you take the first difference. I believe when you define a SARIMAX model in R and if you take 'd' bigger than 0 it will take the difference 'd' times before fitting the model. If you wanna make the data stationary by yourself, such as using log difference over a regular difference operation, you need to set 'd' to 0, so that R does not take the difference for you. Setting 'd' to 0 is a way to tell your model: my data is already stationary. Seasonal order refers to seasonal difference. For instance if your data is both trending and have seasonality you need to remove both before fitting the model, and this corresponds to taking difference 2 times with lags determined by the seasonal and trend order. Looking your code, I see you are grid searching (p, d, q, s), then you should feed the data as it is without any transformation since SARIMAX will do the transformation for you under the hood. Or you can take log-difference set the d to zero and grid-search for (p, q, s) only.


text:
Q: Loop over a loop So far I have gotten my code to loop through five different rows on an excel sheet successfully. I not need it to do this same thing for twelve different sheets. I'm pretty new to python and attempted to put a for loop right on top of my previous for loop, with no success. Here is a snippet of the for loops I am using:
 sheetnames = ['0h UV Exposure, Roll Direction',
          '4h UV Exposure, Roll Direction',
          '8h UV Exposure, Roll Direction',
          '12h UV Exposure, Roll Direction',
          '18h UV Exposure, Roll Direction',
          '24h UV Exposure, Roll Direction',
          '36h UV Exposure, Roll Direction',
          '48h UV Exposure, Roll Direction',
          '68h UV Exposure, Roll Direction',
          '78h UV Exposure, Roll Direction',
          '82h UV Exposure, Roll Direction',
          '96h UV Exposure, Roll Direction']

 samplenums = [1,2,3,4,5]

 for sheet in sheetnames:
     for dataset in samplenums:
         data = get_data(sheetnames[sheet],dataset)

A: The variable sheet is already an element from sheetnames so there is no need to index it (that is actually wrong). You can simply do:
for sheet in sheetnames:
  for dataset in samplenums:
    data = get_data(sheet, dataset)

Without knowing what get_data(arg1, arg2) looks/does there is not much more we can do for you.


text:
Q: There is an issue with Select in my SQL The scoreboard has not been showing up in the rightHighScore div. It's just not showing anything. I'm making a high score board for my javascript snake game. So is there anything wrong with my MYSQL code here?

    <link href='style.css' type='text/css' rel='stylesheet'>

    <canvas id="canvas" width="450" height="450" style="border:1px solid #000000;"></canvas>

    <?php $score = ""?>

Your Final Score:

          <form action="highscoreregistry.php" method="post">
             <input type="hidden" name="score" id="score">

          </form>

        <?php
    $servername = "-";
    $username = "-";
    $password = "-";
    $dbname = "-";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT Name, Score, Date FROM snakehiscore";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    echo "

ID	Name
";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "
".$row["Name"]."	".$row["Score"]." ".$row["Date"]."
";
    }
    echo "
";
} else {
    echo "0 results";
}
$conn->close();
?>

A: *

*Add a semicolon to the query! So:
$sql = "SELECT Name, Score, Date FROM snakehiscore;";
2.Instead of using this:
$result = $conn->query($sql);

try this if you have mysqli installed:
$result = mysqli_query($conn, $sql);
mysqli_num_rows($result) > 0


text:
Q: How do I call a defined variable with jQuery? I'm kinda stuck.
I defined three variables:var part1 = "<form><input type='button' value='Open Window' onclick='window.open('http://jsfiddle.net/
";
var part2="5Xket,"
var part3 = "'toolbar=no',menubar='no')></form>";
My aim is to concat those variables to create a working link when clicking on the button.
This is my try to concat the values of the variables.
var mytest_2=part1+part2+part3;
alert (mytest_2);
By clicking a button the button from mytest2 should appear. Clicking on that button there should be opened a new window with the url http://jsfiddle.net/5Xket/
$('#searchbutton').click(function() {
$("<input id='an_id' type='text'>	").show();
$(mytest_2).insertAfter('#an_id');
Well, the button appears as it should, but won't open a window.
My guess is that I'm wrong with the syntax somewhere because the alert puts out the correct order of variables.
Any ideas? Thank you.

A: I should do this way:
var part1 = '<form><input id="button1" type="button" value="Open Window" /></form>';

$(part1).insertAfter('#an_id');

$('#button1').click(function(){
   window.open('http://jsfiddle.net/','5Xket','toolbar=no,menubar=no');
});

The problem with your code is double/single quotes aren't properly escaped.


text:
Q: One folder, two KML files We want to display two KML files into the Google Earth plugin.  KML 1 will have Folder 1, containing placemarks.  KML 2, will have more placemarks that belong under Folder 1.  Does KML/Google Earth support that?  The reason for two KML's is that we want to display KML 1 before we finish generating KML 2.  Actually, we may have several KML files...

A: Yes there are a number of ways to do this.
One simple way would be to create Folder 1 via the api rather than via KML.
Then when you load your KML files you can simply append them to the folder you created
For example.
var folder = ge.createFolder("folder1");
google.earth.fetchKml(ge, "your.kml", function(kml) {
  if(kml) {
    folder.appendChild(kml);
  }
});

If you did want or need to load Folder 1 via KML you could simply target it via getElementByUrl and then append any further KML to it.
var folder = ge.getElementByUrl("your.kml#folder1");
google.earth.fetchKml(ge, "more.kml", function(kml) {
  if(kml) {
    folder.appendChild(kml);
  }
});

Finally, the KML NetworkLink and NetworkLinkControl elements could be used to link the files together - allowing you to update your data dynamically solely via KML...but without more information on your setup it is hard to offer any specific solutions in this regard.


text:
Q: Batch Delete from tableA based on data on tableB I'm trying to implement a batch delete.
I found this code on the internet:
DECLARE @rowcount int = 1
WHILE (@rowcount != 0 ) BEGIN
    DELETE T1
    FROM (SELECT TOP (50) * FROM Orders WHERE OrderCity = @city) T1

    SELECT @rowcount = @@ROWCOUNT
END

the idea is to delete all orders from @city
It seems to work fine but on my reality, I need to delete from Orders where OrderCity in (select ID from SomeOtherTable)
If I try to do the same, it works but it takes a lot of time because SomeOtherTable will contain around 1.5 million rows and the data is being deleted from the main table, so it doesnt get any smaller (it does not contains cities, its another thing).
I also cant join both tables because it wont run saying that more than one table will be affected.
So basically my question is: Is there anyway to batch delete from tableA where tableA.ID IN (select ID from tableB)

A: Yes you can do it without join as:
DELETE tableA
FROM tableB
WHERE tableA.ID = tableB.ID

A: Delete Order
FROM
Order INNER JOIN SomeOtherTable ON Order.OrderCity = SomeOtherTable.ID

This could solve your problem

A: You should be able to delete based on a join. Try
DELETE FROM tableA
FROM tableA A
JOIN tableB B ON A.ID = B.ID

Also, if tableB has ~ a million rows, it would really help if you have an index on the ID column.


text:
Q: Integro-functional equation I'd like to solve (preferably analytically) the following integro-functional equation or at least to reduce it to some kind of a differential equation if possible:
$\varepsilon \left( {\omega ,q} \right) = \int\limits_a^b {\frac{{{p^2}dp}}{{f\left( p \right) - f\left( {p + q} \right) + \omega }}}$,
where limits of the integration are some numerical values and the function $\varepsilon \left( {\omega ,q} \right)$ is known, for instance $\varepsilon \left( {\omega ,q} \right) = \omega^2 + q^2$.
I would be grateful for any ideas.


text:
Q: How to active outlook add-ins(extension) automatic? I develope a outlook extension(add-ins) and I did a setup.exeby publish projetname.
After I install setup.exe in another computer(windows), I have a problem, because my outlook extension(add-ins) is always inactive by defaut...Every time to start outlook, I need to active my outlook extension(add-ins) by myself...
How to let my outlook extension(add-ins) be active when the outlook is started? Thank you?

A: That means your addin does something (like crashing) that causes Outlook to disable it.

A: Follow the following steps :

*

*open regedit.exe and locate this registry entry:-

HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Outlook\Resiliency\DisabledItems
(Note: 14.0 this depends on the Outlook version you're using, 14.0 is for Outlook 2010, previous versions will have lower version and advanced version will have higher number)
Delete any Reg_binary keys (do not delete default)

*Delete the DisabledItems folder and then restart the outlook


text:
Q: re.findall between two strings (but dismiss numeric digits) I am trying to parse many txt files. The following textis just a part of a bigger txt files.

Prior to this primary offering, there has
been no public market for our common stock. We anticipate that the public offering price of the shares will be between $5.00 and
$6.00. We have applied to list our common stock on the Nasdaq Capital Market (“Nasdaq”) under the symbol “HYRE.”
If our application is not approved or we otherwise determine that we will not be able to secure the listing of our common stock
on the Nasdaq, we will not complete this primary offering.

My desired output: be between $5.00 and and $6.00. So, I need to extract anything between the be betweenuntil the following . (but not taking into account the decimal 5.00 point!). I tried the following (Python 3.7):
shareprice = re.findall(r"be between\s\$.+?\.", text, re.DOTALL)

But this code gives me: be between $5. (stops at the decimal point). I initially add a \s at the end of the string to require a white space after the . which would keep the 5.00 point decimal, but many other txt files do not have a white space right after the ending . of the sentence.
Is there anyway I can specify in my string that I want to "skip" numeric digits after the \.?
Thank you very much. I hope it was clear.
Best

A: After parsing the plain text out of the HTML, you may consider matching any 0+ chars as few as possible followed with a . that is not followed with a digit:
r"be between\s*\$.*?\.(?!\d)"

See the regex demo.
Alternatively, if you only want to ignore the dot STRICTLY in between two digits you may use
r"be between\s*\$.*?\.(?!(?<=\d\.)\d)"

See this regex demo. The (?!(?<=\d\.)\d) makes sure the \d\.\d pattern is skipped up to the first matching ., and not just \.\d.


text:
Q: Oracle JSF Tutorial: GlassFish 3: updatetool crashes I am trying to run the JavaServer Faces tutorial on the Oracle site:
http://docs.oracle.com/javaee/6/tutorial/gexaj.html
However when I run on Ubuntu Linux 12.04.2 LTS I get the following:
$ updatetool
WX import error.  Verify the WX widgets are in the PYTHONPATH.
The following can be reported to GlassFish Update Tool 2.3.5 Development Team <dev@updatecenter.java.net>.

Traceback (innermost last):
  File "/home/johndoe/glassfish3/updatetool/vendor-packages/updatetool/common/boot.py", line 283, in init_app_locale
    import wx
  File "wx/__init__.py", line 45, in ?
  File "wx/_core.py", line 4, in ?
 ImportError: libjpeg.so.62: cannot open shared object file: No such file or directory

Line 283 of boot.py has the following "import wx" statement:
try:
    # XXX : This still fails badly with segfault on bad locales
    import wx
except:
    typ, val, tback = sys.exc_info()
    if str(typ) == "locale.Error":
        if sys.platform not in ['win32'] and os.environ['LANG'] != 'C':
            UPDATETOOL_LOCALE = _set_unix_locale_vars('C')
            try:
                import wx
            except:
                # NOL10N
                uc_error("The current locale is not supported and we could not fallback to english locale.", 1)
        else:
            # NOL10N
            uc_error("The current locale is not supported and we could not fallback to english locale.", 1)
    else:
        import traceback
        lst = traceback.format_tb(tback) + traceback.format_exception_only(typ, val)
        msgx = _("WX import error.  Verify the WX widgets are in the PYTHONPATH.\nThe following can be reported "\
                "to %(email)s.\n\nTraceback " \
                "(innermost last):\n%(tracefirst)-20s %(tracerest)s") % {'email':INFO.REPORT_TO, 'tracefirst': "".join(lst[:-1]), 'tracerest': lst[-1]}
        uc_error(msgx, 1)

_ = wx.GetTranslation

I am running python 2.7.3. Anyone know how to fix this error?

A: Updatetool uses its own 32-bit version of python, so you need to install the i386 version of libjpeg62:
sudo apt-get install libjpeg62:i386


text:
Q: How to control user input in prolog? I have this problem with my code in prolog.
It is about fashion stylist expert system that takes properties from the user and gives her the specified look.
Here is the code:
main_level(2):-
    write('Please enter weight (60s (1), 50s (2)): '), read(W),
    write('Please enter tall (more than 160 (1), less than 160 (2)): '), read(T),
    write('Please enter skin color (bronze (1), white (2), black (3)): '), read(S1),
    write('Please enter hair length (medium (1), short (2), long (3)): '), read(H1),
    write('Please enter hair color (brown (1), black (2), blond (3)): '), read(H2),
    write('Please enter event (wedding (1), fami party (2): '), read(E),

But how I can force the user to enter the correct answer, so the program will not complete until the user enters the correct answer?
I tried to do it by using recursive rule but It didn't work either!

A: Basically, you could validate each input with this schema:
main_level(2):-
    repeat, write('Please enter weight (60s (1), 50s (2)): '), read(W), (W == 1 ; W == 2),
    repeat, write('Please enter tall (more than 160 (1), less than 160 (2)): '), read(T), (T == 1 ; T == 2),
...

but I would suggest instead to code a simple menu, like
menu(Header, Choices, Choice) :-
  repeat,
  write(Header),
  forall(nth1(I,Choices,Value), format('~w (~d) ', [Value,I])),
  read(C),
  nth1(C, Choices, _). % validate index input

and call it with
main_level(2):-
    menu('Please enter weight ',['60s','50s'], W),
    menu('Please enter tall ',['more than 160','less than 160'], T),
    ...

A: You can test if the answer is equal to the expected values, if not the rule fails, you can use a cut (!) after this check to show the error message  as below.
main_level(2):-
write('Please enter weight (60s (1), 50s (2)): '),
read(W), (W == 1; W == 2),!,...

main_level(2):- write('Please enter a value according to the menu').


text:
Q: Ruby ActiveRecord Dynamic Model creation I am trying to establish a multiple DB connection with ActiveRecord.Currently I need to insert data into total 2 Databases. There is a possibility for increase in the No.Of databases.
So I created 2 classes dynamically which will Extend from ActiveRecord::Base
Object.const_set("Connection1",Class.new(ActiveRecord::Base) do
  self.abstract_class = true
  self.establish_connection({
    :host=>"localhost", :username=>"root", :password=>"root", :database=>"db1", :encoding=>"utf8", :adapter=>"mysql2"})
end)

Object.const_set("Connection2",Class.new(ActiveRecord::Base) do
  self.abstract_class = true
  self.establish_connection({
    :host=>"localhost", :username=>"root", :password=>"root", :database=>"db2", :encoding=>"utf8", :adapter=>"mysql2"})
end)

Then I created Dynamic models extends from each class accordingly
Object.const_set("ConnectionUser1",Class.new(Connection1) do
  self.table_name = 'user'
  def self.foo
    all.count
  end
end)

Object.const_set("ConnectionUser2",Class.new(Connection2) do
  self.table_name = 'user'
  def self.foo
    all.count
  end
end)

Then when I tried to call foo method
p ConnectionUser1.foo
p ConnectionUser2.foo

It gives me ActiveRecord::ConnectionNotEstablished Error.
I heard that if the model doesn't have connection ActiveRecord will take connection of their parent.
So according to this ConnectionUser1 should use the connection of Connection1 and ConnectionUser2 use the connection of Connection2.
Then why ActiveRecord fails to Establish Connection?
Any help will be appreciated.
Thank you.

A: Take a look at below link which shows that how to use multiple database with ActiveRecord.
How do i work with two different databases in rails with active records?


text:
Q: Mac Pro won't start from DVD, crashes while trying I have a Mac Pro 10.6.8 which will not start.
I wanted to re-install my Mac Pro (Intel dual core 2.66) which is currently running Mac OS X 10.6.8.
I inserted the retail Mac OS X 10.6 install disc, and held down the C key on my keyboard to boot the machine.
The disc can be heard spinning up, and the grey Apple logo appears. However, the Mac Pro crashes on start up from DVD, what can I do?

A: Assuming your disc is clean and damage free it looks like your optical drive may be at fault. If your disc does have any obvious defects (check for scratches etc. on the label side, these can cause totally unrecoverable data loss) you know where the fault lies. Has the drive had any sort of regular use or is it a while since you used it?
If you have access to another Mac you will be able to copy the 10.6 DVD onto an 8GB USB stick using Disk Utility's Restore function, which will then boot the Mac - if the optical drive is at fault.


text:
Q: Forward incoming connection on one adapter to another adapter? I have two adapters on a server.
For the sake of this example, let's call them ad1 and ad2.
 ad1, ip = xxx.xxx.x.x (internet connection)
 ad2, ip = 192.168.1.1 (this system is the gameway for 192.168.1.5)

I need to forward connections coming in on ad1 on port 1234 to an ip on ad2 that is 192.168.1.5 on port 1238.
I need to know how to do this for both UDP and TCP, but in seperate commands as some times I'll need to forward UDP and some times I'll need to forward TCP.
I'm pretty new to using iptables, so just looking for some help.

A: Thanks to amauk on reddit for this answer. Figured I'd post it here as well in case anyone came across this question.
First, you need to enable IP forwarding.
This is disabled by default, for security reasons.
vim /etc/sysctl.conf
net.ipv4.ip_forward = 1
Then run the following to commit the changes and reload the sysctl configuration
sysctl -p
Then you need to write the IPTables rules to forward the connections.
TCP
iptables -t nat -A PREROUTING -i ad1 -p tcp -m tcp --dport 1234 -j DNAT --to-destination 192.168.1.5:1238

UDP
iptables -t nat -A PREROUTING -i ad1 -p udp --dport 1234 -j DNAT --to-destination 192.168.1.5:1238

Packets incoming from interface ad1 -i ad1 matching the criteria (TCP/UDP + port number), NAT to destination:port
You'll also need to save the IPTables rules somehow, and have these restored on boot
Exactly how you do this is distro specific.
edit
For deleting rules, use -D (delete) in place of -A (append)
Eg.
To delete the TCP forwarding rule
iptables -t nat -D PREROUTING -i ad1 -p tcp -m tcp --dport 1234 -j DNAT --to-destination 192.168.1.5:1238


text:
Q: Failing MERGE Statement: How to monitor with XEvents and specifically get parameter values for a prepared statement? My problem
I am running SQL Server 2017 and would like to investigate an error with a MERGE statement like the following
MERGE INTO table
USING
    (SELECT ? AS Search_Col) AS SRC
    ON table.blobTask_id = SRC.Search_Col
WHEN MATCHED THEN
    UPDATE SET
    x= ?,
    y= ?,
    z= ?
WHEN NOT MATCHED THEN
    INSERT (blobTask_id ,x, y, z, )
    VALUES (SRC.Search_Col, ?, ?, ?)

Error is

Violation of UNIQUE KEY constraint 'IX_U_CCC_GDV_CONTENTCCC__blobTask_id'. Cannot insert duplicate key in object 'table'. The statement has been terminated.

I am aware that the MERGE statement comes with serveral gotchas. However I could outrule the typical issues ( no triggers, no concurrency on data modifications on the table).
Odd thing is that the Error just comes up just every once in a while and executing the statement again works without errors.
My diagnostic approach
I set up an Extended Events Session filtering for just the query_hash of the problematic statement. Jeremiah Peschka has a great blog post which I followed to do this.
Currently my XEvent Session looks like this:
CREATE EVENT SESSION [query hash] ON SERVER
ADD EVENT sqlserver.prepare_sql(
    ACTION(package0.collect_system_time,sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.database_name)
    WHERE ([sqlserver].[query_hash]=(6577967268103212561.))),
ADD EVENT sqlserver.sp_statement_completed(SET collect_statement=(1)
    ACTION(package0.collect_system_time,sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.database_name,sqlserver.sql_text)
    WHERE ([sqlserver].[query_hash]=(6577967268103212561.))),
ADD EVENT sqlserver.sql_statement_completed(
    ACTION(package0.collect_system_time,sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.database_name)
    WHERE ([sqlserver].[query_hash]=(6577967268103212561.)))
ADD TARGET package0.event_file(SET filename=N'X:\DB_Data\query_hash.xel',max_file_size=(5),max_rollover_files=(5),metadatafile=N'X:\DB_Data\query_hash.xem')
WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=5 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)
GO

My question
Problem is that with this session I only get recordings like the following:

Somehow only sp_statement_completed Events show up.
In order to debug the problem it is vital to get to the parameters of the SQL.
Specific question: How do I modify the XEvent session to show me the param values?
I was hoping to get that information from the prepare_sql event but it doesn't show up in the session....perhaps due to my filter?
General request for help: If you know about other ways to effectively troubleshoot and alleviate the issue please let me know as well.
Your Help is much appreciated
Thank you in advance
Martin

A: Your merge statement is not correctly formed and will always insert all the records, so you will need to update it and tell it to insert the records not matched in the destination table using  WHEN NOT MATCHED like this:
MERGE table
USING
    (SELECT ? AS Search_Col) AS SRC
    ON table.blobTask_id = SRC.Search_Col
WHEN MATCHED THEN
    UPDATE SET
    x= ?,
    y= ?,
    z= ?
WHEN NOT MATCHED THEN
    INSERT (blobTask_id ,x, y, z, )
    VALUES (SRC.Search_Col, ?, ?, ?)

To get the exact statement and parameters for a statement that fails you'll need to capture events before the statement is executed, as the statement fails you will not get a completed statement.
 CREATE EVENT SESSION [a] ON SERVER
  ADD EVENT sqlserver.sql_statement_starting(
  ACTION(sqlserver.sql_text))

A: Thank you @Dan Guzman.
rpc_completed was the missing event for me.
Unfortunately there's no simple filtering possible an a query hash because there isn't one associated with the sp_executesql procedure call.
Thus I chose to filter on the sqltext itself (possibly a costly operation but it works).
Here's my final XEvent session in case somebody can take advantage of it:
DROP EVENT SESSION [query hash] ON SERVER;
GO
CREATE EVENT SESSION [query hash] ON SERVER
ADD EVENT sqlserver.sp_statement_completed(SET collect_statement=(1)
    ACTION(package0.collect_system_time,sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.database_name,sqlserver.sql_text,sqlserver.session_id)
    WHERE ([sqlserver].[query_hash]=(6577967268103212561.))),
ADD EVENT sqlserver.rpc_completed(
    ACTION(package0.collect_system_time,sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.database_name, sqlserver.query_hash)
    --WHERE ([sqlserver].[query_hash]=(6577967268103212561.))
    WHERE sqlserver.sql_text LIKE '%ERGE INTO table%'
    ),
ADD EVENT sqlserver.error_reported(
    ACTION(package0.collect_system_time,sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.database_name,sqlserver.sql_text,sqlserver.session_id)
    WHERE (([error_number]=2627))
    )
ADD TARGET package0.ring_buffer(SET max_events_limit=(100000),max_memory=(512000))
WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=5 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)
GO

Now I wait for the next error to occur and will post the findings and the solution after I have one.


text:
Q: Community Builder not working in clean Joomla 3.5 installation (PHP7) I've been using Community Builder (CB) on a Joomla 2.5 website for a while without any problems. Yesterday I tried to install CB v2.0.13 on a clean Joomla 3.5 installation. The actual installation process finishes without any errors, but when I try to access any backend functionality of CB, i.e. the user management, the following error occurs:

Argument 1 passed to CBLib\Session\SessionState::__construct() must implement interface CBLib\Session\SessionInterface, null given

For development, I am using the Bitnami WAMP stack with PHP7. According to https://www.joomlapolis.com/news/18532-cb-2013-ready-for-joomla-35-and-php-70 CB 2.0.13 supports both, PHP7 & Joomla 3.5.
Has anybody come across the same issue and got an idea how to make CB work in my setup?

A: Community Builder v2.0.14 was just released and resolves my issue. It's working like a charme now. More information on the update: https://www.joomlapolis.com/news/18543-joomla-35-and-community-builder-2014-released


text:
Q: Why is React.forwardRef preventing this HOC from rendering when context updates? I came across this behavior while working on this epic react lesson, and after re-reading the react docs on both forwardRef and HOCs cannot figure out why this would be happening.
I've cut the epic react lesson down below to demonstrate what I am seeing.  Basically, it's an AppProvider component providing access to the global state through context, then the withStateSlice HOC retrieves the correct slice of state and injects it into the state prop of the Cell components.
The weird behavior I'm seeing is when the withStateSlice HOC calls forwardRef on the wrapped component:
return React.memo(React.forwardRef(Wrapper))
the profiler shows that only the one Cell that was clicked actually rendered.

If I remove forwardRef from the above so we are left with this:
return React.memo(Wrapper)
then I am seeing all the Cell HOC components rendering, which from what I understand of context should be the expected behavior.

From what I've read this it doesn't seem like forwardRef should affect rendering when context changes but I could be wrong.  This is with React 17.0.2 and I am seeing the same behavior in development and production builds (with profiling turned on using: react-scripts build --profile
import * as React from 'react'

const AppStateContext = React.createContext()
const AppDispatchContext = React.createContext()

function appReducer(state, action) {
  switch (action.type) {
    case 'UPDATE_CELL': {
      const newState = [...state];
      newState[action.i] = state[action.i] + 1;
      return newState
    }
    default: {
      throw new Error(`Unhandled action type: ${action.type}`)
    }
  }
}

function AppProvider({children}) {
  const [state, dispatch] = React.useReducer(appReducer, [5, 5, 5, 5, 5, 5])
  return (
    <AppStateContext.Provider value={state}>
      <AppDispatchContext.Provider value={dispatch}>
        {children}
      </AppDispatchContext.Provider>
    </AppStateContext.Provider>
  )
}

function useAppState() {
  const context = React.useContext(AppStateContext)
  if (!context) {
    throw new Error('useAppState must be used within the AppProvider')
  }
  return context
}

function useAppDispatch() {
  const context = React.useContext(AppDispatchContext)
  if (!context) {
    throw new Error('useAppDispatch must be used within the AppProvider')
  }
  return context
}

function fibonacci(n) {
  return n < 1 ? 0
       : n <= 2 ? 1
       : fibonacci(n - 1) + fibonacci(n - 2)
}

function withStateSlice(Comp, slice) {
  const MemoComp = React.memo(Comp)
  function Wrapper(props, ref) {
    const state = useAppState()
    return <MemoComp ref={ref} state={slice(state, props)} {...props} />
  }
  Wrapper.displayName = `withStateSlice(${Comp.displayName || Comp.name})`
  return React.memo(React.forwardRef(Wrapper)) // return React.memo(Wrapper)
}

function Cell({state: cellValue, i}) {
  const dispatch = useAppDispatch()
  const handleClick = () => dispatch({type: 'UPDATE_CELL', i})

  // Artificial slowdown for better visibility in profiler
  for (let n = 10; n < 20; n++) {
    fibonacci(n);
  }

  return (
    <button
      className="cell"
      onClick={handleClick}
    >
      {Math.floor(cellValue)}
    </button>
  )
}
Cell = withStateSlice(Cell, (state, { i }) => state[i])

function App() {
  return (

        <AppProvider>
          <Cell i={0} />
          <Cell i={1} />
          <Cell i={2} />
          <Cell i={3} />
          <Cell i={4} />
          <Cell i={5} />
        </AppProvider>

  )
}

export default App

A: 1. Problem
It's like a bug in devtools when you put React.forwardRef inside React.memo. Therefore, to know whether these Cells are really re-render or not, you can put console.log() inside Wrapper and then click Cell.
2. Some topics about this
I get some details about this topic but it still has not been solved.

*

*vasilii-kovalev create issue in react

*kentcdodds answer about this question


text:
Q: Wordpress query by multiple Custom fields and order by date So here is my query:
$args = array(
    'post_type' => 'Event',
    'posts_per_page' => 1000,
    'meta_key' => 'event_informations_show_on_the_homepage',
    'meta_value' => 'Show on the homepage',
    'meta_compare' => '==',
    'meta_key' => 'event_informations_date',
    'orderby' => 'meta_value_num',
    'order' => 'ASC'
);

$loop = new WP_Query( $args );

I want to select all posts that have the Custom field event_informations_show_on_the_homepage and the value of the Custom field event_informations_show_on_the_homepage and order by the date Custom field which is stored as a timestamp and is called event_informations_date.
What am I doing wrong?

A: @Uffo I would say your args are wrong, should be something like:
$args = array(
    'post_type' => 'Event',
    'posts_per_page' => 1000,
    'meta_query'=> array(
        array(
            'key'=>'event_informations_show_on_the_homepage',
            'value'=> 'Show on the homepage',
            'compare' => '=='
        )
    ),
    'meta_key'=>'event_informations_date',
    'orderby'=>'meta_value_num',
    'order'=>'ASC'
);

The way you did it, it's just the last meta_key that will be used both for filtering the query and to order. I'm not 100% sure if this way will work but give it a try.
Hope I've helped.

So I think you will need to filter the Group By SQL statement to make it work the way you want, something like that:
$args = array(
    'post_type' => 'Event',
    'posts_per_page' => 1000,
    'meta_query'=> array(
        'relation' => 'OR',
        array(
            'key'=>'event_informations_show_on_the_homepage',
            'value'=> 'Show on the homepage',
            'compare' => '=='
        ),
        array(
            'key'=>'event_informations_date',
        )
    ),
    'orderby'=>'meta_value_num',
    'order'=>'ASC'
);

add_filter('posts_orderby', 'edit_posts_orderby');

function edit_posts_orderby($orderby_statement) {
    $orderby_statement = "mt1.meta_value+0 ASC";
    return $orderby_statement;
}


text:
Q: Lookups based on criteria across sheets I am trying to extrapolate data from a from response in forms/google sheets.
On the attachment, students can select 1, 2 or 3 in any of the columns. I then need the header of the 3 selections to be looked up on the second sheet in the correct column (reducing it down to everything just in the square bracket is a bonus).
This is an example, in the real thing there'd be more students in the list.
Thanks
Lookup Example

A: try:
=ARRAYFORMULA(IFNA(VLOOKUP(A2:A, QUERY(SPLIT(FLATTEN(
 IF('Form responses 1'!C2:1000<>"", 'Form responses 1'!C2:1000&"×"&
 REGEXEXTRACT('Form responses 1'!C1:1, "\[(.*)\]")&"×"&'Form responses 1'!B2:B1000, )), "×"),
 "select Col3,max(Col2) where Col3 is not null group by Col3 pivot Col1"), {2,3,4}, 0)))


text:
Q: Is there any way to build app bundle in Cordova or convert cordova singned apk file into app bundle I have built an android app in Cordova and created the signed APK version too. But When I tried to release my app in the Google Playstore I found Google now does not allow the APK version. But I have no clue how to make an app bundle in Cordova.
Can anyone help me out so that I can create the app bundle to publish in the play store?
I have another question. I have two published apps. Should I have to upload the app bundle in the future for updates?

A: To generate a bundle, build your app with the flags --release -- --packageType=bundle
Yes in the future you should upload bundles


text:
Q: Close app when downloading an enterprise build - iOS 8 We are using the enterprise distribution system internally for our product and everything was working fine on iOS7.
When there is an update to the app, we pop open a UIWebView and show the download link.  The use then clicks the download link and the app minimizes and downloads and then the user can reopen the app.
In iOS8 it seems like the link is being downloaded in the background?  It keeps freezing also.  Is there a way to minimize or notify the user that the app is downloading and then reopen / refresh after the app finishes updating?
Thanks!


text:
Q: nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/test-servlet.xml] I found a lot of example how to solve this problem, but still I'm in the same place. I don't know what is wrong.

text-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />

<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>

<!-- Step 5: Define Spring MVC view resolver -->
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/" />
    <property name="suffix" value=".jsp" />
</bean>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-       app_3_1.xsd"
id="WebApp_ID" version="3.1">

<display-name>spring-mvc-demo</display-name>

<absolute-ordering />

<!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
<servlet>
    <servlet-name>test</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/test-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
<servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

The finally the error:
13-May-2020 20:20:39.198 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [D:\Tomcat9\apache-tomcat-9.0.34\webapps\spring-mvc-demo-1.0-SNAPSHOT.war]

13-May-2020 20:20:39.528 INFO [Catalina-utility-2] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
13-May-2020 20:20:39.838 INFO [Catalina-utility-2] org.springframework.web.servlet.FrameworkServlet.initServletBean Initializing Servlet 'test'
13-May-2020 20:20:39.938 SEVERE [Catalina-utility-2] org.springframework.web.servlet.FrameworkServlet.initServletBean Context initialization failed
    org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/test-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/test-servlet.xml]
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:340)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:305)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:224)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:195)
        at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
        at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:133)
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:637)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:522)
        at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:702)
        at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:668)
        at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:716)
        at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:591)
        at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:530)
        at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:170)
        at javax.servlet.GenericServlet.init(GenericServlet.java:158)
        at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1134)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1089)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:983)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4876)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5185)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:717)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:690)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:705)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:978)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1849)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
        at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
        at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:118)
        at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:773)
        at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:427)
        at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1620)
        at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:305)
        at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
        at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1151)
        at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1353)
        at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1357)
        at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1335)
        at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
        at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
        at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.base/java.lang.Thread.run(Thread.java:834)
    Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/test-servlet.xml]
        at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:159)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:331)
        ... 47 more
13-May-2020 20:20:39.958 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [D:\Tomcat9\apache-tomcat-9.0.34\webapps\spring-mvc-demo-1.0-SNAPSHOT.war] has finished in [760] ms
Can someone give me some tip what is wrong?


text:
Q: how to get JSON result of YQL ordered by the given XPATHs I am trying to crawl a website.
I have made my YQL query with XPATh for headline, Date, then Body of the article.

select * from html where url="mywebsite.com/myarticle" and xpath="headlineXpath | DateXpath | BodyXpath"

now the result in xml is headline, date, then body and this is what i am looking for.
but when i get the result in json format, i get it in another order headline, body then date
my question: how can i get the result in json according to the order of the given XPATHS?
thanks for your help

A: Did you try:
select headline, date, body from html where ...

instead of using *? I don't know much YQL so I may be off on the arguments, but the idea is to specify the order of fields using explicit selection instead of the wildcard.


text:
Q: How to write that as $X$ becomes more similar to $a$, $f(X)$ always becomes more similar to $z$ What would be the ideal formal notation to express that, as a variable $X$ becomes more similar to number $a$, the function $f(X)$ always becomes more similar to number $z$?
As far as I understand, both the following two formal constructs are actually inaccurate:

*

*as $X \to a$, $f(X) \to z$

*$\lim\limits_{X \to a} f(X)=z$
The reason why I think they are both not accurate is that they guarantee only that when $X$ is arbitrarily close to $a$, $f(X)$ becomes arbitrarily close to $z$. Yet, they do not imply a monotonic relation, that is, they do not imply that as $X$ approximates $a$, $f(X)$ always gets closer to $z$.

A: If I understand correctly, then I propose something like "For all $x_1,x_2$: $|x_2-a|<|x_1-a|\implies |f(x_2)-z|<|f(x_1)-z|$" If you also want the difference between $f$ and $z$ to get arbitrarily small, you could add "and $\displaystyle{\lim_{x\to a}}f(x)=z$".


text:
Q: Excluding lines that contain a pattern before replacing in Perl I have the following code to replace version string from a set of files
ack --ignore-file=is:HISTORY.md -l --print0 '1\.1\.1' | xargs -0 perl -pi -e 's/1\.1\.1/1\.1\.2/g'

Now, I realized there are some lines in the doxygen comment that also have the version string like this.
/**
 * Generate Tag id from Tag name
 *
 * @since 1.1.1
 * @static
 * @access public
 *
 */

How can I modify the above snippet so that lines that contain @since will be excluded?

A: To exclude lines with @since you could try this instead of your current perl replace code:
!/\@since/ && s/1\.1\.1/1.1.2/g

or even
/\@since/ || s/1\.1\.1/1.1.2/g


text:
Q: How to open last used preference screen? My application settings can be opened and closed with hardware menu button (as well as with back button when navigating out of the root screen). There are many child screens in this preferences.
(And lets say, there are two activities - main and settings).
I'd like that I could return to the last preference screen I was working with when I access application settings again.
Saving last preferenceScreen key and using setPreferenceScreen(lastPreferenceScreenKey) is not relevant as in this case I can't navigate up the hierarchy.
Setting PreferenceActivity.launchMode="singleTask" and starting main activity when user presses menu button didn't help - when I starting settings activity again Its root screen appears.
Is it possible somehow or another?

A: Maybe try to use a back button pressed listener:
    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        // Back button pressed
    }
    return super.onKeyDown(keyCode, event);
}

A: Try to use sharedPreference for storing last visited screen and use a dispatcher activity to dispatch to the correct activity based on the preference on launching the application.
Refer this link for your reference
.


text:
Q: Problems with using Qemu user mode to run an ARM64 binary I'm trying to run an ARM64 binary on my Kali Linux machine using Qemu user mode. This is the binary
~$ file arm_binary
arm_binary: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-aarch64.so.1, Go BuildID=kuiME-kEtOrjYr0NtuSC/F9nT4PAOBdJwNF6rCoCc/7l0D-CmOuZoubD_SqInN/JtxNTIAPCIxt045aNaaC, not stripped

I can see that it's a Go program and was compiled using musl so I installed musl-cross-make and musl:arm64, libc6-dev-arm64-cross, and gcc-aarch64-linux-gnu  from apt.
However, every time I try to run it, I get all these Error relocating: symbol not found errors.
~$ unset LD_LIBRARY_PATH; LD_DEBUG=libs QEMU_STRACE=1 qemu-aarch64-static -L /usr/aarch64-linux-musl/ arm_binary
Error relocating /lib/aarch64-linux-musl/libgps.so: __fdelt_chk: symbol not found180208 writev(2,0x55007ff7a8,0x2) = 81
180208 writev(2,0x55007ff8a8,0x2) = 0

180208 writev(2,0x55007ff788,0x2) = 1
Error relocating /lib/aarch64-linux-musl/libgps.so: __fprintf_chk: symbol not found180208 writev(2,0x55007ff7a8,0x2) = 83
180208 writev(2,0x55007ff8a8,0x2) = 0

180208 writev(2,0x55007ff788,0x2) = 1
Error relocating /lib/aarch64-linux-musl/libgps.so: __snprintf_chk: symbol not found180208 writev(2,0x55007ff7a8,0x2) = 84
180208 writev(2,0x55007ff8a8,0x2) = 0

180208 writev(2,0x55007ff788,0x2) = 1
Error relocating /lib/aarch64-linux-musl/libgps.so: __syslog_chk: symbol not found180208 writev(2,0x55007ff7a8,0x2) = 82
180208 writev(2,0x55007ff8a8,0x2) = 0

There are many more errors but I've omitted them. I have libgps.so and all the other files that the binary supposedly cannot relocate. Does anyone know what the issue might be?

A: The error is telling you that libgps.so needs the __fdelt_chk, __fprintf_chk, etc symbols from some other library but nothing provided them.
In this case a little googling suggests that those functions __fdelt_chk, __fprintf_chk, etc, are supposed to be provided by the libc (glibc has them, musl may provide them for backwards compatibility, or may not). The library libgps.so was presumably linked against a newer or different version of libc than whatever the one in your sysroot is.


text:
Q: Base class on the initialisation list of a derived class' copy constructor (C++) Let the example be:
class Base {
  Base (const Base & copyFrom) { globalRegister (* this); }
}

class Derived {
  Derived (const Derived & copyFrom) : Base (copyFrom) {}
}

I've read suggestions to include the Base's copy constructor on the initialisation list of Derived in order to copy over the Base's properties (as in the example).
However, I have the Base's copy constructor passing itself (* this) to other object (to be registered with that object). Would that be a case where I actually must use (implicitly or explicitly) Base's (default) constructor on the initialisation list of Derived's copy constructor, and call the Base's copy constructor only in the body of Derived's copy constructor, when there is actually an object that can be attached by Base's copy constructor? Else - is (* this) a valid object?

A:
Would that be a case where I actually must use (implicitly or explicitly) Base's (default) constructor on the initialisation list of Derived's copy constructor, and call the Base's copy constructor only in the body of Derived's copy constructor, when there is actually an object that can be attached by Base's copy constructor?

Why on earth would you want to do that?
(Oh, and you can not call a base class' copy constructor from a derived class' constructor's body. Only from its initialization list.)

Else - is (* this) a valid object?

The moment the base's initialization list has completed, all of base's members (and base classes) are fully constructed. The class itself, however, is only fully constructed when its constructor has finished.
More importantly, the derived class' constructor hasn't even started yet, so the object is not a derived class' object yet.
So whatever that registering function does, it has to take into account that the object's dynamic type is base and that its constructor hasn't finished yet. (To be safe, all it can do is to store the object's address somewhere.)

A: Just for reference, the behavior is specified by § 12.7 2-3 of C++03:

2) To explicitly or implicitly convert a pointer (an lvalue) referring to an object of class X to a pointer (reference) to a direct or indirect base class B of X, the construction of X and the construction of all of its direct or indirect bases that directly or indirectly derive from B shall have started and the destruction of these classes shall not have completed, otherwise the conversion results in undefined behavior.

this is a pointer to Derived. In Base::Base(), this is implicitly cast to a Base*, which is allowed because the construction of Derived has started and it has no other bases that derive from Base.
§ 12.7 2 continues:

To form a pointer to (or access the value of) a direct nonstatic member of an object obj, the construction of obj shall have started and its destruction shall not have completed, otherwise the computation of the pointer value (or accessing the member value) results in undefined behavior.

Finally, § 12.7 3 is also important:

3) Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructor's own class or in one of its bases, but not a function overriding it in a class derived from the con- structor or destructor's class, or overriding it in one of the other base classes of the most derived object (1.8). If the virtual function call uses an explicit class member access (5.2.5) and the object-expression refers to the object under construction or destruction but its type is neither the constructor or destructor's own class or one of its bases, the result of the call is undefined.

These two clauses means an instance of Derived is a fully-fledged Base once a Base constructor begins, though it might be in an inconsistent state.


text:
Q: How do i read a pendulum phase diagram? I'm trying to understand how the intermediate axis theorem works. And in one of the works that I found, they used a pendulum phase diagram, but idk how to read it. Can anybody help please?
The work that I'm looking at is https://arxiv.org/abs/1606.08237 and the diagram I'm looking at is on page 8.
But it looks similar to this:

A: This is a diagram in two dimensional phase space. The horizontal axis $q$ is the angle that the pendulum makes with the vertical. The vertical axis $p$ is the associated momentum i.e. the angular momentum of the pendulum.
In each of the orbits inside the red line the pendulum swings to and fro between a position $A$ with angle $-\theta$ and a position $B$ with angle $\theta$. At $A$ and $B$ the pendulum's angular momentum is zero. As it swings from $A$ to $B$ its angular momentum is positive, reaching a maximum when $q=0$. As it swings from $B$ back to $A$ its angular momentum is  negative, reaching a minimum when $q=0$.
The orbits outside the red line are when the pendulum has sufficient momentum to swing "over the top" and continue rotating for ever. The orbits above the red line are rotations with positive momentum. Those below the red line are rotations in the opposite direction, with negative momentum.
The phase space diagram is laid out on a plane, but if you imagine it wrapped around so that the line $q=\pi$ meets the line $q=-\pi$ then you can see that the phase space of a simple pendulum is actually a cylinder.


text:
Q: Pandas to_csv multiple pages So as of right now I have FINALLY figured out how to get things into a dataframe but am totally new to programming and think something shouldnt be in this loop hence the problem..
So what I am trying to do is pull baseball data from http://rotoguru1.com/cgi-bin/byday.pl?game=dk
The formatting is correct for the df but I have a few problems.
1.) I have the writing to csv in the for loop for the page scraping which I think I have to take out? Do I just create a new variable to store the information before writing it to csv?
2.) the paging goes by dates so I just did for i in range(410, 518) to try and get all the dates between april tenth and may 17th.. However obviously it just increments past the 30th day and goes until 99 so I dont see any data for those.
Regardless here's the code I have so far... I am a newbie so take it easy on me :P
for i in range(410, 518):
    r = requests.get("http://rotoguru1.com/cgi-bin/byday.pl?date={}&game=dk".format(i))

    soup = bs.BeautifulSoup(r.content,"lxml")
    table = soup.find_all('tr')[9]
    headers = [th.getText().replace('\xa0', '') for th in table]
    headers.insert(0,'Position')

    data_rows = soup.find_all('tr')[10:430]
    player_data = [[td.getText().replace('\xa0', '') for td in data_rows[i].find_all('td')] for i in range(len(data_rows))]

    df = pd.DataFrame(player_data, columns=headers)
    df.to_csv("testingbaseball.csv")

A: Is this what you want?
import os
path = 'testingbaseball.csv'
if not os.path.exists(path):
    df.to_csv('testingbaseball.csv')
else:
    df.to_csv('testingbaseball.csv', mode='a', header=False)

This way you'll just keep adding the new data to your csv data file.


text:
Q: Stripping silence with sox I have around 20,000 .wav files (all voice lines) that I need to strip the silence from the start AND end of.
The "silence" isn't pure silence, so I'll need to set a threshold.
I'd also like to leave a little "silence" before the actual sound/voice starts, so each file would get trimmed but .X seconds of the original silence remains.
I've tried various commands and can't get it to set a threshold correctly. I've seen a lot of internet comments about doing this, so I must be using the command wrong.
I also can't figure out how to leave .X seconds of silence.
I assume sox can do this, or at least most of it?

A: Trim the silence beginning of the audio
sox in.wav out1.wav silence 1 0.1 1%

Source: https://digitalcardboard.com/blog/2009/08/25/the-sox-of-silence/

A: Trimming silence at the start and end
One solution would be (based on this Digital Cardboard blog post):
sox in.wav out.wav silence 1 X Y reverse silence 1 X Y reverse

X is the minimum duration (in seconds) of a sound in order to be interpreted as non-silence by sox. For example there might be a loud clicking sound at the beginning of the audio that is 0.15 seconds long. If we set 0.2for X then this loud but short click will be interpreted as silence  and will be removed. If for X we set 0.1 then the click will be interpreted by sox as the start of the non-silence part, meaning everything before the click will be removed but not the click itself.
Also note that a trailing zero should be used if the duration is a whole number, so 1.0 should be used instead of 1 to avoid unexpected behavior.
Y defines a loudness threshold. Everything below it will be interpreted as silence, no matter how long or short it is. So some long rumbling sound at the beginning, that is not very loud might fall below the threshold and thus gets interpreted as silence and thus is not removed. Everything that is loud enough to be above the threshold will be interpreted as the start of non-silence if its duration is long enough (see X).
Note that
digitalcardboard states that the smallest value to be used should be 0.1% instead of 0.
1 simply specifies to remove silence only at the beginning. To trim silence at the end we use the same but reverse the audio first. Why this approach is correct for trimming the end should become apparent below, where I analyze what the solutions of the other answers do.
Leaving a certain amount of silence at the beginning
The simple answer is: sox does not support this.
But we can try to work around this by trimming the silence and then add a fixed amount of silence at the beginning. This can be done with:
sox in.wav out.wav silence 1 0.1 0.1% reverse silence 1 0.1 0.1% reverse pad X 0

X is the duration (in seconds) of the silence that we want to prepend.
0 in this position means that no padding should be added at the end.
Of course this is not the same as keeping some duration of the original silence (if present), because that would also allow result files that don't have any silence at the beginning if the input also doesn't have any silence at the beginning. Still, trimming + padding is the best I could come up with.
Previous answers
So far all the answers here are no solution for the question. OP wanted to remove silence from the start and the end. Here is what the previous solutions do instead, for the interested:

*

*Kid_Learning_C: Multiple output files are generated where each file contains one of the non-silent parts of the input. So suppose the input file consists of Silence->Non-Silence-A->Silence->Non-Silence-B->Silence. Using the arguments from this answer we would get output001.wav containing Non-Silence-A. output002.wav containing Non-Silence-B. And for some reason an extremely short output003.wav.

*DSBLR: The end is not trimmed.

*Anas Naguib: Also removes in-between silence. So with an input file that consists of Silence->Non-Silence-A->Silence->Non-Silence-B->Silence we would get Non-Silence-A->Non-Silence-B which means all silence is removed. Not just at the start and end.

Oh, and all of those answers provide no solution for keeping some of the silence at the beginning as asked by the OP.

A: I found this very useful guide for using SoX Silence. While the official SoX Silence manual page is quite a mess and incomprehensible, this guide provides thorough explanation with examples:
https://digitalcardboard.com/blog/2009/08/25/the-sox-of-silence/comment-page-2/
You can try:
sox input.wav output.wav silence 1 X 0.1% 1 X 0.1% : newfile : restart
with X being a number such as 0.75

A: You can use this command for Sox
sox inputfile.wav tmpoutput.wav silence 1 0.75 0.1% -1 0.75 0.1%


text:
Q: XMLPullParser not reading empty tags like  Below is my XML, I am going to parse it using XMLPullParser. The parser correctly reads values from tags like
<hours>Monday: 1:00 PM - 3:00 PM Thursday: 8:30 AM - 12:30 PM</hours>

But if there is no timing data given by the webservice, the hours tag is empty:
<hours/>

and XMLPullParser skips those tags. I want to read a null value or empty string from such tags.
<?xml version="1.0" encoding="UTF-8"?>
<root>
  <city_data>
    <city_details>
      <id>1</id>
      <city>City1</city>
      <location>5390 Park</location>
      <phoneno>239-963</phoneno>
      <fax>239-963</fax>
      <hours>Monday: 1:00 PM - 3:00 PM Thursday: 8:30 AM - 12:30 PM</hours>
      <latitude>26.2134964</latitude>
      <longitude>-81.7672781</longitude>
      <action>2</action>
    </city_details>
  </city_data>
  <city_data>
    <city_details>
      <id>2</id>
      <city>City2</city>
      <location>13100 Westlinks</location>
      <phoneno>239</phoneno>
      <fax>239-332</fax>
      <hours/>
      <latitude>26.553446</latitude>
      <longitude>-81.7560699</longitude>
      <action>2</action>
    </city_details>
  </city_data>
</root>

A: You need to use XmlPullParser.isEmptyElementTag() to detect empty tags like <hours/>. This will allow you to handle

<hours>Monday: 1:00 PM - 3:00 PM Thursday: 8:30 AM - 12:30
  PM</hours>

differently than

<hours/>.

The documentation is here: XmlPullParser.isEmptyElementTag


text:
Q: Facebook Page Tab Aplication external link I have been creating one little facebook page tab for my company and I have encountered on problem.
I need to link to another website
Visit my website

But facebook wont open linked webside, instead show empty page. Is there some trick how to do this? Some specific tag I need to add somewhere or how to do that?
Thanks

A: Your page tab app is shown inside an iframe on facebook.com. Likely that other site sends an X-FRAME-OPTIONS header, forbidding the browser to display it in 3rd-party (i)frames.
But presumably you don't want to display that page inside the iframe to begin with? Then simply add a target="_blank" to the link, to have it open in a new tab.


text:
Q: How can I avoid overlapping when addView to RelativeLayout? There are some Textview,I need to add them in RelativeLayout dynamically. How can I add them without overlap with previous ? thx :D
public class CusRelativeLayout extends RelativeLayout {

    private String TAG = "CusRelativeLayout";
    ...
    public void add(String s){

        final int childCount = getChildCount();
        final TextView tv = new TextView(context);
        tv.setText(s);
        tv.setTextColor(getResources().getColor(R.color.black));

        LayoutParams params = (LayoutParams) generateDefaultLayoutParams();

        int[] xy = getRandomXY();

        if(childCount == 0){
            //no view
            params.setMargins(xy[0],xy[1],0,0);

        }else{

          //what shoud I do???

        }

        addView(tv,params);

    }
    ...
}

It looks like this:
  result
when I add the first tag, I just need to get random X and Y,and new a textview.I use the method setMargins(x,y,0,0) to adding in the RelativeLayout.
But when I add the second tag , I can use getTop(),getLeft(),getHeight(),getiWidth() to getting the previous position and range.And use getRandomXY() to getting random X and Y for the second.But I can't get the range of the second to determine whether the second overlaps with the first
I tried to do this
    final TextView tv = new TextView(context);
    tv.setText(s);
    tv.setTextColor(getResources().getColor(R.color.black));
    tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));

    tv.post(new Runnable() {
        @Override
        public void run() {
            Log.e(TAG,"height:" + tv.getHeight());
            Log.e(TAG,"width:" + tv.getWidth());
        }
    });

but the value is 0
If I just determine by X and Y , It will be this case.determine by X and Y
I just want to get the range of the new tag before adding to the RelativeLayout ,so I can determine whether it will overlap with the previous.
if I can determine all the tag position before add in Relativelayout?(I know the exact number of tag)

A: RelativeLayout is made to allow views to overlap each other. You could use a LinearLayout.
If you for some reason need to stick to RelativeLayout, then you have to place your new View with some layout parameters relative to previously added children
params.addRule(RelativeLayout.BELOW, R.id.below_id);

instead of R.id.below_id you could use your own ids that you have set on other children
Take a look here
Programatically add view one below other in relative layout


text:
Q:  ruin my css in my Nuxt js app My problem is quite simple and complicated at the same time, I forked this simple HTML, CSS, JS repo : Snake game.
and then I transformed it to a Nuxt Js app : My repo .

*

*when I use the Scoped attribute in my style tag , the Js code works fine, but with no pissibility to see the snake :

*When I remove the Scoped attribute, The snake goes crazy and ouf of borders, and it ruins the style either :

my code :

window.onload = function() {
    // GAME_PIXEL_COUNT is the pixels on horizontal or vertical axis of the game board (SQUARE).
    const GAME_PIXEL_COUNT = 40;
    const SQUARE_OF_GAME_PIXEL_COUNT = Math.pow(GAME_PIXEL_COUNT, 2);

    let totalFoodAte = 0;
    let totalDistanceTravelled = 0;

    /// THE GAME BOARD:
    const gameContainer = document.getElementById("gameContainer");

    const createGameBoardPixels = () => {
        // Populate the [#gameContainer] div with small div's representing game pixels
        for (let i = 1; i <= SQUARE_OF_GAME_PIXEL_COUNT; ++i) {
            gameContainer.innerHTML = `${gameContainer.innerHTML} <div class="gameBoardPixel" id="pixel${i}"></div>`;
        }
    };

    // This variable always holds the updated array of game pixels created by createGameBoardPixels() :
    const gameBoardPixels = document.getElementsByClassName("gameBoardPixel");

    /// THE FOOD:
    let currentFoodPostion = 0;
    const createFood = () => {
        // Remove previous food;
        gameBoardPixels[currentFoodPostion].classList.remove("food");

        // Create new food
        currentFoodPostion = Math.random();
        currentFoodPostion = Math.floor(
            currentFoodPostion * SQUARE_OF_GAME_PIXEL_COUNT
        );
        gameBoardPixels[currentFoodPostion].classList.add("food");
    };

    /// THE SNAKE:

    // Direction codes (Keyboard key codes for arrow keys):
    const LEFT_DIR = 37;
    const UP_DIR = 38;
    const RIGHT_DIR = 39;
    const DOWN_DIR = 40;

    // Set snake direction initially to right
    let snakeCurrentDirection = RIGHT_DIR;

    const changeDirection = (newDirectionCode) => {
        // Change the direction of the snake
        if (newDirectionCode == snakeCurrentDirection) return;

        if (newDirectionCode == LEFT_DIR && snakeCurrentDirection != RIGHT_DIR) {
            snakeCurrentDirection = newDirectionCode;
        } else if (newDirectionCode == UP_DIR && snakeCurrentDirection != DOWN_DIR) {
            snakeCurrentDirection = newDirectionCode;
        } else if (
            newDirectionCode == RIGHT_DIR &&
            snakeCurrentDirection != LEFT_DIR
        ) {
            snakeCurrentDirection = newDirectionCode;
        } else if (newDirectionCode == DOWN_DIR && snakeCurrentDirection != UP_DIR) {
            snakeCurrentDirection = newDirectionCode;
        }
    };

    // Let the starting position of the snake be at the middle of game board
    let currentSnakeHeadPosition = SQUARE_OF_GAME_PIXEL_COUNT / 2;

    // Initial snake length
    let snakeLength = 1000;

    // Move snake continously by calling this function repeatedly :
    const moveSnake = () => {
        switch (snakeCurrentDirection) {
            case LEFT_DIR:
                --currentSnakeHeadPosition;
                const isSnakeHeadAtLastGameBoardPixelTowardsLeft =
                    currentSnakeHeadPosition % GAME_PIXEL_COUNT == GAME_PIXEL_COUNT - 1 ||
                    currentSnakeHeadPosition < 0;
                if (isSnakeHeadAtLastGameBoardPixelTowardsLeft) {
                    currentSnakeHeadPosition = currentSnakeHeadPosition + GAME_PIXEL_COUNT;
                }
                break;
            case UP_DIR:
                currentSnakeHeadPosition = currentSnakeHeadPosition - GAME_PIXEL_COUNT;
                const isSnakeHeadAtLastGameBoardPixelTowardsUp =
                    currentSnakeHeadPosition < 0;
                if (isSnakeHeadAtLastGameBoardPixelTowardsUp) {
                    currentSnakeHeadPosition =
                        currentSnakeHeadPosition + SQUARE_OF_GAME_PIXEL_COUNT;
                }
                break;
            case RIGHT_DIR:
                ++currentSnakeHeadPosition;
                const isSnakeHeadAtLastGameBoardPixelTowardsRight =
                    currentSnakeHeadPosition % GAME_PIXEL_COUNT == 0;
                if (isSnakeHeadAtLastGameBoardPixelTowardsRight) {
                    currentSnakeHeadPosition = currentSnakeHeadPosition - GAME_PIXEL_COUNT;
                }
                break;
            case DOWN_DIR:
                currentSnakeHeadPosition = currentSnakeHeadPosition + GAME_PIXEL_COUNT;
                const isSnakeHeadAtLastGameBoardPixelTowardsDown =
                    currentSnakeHeadPosition > SQUARE_OF_GAME_PIXEL_COUNT - 1;
                if (isSnakeHeadAtLastGameBoardPixelTowardsDown) {
                    currentSnakeHeadPosition =
                        currentSnakeHeadPosition - SQUARE_OF_GAME_PIXEL_COUNT;
                }
                break;
            default:
                break;
        }

        let nextSnakeHeadPixel = gameBoardPixels[currentSnakeHeadPosition];

        // Kill snake if it bites itself:
        if (nextSnakeHeadPixel.classList.contains("snakeBodyPixel")) {
            // Stop moving the snake
            clearInterval(moveSnakeInterval);
            if (!alert(
                    `You have ate ${totalFoodAte} food by travelling ${totalDistanceTravelled} blocks.`
                ))
                window.location.reload();
        }

        nextSnakeHeadPixel.classList.add("snakeBodyPixel");

        setTimeout(() => {
            nextSnakeHeadPixel.classList.remove("snakeBodyPixel");
        }, snakeLength);

        // Update total distance travelled
        totalDistanceTravelled++;
        // Update in UI:
        document.getElementById("blocksTravelled").innerHTML = totalDistanceTravelled;

        if (currentSnakeHeadPosition == currentFoodPostion) {
            // Update total food ate
            totalFoodAte++;
            // Update in UI:
            document.getElementById("pointsEarned").innerHTML = totalFoodAte;

            // Increase Snake length:
            snakeLength = snakeLength + 100;
            createFood();
        }
    };

    /// CALL THE FOLLOWING FUNCTIONS TO RUN THE GAME:

    // Create game board pixels:
    createGameBoardPixels();

    // Create initial food:
    createFood();

    // Move snake:
    var moveSnakeInterval = setInterval(moveSnake, 80);

    // Call change direction function on keyboard key-down event:
    addEventListener("keydown", (e) => changeDirection(e.keyCode));

    // ON SCREEN CONTROLLERS:
    const leftButton = document.getElementById("leftButton");
    const rightButton = document.getElementById("rightButton");
    const upButton = document.getElementById("upButton");
    const downButton = document.getElementById("downButton");

    leftButton.onclick = () => changeDirection(LEFT_DIR);
    rightButton.onclick = () => changeDirection(RIGHT_DIR);
    upButton.onclick = () => changeDirection(UP_DIR);
    downButton.onclick = () => changeDirection(DOWN_DIR);
}

<template>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Snake v8</title>

Food: 0

Blocks: 0

      <button id="leftButton">◀</button>

        <button id="upButton"></button>
        <button id="downButton"></button>

      <button id="rightButton">▶</button>

</template>

Any help please ? thank you

A: I actually found  where the problem is :
in my Nuxt.js app, im using Tailwind, and it applies a default style to all my
 tags .
the solution was to add this to my global CSS :
*
{
box-sizing: initial;
}


text:
Q: Drawing a triangle in Core Graphics I've been trying to draw a triangle in Core Graphics for some time. I've figured out how to by I'm not quite sure if it is the best way.
I also can't figure out how to center it in the UIView
Here is my code
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL,10, 100);
CGPathAddLineToPoint(path, NULL,100,10);
CGPathAddLineToPoint(path, NULL,200,100);
CGPathAddLineToPoint(path, NULL,100,100);
CGPathCloseSubpath(path);

CGContextSetFillColorWithColor(context, white);
CGContextAddPath(context, path);
CGContextFillPath(context);

A: To center your triangle, you would have to do a little math -- there are actually several "centers" of triangles, but the one where you draw a line from each vertex to the center of the opposite line, defines the center as where these lines cross.  This center is easy to find, by averaging the x values and the y values -- so in your case where you have (10,100), (100,10) and (200,100) as your vertices, the center would be (10+100+200/3 , 100+10+100/3) or (103.3,70).  The full screen of an iPhone, which is 320 wide by 460 high, has its center at (160,230).  So basically, you need to add the difference between your triangles center and the screen center to each point -- add 160-103.3 to each x value and 230-70 to each y point, and that will draw the same triangle, but centered in the screen.