kandi background
Explore Kits

Robust | Android HotFix solution with high compatibility

 by   Meituan-Dianping Java Version: 0.4.87 License: Apache-2.0

 by   Meituan-Dianping Java Version: 0.4.87 License: Apache-2.0

Download this library from

kandi X-RAY | Robust Summary

Robust is a Java library. Robust has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can download it from GitHub.
Robust is an Android HotFix solution with high compatibility and high stability. Robust can fix bugs immediately without publishing apk. More help on Wiki.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • Robust has a medium active ecosystem.
  • It has 4019 star(s) with 714 fork(s). There are 152 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 136 open issues and 225 have been closed. On average issues are closed in 39 days. There are 6 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of Robust is 0.4.87
Robust Support
Best in #Java
Average in #Java
Robust Support
Best in #Java
Average in #Java

quality kandi Quality

  • Robust has 0 bugs and 0 code smells.
Robust Quality
Best in #Java
Average in #Java
Robust Quality
Best in #Java
Average in #Java

securitySecurity

  • Robust has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • Robust code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
Robust Security
Best in #Java
Average in #Java
Robust Security
Best in #Java
Average in #Java

license License

  • Robust is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
Robust License
Best in #Java
Average in #Java
Robust License
Best in #Java
Average in #Java

buildReuse

  • Robust releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
Robust Reuse
Best in #Java
Average in #Java
Robust Reuse
Best in #Java
Average in #Java
Top functions reviewed by kandi - BETA

kandi has reviewed Robust and discovered the below as its top functions. This is intended to give you an instant insight into Robust implemented functionality, and help decide if they suit your requirements.

  • Returns the access method body
  • Verify a patch
  • handle smaliases
  • Determines if the given method is a call method .
  • Read mapping file .
  • Prints the member mapping info .
  • Create insert method .
  • Initializes the View .
  • Get declared method .
  • Create the patches info class .

Robust Key Features

Support 2.3 to 10 Android OS

Perfect compatibility

Patch takes effect without a reboot

Support fixing at method level,including static methods

Support add classes and methods

Support ProGuard,including inline methods or changing methods' signature

Usage

copy iconCopydownload iconDownload
	apply plugin: 'com.android.application'
	//please uncomment fellow line before you build a patch
	//apply plugin: 'auto-patch-plugin'
	apply plugin: 'robust'

	compile 'com.meituan.robust:robust:0.4.99'

Steps

copy iconCopydownload iconDownload
	 apply plugin: 'com.android.application'
	 apply plugin: 'auto-patch-plugin'

Demo Usage

copy iconCopydownload iconDownload
	./gradlew clean  assembleRelease --stacktrace --no-daemon

Attentions

copy iconCopydownload iconDownload
	method a(){
	  return this;
	}

License

copy iconCopydownload iconDownload
Copyright 2017 Meituan-Dianping

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Creating nested columns in python dataframe

copy iconCopydownload iconDownload
import pandas as pd

# I assume that you can read raw data named test.csv by pandas and
# set header = None cause you mentioned the Test data without any headers, so:
df = pd.read_csv("test.csv", header = None)

# Then define preferred Columns! 
MyColumns = pd.MultiIndex.from_tuples([("Models" , ""),
                                       ("Accuracy without normalization" , ""),
                                       ("Accuracy with normalization" , "zscore"),
                                       ("Accuracy with normalization" , "minmax"),
                                       ("Accuracy with normalization" , "maxabs"),
                                       ("Accuracy with normalization" , "robust")])

# Create new DataFrame with specified Columns, after this you should pass values 
New_DataFrame = pd.DataFrame(df , columns = MyColumns)

# a loop for passing values
for item in range(len(MyColumns)):
    New_DataFrame.loc[: , MyColumns[item]] = df.iloc[: , item]
New_DataFrame.set_index(New_DataFrame.columns[0][0] , inplace=True)
New_DataFrame
-----------------------
import pandas as pd

# I assume that you can read raw data named test.csv by pandas and
# set header = None cause you mentioned the Test data without any headers, so:
df = pd.read_csv("test.csv", header = None)

# Then define preferred Columns! 
MyColumns = pd.MultiIndex.from_tuples([("Models" , ""),
                                       ("Accuracy without normalization" , ""),
                                       ("Accuracy with normalization" , "zscore"),
                                       ("Accuracy with normalization" , "minmax"),
                                       ("Accuracy with normalization" , "maxabs"),
                                       ("Accuracy with normalization" , "robust")])

# Create new DataFrame with specified Columns, after this you should pass values 
New_DataFrame = pd.DataFrame(df , columns = MyColumns)

# a loop for passing values
for item in range(len(MyColumns)):
    New_DataFrame.loc[: , MyColumns[item]] = df.iloc[: , item]
New_DataFrame.set_index(New_DataFrame.columns[0][0] , inplace=True)
New_DataFrame

Discrepancy in Javascript Intl.DateTimeFormat() Outputs for the Islamic (Hijri) Calendar between 'islamic' and 'ar-SA'

copy iconCopydownload iconDownload
new Date('2022-03-03').toLocaleDateString('en-US');
// outputs '3/2/2022' when run in San Francisco

new Date('2022-03-03').toLocaleDateString('en-US', { timeZone: 'UTC' });
// outputs '3/3/2022' as expected. UTC is used both for declaring and formatting.

new Date('2022-03-03').toLocaleDateString(
  'en-SA-u-ca-islamic-umalqura',
  { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' }
);
// outputs 'Rajab 30, 1443 AH' as expected
new Intl.DateTimeFormat('ar-SA').resolvedOptions();
// {
//   calendar: "islamic-umalqura"
//   day: "numeric"
//   locale: "ar-SA"
//   month: "numeric"
//   numberingSystem: "arab"
//   timeZone: "America/Los_Angeles"
//   year: "numeric"
// }
calendars = ["islamic", "islamic-umalqura", "islamic-tbla", "islamic-civil", "islamic-rgsa"];
options = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
date = new Date('2022-03-03');
calendars.forEach(calendar => {
  formatted = date.toLocaleDateString(`en-SA-u-ca-${calendar}`, options);
  console.log(`${calendar}: ${formatted}`);
});
// The code above outputs the following:
//   islamic: Shaʻban 1, 1443 AH
//   islamic-umalqura: Rajab 30, 1443 AH
//   islamic-tbla: Rajab 30, 1443 AH
//   islamic-civil: Rajab 29, 1443 AH
//   islamic-rgsa: Shaʻban 1, 1443 AH
-----------------------
new Date('2022-03-03').toLocaleDateString('en-US');
// outputs '3/2/2022' when run in San Francisco

new Date('2022-03-03').toLocaleDateString('en-US', { timeZone: 'UTC' });
// outputs '3/3/2022' as expected. UTC is used both for declaring and formatting.

new Date('2022-03-03').toLocaleDateString(
  'en-SA-u-ca-islamic-umalqura',
  { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' }
);
// outputs 'Rajab 30, 1443 AH' as expected
new Intl.DateTimeFormat('ar-SA').resolvedOptions();
// {
//   calendar: "islamic-umalqura"
//   day: "numeric"
//   locale: "ar-SA"
//   month: "numeric"
//   numberingSystem: "arab"
//   timeZone: "America/Los_Angeles"
//   year: "numeric"
// }
calendars = ["islamic", "islamic-umalqura", "islamic-tbla", "islamic-civil", "islamic-rgsa"];
options = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
date = new Date('2022-03-03');
calendars.forEach(calendar => {
  formatted = date.toLocaleDateString(`en-SA-u-ca-${calendar}`, options);
  console.log(`${calendar}: ${formatted}`);
});
// The code above outputs the following:
//   islamic: Shaʻban 1, 1443 AH
//   islamic-umalqura: Rajab 30, 1443 AH
//   islamic-tbla: Rajab 30, 1443 AH
//   islamic-civil: Rajab 29, 1443 AH
//   islamic-rgsa: Shaʻban 1, 1443 AH
-----------------------
new Date('2022-03-03').toLocaleDateString('en-US');
// outputs '3/2/2022' when run in San Francisco

new Date('2022-03-03').toLocaleDateString('en-US', { timeZone: 'UTC' });
// outputs '3/3/2022' as expected. UTC is used both for declaring and formatting.

new Date('2022-03-03').toLocaleDateString(
  'en-SA-u-ca-islamic-umalqura',
  { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' }
);
// outputs 'Rajab 30, 1443 AH' as expected
new Intl.DateTimeFormat('ar-SA').resolvedOptions();
// {
//   calendar: "islamic-umalqura"
//   day: "numeric"
//   locale: "ar-SA"
//   month: "numeric"
//   numberingSystem: "arab"
//   timeZone: "America/Los_Angeles"
//   year: "numeric"
// }
calendars = ["islamic", "islamic-umalqura", "islamic-tbla", "islamic-civil", "islamic-rgsa"];
options = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
date = new Date('2022-03-03');
calendars.forEach(calendar => {
  formatted = date.toLocaleDateString(`en-SA-u-ca-${calendar}`, options);
  console.log(`${calendar}: ${formatted}`);
});
// The code above outputs the following:
//   islamic: Shaʻban 1, 1443 AH
//   islamic-umalqura: Rajab 30, 1443 AH
//   islamic-tbla: Rajab 30, 1443 AH
//   islamic-civil: Rajab 29, 1443 AH
//   islamic-rgsa: Shaʻban 1, 1443 AH
-----------------------
============================================================
islamic diff from islamic-tbla           :6369  days (34.19%)
islamic diff from islamic-rgsa           :0     days ( 0.00%)
islamic diff from islamic-umalqura       :11425 days (61.33%)
islamic diff from islamic-civil          :15919 days (85.46%)
------------------------------------------------------------
islamic-tbla diff from islamic-rgsa      :6369  days (34.19%)
islamic-tbla diff from islamic-umalqura  :10777 days (57.85%)
islamic-tbla diff from islamic-civil     :18628 days (100.00%)
-------------------------------------------------------------
islamic-rgsa diff from islamic-umalqura  :11425 days (61.33%)
islamic-rgsa diff from islamic-civil     :15919 days (85.46%)
-------------------------------------------------------------
islamic-umalqura diff from islamic-civil :9049  days (48.58%)
=============================================================
console.log("Comparing 50 years results under the 5 islamic calendar formats (from year 1980 to 2030)");
console.log("=".repeat(60));

let startDate = new Date("1980-01-01");  // date to start test from
let options   = {year: 'numeric', month: 'long', day: 'numeric'};
let d         = startDate;
let diff      = [0,0,0,0,0,0,0,0,0,0];  // array to hold the diff results
let totalDays = 18628;                  // total days approx 50 Gregorian years
for (let i=0; i<totalDays; i++) {
let dateIslamic     = new Intl.DateTimeFormat('en-u-ca-islamic'         ,options).format(d),
    dateIslamicTBLA = new Intl.DateTimeFormat('en-u-ca-islamic-tbla'    ,options).format(d),
    dateIslamicRGSA = new Intl.DateTimeFormat('en-u-ca-islamic-rgsa'    ,options).format(d),
    dateIslamicUMQ  = new Intl.DateTimeFormat('en-u-ca-islamic-umalqura',options).format(d),
    dateIslamicCIVL = new Intl.DateTimeFormat('en-u-ca-islamic-civil'   ,options).format(d);

if (dateIslamic != dateIslamicTBLA) diff[0]++;
if (dateIslamic != dateIslamicRGSA) diff[1]++;
if (dateIslamic != dateIslamicUMQ)  diff[2]++;
if (dateIslamic != dateIslamicCIVL) diff[3]++;

if (dateIslamicTBLA != dateIslamicRGSA) diff[4]++;
if (dateIslamicTBLA != dateIslamicUMQ)  diff[5]++;
if (dateIslamicTBLA != dateIslamicCIVL) diff[6]++;

if (dateIslamicRGSA != dateIslamicUMQ)  diff[7]++;
if (dateIslamicRGSA != dateIslamicCIVL) diff[8]++;

if (dateIslamicUMQ != dateIslamicCIVL)  diff[9]++;

d    = new Date(d.setDate(d.getDate() + 1)); // next day
}

console.log("islamic diff from islamic-tbla           :"+perc(0));
console.log("islamic diff from islamic-rgsa           :"+perc(1));
console.log("islamic diff from islamic-umalqura       :"+perc(2));
console.log("islamic diff from islamic-civil          :"+perc(3));
console.log("-".repeat(50));
console.log("islamic-tbla diff from islamic-rgsa      :"+perc(4));
console.log("islamic-tbla diff from islamic-umalqura  :"+perc(5));
console.log("islamic-tbla diff from islamic-civil     :"+perc(6));
console.log("-".repeat(50));
console.log("islamic-rgsa diff from islamic-umalqura  :"+perc(7));
console.log("islamic-rgsa diff from islamic-civil     :"+perc(8));
console.log("-".repeat(50));
console.log("islamic-umalqura diff from islamic-civil :"+perc(9));


function perc(n) {return + diff[n]+" days (" +((diff[n]/totalDays)*100).toFixed(2)+"%)";}
-----------------------
============================================================
islamic diff from islamic-tbla           :6369  days (34.19%)
islamic diff from islamic-rgsa           :0     days ( 0.00%)
islamic diff from islamic-umalqura       :11425 days (61.33%)
islamic diff from islamic-civil          :15919 days (85.46%)
------------------------------------------------------------
islamic-tbla diff from islamic-rgsa      :6369  days (34.19%)
islamic-tbla diff from islamic-umalqura  :10777 days (57.85%)
islamic-tbla diff from islamic-civil     :18628 days (100.00%)
-------------------------------------------------------------
islamic-rgsa diff from islamic-umalqura  :11425 days (61.33%)
islamic-rgsa diff from islamic-civil     :15919 days (85.46%)
-------------------------------------------------------------
islamic-umalqura diff from islamic-civil :9049  days (48.58%)
=============================================================
console.log("Comparing 50 years results under the 5 islamic calendar formats (from year 1980 to 2030)");
console.log("=".repeat(60));

let startDate = new Date("1980-01-01");  // date to start test from
let options   = {year: 'numeric', month: 'long', day: 'numeric'};
let d         = startDate;
let diff      = [0,0,0,0,0,0,0,0,0,0];  // array to hold the diff results
let totalDays = 18628;                  // total days approx 50 Gregorian years
for (let i=0; i<totalDays; i++) {
let dateIslamic     = new Intl.DateTimeFormat('en-u-ca-islamic'         ,options).format(d),
    dateIslamicTBLA = new Intl.DateTimeFormat('en-u-ca-islamic-tbla'    ,options).format(d),
    dateIslamicRGSA = new Intl.DateTimeFormat('en-u-ca-islamic-rgsa'    ,options).format(d),
    dateIslamicUMQ  = new Intl.DateTimeFormat('en-u-ca-islamic-umalqura',options).format(d),
    dateIslamicCIVL = new Intl.DateTimeFormat('en-u-ca-islamic-civil'   ,options).format(d);

if (dateIslamic != dateIslamicTBLA) diff[0]++;
if (dateIslamic != dateIslamicRGSA) diff[1]++;
if (dateIslamic != dateIslamicUMQ)  diff[2]++;
if (dateIslamic != dateIslamicCIVL) diff[3]++;

if (dateIslamicTBLA != dateIslamicRGSA) diff[4]++;
if (dateIslamicTBLA != dateIslamicUMQ)  diff[5]++;
if (dateIslamicTBLA != dateIslamicCIVL) diff[6]++;

if (dateIslamicRGSA != dateIslamicUMQ)  diff[7]++;
if (dateIslamicRGSA != dateIslamicCIVL) diff[8]++;

if (dateIslamicUMQ != dateIslamicCIVL)  diff[9]++;

d    = new Date(d.setDate(d.getDate() + 1)); // next day
}

console.log("islamic diff from islamic-tbla           :"+perc(0));
console.log("islamic diff from islamic-rgsa           :"+perc(1));
console.log("islamic diff from islamic-umalqura       :"+perc(2));
console.log("islamic diff from islamic-civil          :"+perc(3));
console.log("-".repeat(50));
console.log("islamic-tbla diff from islamic-rgsa      :"+perc(4));
console.log("islamic-tbla diff from islamic-umalqura  :"+perc(5));
console.log("islamic-tbla diff from islamic-civil     :"+perc(6));
console.log("-".repeat(50));
console.log("islamic-rgsa diff from islamic-umalqura  :"+perc(7));
console.log("islamic-rgsa diff from islamic-civil     :"+perc(8));
console.log("-".repeat(50));
console.log("islamic-umalqura diff from islamic-civil :"+perc(9));


function perc(n) {return + diff[n]+" days (" +((diff[n]/totalDays)*100).toFixed(2)+"%)";}

Javascript: frame precise video stop

copy iconCopydownload iconDownload
   const callback = (now, metadata) => {
      if (startTime == 0) {
        startTime = now;
      }
      elapsed = metadata.mediaTime;
      currentFrame = metadata.presentedFrames - doneCount;

      fps = (currentFrame / elapsed).toFixed(3);
      fps = !isFinite(fps) ? 0 : fps;

      updateStats();
      if (stopFrames.includes(currentFrame)) {
        pauseMyVideo();
      } else {
        video.requestVideoFrameCallback(callback);
      }
   };
   video.requestVideoFrameCallback(callback);
-----------------------
<!DOCTYPE html>
<html>
<body>

<h1 style="position: absolute; top: 10px; left: 10px" > Demo // Stop Video at Specific Frame(s) : </h1>
<br>

<div style="z-index: 1; overflow:hidden; position: absolute; top: 60px; left: 10px; font-family: OpenSans; font-size: 14px">
<p> <b> Choose an .MP4 video file... </b> </p>
<input type="file" id="choose_media" accept=".mov, .mp4" />
</div>

<video id="myVideo" width="640" height="480" controls muted playsinline 
style="position: absolute; top: 80px; left: 10px" >
<source src="vc_timecode3.mp4" type="video/mp4">
</video>

<div id="cont_texts" style="position: absolute; top: 80px; left: 700px" >

<span> Current Time : </span> <span id="txt_curr_time"> 00:00:00 </span> 
<br><br>
<span> Estimated Frame Num : </span> <span id="txt_est_frame"> 0 </span> 
<br><br>
<span> Total Frames (video) : </span> <span id="txt_total_frame"> -999 </span> 
<br><br>

<span onclick="check_points()" > Stopping Points Array : </span> <input type="text" id="stopPointsArray" value="" > 

</div>

</body>


<script>


////////////////////////////////

//# VARS
var myVideo = document.getElementById( 'myVideo' );
var video_duration;

var h; var m; var s;
var h_time; var m_time; var s_time;

var vid_curr_time = document.getElementById( 'txt_curr_time' );
var vid_est_frame = document.getElementById( 'txt_est_frame' );
var vid_total_frame = document.getElementById( 'txt_total_frame' );

var reader; //to get bytes from file into Array
var bytes_MP4; //updated as Array

//# MP4 related vars
var got_FPS = false; var video_FPS = -1; 
var temp_Pos = 0;  var sampleCount = -1;
var temp_int_1, temp_int_2 = -1;

                    
var array_points = document.getElementById("stopPointsArray");
array_points.addEventListener('change', check_points );

//# EVENTS
document.getElementById('choose_media').addEventListener('change', onFileSelected, false);

myVideo.addEventListener("timeupdate", video_timeUpdate);           
myVideo.addEventListener("play", handle_Media_Events );
myVideo.addEventListener("pause", handle_Media_Events );
myVideo.addEventListener("ended", handle_Media_Events );

//# LET'S GO...
        
function onFileSelected ( evt )
{
    file = evt.target.files[0];
    path = (window.URL || window.webkitURL).createObjectURL(file);
    
    reader = new FileReader();
    reader.readAsArrayBuffer(file);
    
    
    reader.onloadend = function(evt) 
    {
        //alert( " file is selected ... " );
        
        if (evt.target.readyState == FileReader.DONE) 
        {
            bytes_MP4 = new Uint8Array( evt.target.result );
            get_MP4_info( bytes_MP4 );
            
            //# use bytes Array as video tag source
            let path_MP4 = (window.URL || window.webkitURL).createObjectURL(new Blob([bytes_MP4], { type: 'video/mp4' })); //'image/png' //'application/octet-stream'
            myVideo.src = path_MP4;
            myVideo.load();
            
            video_duration = myVideo.duration;
            txt_total_frame.innerHTML =( sampleCount);
            //alert("video FPS : " + video_FPS);
        }
        
    }
    
}

function check_points (e)
{
    alert( "Array Points are : " + e.target.value );
}

function handle_Media_Events()
{
    if ( event.type == "ended" )
    { 
        myVideo.currentTime = 0; myVideo.play(); myVideo.pause(); myVideo.play();
    }
    
    //{ myVideo.currentTime = 8; btn_ctrl.src = "ico_vc_play.png"; vid_isPlaying = false; bool_isPlaying = true; }
    
    if ( event.type == "play" )
    {
        if ( myVideo.nodeName == "VIDEO" )
        {

        }
    
    }
    
    else if ( event.type == "pause" )
    {
        
        
    }
    
    else if ( event.type == "seeked" )
    {
        
        
    }
    
}

function video_timeUpdate()
{
    vid_curr_time.innerHTML = ( convertTime ( myVideo.currentTime ) );
    
    vid_est_frame.innerHTML = Math.round ( video_FPS * myVideo.currentTime );
    
}

function convertTime ( input_Secs ) 
{
    h = Math.floor(input_Secs / 3600);
    m = Math.floor(input_Secs % 3600 / 60);
    s = Math.floor(input_Secs % 3600 % 60);

    h_time = h < 10 ? ("0" + h) : h ;
    m_time = m < 10 ? ("0" + m) : m ;
    s_time = s < 10 ? ("0" + s) : s ;
    
    if ( (h_time == 0) && ( video_duration < 3600) ) 
    { return ( m_time + ":" + s_time ); }
    else 
    { return ( h_time + ":" + m_time + ":" + s_time ); }
     
}

function get_MP4_info( input ) //# "input" is Array of Byte values
{
    //# console.log( "checking MP4 frame-rate..." );
    
    got_FPS = false;
    temp_Pos = 0; //# our position inside bytes of MP4 array
     
    let hdlr_type = "-1"; 
    
    while(true)
    {
        //# Step 1) Prepare for when metadata pieces are found  
        //# When VIDEO HANDLER Atom is found in MP4
        
        //# if STSZ ... 73 74 73 7A  
        if (input[ temp_Pos+0 ] == 0x73)
        {
            if ( ( input[temp_Pos+1] == 0x74 ) && ( input[temp_Pos+2] == 0x73 ) && ( input[temp_Pos+3] == 0x7A ) )
            {
                if ( hdlr_type == "vide" ) //# only IF it's the "video" track
                {
                    temp_Pos += 12;
                    sampleCount = ( ( input[temp_Pos+0] << 24) | (input[temp_Pos+1] << 16) | (input[temp_Pos+2] << 8) | input[temp_Pos+3] );
                    console.log( "found VIDEO sampleCount at: " + sampleCount );
                    
                    video_FPS = ( ( sampleCount * temp_int_1 ) / temp_int_2 );
                    console.log( "FPS of MP4 ### : " +  video_FPS );
                }
                
            }
            
        }
        
        //# Step 2) Find the pieces of metadata info
        //# Find other Atoms with data needed by above VIDEO HANDLER code.
        
        
        //# for MOOV and MDAT
        if (input[ temp_Pos ] == 0x6D) //0x6D
        {
            //# if MDAT ... 6D 64 61 74
            if ( ( temp_Pos[temp_Pos+1] == 0x64 ) && ( input[temp_Pos+2] == 0x61 ) && ( input[temp_Pos+3] == 0x74 ) )
            {
                temp_int = ( ( input[temp_Pos-4] << 24) | (input[temp_Pos-3] << 16) | (input[temp_Pos-2] << 8) | input[temp_Pos-1] );
                temp_Pos = (temp_int-1);
                if ( temp_Pos >= (input.length-1) ) { break; }
            }
            
            //# if MOOV ... 6D 6F 6F 76
            if ( ( input[temp_Pos+1] == 0x6F ) && ( input[temp_Pos+2] == 0x6F ) && ( input[temp_Pos+3] == 0x76 ) )
            {
                temp_int = ( ( input[temp_Pos-4] << 24) | (input[temp_Pos-3] << 16) | (input[temp_Pos-2] << 8) | input[temp_Pos-1] );
            }
            
            //# if MDHD ... 6D 64 68 64
            if ( ( input[temp_Pos+1] == 0x64 ) && ( input[temp_Pos+2] == 0x68 ) && ( input[temp_Pos+3] == 0x64 ) )
            {
                temp_Pos += 32;
                
                //# if HDLR ... 68 64 6C 72
                if (  input[temp_Pos+0] == 0x68 )
                {
                    if ( ( input[temp_Pos+1] == 0x64 ) && ( input[temp_Pos+2] == 0x6C ) && ( input[temp_Pos+3] == 0x72 ) )
                    {
                        temp_Pos += 12;
                        hdlr_type = String.fromCharCode(input[temp_Pos+0], input[temp_Pos+1], input[temp_Pos+2], input[temp_Pos+3] );
                    }
                }
            }
            
            //# if MVHD ... 6D 76 68 64
            if ( ( input[temp_Pos+1] == 0x76 ) && ( input[temp_Pos+2] == 0x68 ) && ( input[temp_Pos+3] == 0x64 ) )
            {
                temp_Pos += (12 + 4);
                
                //# get timescale
                temp_int_1 = ( ( input[temp_Pos+0] << 24) | (input[temp_Pos+1] << 16) | (input[temp_Pos+2] << 8) | input[temp_Pos+3] );
                ///console.log( "MVHD timescale at: " + temp_int_1 );
                
                //# get duration
                temp_int_2 = ( ( input[temp_Pos+4+0] << 24) | (input[temp_Pos+4+1] << 16) | (input[temp_Pos+4+2] << 8) | input[temp_Pos+4+3] );
                ///console.log( "MVHD duration at: " + temp_int_2 );
            }
            
        }
        
        if( temp_Pos >= (input.length-1) ) { break; }
        if( got_FPS == true) { break; }
        
        temp_Pos++;
    }
    
}

</script>

</html>

In the ompr package in R, how can I rephrase my objective/constraints/variables so as to avoid the &quot;problem too large&quot; error?

copy iconCopydownload iconDownload
require(slam)
boatsSTM<-as.simple_triplet_matrix(boats.n.ij)
...

#setting the objective function
set_objective(sum_expr(u[boatsSTM$i[k], boatsSTM$j[k]] * boatsSTM$v[k], k = 1:length(boatsSTM$i)))

Which form is better for return value of functions in embedded C?

copy iconCopydownload iconDownload
locvar = func();

if ((locvar == 1) || (locvar == 2)) {
  ...
}

Why does summary() show different standard errors than coeftest()?

copy iconCopydownload iconDownload
fit <- glm(am ~ hp + cyl, family=binomial(link="logit"), mtcars)

summary(fit)
#             Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.83220    2.06595   2.823  0.00476 **
# hp           0.02775    0.01366   2.031  0.04228 * 
# cyl         -1.70306    0.60286  -2.825  0.00473 **
library(sandwich); library(lmtest)

coeftest(fit, vcov.=vcov(fit))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.065949  2.8230 0.004757 **
# hp           0.027748   0.013664  2.0307 0.042282 * 
# cyl         -1.703064   0.602862 -2.8250 0.004729 **
(ct <- coeftest(fit, vcov.=vcovHC(fit, type='HC0')))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.139307  2.7262 0.006407 **
# hp           0.027748   0.012254  2.2643 0.023553 * 
# cyl         -1.703064   0.572045 -2.9772 0.002909 **
texreg::screenreg(fit)
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.07)  
# hp                0.03 * 
#                  (0.01)  
# cyl              -1.70 **
#                  (0.60)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
texreg::screenreg(fit, 
                  override.pvalues=ct[, 4],
                  override.se=ct[, 3])
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.73)  
# hp                0.03 * 
#                  (2.26)  
# cyl              -1.70 **
#                 (-2.98)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
-----------------------
fit <- glm(am ~ hp + cyl, family=binomial(link="logit"), mtcars)

summary(fit)
#             Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.83220    2.06595   2.823  0.00476 **
# hp           0.02775    0.01366   2.031  0.04228 * 
# cyl         -1.70306    0.60286  -2.825  0.00473 **
library(sandwich); library(lmtest)

coeftest(fit, vcov.=vcov(fit))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.065949  2.8230 0.004757 **
# hp           0.027748   0.013664  2.0307 0.042282 * 
# cyl         -1.703064   0.602862 -2.8250 0.004729 **
(ct <- coeftest(fit, vcov.=vcovHC(fit, type='HC0')))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.139307  2.7262 0.006407 **
# hp           0.027748   0.012254  2.2643 0.023553 * 
# cyl         -1.703064   0.572045 -2.9772 0.002909 **
texreg::screenreg(fit)
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.07)  
# hp                0.03 * 
#                  (0.01)  
# cyl              -1.70 **
#                  (0.60)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
texreg::screenreg(fit, 
                  override.pvalues=ct[, 4],
                  override.se=ct[, 3])
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.73)  
# hp                0.03 * 
#                  (2.26)  
# cyl              -1.70 **
#                 (-2.98)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
-----------------------
fit <- glm(am ~ hp + cyl, family=binomial(link="logit"), mtcars)

summary(fit)
#             Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.83220    2.06595   2.823  0.00476 **
# hp           0.02775    0.01366   2.031  0.04228 * 
# cyl         -1.70306    0.60286  -2.825  0.00473 **
library(sandwich); library(lmtest)

coeftest(fit, vcov.=vcov(fit))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.065949  2.8230 0.004757 **
# hp           0.027748   0.013664  2.0307 0.042282 * 
# cyl         -1.703064   0.602862 -2.8250 0.004729 **
(ct <- coeftest(fit, vcov.=vcovHC(fit, type='HC0')))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.139307  2.7262 0.006407 **
# hp           0.027748   0.012254  2.2643 0.023553 * 
# cyl         -1.703064   0.572045 -2.9772 0.002909 **
texreg::screenreg(fit)
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.07)  
# hp                0.03 * 
#                  (0.01)  
# cyl              -1.70 **
#                  (0.60)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
texreg::screenreg(fit, 
                  override.pvalues=ct[, 4],
                  override.se=ct[, 3])
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.73)  
# hp                0.03 * 
#                  (2.26)  
# cyl              -1.70 **
#                 (-2.98)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
-----------------------
fit <- glm(am ~ hp + cyl, family=binomial(link="logit"), mtcars)

summary(fit)
#             Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.83220    2.06595   2.823  0.00476 **
# hp           0.02775    0.01366   2.031  0.04228 * 
# cyl         -1.70306    0.60286  -2.825  0.00473 **
library(sandwich); library(lmtest)

coeftest(fit, vcov.=vcov(fit))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.065949  2.8230 0.004757 **
# hp           0.027748   0.013664  2.0307 0.042282 * 
# cyl         -1.703064   0.602862 -2.8250 0.004729 **
(ct <- coeftest(fit, vcov.=vcovHC(fit, type='HC0')))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.139307  2.7262 0.006407 **
# hp           0.027748   0.012254  2.2643 0.023553 * 
# cyl         -1.703064   0.572045 -2.9772 0.002909 **
texreg::screenreg(fit)
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.07)  
# hp                0.03 * 
#                  (0.01)  
# cyl              -1.70 **
#                  (0.60)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
texreg::screenreg(fit, 
                  override.pvalues=ct[, 4],
                  override.se=ct[, 3])
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.73)  
# hp                0.03 * 
#                  (2.26)  
# cyl              -1.70 **
#                 (-2.98)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
-----------------------
fit <- glm(am ~ hp + cyl, family=binomial(link="logit"), mtcars)

summary(fit)
#             Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.83220    2.06595   2.823  0.00476 **
# hp           0.02775    0.01366   2.031  0.04228 * 
# cyl         -1.70306    0.60286  -2.825  0.00473 **
library(sandwich); library(lmtest)

coeftest(fit, vcov.=vcov(fit))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.065949  2.8230 0.004757 **
# hp           0.027748   0.013664  2.0307 0.042282 * 
# cyl         -1.703064   0.602862 -2.8250 0.004729 **
(ct <- coeftest(fit, vcov.=vcovHC(fit, type='HC0')))
#              Estimate Std. Error z value Pr(>|z|)   
# (Intercept)  5.832204   2.139307  2.7262 0.006407 **
# hp           0.027748   0.012254  2.2643 0.023553 * 
# cyl         -1.703064   0.572045 -2.9772 0.002909 **
texreg::screenreg(fit)
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.07)  
# hp                0.03 * 
#                  (0.01)  
# cyl              -1.70 **
#                  (0.60)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05
texreg::screenreg(fit, 
                  override.pvalues=ct[, 4],
                  override.se=ct[, 3])
# =========================
#                 Model 1  
# -------------------------
# (Intercept)       5.83 **
#                  (2.73)  
# hp                0.03 * 
#                  (2.26)  
# cyl              -1.70 **
#                 (-2.98)  
# -------------------------
# AIC              34.63   
# BIC              39.02   
# Log Likelihood  -14.31   
# Deviance         28.63   
# Num. obs.        32      
# =========================
# *** p < 0.001; ** p < 0.01; * p < 0.05

Is mass assignment protection needed when properly using validation?

copy iconCopydownload iconDownload
if(isset($request->forbidden_param))
//in controller
MyModel::update($request->input())

// in model

$fillable = [ ... ]
//or
$guarded = [ ... ]
Model::update([
    'permitted_param1' => $request->permitted_param
    'permitted_param2' => $request->permitted_param2
]);
$guarded = [];
User::create($request->except('password') + [ 'secret' => bcrypt($request->password)] );
MyModel::update($request->safe()->all());
MyModel::update($request->validated())
-----------------------
if(isset($request->forbidden_param))
//in controller
MyModel::update($request->input())

// in model

$fillable = [ ... ]
//or
$guarded = [ ... ]
Model::update([
    'permitted_param1' => $request->permitted_param
    'permitted_param2' => $request->permitted_param2
]);
$guarded = [];
User::create($request->except('password') + [ 'secret' => bcrypt($request->password)] );
MyModel::update($request->safe()->all());
MyModel::update($request->validated())
-----------------------
if(isset($request->forbidden_param))
//in controller
MyModel::update($request->input())

// in model

$fillable = [ ... ]
//or
$guarded = [ ... ]
Model::update([
    'permitted_param1' => $request->permitted_param
    'permitted_param2' => $request->permitted_param2
]);
$guarded = [];
User::create($request->except('password') + [ 'secret' => bcrypt($request->password)] );
MyModel::update($request->safe()->all());
MyModel::update($request->validated())
-----------------------
if(isset($request->forbidden_param))
//in controller
MyModel::update($request->input())

// in model

$fillable = [ ... ]
//or
$guarded = [ ... ]
Model::update([
    'permitted_param1' => $request->permitted_param
    'permitted_param2' => $request->permitted_param2
]);
$guarded = [];
User::create($request->except('password') + [ 'secret' => bcrypt($request->password)] );
MyModel::update($request->safe()->all());
MyModel::update($request->validated())
-----------------------
if(isset($request->forbidden_param))
//in controller
MyModel::update($request->input())

// in model

$fillable = [ ... ]
//or
$guarded = [ ... ]
Model::update([
    'permitted_param1' => $request->permitted_param
    'permitted_param2' => $request->permitted_param2
]);
$guarded = [];
User::create($request->except('password') + [ 'secret' => bcrypt($request->password)] );
MyModel::update($request->safe()->all());
MyModel::update($request->validated())
-----------------------
if(isset($request->forbidden_param))
//in controller
MyModel::update($request->input())

// in model

$fillable = [ ... ]
//or
$guarded = [ ... ]
Model::update([
    'permitted_param1' => $request->permitted_param
    'permitted_param2' => $request->permitted_param2
]);
$guarded = [];
User::create($request->except('password') + [ 'secret' => bcrypt($request->password)] );
MyModel::update($request->safe()->all());
MyModel::update($request->validated())
-----------------------
if(isset($request->forbidden_param))
//in controller
MyModel::update($request->input())

// in model

$fillable = [ ... ]
//or
$guarded = [ ... ]
Model::update([
    'permitted_param1' => $request->permitted_param
    'permitted_param2' => $request->permitted_param2
]);
$guarded = [];
User::create($request->except('password') + [ 'secret' => bcrypt($request->password)] );
MyModel::update($request->safe()->all());
MyModel::update($request->validated())

How can I specialize std::common_type&lt;A,B&gt; so that it's naturally commutative?

copy iconCopydownload iconDownload
// define concept of `common_type<A,B>` existing
template <typename A, typename B>
concept has_in_common_ordered = requires { common_type<A,B>::type; };

namespace std {
    
    // define common_type<A,B> if common_type<B,A>::type exists:
    template <typename A, has_in_common_ordered<A> B>
    struct common_type<A,B> : public common_type<B,A> {};
    
}
struct X {};
struct Y {};

namespace std {
    
    template<>
    struct common_type<X,Y> {
        using type = X; // or whatever
    };
    
}

int main() {
    // even though we only specialized for one ordering,
    // both orderings now exist:
    std::common_type<X,Y>::type a;
    std::common_type<Y,X>::type b;
}
-----------------------
// define concept of `common_type<A,B>` existing
template <typename A, typename B>
concept has_in_common_ordered = requires { common_type<A,B>::type; };

namespace std {
    
    // define common_type<A,B> if common_type<B,A>::type exists:
    template <typename A, has_in_common_ordered<A> B>
    struct common_type<A,B> : public common_type<B,A> {};
    
}
struct X {};
struct Y {};

namespace std {
    
    template<>
    struct common_type<X,Y> {
        using type = X; // or whatever
    };
    
}

int main() {
    // even though we only specialized for one ordering,
    // both orderings now exist:
    std::common_type<X,Y>::type a;
    std::common_type<Y,X>::type b;
}

Periodically restart Python multiprocessing pool

copy iconCopydownload iconDownload
from multiprocessing import Pool, TimeoutError, cpu_count
from time import sleep
from random import randint


def log():
    print("logging is a dangerous activity: wear a hard hat.")


def work(d):
    sleep(randint(1, 100) / 100)
    print("finished working")
    if randint(1, 10) == 1:
        print("blocking...")
        while True:
            sleep(0.1)

    return d
data = list(range(100))
nproc = cpu_count()
while data:
    print(f"== Processing {len(data)} items. ==")
    with Pool(nproc) as p:
        tasks = [p.apply_async(work, (d,)) for d in data]
        for task in tasks:
            try:
                res = task.get(timeout=1)
                data.remove(res)
                log()
            except TimeoutError:
                failed.append(task)
                if len(failed) < nproc:
                    print(
                        f"{len(failed)} processes are blocked,"
                        f" but {nproc - len(failed)} remain."
                    )
                else:
                    break
            for task in failed:
                try:
                    res = task.get(timeout=0.01)
                    data.remove(res)
                    failed.remove(task)
                    log()
                except TimeoutError:
                    continue
-----------------------
from multiprocessing import Pool, TimeoutError, cpu_count
from time import sleep
from random import randint


def log():
    print("logging is a dangerous activity: wear a hard hat.")


def work(d):
    sleep(randint(1, 100) / 100)
    print("finished working")
    if randint(1, 10) == 1:
        print("blocking...")
        while True:
            sleep(0.1)

    return d
data = list(range(100))
nproc = cpu_count()
while data:
    print(f"== Processing {len(data)} items. ==")
    with Pool(nproc) as p:
        tasks = [p.apply_async(work, (d,)) for d in data]
        for task in tasks:
            try:
                res = task.get(timeout=1)
                data.remove(res)
                log()
            except TimeoutError:
                failed.append(task)
                if len(failed) < nproc:
                    print(
                        f"{len(failed)} processes are blocked,"
                        f" but {nproc - len(failed)} remain."
                    )
                else:
                    break
            for task in failed:
                try:
                    res = task.get(timeout=0.01)
                    data.remove(res)
                    failed.remove(task)
                    log()
                except TimeoutError:
                    continue
-----------------------
from multiprocessing import Pool, TimeoutError, cpu_count
from time import sleep
from random import randint


def log():
    print("logging is a dangerous activity: wear a hard hat.")


def work(d):
    sleep(randint(1, 100) / 100)
    print("finished working")
    if randint(1, 10) == 1:
        print("blocking...")
        while True:
            sleep(0.1)

    return d
data = list(range(100))
nproc = cpu_count()
while data:
    print(f"== Processing {len(data)} items. ==")
    with Pool(nproc) as p:
        tasks = [p.apply_async(work, (d,)) for d in data]
        for task in tasks:
            try:
                res = task.get(timeout=1)
                data.remove(res)
                log()
            except TimeoutError:
                failed.append(task)
                if len(failed) < nproc:
                    print(
                        f"{len(failed)} processes are blocked,"
                        f" but {nproc - len(failed)} remain."
                    )
                else:
                    break
            for task in failed:
                try:
                    res = task.get(timeout=0.01)
                    data.remove(res)
                    failed.remove(task)
                    log()
                except TimeoutError:
                    continue
-----------------------
from multiprocessing import Pool, TimeoutError, cpu_count
from time import sleep
from random import randint


def log():
    print("logging is a dangerous activity: wear a hard hat.")


def work(d):
    sleep(randint(1, 100) / 100)
    print("finished working")
    if randint(1, 10) == 1:
        print("blocking...")
        while True:
            sleep(0.1)

    return d
data = list(range(100))
nproc = cpu_count()
while data:
    print(f"== Processing {len(data)} items. ==")
    with Pool(nproc) as p:
        tasks = [p.apply_async(work, (d,)) for d in data]
        for task in tasks:
            try:
                res = task.get(timeout=1)
                data.remove(res)
                log()
            except TimeoutError:
                failed.append(task)
                if len(failed) < nproc:
                    print(
                        f"{len(failed)} processes are blocked,"
                        f" but {nproc - len(failed)} remain."
                    )
                else:
                    break
            for task in failed:
                try:
                    res = task.get(timeout=0.01)
                    data.remove(res)
                    failed.remove(task)
                    log()
                except TimeoutError:
                    continue
-----------------------
from multiprocessing import Pool, TimeoutError, cpu_count
from time import sleep
from random import randint


def log():
    print("logging is a dangerous activity: wear a hard hat.")


def work(d):
    sleep(randint(1, 100) / 100)
    print("finished working")
    if randint(1, 10) == 1:
        print("blocking...")
        while True:
            sleep(0.1)

    return d
data = list(range(100))
nproc = cpu_count()
while data:
    print(f"== Processing {len(data)} items. ==")
    with Pool(nproc) as p:
        tasks = [p.apply_async(work, (d,)) for d in data]
        for task in tasks:
            try:
                res = task.get(timeout=1)
                data.remove(res)
                log()
            except TimeoutError:
                failed.append(task)
                if len(failed) < nproc:
                    print(
                        f"{len(failed)} processes are blocked,"
                        f" but {nproc - len(failed)} remain."
                    )
                else:
                    break
            for task in failed:
                try:
                    res = task.get(timeout=0.01)
                    data.remove(res)
                    failed.remove(task)
                    log()
                except TimeoutError:
                    continue

How to use pytest to simulate full reboot

copy iconCopydownload iconDownload
import os
import time
import signal
import multiprocessing


class MyClass(multiprocessing.Process):
    def run(self):
        # Ping localhost for a limited amount of time
        os.system("ping -c 12 127.0.0.1")


process = MyClass()
process.start()

time.sleep(4)

print("terminating early")

# Send SIGKILL signal to the entire process group
group_id = os.getpgid(process.pid)
os.killpg(group_id, signal.SIGKILL)

print("done")
import os
import time
import multiprocessing

import psutil


class MyClass(multiprocessing.Process):
    def run(self):
        # Ping localhost for a limited amount of time
        os.system("ping -c 12 127.0.0.1")


def kill_process_group(pid):
    process = psutil.Process(pid)
    children = process.children(recursive=True)

    # First terminate all children
    for child in children:
        child.kill()
    psutil.wait_procs(children)

    # Then terminate the parent process
    process.kill()
    process.wait()


process = MyClass()
process.start()

time.sleep(4)

print("terminating early")

kill_process_group(process.pid)

print("done")
-----------------------
import os
import time
import signal
import multiprocessing


class MyClass(multiprocessing.Process):
    def run(self):
        # Ping localhost for a limited amount of time
        os.system("ping -c 12 127.0.0.1")


process = MyClass()
process.start()

time.sleep(4)

print("terminating early")

# Send SIGKILL signal to the entire process group
group_id = os.getpgid(process.pid)
os.killpg(group_id, signal.SIGKILL)

print("done")
import os
import time
import multiprocessing

import psutil


class MyClass(multiprocessing.Process):
    def run(self):
        # Ping localhost for a limited amount of time
        os.system("ping -c 12 127.0.0.1")


def kill_process_group(pid):
    process = psutil.Process(pid)
    children = process.children(recursive=True)

    # First terminate all children
    for child in children:
        child.kill()
    psutil.wait_procs(children)

    # Then terminate the parent process
    process.kill()
    process.wait()


process = MyClass()
process.start()

time.sleep(4)

print("terminating early")

kill_process_group(process.pid)

print("done")

Community Discussions

Trending Discussions on Robust
  • Creating nested columns in python dataframe
  • GitLab Runner fails to upload artifacts with &quot;invalid argument&quot; error
  • Discrepancy in Javascript Intl.DateTimeFormat() Outputs for the Islamic (Hijri) Calendar between 'islamic' and 'ar-SA'
  • Javascript: frame precise video stop
  • In the ompr package in R, how can I rephrase my objective/constraints/variables so as to avoid the &quot;problem too large&quot; error?
  • Which form is better for return value of functions in embedded C?
  • A clarification on the named requirements for containers
  • Why does summary() show different standard errors than coeftest()?
  • Is mass assignment protection needed when properly using validation?
  • How can I specialize std::common_type&lt;A,B&gt; so that it's naturally commutative?
Trending Discussions on Robust

QUESTION

Creating nested columns in python dataframe

Asked 2022-Feb-20 at 15:56

I have 3 columns namely Models(should be taken as index), Accuracy without normalization, Accuracy with normalization (zscore, minmax, maxabs, robust) and these are required to be created as:

 ------------------------------------------------------------------------------------
|   Models  |  Accuracy without normalization    |      Accuracy with normalization  |
|           |                                    |-----------------------------------|
|           |                                    | zscore | minmax | maxabs | robust |
 ------------------------------------------------------------------------------------

dfmod-> Models column
dfacc-> Accuracy without normalization
dfacc1-> Accuracy with normalization - zscore
dfacc2-> Accuracy with normalization - minmax
dfacc3-> Accuracy with normalization - maxabs
dfacc4-> Accuracy with normalization - robust
dfout=pd.DataFrame({('Accuracy without Normalization'):{dfacc},
     ('Accuracy using Normalization','zscore'):{dfacc1},
     ('Accuracy using Normalization','minmax'):{dfacc2},
     ('Accuracy using Normalization','maxabs'):{dfacc3},
     ('Accuracy using Normalization','robust'):{dfacc4},
   },index=dfmod
)

I was trying to do something like this but i can't figure out any further

Test data:

qda    0.6333       0.6917      0.5917      0.6417     0.5833
svm    0.5333       0.6917      0.5333      0.575      0.575
lda    0.5333       0.6583      0.5333      0.5667     0.5667
lr     0.5333       0.65        0.4917      0.5667     0.5667
dt     0.5333       0.65        0.4917      0.5667     0.5667
rc     0.5083       0.6333      0.4917      0.525      0.525
nb     0.5          0.625       0.475       0.5        0.4833
rfc    0.5          0.625       0.4417      0.4917     0.4583
knn    0.3917       0.6         0.4417      0.4833     0.45
et     0.375        0.5333      0.4333      0.4667     0.45
dc     0.375        0.5333      0.4333      0.4667     0.425
qds    0.3417       0.5333      0.4         0.4583     0.3667
lgt    0.3417       0.525       0.3917      0.45       0.3583
lt     0.2333       0.45        0.3917      0.4167     0.3417

These are values for respective subcolumns in order specified in the table above

ANSWER

Answered 2022-Feb-20 at 13:01

There's a dirty way to do this, I'll write about it till someone answers with a better idea. Here we go:

import pandas as pd

# I assume that you can read raw data named test.csv by pandas and
# set header = None cause you mentioned the Test data without any headers, so:
df = pd.read_csv("test.csv", header = None)

# Then define preferred Columns! 
MyColumns = pd.MultiIndex.from_tuples([("Models" , ""),
                                       ("Accuracy without normalization" , ""),
                                       ("Accuracy with normalization" , "zscore"),
                                       ("Accuracy with normalization" , "minmax"),
                                       ("Accuracy with normalization" , "maxabs"),
                                       ("Accuracy with normalization" , "robust")])

# Create new DataFrame with specified Columns, after this you should pass values 
New_DataFrame = pd.DataFrame(df , columns = MyColumns)

# a loop for passing values
for item in range(len(MyColumns)):
    New_DataFrame.loc[: , MyColumns[item]] = df.iloc[: , item]

This gives me:

enter image description here

after all, if you want to set Models as the index of New_DataFrame, You can continue with:

New_DataFrame.set_index(New_DataFrame.columns[0][0] , inplace=True)
New_DataFrame

This gives me:

enter image description here

Source https://stackoverflow.com/questions/71193085

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install Robust

You can download it from GitHub.
You can use Robust like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the Robust component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.