text:
Q: How to give message when user try to type alphabets in Number using extjs I want to send message when user try to enter alphabets in number filed of extjs. My code is as follow:
txtDecDHR = Ext.create('Ext.form.field.Number', {
    width: 320,
    hideTrigger: true,
    keyNavEnabled: false,
    mouseWheelEnabled: false,
    value:'10.69',
    labelWidth: 100,
    style: {
            marginLeft: '10px',
                marginTop: '2px'
        },
    fieldLabel: 'Number*',
});

please help me for same
;

A: Please find the example.
Ext.onReady(function(){
txtDecDHR = Ext.create('Ext.form.field.Number',
{
width: 320,

hideTrigger: true,

enableKeyEvents:true,

keyNavEnabled: false,

mouseWheelEnabled: false,

 listeners:{

    keyup:function( field, event ){

           var keyNum=parseInt(event.getCharCode());

           if(keyNum>47 && keyNum <58 || keyNum>95 && keyNum<106 ){

               alert("Number");

             }
                else{
               alert("alphabet or special character");

               }

          }

    },

value:'10.69',

renderTo:document.body,

labelWidth: 100,

style: {

        marginLeft: '10px',

            marginTop: '2px'

    },

fieldLabel: 'Number*'

});
});

A: ExtJS numberfield is already designed to prevent entering non-numerical values. Thus, the only letter that you can enter is E, because it is allowed to enter something like 10E38 (which is then translated into 10^38). However, this way you can trick the number field and leave just E, which of course is not a valid numerical value. Default message in that case is 'The value in this field is invalid', which can be changed by setting the value of the property invalidText.
See also:

*

*ExtJS documentation (numberfield)


text:
Q: Bootstrap dropdown menu show animation working but how to exit animation on dropdown menu hide I have put css animation dropdown menu which you can see here:

/* CSS used here will be applied after bootstrap.css */

.dropdown .dropdown-menu {
  animation-name: example;
  animation-duration: 1s;
}

@keyframes example {
  from {
    transform: scale(0);
    opacity: 0;
    -webkit-transition: all .2s linear;
    -o-transition: all .2s linear;
    transition: all .2s linear;
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

        <button type="button" class="btn btn-primary dropdown-toggle" data-display="static" data-toggle="dropdown">Dropdown button</button>

          Link 1 Link 2 Link 3

        <button type="button" class="btn btn-secondary dropdown-toggle" data-display="static" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropleft
  </button>

          Action
          Another action
          Something else here

        <button type="button" class="btn btn-secondary dropdown-toggle" data-display="static" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    DropRight
  </button>

          Action
          Another action
          Something else here

On dropdown menu show animation is working as expected. But how to do exit animation when dropdown menu is hiding. I want to exit animation look like the reverse animation on dropdown menu show. Please suggest

A: It will happen b'coz of when we set display:block or display:none then our animation is not working.
You just need to set transform: scale(0); instead of display:none. Please review my styling for more information.
Let me know if you have a question about the same
Hope this help

.dropdown .dropdown-menu {
  animation-name: example;
  animation-duration: 1s;
  -webkit-transition: all .2s linear;
  -o-transition: all .2s linear;
  transition: all .2s linear;
  opacity: 1;
  transform: scale(1);
}

.dropdown .dropdown-menu{
  transform: scale(0);
  opacity: 0; display:
  block !important;
 }
.dropdown-menu.show {
  display: block;
  transform: scale(1);
  opacity: 1;
}

@keyframes example {
  from {
    transform: scale(0);
    opacity: 0;
    -webkit-transition: all .2s linear;
    -o-transition: all .2s linear;
    transition: all .2s linear;
  }
  to {
        -webkit-transition: all .2s linear;
    -o-transition: all .2s linear;
    transition: all .2s linear;
    opacity: 1;
    transform: scale(1);
  }
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

        <button type="button" class="btn btn-primary dropdown-toggle" data-display="static" data-toggle="dropdown">Dropdown button</button>

          Link 1 Link 2 Link 3

        <button type="button" class="btn btn-secondary dropdown-toggle" data-display="static" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropleft
  </button>

          Action
          Another action
          Something else here

        <button type="button" class="btn btn-secondary dropdown-toggle" data-display="static" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    DropRight
  </button>

          Action
          Another action
          Something else here

A: you need to remove the animations from your css and make your .dropdown-menu display: block !important because it was a js to hide and show dropdown in bootstrap, for initially you have to make transform: scale(0); to .dropdown-menu and also apply transition to it and when you click on button the class .show added with the class .dropdown-menu now when show class appears make css transform: scale(1); for more understanding see the following snippet.

.dropdown .dropdown-menu {
  -webkit-transition: all .2s linear;
  -o-transition: all .2s linear;
  transition: all .2s linear;
  display: block !important;
  transform: scale(0);
}
.dropdown .dropdown-menu.show{
  transform: scale(1);
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

        <button type="button" class="btn btn-primary dropdown-toggle" data-display="static" data-toggle="dropdown">Dropdown button</button>

          Link 1 Link 2 Link 3

        <button type="button" class="btn btn-secondary dropdown-toggle" data-display="static" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropleft
  </button>

          Action
          Another action
          Something else here

        <button type="button" class="btn btn-secondary dropdown-toggle" data-display="static" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    DropRight
  </button>

          Action
          Another action
          Something else here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why SQL does not throw error when I try to sort based on same column twice? I have a table EMPLOYEE in MYSQL database of version 5.7.22. I write a select query:
SELECT * from EMPLOYEE ORDER BY NAME ASC, SALARY DESC, NAME ASC;

The result of this is same as
SELECT * from EMPLOYEE ORDER BY NAME ASC, SALARY DESC;

Similarly results of
SELECT * from EMPLOYEE ORDER BY NAME ASC, SALARY DESC, NAME DESC;

is same as
SELECT * from EMPLOYEE ORDER BY NAME ASC, SALARY DESC;

In this case, NAME ASC second time is redundant. Why does not SQL throw error / warning in this case ?

A: Your question is "Why doesn't MySQL (or any other database) returns a warning or error when there are redundant ORDER BY keys?"
When writing a language or compiler, the designers have to make decisions on what to work on.
The first observation about all your examples is that they are valid SQL.  The standard has nothing to say about redundant ORDER BY keys, so why do anything?
The second observation is that the additional key has no impact on the result set and minimal impact on the results.  That would make even a warning very low priority.
The third is where to stop?  Does the compiler have errors or warnings for things like:

*

*+ 0 ?

** 1 ?

*WHERE 1=1 ?

*etc. etc. etc.

Why should effort go into fixing "bad" code when effort can go into making the engine work better for everyone?

A: *

*Syntax is true that's why gives no Error

*Same result because Order By work Orderly as follows
SELECT * from EMPLOYEE ORDER BY NAME(1) ASC, SALARY(2) DESC, NAME(3) ASC;
As a result No Problem just relax and recheck


text:
Q: Can PowerShell synch Nuget packages between Devs' workstations? Seeking PS script that would

*

*inspect packages installed on my
MasterWorkstation, then;

*Produce a list of commands that can
be executed on other workstations so
as to produce a synched dev image.
thx

A: NuGet doesn't really have the concept of packages that are installed at the machine level. Instead, packages are installed in each project that needs it.
When packages are installed in a project, a repository.config file is created that lists what's installed. Using that file, you can then easily re-fetch the same packages on another machine, keeping things essentially in sync.
See my post for more details on this workflow.


text:
Q: Script to generate a MATRIX I wish to have a script to generate all possible possibility from 'NxN' matrix using powershell.
I couldn't find anything over the web, and don't have anything to start with.
does anyone has something similar?
Edit:
Lets say I have 2x2 matrix, the possibilities are:

1 1|
1 2|
2 1|
2 2|

lets say I have 10 strings... each string has 1 or 0 for value, I wish to extract/generate all possible combinations.

A: # For read from cmd
param([parameter(ValueFromPipeline=$true)] [int] $inputvalue)

if($inputvalue){$matrixheight = "$inputvalue"}
else{$matrixheight = read-host -prompt "What is size of matrix...?"}

For($i = 1; $i -le $matrixheight; $i ++){
    For($j = 1; $j -le $matrixheight; $j ++){
        Write-Host "$i" "$j" "|"
    }
}


text:
Q: Getting background-color of body in iframe I have an html page with iframe in it. There is a website in the iframe. The domains of the website and the web page are the same. I want to get background-color of the website in the frame from the web page. How can I do that?
For example, I want to get the background color of the website in iframe from the html page below.

<html>

  <head>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="style.css">

  </head>

  <body>

    <iframe id="my-iframe" frameBorder="0"
      src="https://MYWEBSİTE.COM (Same domain)" title="My Website">
    </iframe>

  </body>

</html>

A: You can access it with JavaScript using .getComputedStyle() of the iframe's body by selecting .contentWindow.document.body then selecting the body's background color.
var iFrameEl = document.getElementById('my-iframe');
var backgroundColor = iFrameEl.contentWindow.getComputedStyle(iFrameEl.contentWindow.document.body).backgroundColor;


text:
Q: How can I make this conceptual model better? Good friends. I'm working on a Laravel application which is like a Student Management System for Schools in my Country. The application requires that I stored scores of students and further generate reports for the period or semester the student achieved that score.
In my Country normally there are six(6) periods in an academic year. A period spans 4 weeks. Also there are two(2) semesters in an academic year which spans 3 and a half months. There are four(4) terms in every semester.
Here is a picture that explains how things looks:

Since I have to generate a report of each student for a given period of semester this is how my conceptual model looks:
Students table:
students
--------
id *
name
grade_id (fk)

Subjects table:
subjects
--------
id *
name

Grades table:
grades
--------
id *
name

Note The grades table store the name of each class in the school. ex. grade 12, grade 11 etc.
Now, these are the tables the student scores for subjects of a given period or semester are store in.
period_one (1st Period)
-----------------------
id *
student_id (fk)
subject_id (fk)
grade_id (fk)
score

first_exam (1st Sem. Exam)
-----------------------
id *
student_id (fk)
subject_id (fk)
grade_id (fk)
score

period_four (4th Period)
-----------------------
id *
student_id (fk)
subject_id (fk)
grade_id (fk)
score

Note the same holds true for second period, third period, 5th period, six period etc
By this time I know someone have seen something fishy or unintelligent here. I'm repeating the same columns in every table and I believe that it could be done better.
But there is a reason why I did it this way and that has to do with generating reports. With the above setup I can easily structure my queries to generate reports.
This is the query I used to generate periodic reports
// the function runs a select all query for all the period/term grades tables
// It displays the periodic grades sheet

$student_id = 1; // any id could be passed
$term = "period_one"; // giving the exact table name to fetch record from
$class_id = 2; // 2 may represent grade 12 in this case.

function periodic_report($term, $student_id, $class_id)
{
    global $connection;
    $query = "SELECT $table.student_id, score, subject_name, class_name
                from $term
                INNER JOIN students
                        ON students.student_id = $table.student_id
                    INNER JOIN classes
                        ON classes.class_id = $table.class_id
                    INNER JOIN subjects
                        ON subjects.subject_id = $table.subject_id
              WHERE $table.student_id = $student_id AND $table.class_id = $class_id";

    $result_set = mysqli_query($connection, $query);

    // Test if there was a query/syntax error
    confirm_query($result_set);
    return $result_set;
}

this is how the result may look:

Query to generate first semester reports:
// the function runs a select all query for semester grades
// It displays the first semester grades sheet
function first_semester_report($student_id) {
    global $connection;
    $query = "SELECT subjects.subject_name, period_one.score, period_two.score, period_three.score, first_exam.score
        FROM subjects

        LEFT JOIN period_one
            ON period_one.subject_id = subjects.subject_id
            AND period_one.student_id = {$student_id}

        LEFT JOIN period_two
            ON period_two.subject_id = subjects.subject_id
            AND period_two.student_id = {$student_id}

        LEFT JOIN period_three
            ON period_three.subject_id = subjects.subject_id
            AND period_three.student_id = {$student_id}

        LEFT JOIN first_exam
            ON first_exam.subject_id = subjects.subject_id
            AND first_exam.student_id = {$student_id}

        LEFT JOIN students
            ON students.student_id = {$student_id}

        WHERE period_one.subject_id = subjects.subject_id OR period_two.subject_id = subjects.subject_id OR period_three.subject_id = subjects.subject_id OR first_exam.subject_id = subjects.subject_id
        ORDER BY subjects.subject_name";

    $result_set = mysqli_query($connection, $query);

    if(!$result_set){
        die("Database query failed. Error from first semester report: ".mysqli_error($connection)." Error number is: ".mysqli_errno($connection));
    }

    // Test if there was a query/syntax error
    //confirm_query($result_set);
    return $result_set;
}

Query to generate second semester report:
// the function runs a select all query for semester grades
// It displays the second semester grades sheet
function second_semester_report($student_id) {
    global $connection;
    $query = "SELECT subjects.subject_name, period_four.score, period_five.score, period_six.score, second_exam.score
        FROM subjects

        LEFT JOIN period_four
            ON period_four.subject_id = subjects.subject_id
            AND period_four.student_id = {$student_id}

        LEFT JOIN period_five
            ON period_five.subject_id = subjects.subject_id
            AND period_five.student_id = {$student_id}

        LEFT JOIN period_six
            ON period_six.subject_id = subjects.subject_id
            AND period_six.student_id = {$student_id}

        LEFT JOIN second_exam
            ON second_exam.subject_id = subjects.subject_id
            AND second_exam.student_id = {$student_id}

        LEFT JOIN students
            ON students.student_id = {$student_id}

        WHERE period_four.subject_id = subjects.subject_id OR period_five.subject_id = subjects.subject_id OR period_six.subject_id = subjects.subject_id OR second_exam.subject_id = subjects.subject_id
        ORDER BY subjects.subject_name";

    $result_set = mysqli_query($connection, $query);

    if(!$result_set){
        die("Database query failed. Error from second semester report: ".mysqli_error($connection)." Error number is: ".mysqli_errno($connection));
    }

    // Test if there was a query/syntax error
    //confirm_query($result_set);
    return $result_set;
}

this is how the semester report may look based on the semester query for:

At times I'm trouble that this could be done better, but the shame is I don't know how.
Are there better ways to do this? Also it's only 70 percent of schools who plan their academic year in periods others use different ways. Is there a way to customize this in a way that schools can specified the periods or terms in the academic year and a table be created for each period or term?
Will appreciate practical implications and suggestions. Thanks!!!!


text:
Q: How to wait for completion handler in AppDelegate in React-Native JS I'm quite new to React-Native and I can't find the solution to this despite a lot of searching.
I have a completion handler that gets run asynchronously in my AppDelegate's didFinishLaunchingWithOptions method.
Question: How do I wait for its execution to complete before showing the root React.Component?
Needless to say, the completion handler sets important info at the start, without which the app cannot function properly.

A: The idea is to use a native iOS module with a promise: https://facebook.github.io/react-native/docs/native-modules-ios


text:
Q: ExchangeService suddenly not seeing shared calendars Some code, originally written by someone else, has suddenly stopped doing what it's supposed to.
The code is supposed to find a shared calendar from a different account and get the events within, but it no longer finds this shared calendar, or any shared calendars.
I don't have access to the account sharing the calendar, but I tried sharing a calendar from a different account and it would not show up either, however when creating a calendar in the account used by the script it appears fine.
The shared calendars are visible when logged into the account though. And events can be created and seen.
I have limited knowledge of exchange, but I need this script to work.
I've looked around for already answered questions with similar issues and tried some solutions, but none have worked so far or been prevented by other problems and/or lack of knowledge.
Nothing has changed on this end that I'm aware, and the owner of the account claims that I have full access to the calendar and that nothing has changed on their end. So I have no idea why this would suddenly stop working.
For clarification, there are no errors. The try-catch doesn't trigger, and the script prints a list of folders to the page.
The issue is that this list doesn't contain the shared calendars visible on the site.
const string EWSUrl = @"https://outlook.office365.com/ews/exchange.asmx";

const string EmailAdre = "myEmail";
const string EmailPass = "myPassword";
const string EmailDomi = "domi";
const string EmailCale = "targetAccount";

const int calFolderLimit = 200; // Limit on folder search
const int calMaxItemsReturned = 500; // Max limit cal fetch
const int calMonthLimit = 12; // How many months to fetch
const int calMonthBack = 1; // Update how many days back

// Tries to find one of this
const string calFolderName = "Ekonomi Årskalender";
const string calFolderID = "AQMkAGU5NTdjYTE5LTZiNWMtNDYzMi05MWQ4LWQ5MDcyMgA1YjMwMTYALgAAA5ukgsUdw+BFjn7iHZ02H3gBAM/bOclCwmFEsqKa2vRsw2EAAAIBWQAAAA==";

const string EWSUrl = @"https://outlook.office365.com/ews/exchange.asmx";

const string EmailAdre = "myEmail";
const string EmailPass = "myPassword";
const string EmailDomi = "domi";
const string EmailCale = "targetAccount";

const int calFolderLimit = 200; // Limit on folder search
const int calMaxItemsReturned = 500; // Max limit cal fetch
const int calMonthLimit = 12; // How many months to fetch
const int calMonthBack = 1; // Update how many days back

// Tries to find one of this
const string calFolderName = "Ekonomi Årskalender";
const string calFolderID = "AQMkAGU5NTdjYTE5LTZiNWMtNDYzMi05MWQ4LWQ5MDcyMgA1YjMwMTYALgAAA5ukgsUdw+BFjn7iHZ02H3gBAM/bOclCwmFEsqKa2vRsw2EAAAIBWQAAAA==";

protected string syncCalendar(HttpContext context)
{
    string response = "";
    try
    {
        // CONNECT TO EXCHANGE
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
        service.Credentials = new WebCredentials(EmailAdre, EmailPass, EmailDomi);
        service.TraceEnabled = true;
        service.TraceFlags = TraceFlags.All;

        service.EnableScpLookup = true;
        service.AcceptGzipEncoding = true;
        service.Url = new Uri(EWSUrl);

        // Find Folder
        FolderView folderView = new FolderView(calFolderLimit);
        folderView.Traversal = FolderTraversal.Deep;
        folderView.PropertySet = new PropertySet(FolderSchema.FolderClass, FolderSchema.DisplayName, FolderSchema.TotalCount, FolderSchema.ParentFolderId);

        FindFoldersResults folders = service.FindFolders(new FolderId(WellKnownFolderName.Root), folderView);

        foreach (var myFolder in folders.Folders)
        {
            if (myFolder is CalendarFolder && (myFolder.DisplayName == calFolderName || myFolder.Id.ToString() == calFolderID))
            {
                //Doing stuff with matched calendar folder
                //Print name for debugging
                response += "
" + myFolder.DisplayName + "
";
            }
        }
    }
    catch (Exception ex)
    {
        response += "[ERROR]
" + ex.Message + "

" + ex.StackTrace + "
";
    }
    return response;
}

A: This code you posted doesn't make a lot of sense without talking to the original author its hard to determine why its been done that way. Let start by looking at

const string calFolderID = "AQMkAGU5NTdjYTE5LTZiNWMtNDYzMi05MWQ4LWQ5MDcyMgA1YjMwMTYALgAAA5ukgsUdw+BFjn7iHZ02H3gBAM/bOclCwmFEsqKa2vRsw2EAAAIBWQAAAA==";

Looks like the ews FolderId of the folder your trying to find hard coded ? Not such a great idea eg if the Mailbox was migrated from OnPrem to Office365 the FolderId would be different which would break the code (that would be my first guess as to why it doesn't work if you said it did work in the first place).
However if you already have the EWS FolderId of the folder then the rest of the code is redudant and you could have done the same thing by just binding to the folderId eg
       FolderId fldId = new FolderId("AQMkAGU5NTdjYTE5LTZiNWMtNDYzMi05MWQ4LWQ5MDcyMgA1YjMwMTYALgAAA5ukgsUdw+BFjn7iHZ02H3gBAM/bOclCwmFEsqKa2vRsw2EAAAIBWQAAAA==");
       Folder myFolder = Folder.Bind(service, fldId);

But most likely as the FolderId you want to access has probably changed the only way to fix it quickly would be open the Target Mailbox where the calendar you want to bind to is and grab the new folderId. You can use the EWSEditor https://ewseditor.codeplex.com/ to obtain that without needing to write any code. Once you have the quick fix working I would suggest you rewrite the whole thing to stop it breaking in the future.


text:
Q: how to simulate the inheritance of a record? I'd like to inherit records, since this is not possible the best solution is to create classes with public fields and use inheritance against them?

A: Yes, uses classes. There is a complete discussion in the Stack Overflow question Why can't Delphi records have inheritance?


text:
Q: No me funcionan ambas condiciones del if, con el AND solo una a la vez para un proyecto estoy intentando una validación desde el local storage, con un for y key que me trae los valores almacenados.
La idea es que desde el input compare a través del IF y si es correcto haga una u otra cosa. Para probar el funcionamiento correcto del IF puse directamente ambos strings, usuario y contraseña para que compare con lo contenido en el local storage. El tema es que solo me levanta el primer dato y ya lo da como valido, o de a uno a la vez, no me toma el AND para que valide usuario y contraseña contra lo que hay en el local Storage. Probe diferentes sintaxis y nada, sigue pasando lo mismo.
Dejo el codigo, la primera parte es el registro que guarda en el LS y la segunda es donde debiera poder hacer la validación...

document.getElementById("nuevo-usuario").addEventListener("submit", nuevoUsuario,false);

        function nuevoUsuario (){

    const usuarioIngresado = document.getElementById("usuario");
    const passwordIngresado = document.getElementById("pass");

                 const user = JSON.stringify(usuarioIngresado.value);
                 const pass = JSON.stringify(passwordIngresado.value);

                 localStorage.setItem(user, user);
                 localStorage.setItem(pass, pass);

}

//INICIO DE CESION
document.getElementById("usuario-registrado").addEventListener("submit",inicioCesion);

function inicioCesion(e) {
    e.preventDefault()

//RECORRO EL LOCAL STORAGE PARA OBTENER LAS KEYS

for (let i = 0; i < localStorage.length; i++) {
   let clave = localStorage.key(i);
   let login = JSON.parse( localStorage.getItem(clave));

   console.log(login);

    //EL CONDICIONAL PARA COMPARAR Y VALIDAR LAS EXPRESIONES (ESTA ES LA ULTIMA QUE PROBE, PERO INTENTE DE VARIAS MANERAS, PERO NO HAY CASO, NO ME VALIDA AMBAS EXPRESIONES

    let nombre = "Cristian"
    let contra = "1234"

    if (login == nombre && contra) {

        console.log(' Alcoyana Alcoyana');
    }
     else {
        console.log(":((");
    }

}

}

A: El tipo de operador lógico que necesitas es un OR no un AND, porque lo que quieres verificar es si login coincide con nombre O si coincide con contra.
Por tanto, en un solo condicional tendrías que poner esto: if (login == nombre || login == contra) {, donde || significa OR (que coincida uno u otro).
Veamos dos ejemplos, con valores puestos a mano, sólo para prueba:
Ejemplo 1

let login = "Cristian";
let nombre = "Cristian";
let contra = "1234";

if (login == nombre || login == contra) {
  console.log(' Alcoyana Alcoyana');
} else {
  console.log(":((");
}

Ejemplo 2

let login = "1234";
let nombre = "Cristian";
let contra = "1234";

if (login == nombre || login == contra) {
  console.log(' Alcoyana Alcoyana');
} else {
  console.log(":((");
}

Si quieres simplificar, también puedes combinar con un operador ternario.
Ejemplo con ternario

let login = "1234";
let nombre = "Cristian";
let contra = "1234";

let msg = (login == nombre || login == contra) ? 'Alcoyana Alcoyana' : ':((';

console.log(msg);


text:
Q: Saving and Deleting Files Properly - Android I have an Android (API 26) application that downloads files, saves them to the device storage, opens them in their respective application and deletes them after they are done being viewed.  My problem is with the Android file system.
To create the file, I use:
File localFile =
new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
+ File.separator
+ GlobalSettings.getTempFolderName()
+ File.separator
+ file.getName());
// resolves to: /storage/emulated/0/Download/Temp/0500-001.pdf

if (!localFile.exists())
{
    localFile.getParentFile().mkdirs();
    localFile.createNewFile();
}

When I go to delete the same file, I use:
File fileToDelete = new File(path);
// path resolves to /storage/emulated/0/Download/Temp/0500-001.pdf

if (fileToDelete.exists())
    test = fileToDelete.delete();

The problem I have is Android is creating a copy of the file that I can only see via Windows' File Explorer when the device is connected to my PC via USB.  At the path PC\ET5X\Internal storage\Download\Temp in File Explorer I see the 0500-001.pdf file, even after deleting it using the code above.  I cannot find this file with the Android file explorer (even performing a search from root level) or even ES File Explorer.  I can't have a bunch of files taking up storage.. they must be deleted after they are viewed.
How can I save and delete files without Android making a duplicate, or how can I delete the duplicate as well?


text:
Q: Finding eigenvalues of given matrix $A = \left(\begin{array}{ccc}0 & -1 & 0 \\0 & 0 & 1 \\-1 & -3 & 3\end{array}\right)$
I want to find eigenvalues of this matrix.
The answer given to me is: 1,1,1.
I cannot arrive at that answer. I get complex numbers for my eigenvalues.
Am I doing something wrong? Is there a way to get 1,1,1 as your eigenvalues?

A: Calculate the characteristic polynomial, $\det|sI-A|$,
$$\det\left(\begin{array}{ccc}s & 1 & 0 \\0 & s & -1 \\1 & 3 & s-3\end{array}\right)=s(s(s-3)+3)-1(1)=s^3-3s^2+3s-1=(s-1)^3$$
The three eigenvalues are the roots of this polynomial, and hence are all equal to $1$.

A: The eigenvalues can be obtained by equating the determinant of $A-\lambda I$ to zero.
$$
\det(A-\lambda I)=
\left|
\begin{array}{ccc}
-\lambda & -1 & 0 \\
0 & -\lambda & 1 \\
-1 & -3 & 3-\lambda
\end{array}
\right|=
\lambda^2(3-\lambda)+1-3\lambda=(1-\lambda)^3
$$
Hence they are given by the solutions of $(1-\lambda)^3=0$


text:
Q: Architecture for application-wide diagnostic-gathering tool? My product owner wants us to report more information on the state of the product when a user contacts customer service through an in-app form.  The form eventually results in an email being sent to a customer service email list and handled elsewhere.
The part I'm struggling with is how to augment my existing iOS project to allow for some controller to collect diagnostic information from a variety of disparate classes, and do it in a way that's minimally invasive and won't cause a headache if refactoring later.
Blocks
I've experimented with a few ideas, including having an interface that allows an arbitrary class to register a block to be executed when attempting to collect the diagnostic information:
[DiagnosticCollectionController addBlockForDiagnosis:^(DiagnosticCollectionController *controller){
    // Add some information here to the controller to send in the diagnostic report
}];

Notifications
Another idea I had in mind was to have the diagnostic controller broadcast a notification when it's ready to start gathering information, so that other objects can attach what they need to.  The (potential) advantage here is that I can get away from using blocks thus prevent myself from having block copy issues:
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(someSelectorToHandleDiagnosticPopulation:)
                                             name:DiagnosticCollectionControllerWillSendDiagnostics
                                           object:someDiagnosticController];
// Elsewhere
- (void) someSelectorToHandleDiagnosticPopulation:(NSNotification *)note {
    DiagnosticController *controller = [note object];
    [controller addDiagnosticData:someDataDictionary];
}

A: I like your notification approach better than your block approach. I recommend having each pertinent subsystem or component implement an interface that can return status information when requested. They would then register themselves with a centralized status collection service. At key times, the status service could fetch status from each registered component, build a report, and attach it to the customer service email. Whether the fetching is done manually or through the iOS notification system is less important, I think.
BTW, if the objects that can provide status are transient, then you might need to be careful that the status collection service not hold references to them when they are no longer needed. A weak reference might help here.

A: Finally, I went with a setup close to what Randall suggested, after some more thinking and some distraction.
The interfaces that handle coordinating the diagnostic work look like this:
@interface DiagnosticController
+ (void) addDiagnosticProvider:(id<DiagnosticProvider>)provider;
+ (void) removeDiagnosticProvider:(id<DiagnosticProvider>)provider;
@end

@protocol DiagnosticProvider <NSObject>
- (NSDictionary *) diagnosticData;
@end

The DiagnosticController itself keeps a list of __unsafe_unretained pointers so objects can remove themselves from the list of providers when they dealloc.  I went with __unsafe_unretained to make this backward compatible with earlier versions of iOS instead of, say, NSHashTable with the NSHashTableWeakMemory option.  If I have some time in the future, I might cluster the DiagnosticController to allow for multiple backing stores depending on the runtime.


text:
Q: Modify value inside href links using beautiful soup I am able to extract the 'href' but I also want to modify the values in href link.
Below is the example:-
Input-

                                                         Unsubscribe

Output-

                                                         Unsubscribe

A: from bs4 import BeautifulSoup

html = ' Unsubscribe '

soup = BeautifulSoup(html, 'html.parser')

for a in soup.find_all('a'):
  a['href'] = a['href'].replace("[sample]", "samplevalue").replace('[hashkey]', "123")

Result print(soup.prettify(formatter=None)):
 Unsubscribe


text:
Q: Winforms/Devcomponents - Window gets padding because a variable gets set automatically on save So I've inherited this Visual Basic project made with Winforms (originally .NET Framework 2.0 but I've set it to 4.8 as I need it. The problem exists in both versions. (Visual studio 2022, Windows 10)) but it has a problem.
Seen on the picture, left side is the design view where everything looks just fine. Right side however is when I run it. Some kind of padding on the right can be seen*.

If I look at the diff I can see the following (plaintext):

Now that Me.RibbonPanel1.Visible = True is what breaks it. I know that because if I remove it I get the following view:

Now the obvious solution would be to remove it, but it gets automatically inserted every time I enter the design view. You may also be able to notice that the last listview has a different size than in the first picture.
So besides never opening the design view, and when I do remember to remove it what can I do? There are lots of pages but none that behave like this.
* Yeah there's also the grey top bar, but I don't think I can do much about that (and I haven't heard the customers mention it)


text:
Q: Como puedo implementar un observer con Voyager en Laravel? quisiera saber si alguien me podria dar una mano con el paquete admin Voyager de Laravel. Estoy tratando de usar un observer para el modelo User, sin embargo el sistema no detecta ningun evento del Observer, intento enviar un mail cuando se cree un user en la vista de admin de voyager.

Los modelos que tengo fuera de las rutas de voyager si oyen los eventos sin problema.
Adjunto captura del Observer que quiero implementar cuando se creen usuarios, intente tambien probar con el modelo que genera voyager pero ni siquiera entra al metodo created.

El observer esta registrado en el EventServiceProvider


text:
Q: Vuetify: Using Vue's Default Footer with Custom Sort I would like to utilize the :custom-sort binding while also not disabling Vue's default footer. So far, either one or the other works. Either I disable the footer and my custom sorting method works, or I lose the custom sort for pagination. Is it possible to use the the default Vue footer for datatables while also sorting using my custom method?
Here is the relevant code:
list.html (with no hide-default-table):
<v-data-table :headers="tableProjectHeaders" :items="projectList" :page.sync="pageNumber" :pageCount="numberofPages" :items-per-page.sync="itemsPerPage" :server-items-length="totalProjects.length" :custom-sort="customSort" :options.sync="siteOptions">
<!-- Content gets Rendered Here -->
</v-datatable>

I'm not sure how helpful having the code from the vue component will be, but here's what the relevant parts of the vue app look like:
var app = new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    methods:{
              customSort: function (items, index, isDesc){
              // Too much code, will share upon request but not sure the nitty gritty is relevant
              return items;
              }
        },
    data(){
        return {
            ...
            pageNumber: 1,
            totalProjects: 0,
            numberofPages:0,
            siteOptions:{},
        }
       }
      });

Any ideas? Is this possible? Do I have to create a custom footer and manually implement the pagination? Let me know if there is any more code I can share to illuminate the issue.


text:
Q: Index for list slices Consider this main list:
 main_list = [['room A0', 'level0'],
              ['room A1', ''],
              ['room John Doe', ''],
              ['room 10', 'levelz'],
              ['room 102', ''],
              ['Big hall', 'level1a'],
              ['xyz', '']]

It is an ordered list:
- level0: 0,1,2
- levelz: 3,4
- level1a: 5,6

I would like to create a second list (or other data structure),
 which helps me fast lookup.
Example:
question: 'Give me index 4',
answer: 'room 102', 'levelz' (hidden lookup for levelz, which is at index3)

The main_list list is typically reads many times, and modified only occasionally.
Right now this is my solution:
 par_table = ['level0', 'level1', 'level1a']
 ref_par_table = [0,0,0,1,1,2,2]

ref_par_table list is exactly the same length as the original main_list.
par_table contains only the keywords, picked from the original list.
When I modify the main_list, I also update the par_table and ref_par_table too.
So the original example, looks like this:
question: 'Give me index 4',
answer: main_list[4], par_table[ref_par_table[4]]
('room 102', 'levelz')

Are there any more elegant way of doing this?
EDIT: My question is more about the data structure, then actual parsing of the main_list.
In real life, the main list is typically between 1000-99000 elements, where each element is a list of 7 length. So parsing(searching) the main_list for each lookup is a big no in this case.

A: You can parse the main_list for the right level number like this:
def getRoomTuple(list, index):
    name = list[index][0]
    level = list[index][1]
    i = 0
    while level is "":
        level = list[index-i][1]
        i += 1
    return name, level

print getRoomTuple(main_list, 2) # ('room John Doe', 'level0')

You only need to step over as many list items as it takes to find the last room with a specified level. So getRoomTuple(0) will return straight away; getRoomTuple(2) has to check indices 2, 1 and 0.
If possible, you should also use more semantic data structures.
class Room(object):
    name = None
    level = None
    def __init__(self, name, level):
        self.name = name
        self.level = level

main_list = [Room('A0', 'level0'), Room('A1', 'level1'), ...]


text:
Q: Where can I find Delphi´s component editor for TPopupMenu and TMenuItem? I need to write custom component editors for Delphi's TPopupMenu and TMenuItem descendent controls.
Finding the native editors will make my work a lot easier, but after inspecting the folder "\source\Property Editors", I was unable to find files that seems to be the right ones for them.
Any help will be much appreciate.

A:
Where can I find Delphi's component editor for TPopupMenu and TMenuItem?

You can't. The source code for these component editors is not published.


text:
Q: Update Contact Picklist field when related Account is updated I'm trying to figure out how to update a Contact field when a related Account field is updated. This is probably trivial for seasoned Salesforce admins...
Under Accounts I have a Lookup field called "Primary Contact" which allows you to pick any Contact.
Under Contacts I have Picklist field called "Contact Type" with the options "Primary Contact, Previous Primary Contact".
How can I update the picklist field value when a change happens on the Account record?
E.g if a new contact is selected, the Contact Type field for the current Contact should be updated to "Previous Primary Contact" and the newly selected contact should be updated to "Primary Contact".
In (terrible) pseudo code, I'm try to achieve the following:
On Account update
If Primary Contact field is updated, then
Set old contact to "Previous Primary Contact"
Set new contact to "Primary Contact"

Sorry if the explanation isn't clear, I'm struggling to make sense of how to do it myself. I've tried doing this using Process Builder, but it doesn't seem to let me update a Contact's field when an Account is updated. Am I missing something? Or is this only possible using Apex code? If it's the latter, any pointers would be appreciated. Thank you!

A: You can use process builder to update a related record (the Contact).  However, you CANNOT update an old value after the change has been made.  IE: if an Account has the Primary Contact set to Contact A, and the value is changed to Contact B, you can only update Contact B directly within the Process Builder.
You could use a flow or Apex code to accomplish this.  In either, when the Account has the primary contact changed, you'd query for all Contacts on that Account where Contact Type = Primary, but weren't equal to the current Primary Contact.  Then update them to Previous Primary Contact.
I'd recommend trying this in a sandbox, not directly in your live Salesforce site.  Also, you can make the Flow triggered by process builder, which makes it easier to control the criteria, deactivate, etc.
Good luck!


text:
Q: Query by attributes in pre-queried records (Oracle) There is a table MEETINGPARTICIPANT as below, PK is ORGID, MEETINGID and PARTICIPANTID
Name               Null?    Type
------------------ -------- -------------
ORGID              NOT NULL NUMBER(10)
MEETINGID          NOT NULL VARCHAR2(32)
PARTICIPANTID      NOT NULL VARCHAR2(32)
EMPLOYEEID         NOT NULL VARCHAR2(32)
DISPLAYNAME                 VARCHAR2(128)
EMAIL                       VARCHAR2(128)
JOINTIME           NOT NULL DATE
LEAVETIME          NOT NULL DATE
CREATETIME         NOT NULL DATE
LASTMODIFIEDTIME   NOT NULL DATE

Step 1, list records by ORGID, MEETINGID and EMPLOYEEID, get a record list.
SELECT
    *
FROM
    MEETINGPARTICIPANT
WHERE
    ORGID=#{orgId}
    AND MEETINGID=#{meetingId}
    AND EMPLOYEEID=#{employeeId}

Step 2, iterate each record of step 1, search again by EMAIL and DISPLAYNAME of step 1, merge to a large record list
for (each record in step 1) {

    SELECT
        *
    FROM
        MEETINGPARTICIPANT
    WHERE
        ORGID=#{orgId}
        AND MEETINGID=#{meetingId}
        AND EMAIL=#{record.email} AND DISPLAYNAME=#{record.displayName}

    Merge searched records to mergedRecords
}

Step 3, return mergedRecords
Question is, how to merge the SQLs in step 1 and 2 into a single SQL?

A: It appears the SQL below works. The NVL(EMAIL, ' ') and NVL(DISPLAYNAME, ' ') are going to handle records whose EMAIL or DISPLAYNAME are null.
SELECT
    *
FROM
    MEETINGPARTICIPANT
WHERE
    ORGID=#{orgId}
    AND MEETINGID=#{meetingId}
    AND (NVL(EMAIL, ' '), NVL(DISPLAYNAME, ' ')) IN (
        SELECT
            NVL(EMAIL, ' '), NVL(DISPLAYNAME, ' ')
        FROM
            MEETINGPARTICIPANT
        WHERE
            ORGID=#{orgId}
            AND MEETINGID=#{meetingId}
            AND EMPLOYEEID=#{employeeId}
    )


text:
Q: HDCP and Asus P8H67-M LE motherboard I purchased the Asus P8H67-M LE motherboard because they said it is HDCP-compliant.  I have just installed my CableCard and am running through the Windows Media Center setup.  But now it says "Your computer is not digital cable ready.  You will not be able to set it up for use with a CableCARD".
Upon searching online, other users have suggested that this error means that the video card is not HDCP-compliant, but that's not what Asus said...  Do you usually have to install another software package in addition to the video drivers to make HDCP work?

A: I got it working.  I had read posts about running the Digital Cable Advisor, but I ran the test tool from Ceton.  Turns out that the DCA is installed from Extras -> Gallery.  Once I ran that, it made changes to my system config in the background.  When I reran the tuner setup, it passed the test!


text:
Q: Rails 3 - Subdomain Issue Moving to Heroku I've written an application that uses a subdomain per user account to segregate environments. All this is working fine, except I have one issue. I can't get both www and "" to have a different root path than all other subdomains.
For all account subdomains, I have a root page of:
root :to => "applications#index"

I need this to be the root page for all subdomains except for a blank subdomain of "" and then "www". For www, I have this in the routes:
constraints(:subdomain => "www") do
    root :to => "promos#index"
  end

What I'm struggling with, is getting it so "" will also use promos#index as the root path. When it's not the root path, mywebsite.com sends them to the applications#index, which requires a login. Something I don't want users to see on a first visit.
Is there anyway to modify this code to also include mywebsite.com to have the different root? I've tried things like duplicating the code with "", but this tends to mess up all other subdomains, regardless of order. Below is the in of my routes file:
constraints(:subdomain => "www") do
    root :to => "promos#index"
  end

  root :to => "applications#index"

A: You can use an object that implements 'matches?' to do some real custom stuff. Below we'll set applications#index if you are a customer subdomain, and send you to promo#index if you're not
In your routes:
Yourapp::Application.routes.draw do
  constraints(SubDomain) do
    root :to => "applications#index"
  end
  root :to => "promo#index"
  ...
end

and then the Subdomain matcher file:
config/initializers/subdomain.rb
class SubDomain
  def self.matches?(request)
    case request.subdomain
    when 'www', '', nil, #admin/api/etc could also go here
      false
    else
      true
    end
  end
end

subdomain.rb can also live in lib (if it's being auto-loaded)


text:
Q: How to pass raw data in API request using Retrofit2 I am trying to call login API using Retrofit2.
But in onResponse i alwasy get null as response.
Login API endpoint
@FormUrlEncoded
@POST("/api/login/{mobile}")
Call<ResObj> userLogin( @Field("phoneNumber") String mobile );

And the API implementation
private void doLogin(final String mobile){
        Call<ResObj> call = userService.login(mobile);
        call.enqueue(new Callback<ResObj>() {
            @Override
            public void onResponse(Call<ResObj> call, Response<ResObj> response) {

                    ResObj resObj = response.body(); // here i am getting null response.body()

                    if(resObj.getMessage().equals("true")){

                        Intent intent = new Intent(Login.this, ListActivity.class);
                        intent.putExtra("mobile", mobile);
                        startActivity(intent);

                    } else{
                        Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();

                    }
                }

            @Override
            public void onFailure(Call<ResObj> call, Throwable t) {
                Toast.makeText(Login.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

ResObj class:
public class ResObj {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

I just want to  know what causes the error and what are possible solutions.
UPDATE
POSTMAN

A: You are getting null response in your login API. It may be due to many reasons. You can check your API is working as expected or not using POSTMAN.
And inside your code, you can prevent this type of exception by checking OBJECT is null or not. like the following.
@Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {

       ResObj resObj = response.body();

       if(resObj != null){ // checking object is not null

          if(resObj.getStatus()){

              Intent intent = new Intent(Login.this, ListActivity.class);
              intent.putExtra("mobile", mobile);
              startActivity(intent);

          } else{
              Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
          }
       }else{
          // handle null response here.
       }
}

Update:
According to your Response JSON, Your Model(ResObj) class should be like the following.
public class ResObj
{
    private String date;

    private String address;

    private String accountName;

    private String contactPerson;

    private String timeOut;

    private String problem;

    private String srNo;

    private String fieldEngineer;

    private String joNo;

    private String irNo;

    private String designation;

    private String email;

    private String timeIn;

    private String productType;

    private boolean status;

    private String contactNo;

    public String getDate ()
    {
        return date;
    }

    public void setDate (String date)
    {
        this.date = date;
    }

    public String getAddress ()
    {
        return address;
    }

    public void setAddress (String address)
    {
        this.address = address;
    }

    public String getAccountName ()
    {
        return accountName;
    }

    public void setAccountName (String accountName)
    {
        this.accountName = accountName;
    }

    public String getContactPerson ()
    {
        return contactPerson;
    }

    public void setContactPerson (String contactPerson)
    {
        this.contactPerson = contactPerson;
    }

    public String getTimeOut ()
    {
        return timeOut;
    }

    public void setTimeOut (String timeOut)
    {
        this.timeOut = timeOut;
    }

    public String getProblem ()
    {
        return problem;
    }

    public void setProblem (String problem)
    {
        this.problem = problem;
    }

    public String getSrNo ()
    {
        return srNo;
    }

    public void setSrNo (String srNo)
    {
        this.srNo = srNo;
    }

    public String getFieldEngineer ()
    {
        return fieldEngineer;
    }

    public void setFieldEngineer (String fieldEngineer)
    {
        this.fieldEngineer = fieldEngineer;
    }

    public String getJoNo ()
    {
        return joNo;
    }

    public void setJoNo (String joNo)
    {
        this.joNo = joNo;
    }

    public String getIrNo ()
    {
        return irNo;
    }

    public void setIrNo (String irNo)
    {
        this.irNo = irNo;
    }

    public String getDesignation ()
    {
        return designation;
    }

    public void setDesignation (String designation)
    {
        this.designation = designation;
    }

    public String getEmail ()
    {
        return email;
    }

    public void setEmail (String email)
    {
        this.email = email;
    }

    public String getTimeIn ()
    {
        return timeIn;
    }

    public void setTimeIn (String timeIn)
    {
        this.timeIn = timeIn;
    }

    public String getProductType ()
    {
        return productType;
    }

    public void setProductType (String productType)
    {
        this.productType = productType;
    }

    public boolean getStatus ()
    {
        return status;
    }

    public void setStatus (boolean status)
    {
        this.status = status;
    }

    public String getContactNo ()
    {
        return contactNo;
    }

    public void setContactNo (String contactNo)
    {
        this.contactNo = contactNo;
    }
}

You are passing parameter as raw data(according to your screen-shot). So your API endpoint would be like below.
@Headers("Content-Type: application/json")
@POST("/api/login")
Call<ResObj> userLogin(@Body JsonObject jsonObject);

And call your API like this
private void doLogin(final String mobile){
      try {
           JsonObject paramObject = new JsonObject();
           paramObject.addProperty("mobile", mobile);
        } catch (JSONException e) {
            e.printStackTrace();
        }

      Call<ResObj> call = userService.login(paramObject);
      call.enqueue(new Callback<ResObj>() {

        //your rest of code

      });
}

UPDATE-2:
To send object from one Activity to another using intent you have to make your model class Percelable. like this
// implements Parcelable

public class ResObj implements Parcelable {
    // ...........your previous code here

    // just simply add the following methods

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(date);
        dest.writeString(address);
        dest.writeString(accountName);
        dest.writeString(contactPerson);
        dest.writeString(timeOut);
        dest.writeString(problem);
        dest.writeString(srNo);
        dest.writeString(fieldEngineer);
        dest.writeString(joNo);
        dest.writeString(irNo);
        dest.writeString(designation);
        dest.writeString(email);
        dest.writeString(timeIn);
        dest.writeString(productType);
        dest.writeByte((byte) (status ? 1 : 0));
        dest.writeString(contactNo);
    }
    public static final Parcelable.Creator<ResObj> CREATOR
            = new Parcelable.Creator<ResObj>() {
        public ResObj createFromParcel(Parcel in) {
            return new ResObj(in);
        }

        public ResObj[] newArray(int size) {
            return new ResObj[size];
        }
    };

    protected ResObj(Parcel in) {
        date = in.readString();
        address = in.readString();
        accountName = in.readString();
        contactPerson = in.readString();
        timeOut = in.readString();
        problem = in.readString();
        srNo = in.readString();
        fieldEngineer = in.readString();
        joNo = in.readString();
        irNo = in.readString();
        designation = in.readString();
        email = in.readString();
        timeIn = in.readString();
        productType = in.readString();
        status = in.readByte() != 0;
        contactNo = in.readString();

    }
}

Now pass your object via intent like the following.
if(resObj != null){

    if(resObj.getStatus()){

        Intent intent = new Intent(Login.this, ListActivity.class);
        intent.putExtra("your_key", resObj); // pass resObj and use same key to get data
        startActivity(intent);

    } else{
        Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
    }
}

Get data from your ListActivity like this
@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_second);

     final ResObj yourObject = getIntent().getParcelableExtra("your_key"); // make sure you use same key like data.

     // Now you can use your data like that
     yourEditText.setText(yourObject.getEmail());
}


text:
Q: How to retrieve os_log messages from detached hard drive? My daemon and application generated log messages using os_log(). Unfortunately the Mac mini running macOS Big Sur is no longer running as it always goes to the bootcamp partition when restarted. Now that hard drive has been removed from the Mini and being shipped to me.
When the computer is running, I usually use the log command to retrieve log messages
log show --predicate 'senderImagePath contains "com.mycompany"'
My question, is it possible to get the log messages from this particular hard drive when I plug it to the dock? At the moment I don't know what other volumes are available/readable from that drive. If I can get the log messages, I'd like to learn if my daemon had anything to do with the crash.
Where does macOS Big Sur (or Catalina) keep the os_log database? I didn't find any Apple documentation mentioning this, and I know it is not in /private/var/log/system.log.


text:
Q: SQL SELECT multiple criterias IF not null I have a dataset where i want to select the records that matches my input values. But i only want to try matching a field in my dataset against the input value, if the dataset value is not NULL.
I always submit all 4 input values.
@Tyreid, @CarId,@RegionId,@CarAgeGroup
So for the first record in the dataset i get a successful output if my input values matches RegionId and CarAgeGroup.
I cant figure out how to create the SQL script for this SELECT?
My dataset
TyreId  CarId   RegionId    CarAgeGroup
------  -----   --------    -----------
NULL    NULL    1084            2
65      35      1084            1
5       35      1084            1
NULL    41      1085            NULL
120     NULL    NULL            NULL
NULL    NULL    1084            2
65      NULL    1084            NULL

A: You might use ISNULL or Coalecse to reach the expected result, if the Field is NULL the parameter will be compared with the parameter.
Select * from aTable
Where ISNULL(Tyreid,@Tyreid)=@Tyreid
AND   ISNULL(CarId ,@CarId )=@CarId
AND   ISNULL(RegionId,@RegionId)=@RegionId
AND   ISNULL(CarAgeGroup,@CarAgeGroup)=@CarAgeGroup

A: Keeping in mind that NULL = <any value> yields NULL you need to check for NULL column values separately:
WHERE (TyreId      IS NULL OR TyreId      = @Tyreid)
AND   (CarId       IS NULL OR CarId       = @CarId)
AND   (RegionId    IS NULL OR RegionId    = @RegionId)
AND   (CarAgeGroup IS NULL OR CarAgeGroup = @CarAgeGroup)

A: Maybe this is what you want?
SELECT * FROM YourTable
WHERE (TyreId = @Tyreid OR TyreId IS NULL)
    AND (CarId = @CarId OR CarId IS NULL)
    AND (RegionId = @RegionId OR RegionId IS NULL)
    AND (CarAgeGroup = @CarAgeGroup OR CarAgeGroup IS NULL)

Sample SQL Fiddle


text:
Q: how to check if a particular user is a owner of certain directories and if not then assign this user as a owner using bash script I am new in linux and currently have to perform a task where I have to check if a particular user is an owner of a directory and its subdirectory and if not then assign him as a owner. I need to do this in a bash script so anyone if can provide me a sample would be really great.
Scenario:
path = "/opt/dev/myapp"
this directory contains more subdirectories and the files
Need to check if the user "devuser" is an owner or not and if not then assign him as an owner.
Thanks in Advance!

A: You could just assign the user to that directory, regardless the fact that before doing the check it was or wasn't:
chown -R bob bobs-directory

where -R means go recursively down the directory tree, bob is the name of the user and bobs-directory is the root directory you want to give ownership to.

A: As Alberto Zaccagni correctly said, you could just change the owner right away. If you want to check anyway, you can do it like this:
dir="/opt/dev/myapp"
username=devuser

[ "$(stat -c "%U" "$dir")" == "$username" ] || chown -R $username "$dir"

stat is a utility for displaying information about files (owner, permissions, times, …).
Please note that you must not put whitespace around the = when assigning variables. Also, I'd recommend against using a variable name like path as that's easily confused with the environment variable $PATH.
Edit: Mac OS X ships BSD stat, which has different options, so you have to change the command like this:
[ "$(stat -f "%Su" "$dir")" == "$username" ] || chown -R $username "$dir"


text:
Q: Any way to grab a numeric value from a file and add it? Here's a step wise explanation of what I want

*

*The script is ran 10 time

*On typing the command su -c hackbench -pTl 4000 it'll export a message like Running in threaded mode with 10 groups using 40 file descriptors each (== 400 tasks) Each sender will pass 4000 messages of 100 bytes Time: 13.353 with differing time in place of 13.353

*I want to add the 13.353 to the next value of su -c hackbench -pTl 4000 which for example is Running in threaded mode with 10 groups using 40 file descriptors each (== 400 tasks) Each sender will pass 4000 messages of 100 bytes Time: 10.476 in order to find the average of 10 runs

I know that it can be looped using a for loop and I even know the time can be added like maybe
TIME=$(($TIME + $("somehow we have to bring '10.476' here")))
I just don't know how I can grab ONLY the 13.353 and 10.476

A: Using awk:
$ su -c hackbench -pTl 4000| awk '{print $NF}'
13.353

Awk splits each input line into fields.  $NF is the last field on the line.
Using grep:
$ su -c hackbench -pTl 4000| grep -oE '[[:digit:]+-.]+$'
13.353

-o tells grep to print only the matched content.  [:digit:]+-.]+$ matches the number at the end of the line.
Using sed:
$ su -c hackbench -pTl 4000| sed 's/.* //'
13.353

s/.* // removes all content on the line up to and including the last space.  Only the final number remains.
Using bash:
$ readarray -d' ' arr < <(su -c hackbench -pTl 4000); echo "${arr[-1]}"
13.353

This reads the output of the hackbench command into array arr.  ${arr[-1]} prints the last element of the array.  (This requires a recent version of bash.)
Adding
Bash does not understand floating point numbers.  So, one must use awk or bc or another tool.  For example:
$ time=10
$ time=$(echo "$time + ${arr[-1]}" | bc -l)
$ echo "$time"
23.353

As an aside, it is best practice to use lower or mixed-case names for shell variable names in your work.  This is because the system uses upper-case names for its variables and you don't want to accidentally overwrite one of them.


text:
Q: question about infinite product I'm studying infinite products appearing in complex analysis these days. There are lots of
theorems regarding it, for example, for $0<u_n <1,  \prod (1-u_n) > 0$, iff $\Sigma u_n < \infty $.
I come up with a following question which No elementary book say about it..
within above condition, $\prod u_n =1  $ is impossible, but i thought intuitively that by approaching$ u_n$ rapidly to 1, it is possible to get a value of infinite product is larger than 1-$\epsilon$ for any $\epsilon >0$
(of course our$ u_n $can depend on $\epsilon$)
if anyone know about theorem regrading it or can prove about this? thanks.

A: Note that if $0 < u_j < 1$,
$$ \prod_{j=1}^\infty u_j = \exp\left( \sum_{j=1}^\infty \ln(u_j) \right)$$
So you want $$\ln(1-\epsilon) < \sum_{j=1}^\infty \ln(u_j)$$
Can you think an infinite sum of negative terms that is greater than $\ln(1-\epsilon)$?


text:
Q: Locating a graphic function (Python) First off, thanks to the site and everybody on it.  I am taking my first python class and have come across this site many times when trouble-shooting coding problems.  Thanks to everybody who have already helped me out a little thus far.  But, I do have a problem I can't figure out:
I have to draw the "5" side of a die in a python graphics window.  The catch is that I can't just draw them.  My "Dot" function has to be called 5 times to complete the graphic.  I had trouble with the dot being placed on the rectangle, but the prof helped me out there.  I just can't seem to locate the same dot in different locations.  Here is my code so far:
from graphics import*

def Dot(win):

    # Draw a dot

    center=Point(150,150)
    circ=Circle(center,25)
    circ.setFill('Black')
    circ.draw(win)

def Dice():

    #Build the dice (fill white, background green)
    win=GraphWin('Shapes',500,500)
    win.setBackground('Green')
    rect=Rectangle(Point(100,100),Point(400,400))
    rect.setFill('White')
    rect.draw(win)

    #Call dot 5 times with different locations:

    Dot(win)

    Dot(win)

    Dot(win)

    Dot(win)

    Dot(win)

def main():

    Dice()

main()

I have to call the "Dot" function 5 times.  However, I have tried to ".move(pt,pt), .locate, etc.  I can't figure out how to take the "Dot" function and move it to a different location on the graphics window.  Any help would be greatly appreciated.
Thanks.

A: I was finally able to get this one.  I wasn't aware you could command after the window arguement.  So, the Dot(win, 350,150)  etc. with the different coordinates worked well.  Thanks for the responses and help!


text:
Q: _mydatePicker.enabled = FALSE; prevents datepicker movement in iOS 6 but not iOS 7 In viewDidAppear I have set _mydatePicker.enabled =FALSE.  This "freezes" the date picker and does not respond to touch when used in iOS 6;  However in iOS 7 the date picker wheel continues to be able to be turned by the user. Is there a way of "freezing" the datepicker wheel unless _mydatPicker.enabled =TRUE is called?

A: How about using the userInteractionEnabled property?

A: Use :
datePicker.userInteractionEnabled = FALSE;

It will work in iOS 7 or iOS 6.


text:
Q: Entity Framework | log the SQL generated by the System.Data.Entity.DbContext I get the idea that I can use the following for SQL statements
Database.Log = (data) =>
                {
                    LogManager.Log(data, LogManager.Severity.Info,  false);
                };
However, what I have been finding that the behavior is such that when the script is unsuccessful, the above action i.e. Database.Log(...) is not called at all.
If it is true then I would like to catch the exception when .SaveChanges(...) has been called. I would want to get the SQL Script that has been executed. Please advise.


text:
Q: How I can get list item values when I click on list view In list view my list contains four data  i.e Fine_ID , Street , Area and Car_No. and I want to fetch all this value, when I am clicking on Clamp Vehicle that is my context menu. And I want to pass all this four values into my database but the problem is that when I click on another list its dosent change all that previous value.
here is my clamper activity code
public class ClamperActivity extends ListActivity {

 private ProgressDialog pDialog;

 JSONParser jsonParser = new JSONParser();

private static final String CAR_NO = "car_no";
private static final String FINE_ID = "fine_id";
private static final String AREA = "area";
private static final String STREET = "street";

JSONArray jsonArray = null;

private static String userId = LoginActivity.user_id;
private static String fineId1;
private static String street1;
private static String area1;
private static String carNo1;

 ArrayList<HashMap<String, String>> jsonlist;

 public static String user_id="";

 static String url= "http://192.168.1.7/testkrcs/main/get_clamped";
 static String url1="https://192.168.1.3/testkrcs/main/clamp_vehicle";

 // JSON Node names
 private static final String TAG_SUCCESS = "success";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clamper);
jsonlist = new ArrayList<HashMap<String,String>>();

ListView lv = (ListView) findViewById(android.R.id.list);
registerForContextMenu(lv);

new FetchVehiclesTask().execute();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Select The Action");
    menu.add(0, v.getId(), 0, "Clamp Vehicle");
    menu.add(0, v.getId(), 0, "Cancel");
}
@Override
public boolean onContextItemSelected(MenuItem item){
      if(item.getTitle()=="Clamp Vehicle"){
          carNo1 = ((TextView)findViewById(R.id.carNo))
                .getText().toString();
        fineId1 = ((TextView) findViewById(R.id.fineId))
                .getText().toString();
        area1 = ((TextView) findViewById(R.id.area1))
                .getText().toString();
        street1  = ((TextView)findViewById(R.id.street1))
                .getText().toString();
          //Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_LONG).show();
          new ClamperVehicleTask().execute();
      }

       if(item.getTitle()=="Cancel"){

      }else{
         return false;
      }
    return true;
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
openContextMenu(v);

}

class ClamperVehicleTask extends AsyncTask<String, String, String>
{
  protected String doInBackground(String... args )
  {
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("street",ClamperActivity.street1));
      params.add(new BasicNameValuePair("area",ClamperActivity.area1));
      params.add(new BasicNameValuePair("user_id",ClamperActivity.userId));
      params.add(new BasicNameValuePair("fine_id",ClamperActivity.fineId1));
      params.add(new BasicNameValuePair("car_no",ClamperActivity.carNo1));

 JSONObject json = jsonParser.getJSONFromUrl(url1, params);

      System.out.println("ClamperVehicleTask UID = "+ClamperActivity.userId);
      System.out.println("ClamperVehicleTask Street = "+ClamperActivity.street1);
      System.out.println("ClamperVehicleTask Area = "+ClamperActivity.area1);
      System.out.println("ClamperVehicleTask Fine ID = "+ClamperActivity.fineId1);
      System.out.println("ClamperVehicleTask Car No. = "+ClamperActivity.carNo1);

      Log.d("ClamperVehicleTask Response", json.toString());
      return null;
  }
}

class FetchVehiclesTask extends AsyncTask<Void, Void, Void>
{
private ListActivity activity;

 protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(ClamperActivity.this);
    pDialog.setMessage("Fetching Vehicles List...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
}

protected Void doInBackground(Void... args0)
{

     System.out.println("Login Street clamper ="+LoginActivity.street);
     System.out.println("Login Area clamper ="+LoginActivity.area);
     System.out.println("Login Uid clamper = "+LoginActivity.user_id);
     JSONParser jsonParser = new JSONParser();
        UserFunctions userFunction = new UserFunctions();

        String json = userFunction.clamperFetch(LoginActivity.street, LoginActivity.area, LoginActivity.user_id);
        Log.d("Response:",json);
        if(json!=null)
        {
            try{

                jsonArray = new JSONArray(json);
                for(int i=0;i<jsonArray.length();i++)
                {
                    JSONObject c = jsonArray.getJSONObject(i);
                     String fineId = c.getString(FINE_ID);
                     String street2 = c.getString(STREET);
                     String area2 = c.getString(AREA);
                     String carNo = c.getString(CAR_NO);

                    System.out.println("FineId = " +fineId);
                    System.out.println("Street = "+street2);
                    System.out.println("Area = "+area2);
                    System.out.println("Car_No = "+carNo);

                    HashMap<String,String>jsonArray = new HashMap<String,String>();
                    jsonArray.put(FINE_ID,fineId);
                    jsonArray.put(STREET, street2);
                    jsonArray.put(AREA, area2);
                    jsonArray.put(CAR_NO, carNo);
                    jsonlist.add(jsonArray);

                }
            }catch(JSONException e){
                e.printStackTrace();
            }
        }else {
            Log.e("JASON Parser", "Couldn't get any data from the url");
        }

        System.out.println("Fetching Response" +json);

           return null;
}
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    // dismiss the dialog once done
    if(pDialog.isShowing())
    {
        pDialog.dismiss();
    }
    System.out.println("Result"+result);

    ListAdapter adapter = new SimpleAdapter(
            ClamperActivity.this,jsonlist,
            R.layout.list_item,
            new String[]{FINE_ID,STREET,AREA,CAR_NO},
            new int[]{R.id.carNo,R.id.fineId,R.id.area1,R.id.street1});
    setListAdapter(adapter);
    System.out.println("Adapter"+adapter);

}
}

}

like this i am trying to fetch value from list view its not working properly when I am trying to click on another list its remain the same value it didnt change the new value,
public boolean onContextItemSelected(MenuItem item){
      if(item.getTitle()=="Clamp Vehicle"){
          carNo1 = ((TextView)findViewById(R.id.carNo))
                .getText().toString();
        fineId1 = ((TextView) findViewById(R.id.fineId))
                .getText().toString();
        area1 = ((TextView) findViewById(R.id.area1))
                .getText().toString();
        street1  = ((TextView)findViewById(R.id.street1))
                .getText().toString();
          //Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_LONG).show();
          new ClamperVehicleTask().execute();
      }

       if(item.getTitle()=="Cancel"){

      }else{
         return false;
      }
    return true;
}

In this way I am trying to pass all four values into database
     class ClamperVehicleTask extends AsyncTask
 {
  protected String doInBackground(String... args )
  {
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("street",ClamperActivity.street1));
      params.add(new BasicNameValuePair("area",ClamperActivity.area1));
      params.add(new BasicNameValuePair("user_id",ClamperActivity.userId));
      params.add(new BasicNameValuePair("fine_id",ClamperActivity.fineId1));
      params.add(new BasicNameValuePair("car_no",ClamperActivity.carNo1));
      JSONObject json = jsonParser.getJSONFromUrl(url1, params);
      System.out.println("ClamperVehicleTask UID = "+ClamperActivity.userId);
      System.out.println("ClamperVehicleTask Street = "+ClamperActivity.street1);
      System.out.println("ClamperVehicleTask Area = "+ClamperActivity.area1);
      System.out.println("ClamperVehicleTask Fine ID = "+ClamperActivity.fineId1);
      System.out.println("ClamperVehicleTask Car No. = "+ClamperActivity.carNo1);

      Log.d("ClamperVehicleTask Response", json.toString());
      return null;
  }
}

A: You must have stored the List before attaching to the listview using adapter class. The just fetch it by using the get(position).
for eg:- I Have used simple example for just explaining the concept.
I hope you know how to add data in the arraylist.
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter(this,android.R.layout.simple_list.xml, list)
listview.setAdapter(adapter)

now you have attached that list to adapter class.Then just include the following code on onListItemClick(ListView l, View v, int position, long id) event
list.get(position)

Here are some good links 1, this and this and this
Hope it helps

A: Within the onContextItemSelected handler you may use AdapterContextMenuInfo to get information about the selected item position and even the view associated with the list item. Check
How to get View in OnContextItemSelected event?.
Calling the findViewById method on the retrieved item view, you are able to access text views of the clicked item.
Try also exploiting AsyncTask parameters to pass your strings to the doInBackground() method, instead of static class fields.
@Override
public boolean onContextItemSelected(MenuItem item){
   AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
   View view = info.targetView;

   String carNo1, fineId1, area1, street1, uId = userId;
   if(item.getTitle()=="Clamp Vehicle"){
      carNo1 = ((TextView) view.findViewById(R.id.carNo))
            .getText().toString();
      fineId1 = ((TextView) view.findViewById(R.id.fineId))
            .getText().toString();
      area1 = ((TextView) view.findViewById(R.id.area1))
            .getText().toString();
      street1  = ((TextView) view.findViewById(R.id.street1))
            .getText().toString();
      new ClamperVehicleTask().execute(carNo1, fineId1, uId, area1, street1);
  }

   if(item.getTitle()=="Cancel"){

  }else{
     return false;
  }
  return true;
}

Changes in doInBackground():
protected String doInBackground(String... args )
{
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("street",args[4]));
  params.add(new BasicNameValuePair("area",args[3]));
  params.add(new BasicNameValuePair("user_id",args[2]));
  params.add(new BasicNameValuePair("fine_id",args[1]));
  params.add(new BasicNameValuePair("car_no",args[0]));

  JSONObject json = jsonParser.getJSONFromUrl(url1, params);

  System.out.println("ClamperVehicleTask UID = "+args[2]);
  System.out.println("ClamperVehicleTask Street = "+args[4]);
  System.out.println("ClamperVehicleTask Area = "+args[3]);
  System.out.println("ClamperVehicleTask Fine ID = "+args[1]);
  System.out.println("ClamperVehicleTask Car No. = "+args[0]);

  Log.d("ClamperVehicleTask Response", json.toString());
  return null;
}

In addition, I would also suggest you to open the context menu in a more correct way (check https://stackoverflow.com/a/8872337/3423110)
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
    l.showContextMenuForChild(v);
}

A: Actually you have a problem with this you are finding your view globally in main layout while it is a part of you listview so find like this so you can get the values.       public boolean onContextItemSelected(MenuItem item){
      if(item.getTitle()=="Clamp Vehicle"){
          carNo1 = ((TextView)listview.findViewById(R.id.carNo))
                .getText().toString();
        fineId1 = ((TextView) listview.findViewById(R.id.fineId))
                .getText().toString();
        area1 = ((TextView) listview.findViewById(R.id.area1))
                .getText().toString();
        street1  = ((TextView)listview.findViewById(R.id.street1))
                .getText().toString();
          //Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_LONG).show();
          new ClamperVehicleTask().execute();
      }
   if(item.getTitle()=="Cancel"){

  }else{
     return false;
  }
return true;

}


text:
Q: Group data values using xpath & php So my XML document looks something like this:
<output>
   <workouts>
       <workout>
         <workout_date>
           <![CDATA[ 2014-04-05 ]]>
         </workout_date>
         <distance>
           <![CDATA[ 15 ]]>
         </distance>
       </workout>
       <workout>
         <workout_date>
           <![CDATA[ 2014-04-08 ]]>
         </workout_date>
         <distance>
           <![CDATA[ 2 ]]>
         </distance>
       </workout>
       <workout>
         <workout_date>
           <![CDATA[ 2014-03-28 ]]>
         </workout_date>
         <distance>
           <![CDATA[ 3.3 ]]>
         </distance>
       </workout>

   </workouts>
</output>

Now I am using XPath and PHP to output the date like so:
$typesListXml = $xml->xpath('output/workouts/workout/workout_date');
if (!empty($typesListXml)) {
    $typesList = array();
    foreach ($typesListXml as $typeXml) {
             // using strtotime to output the month only (commented out below)
        //$typesList[] = date('F', strtotime((string)$typeXml));
                $typesList[] = (string)$typeXml;

    }

    //var_dump($typesList);
    $typesList = array_unique($typesList);
    var_dump($typesList);

This will output only unique values so I'm not repeating each month, however, I'm not able to output the sum of all the "distance" values for each month.  So essentially, the final result will look something like this:
Result:

April
total distance =  17
March
total distance = 3.3
etc...

A: I am not sure if PHP provides XPath/XQuery 3 support or not, but if it does you could achieve what you are looking for with this expression:
for $workout in /output/workouts/workout
let $date := xs:date($workout/workout_date)
let $month := month-from-date($date)
let $year := year-from-date($date)
group by $year, $month
return
    let $padded-month := substring(concat('0', $month), string-length(string($month)))
    let $month-year := format-date(xs:date(string-join((string($year), $padded-month, '01'), "-")), "[MNn] [Y]")
    return
        ($month-year, sum($workout/distance))

A: I was able to group them using this logic.  Just need to add the distance values from the array now
 $distanceforDate = array();
    foreach ($typesList as $type) {
     $Data = $xml->xpath('output/workouts/workout[workout_date="' . $type . '"]');
        $M = date('F', strtotime($type));
        if (!empty($Data)) {
            foreach ($Data as $rawData) {
                //print_r ($M);
                $distanceforDate[$M][] = '' . $rawData->distance;
            }
        }
    }
  print_r($distanceforDate);
    echo array_sum($distanceforDate);

}


text:
Q: Why does '12345'.count('') return 6 and not 5? >>> '12345'.count('')
6

Why does this happen? If there are only 5 characters in that string, why is the count function returning one more?
Also, is there a more effective way of counting characters in a string?

A: The most common way is to use len('12345'). It returns the number of characters in a given string - in this case 5.

A: That is because there are six different substrings that are the empty string: Before the 1, between the numbers, and after the 5.
If you want to count characters use len instead:
>>> len("12345")
5

A: How many pieces do you get if you cut a string five times?
---|---|---|---|---|---     -> 6 pieces

The same thing is happening here. It counts the empty string after the 5 also.
len('12345') is what you should use.

A: count returns how many times an object occurs in a list, so if you count occurrences of '' you get 6 because the empty string is at the beginning, end, and in between each letter.
Use the len function to find the length of a string.

A: Count and Len are two very different things. Len simply prints the length of the string (hence the name 'Len'), while Count iterates through the string or list and gives you the number of times an object occurs, which counts the beginning and end of the string as well as in between each letter.

A: It's the same reason why it makes sense for ''.count('') to return 1, not 0.


text:
Q: Google Chrome Uncaught (in promise) DOMException while playing audio.play() method $scope.sound = function () {
    // $scope.totalQueueList -->response is saved in this variable

    if ($scope.totalQueueList) {
        var audio = new Audio();
        audio.src = 'rest/assets/images/beep.mp3';
        var playedPromise = audio.play();
        if (playedPromise) {
            playedPromise.catch((e) => {
                console.log(e)
                if(e.name === 'NotAllowedError' || e.name === 'NotSupportedError') {
                    console.log(e.name);
                    audio.loop = true
                }
            }).then(() => {

            });
        }
    }
}

This code is not working when doing a manual page refresh of the chrome browser. It gives DOMException for audio.play() method.
For normal flow without a browser page refresh, it works. Please provide a solution.

A: You have to wait until the sound resource has been loaded by your browser. Use the method canPlayThrough to get informed when the resource is ready to be played:
$scope.sound = function() {
  // $scope.totalQueueList -->response is saved in this variable

  if ($scope.totalQueueList) {
    var audio = new Audio();
    audio.src = 'rest/assets/images/beep.mp3';

    // when the sound has been loaded, execute your code
    audio.oncanplaythrough = (event) => {
      var playedPromise = audio.play();
      if (playedPromise) {
        playedPromise.catch((e) => {
          console.log(e)
          if (e.name === 'NotAllowedError' || e.name === 'NotSupportedError') {
            console.log(e.name);
            audio.loop = true
          }
        }).then(() => {

        });
      }
    }
  }
}


text:
Q: GIT - Hello world! Может кто подсказать как работать с GIT ? Для работы с ним поставил себе TurtoiseGIT.

*

*Есть проект(папка) с единственным файлом - Hello.txt.

*Создаю репозиторий GIT в этой папке(Create GIT repository here, папка расшарена).

*Делаю Commit, добавляя в созданный репозиторий единственный файл - hello.txt, с текстом - Hello world!

*Клонирую себе этот проект в свой локальный репозиторий

*В своём локальном(клонированном) репозитории изменяю текст единственного файла, на "Hello World again!" и делаю Commit на локальный репозиторий.

*Пытаюсь отправить изменения в главный репозиторий -(Push в Origin) и вылетает ошибка: refusing to update checked out branch: refs/heads/master

Что я сделал не так ?
1. Как отправить изменившейся файл в удалённый репозиторий с TurtoiseGIT ?

A: В самом начале Вы сделали большую ошибку - поставили TurtoiseGIT. Сносите. Оно не нужно.
Поставьте нормальный, правильный гит с официального сайта https://git-scm.com/
Так как Вы делаете два репозитория, никто обычно не делает.
Существуют два типа репозитория - обычный и голый (bare). В Вашем случае нужен один bare репозиторий и один и более обычных. На "сервере"  (это может быть диск D на этой же машине) создаете bare репу
git init --bare

Bare репозиторий не имеет рабочего каталога (working dir) и в нем "коммить" нельзя (точнее можно, но не так просто).
Все. теперь переходим к обычному рабочему каталогу, который клонируете через clone
git clone "D:\Repo\"

(или как там у Вас с путями). Теперь можно спокойно создавать файлы, коммитить и пушить. Все будет работать.
Теперь можно склонировать репозиторий ещё куда-нибудь и работать там себе в параллель.
То есть, если Вам нужна классическая схема сервер и клиенты, то Вам нужен один bare репозиотрий.
Но что, если все таки хочется "запушить" в "не bare" репу? В этом случае обычно применяют обратный процесс - pull  с другой стороны. То есть, если A хочет запушить B, то нужно делать наоборот - B пуллит изменения от A.

К ней(к главному репозиторию) будет открыт сетевой доступ

Так можно сделать. Более того, даже будет работать. Но лучше поднять себе любой гит сервер - будет надежнее. Если локальный нужен, то тут хорошо gogs.  Но никто не отменял gitlab/github.

A: Получается, последовательность действий такая:

*

*Создаём новый Bare-репозиторий(пустой, ставя галочку "Bare").

*Клонируем этот пустой репозиторий к себе (git clone)

*В него кладём нужные файлы и делаем Commit локальному репозиторию.

*Что бы положить в "удалённый" репозиторий, делаем Push в Origin


text:
Q: InvalidSignatureException in using GetSecretValue AWS secrets manager API I am getting Invalid Request with below error message when trying to retrieve secret value using AWS secrets manager REST API GetSecretValue
I followed the steps given here (https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html#sig-v4-examples-post) to sign the request using sigv4.
My code looks like below:
    def sign(self, key, msg):
        return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

    def get_signature_key(self, key, dateStamp, regionName, serviceName):
        kDate = self.sign(('AWS4' + key).encode('utf-8'), dateStamp)
        kRegion = self.sign(kDate, regionName)
        kService = self.sign(kRegion, serviceName)
        kSigning = self.sign(kService, 'aws4_request')
        return kSigning

    def get_request_url(self, region, access_key, secret_key, token, secret_name):
        method = 'POST'
        service = 'secretsmanager'
        host = 'secretsmanager.' + region + '.amazonaws.com'
        endpoint = 'https://secretsmanager.' + region + '.amazonaws.com'
        content_type = 'application/x-amz-json-1.0'
        amz_target = 'secretsmanager.GetSecretValue'
        request_parameters = '{'
        request_parameters += '"SecretId":"%s"' %(secret_name)
        request_parameters += '}'

        t = datetime.datetime.utcnow()
        amz_date = t.strftime('%Y%m%dT%H%M%SZ')
        date_stamp = t.strftime('%Y%m%d')

        canonical_uri = '/'
        canonical_querystring = ''
        canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n' + 'x-amz-target:' + amz_target + '\n' + 'x-amz-security-token:' + token + '\n'

        signed_headers = 'content-type;host;x-amz-date;x-amz-target;x-amz-security-token'
        payload_hash = hashlib.sha256(request_parameters.encode('utf-8')).hexdigest().strip()

        canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

        algorithm = 'AWS4-HMAC-SHA256'
        credential_scope = date_stamp + '/' + region + '/' + service + '/' + 'aws4_request'
        string_to_sign = algorithm + '\n' +  amz_date + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()

        signing_key = self.get_signature_key(secret_key, date_stamp, region, service)
        signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()

        authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

        headers = { 'Content-Type':content_type, 'Host':host, 'X-Amz-Date':amz_date, 'X-Amz-Target':amz_target, 'X-Amz-Content-Sha256':payload_hash, 'X-Amz-Security-Token':token.encode('ascii'), 'Authorization':authorization_header.encode('ascii')}

        # ************* SEND THE REQUEST *************
        print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
        print('Request URL = ' + endpoint)

        r = requests.post(endpoint, headers=headers, data=request_parameters)

        print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
        print('Response code: %d\n' % r.status_code)
        print(r.text)

A: Order Matters
Both canonical_headers and signed_headers should be sorted.  From your link:

Create the canonical headers. Header names must be trimmed and lowercase, and sorted in code point order from low to high.

and

Create the list of signed headers. This lists the headers in the canonical_headers list, delimited with ";" and in alpha order.

This implies that x-amz-security-token must come before x-amz-target:
    canonical_headers = 'content-type:' + content_type + '\n' + 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n' + 'x-amz-security-token:' + token + '\n' + 'x-amz-target:' + amz_target + '\n'

    signed_headers = 'content-type;host;x-amz-date;x-amz-security-token;x-amz-target'

Also, I believe you'll need to update the Content-Type to application/x-amz-json-1.1.
Tested using this lightly modified version of your code.


text:
Q: Increase of the rms during diffusion - Derivatives calculation We consider a diffusion equation of the form
$$
\frac{\partial F}{\partial t} = \frac{\partial }{\partial x} \!\cdot\! \left[ - \mathcal{F} (t , x) \right] \,
$$
where ${ \mathcal{F} (t ,x) }$ is the flux vector of the diffusion. The initial conditions of the diffusion is given by
$$
F (x , t \!=\! 0) = F_{0} (x) \, .
$$
I am interested in the evolution of the rms of the function $F$ during diffusion. As a consequence, I naturally introduce the well-defined function $g$ as
$$
g (t) = \sqrt{\int \!\! \mathrm{d} x \, \left[ F (x , t) \!-\! F_{0} (x) \right]^{2}} \, .
$$
One can note that ${ g (t \!=\! 0) \!=\! 0 }$. I am interested in the behavior of $g$ for small times, so that I introduce the limited development
$$
g(t) \simeq g_{0} \!+\! g_{1} t \!+\! g_{2} \frac{t^{2}}{2} \!+\! ... \, ,
$$
where we have
$$
\begin{cases}
\displaystyle g_{0} = g (t \!=\! 0) \, ,
\\
\displaystyle g_{1} = \frac{\mathrm{d} g}{\mathrm{d} t} \bigg|_{t = 0} \, ,
\\
\displaystyle g_{2} = \frac{\mathrm{d}^{2} g}{\mathrm{d} t^{2}} \bigg|_{t = 0} \, .
\end{cases}
$$
To compute the coefficient $g_{1}$, I naively applied the chain rule and the derivation under the integral sign to write
$$
\frac{\mathrm{d} g}{\mathrm{d} t} = \frac{\displaystyle \int \!\! \mathrm{d} x \, \left[ F (x , t) \!-\! F_{0} (x) \right] \frac{\partial F}{\partial t}}{\displaystyle  \sqrt{\int \!\! \mathrm{d} x \, \left[ F (x , t) \!-\! F_{0} (x) \right]^{2}}} \, .
$$
However, one should note that this expression when evaluated in ${ t \!=\! 0 }$ is ill-defined, since it takes the form ${ \sim 0 / 0 }$. However, the coefficient $g_{1}$ should be a perfectly well-defined function, since the function $g$ is a perfectly regular function.
How should one proceed to write a correct expression for $g_{1}$ ?
(Additional question : I have the same issue with $g_{2}$ that I also need to evaluate...)


text:
Q: Why can't I put the HTML page returned by $.ajax in the jQuery wrapper? The HTML returned in the $.ajax success callback doesn't let me put it in a jQuery wrapper and apply standard jQuery methods to it. Why is this? For example, this alerts null:
dataType: "html",
success: function(myHTML) {
   var $myHTML = $(myHTML);
   alert( $myHTML.html() ); // returns null
}

My intention is to modify the myHTML using jQuery methods (this is why I need to put it in the jQuery wrapper), and then return the modified html (full, including , scripts, etc.) as a string. But none of the jQuery methods I try work on $(myHTML). How come?
A working version of the code is here: http://jsfiddle.net/supertrue/Uw5dc/
var getHTML = function ( url ){

        $.ajax({
                  url: url,
                  dataType: "html",
                  success: function( myHTML ) {

                      // view the returned HTML
                      alert('Successfully grabbed this HTML: \n\n' + myHTML);

                      // the opening  tag is missing (no idea why)
                      myHTML.replace('', '');

                      // put it in a jQuery wrapper
                      var $myHTML = $(myHTML);

                      // use jQuery to manipulate it
                      // $myHTML.find('script').remove(); // just an example

                      // then view the final html
                      alert('$myHTML.html(): \n\n' + $myHTML.html()); // doesn't work!

                      // that didn't work; try getting outerHTML
                      $myHTML = $('

').append(myHTML);
                      alert('$myHTML.html(): \n\n' + $myHTML.html()); // highly incomplete! missing scripts and ,  wrappers

                  }
              });

     }

A: Look at the documentation of jQuery method here (scroll down to the part for jQuery(html[, ownerDocument])), it says this:

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, we use the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as , <title>, or  elements. As a result, the elements inserted may not be representative of the original string passed.

Given this, it's unlikely you are going to be able to generate the whole page (i.e. including  and tags like that) using $(html), only parts that are compatible with how it works (e.g. tags that you would normally use within  should probably work OK).


text:
Q: Show text and disable checkbox on click So I have two separate functions, one for disabling the second checkbox when someone clicks on the first and another function which displays some text when someone clicks on a checkbox but I can't get the two functions to play nicely together. The functions work fine on there own. The whole thing breaks when you try to use both functions:

 // on click disable other text box
    function ckChange1(direct) {
      var ckName = document.getElementsByName(direct.name);
      for (var i = 0, c; c = ckName[i]; i++) {
       c.disabled = !(!direct.checked || c === direct);
      }
    }

    // shows text on click
    function showText() {
      const checkBox = document.getElementById("progress1");
      const text = document.getElementById("text");
      if ((checkBox.checked = true)){
            text.style.display = "block";
        } else {
           text.style.display = "none";
        }
    }
   #text{
      display: none;
    }
    <input type="checkbox"  id="progress2" onclick="ckChange1(this); showText();">
    DIRECT

    <input type="checkbox" id="progress1" onclick="ckChange1(this); showText();">
    MULTI-ROUTE TYPE

Drop Off

First Drop Off

I can't seem to figure this one out since the second function isn't changing the value of the checkbox at all rather it's just checking the value so I don't see why it would interfere with the first function.
Thanks for any help in advance.

A: I think I didn't understand your request
but try this

function ckChange1(direct) {
 var element=document.getElementById(direct);
 var ed=element.disabled;
 element.disabled=!ed;
 showText(!ed);
}
function showText(ed) {
 const text = document.getElementById("text");
 text.style.display = ed?"block":"none";
}
#text{
  display: none;
}
<input type="checkbox"  id="progress2" onclick="ckChange1('progress1');">
DIRECT
<input type="checkbox" id="progress1" onclick="ckChange1('progress2');">
MULTI-ROUTE TYPE

Drop Off

First Drop Off

A: Try This :

function ckChange1(t) {

  var allRadios = document.getElementsByClassName('rad') ;
  var text = document.getElementById('text') ;

  t.checked = t.checked ? true : false ;

  for( var i = 0; i < allRadios.length ; i++) {
    if (allRadios[i] != t) {
      allRadios[i].checked = false ;
      allRadios[i].disabled = t.checked ;
    }
  }

  text.style.display = t.checked ? "block" : "none" ;

}
#text {
  display: none;
}
<input type="checkbox"  class="rad" id="progress2" onclick="ckChange1(this)">
DIRECT

<input type="checkbox" class="rad" id="progress1" onclick="ckChange1(this);">
MULTI-ROUTE TYPE

Drop Off

First Drop Off