#StackBounty: #systemd #audio #alsa #suspend Crackling sound with ALSA from an USB sound card after resuming from suspend

Bounty: 50

I run Arch Linux using Systemd and ALSA on a Thinkpad X200 and I have an USB sound card connected, which I use for audio output.

The audio is fine until I suspend my machine with $ systemctl suspend. After resuming, the USB sound card’s audio output is broken and irregularly produces crackling noises.

What is possibly causing this? How can I fix this?

Plugging the USB sound card in and out neither produces this issue nor does it solve it. I don’t have a ~/.asoundrc.


Some information. Here is the dmesg output

Here’s my kernel:

$ uname -srvo
Linux 4.18.6-gnu-1 #1 SMP PREEMPT Sat Sep 8 14:43:46 UTC 2018 GNU/Linux

The USB sound card is actually a DAC, namely FiiO E10. Here’s how ALSA sees it:

$ aplay --list-devices
…
card 1: Audio [DigiHug USB Audio], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
…

The sound driver I use for the card is apparently snd_usb_audio according to $ lsmod | grep snd.


Get this bounty!!!

#StackBounty: #windows-10 #multi-boot #system-restore #grub2 #hard-drive-recovery Get a Windows machine to boot again after GRUB broken…

Bounty: 50

The Grub2 files on a Lenovo dual boot machine have been erased, along with everything else in the Ext4 partition, when the user resized the Ext4 partition to make more space for Windows 10 Pro 64-bit ver 1709. /boot/grub/grub.cfg /etc/grub.d/ and /etc/default/grub are all gone along with everything else in the ext4 filesystem.

So the system doesn’t boot and I need to get Windows booting again as a priority; once Windows boots, reinstalling Linux is easy.

There are three NTFS partitions on the machine’s drive, plus a vacant Ext4 partition in a position relocated from its original place. I want to get Windows booting again as a priority; the user can wait for Linux, although I certainly am not averse to the recovery tools of Debian derived distros.

Can’t boot from a LiveUSB with grub-recovery; when I do, I get a Windows boot manager error message. Without the LiveUSB, I get a Grub error prompt.

Looked for the original Windows 10 recovery USB, found it was physically destroyed (two moves = one fire, as they say).

Created a Recovery USB from another Windows 10 (ver 1803) machine and ran bootrec.exe /fixmbr Enter responded with “The operation completed successfully”. Closed the command window, powered down, unplugged the USB and powered up; failed to boot with “BOOTMGR is missing.”

Bootrec.exe /rebuildbcd tells me 0 drives repaired and rebooting failed to boot with “BOOTMGR is missing.”

Bootrec.exe /fixboot tells me “Access is denied.”

How may I resolve this?


Get this bounty!!!

#StackBounty: #swift #calayer #cabasicanimation #avassetexportsession #avvideocomposition Can't show animated CALayer in video usin…

Bounty: 50

UPDATE 6:
I’ve managed to fix my issue completely but I still would like a better explanation than what I’m guessing is the reason it didn’t work if I’m incorrect

I’ve been trying to animate a sprite sheet over a video but every time I export the video the end result is the sample video I start with.

Here’s my code:

First up my custom CALayer to handle my own sprite sheets

class SpriteLayer: CALayer {
    var frameIndex: Int

    override init() {
        // Using 0 as a default state
        self.frameIndex = 0
        super.init()
    }

    required init?(coder aDecoder: NSCoder) {
        self.frameIndex = 0
        super.init(coder: aDecoder)
    }

    override func display() {
        let currentFrameIndex = self.frameIndex
        if currentFrameIndex == 0 {
            return
        }
        let frameSize = self.contentsRect.size
        self.contentsRect = CGRect(x: 0, y: CGFloat(currentFrameIndex - 1) * frameSize.height, width: frameSize.width, height: frameSize.height)
    }

    override func action(forKey event: String) -> CAAction? {
        if event == "contentsRect" {
            return nil
        }
        return super.action(forKey: event)
    }

    override class func needsDisplay(forKey key: String) -> Bool {
        return key == "frameIndex"
    }
}

Gif is a basic class with nothing fancy and works just fine. gif.Strip is a UIImage of a vertical sprite sheet representing the gif.

Now comes the method that should export a new video (it is part of a larger class used for exporting.

func convertAndExport(to url :URL , completion: @escaping () -> Void ) {
        // Get Initial info and make sure our destination is available
        self.outputURL = url
        let stripCgImage = self.gif.strip!.cgImage!
        // This is used to time how long the export took
        let start = DispatchTime.now()
        do {
            try FileManager.default.removeItem(at: outputURL)
        } catch {
            print("Remove Error: (error.localizedDescription)")
            print(error)
        }
        // Find and load "sample.mp4" as a AVAsset
        let videoPath = Bundle.main.path(forResource: "sample", ofType: "mp4")!
        let videoUrl = URL(fileURLWithPath: videoPath)
        let videoAsset = AVAsset(url: videoUrl)
        // Start a new mutable Composition with the same base video track
        let mixComposition = AVMutableComposition()
        let compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)!
        let clipVideoTrack = videoAsset.tracks(withMediaType: .video).first!
        do {
            try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: clipVideoTrack, at: kCMTimeZero)
        } catch {
            print("Insert Error: (error.localizedDescription)")
            print(error)
            return
        }
        compositionVideoTrack.preferredTransform = clipVideoTrack.preferredTransform
        // Quick access to the video size
        let videoSize = clipVideoTrack.naturalSize
        // Setup CALayer and it's animation
        let aLayer = SpriteLayer()
        aLayer.contents = stripCgImage
        aLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
        aLayer.opacity = 1.0
        aLayer.masksToBounds = true
        aLayer.bounds = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
        aLayer.contentsRect = CGRect(x: 0, y: 0, width: 1, height: 1.0 / 3.0)
        let spriteAnimation = CABasicAnimation(keyPath: "frameIndex")
        spriteAnimation.fromValue = 1
        spriteAnimation.toValue = 4
        spriteAnimation.duration = 2.25
        spriteAnimation.repeatCount = .infinity
        spriteAnimation.autoreverses = false
        spriteAnimation.beginTime = AVCoreAnimationBeginTimeAtZero
        aLayer.add(spriteAnimation, forKey: nil)
        // Setup Layers for AVVideoCompositionCoreAnimationTool
        let parentLayer = CALayer()
        let videoLayer = CALayer()
        parentLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
        videoLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
        parentLayer.addSublayer(videoLayer)
        parentLayer.addSublayer(aLayer)
        // Create the mutable video composition
        let videoComp = AVMutableVideoComposition()
        videoComp.renderSize = videoSize
        videoComp.frameDuration = CMTimeMake(1, 30)
        videoComp.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)
        // Set the video composition to apply to the composition's video track
        let instruction = AVMutableVideoCompositionInstruction()
        instruction.timeRange = CMTimeRangeMake(kCMTimeZero, mixComposition.duration)
        let videoTrack = mixComposition.tracks(withMediaType: .video).first!
        let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
        instruction.layerInstructions = [layerInstruction]
        videoComp.instructions = [instruction]
        // Initialize export session
        let assetExport = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetPassthrough)!
        assetExport.videoComposition = videoComp
        assetExport.outputFileType = AVFileType.mp4
        assetExport.outputURL = self.outputURL
        assetExport.shouldOptimizeForNetworkUse = true
        // Export
        assetExport.exportAsynchronously {
            let status = assetExport.status
            switch status {
            case .failed:
                print("Export Failed")
                print("Export Error: (assetExport.error!.localizedDescription)")
                print(assetExport.error!)
            case .unknown:
                print("Export Unknown")
            case .exporting:
                print("Export Exporting")
            case .waiting:
                print("Export Waiting")
            case .cancelled:
                print("Export Cancelled")
            case .completed:
                let end = DispatchTime.now()
                let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds
                let timeInterval = Double(nanoTime) / 1_000_000_000
                // Function is now over, we can print how long it took
                print("Time to generate video: (timeInterval) seconds")
                completion()
            }
        }
}

EDIT:
I based my code on the following links

UPDATE 1:
I’ve tried removing the CABasicAnimation part of my code and played around with my CALayer but to no avail. I can’t even get the image to show up.
To test things out I tried animating this sprite sheet using a CAKeyframeAnimation on contentsRect in a Xcode Playground and it worked fine so I don’t think the issue is with the CABasicAnimation, and maybe not even with the CALayer itself. I could really use some help on this because I don’t understand why I can’t even get an image to show over my sample video on the export.

UPDATE 2:
In response to matt’s comment I’ve tried forgetting about the sprite sheet for a bit and changed it into a CATextLayer but still not seeing anything on my video (it has dark images so white text should be perfectly visible)

let aLayer = CATextLayer()
aLayer.string = "This is a test"
aLayer.fontSize = videoSize.height / 6
aLayer.alignmentMode = kCAAlignmentCenter
aLayer.foregroundColor = UIColor.white.cgColor
aLayer.bounds = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height / 6)

UPDATE 3:
As per Matt’s request I tried changing parentLayer.addSublayer(aLayer) to videoLayer.addSublayer(aLayer) but still nothing changed, but I thought as much because the documentation for the AVVideoCompositionCoreAnimationTool is as follows

convenience init(postProcessingAsVideoLayer videoLayer: CALayer, 
              in animationLayer: CALayer)

meaning my parentLayer is it’s animationLayer and probably means any animations should be done in this layer.

UPDATE 4:
I’m starting to go crazy over here, I’ve given up for now the idea of showing text or an animated image I just want to affect my video in any way possible so I changed aLayer to this:

let aLayer = CALayer()
aLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
aLayer.backgroundColor = UIColor.white.cgColor

Well, this does absolutely nothing, I still get my sample video at my outputUrl (I started testing this in a playground with the following code if you want to “play” along)

import PlaygroundSupport
import UIKit
import Foundation
import AVFoundation

func convertAndExport(to url :URL , completion: @escaping () -> Void ) {
    let start = DispatchTime.now()
    do {
        try FileManager.default.removeItem(at: url)
    } catch {
        print("Remove Error: (error.localizedDescription)")
        print(error)
    }

    let videoPath = Bundle.main.path(forResource: "sample", ofType: "mp4")!
    let videoUrl = URL(fileURLWithPath: videoPath)
    let videoAsset = AVURLAsset(url: videoUrl)
    let mixComposition = AVMutableComposition()
    let compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)!
    let clipVideoTrack = videoAsset.tracks(withMediaType: .video).first!

    do {
        try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: clipVideoTrack, at: kCMTimeZero)
    } catch {
        print("Insert Error: (error.localizedDescription)")
        print(error)
        return
    }
    compositionVideoTrack.preferredTransform = clipVideoTrack.preferredTransform
    let videoSize = clipVideoTrack.naturalSize
    print("Video Size Detected: (videoSize.width) x (videoSize.height)")

    let aLayer = CALayer()
    aLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
    aLayer.backgroundColor = UIColor.white.cgColor

    let parentLayer = CALayer()
    let videoLayer = CALayer()
    parentLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
    videoLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
    parentLayer.addSublayer(videoLayer)
    parentLayer.addSublayer(aLayer)
    aLayer.setNeedsDisplay()
    let videoComp = AVMutableVideoComposition()
    videoComp.renderSize = videoSize
    videoComp.frameDuration = CMTimeMake(1, 30)
    videoComp.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)

    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, mixComposition.duration)
    let videoTrack = mixComposition.tracks(withMediaType: .video).first!
    let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
    instruction.layerInstructions = [layerInstruction]
    videoComp.instructions = [instruction]

    let assetExport = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetPassthrough)!
    assetExport.videoComposition = videoComp
    assetExport.outputFileType = AVFileType.mp4
    assetExport.outputURL = url
    assetExport.shouldOptimizeForNetworkUse = true

    assetExport.exportAsynchronously {
        let status = assetExport.status
        switch status {
        case .failed:
            print("Export Failed")
            print("Export Error: (assetExport.error!.localizedDescription)")
            print(assetExport.error!)
        case .unknown:
            print("Export Unknown")
        case .exporting:
            print("Export Exporting")
        case .waiting:
            print("Export Waiting")
        case .cancelled:
            print("Export Cancelled")
        case .completed:
            let end = DispatchTime.now()
            let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds
            let timeInterval = Double(nanoTime) / 1_000_000_000
            print("Time to generate video: (timeInterval) seconds")
            completion()
        }
    }
}

let outputUrl = FileManager.default.temporaryDirectory.appendingPathComponent("test.mp4")
convertAndExport(to: outputUrl) {
    print(outputUrl)
}

Please someone help me understand what I’m doing wrong…

UPDATE 5:
I am running everything except playground tests from an iPad Air 2 (so no simulator) because I use the camera to take pictures and then stitch them into a sprite sheet I then planned on animating on a video I would send by email. I started doing Playground testing because every test from the iPad required me to go through the whole app cycle (countdown, photos, form, email sending/receiving)


Get this bounty!!!

#StackBounty: #php #litespeed #headers LiteSpeed ignore PHP header 404 status

Bounty: 50

After moving my website to a webhost which uses LiteSpeed it seems PHP header is ignored.

I have tried these variations:

  • $s = "HTTP/1.1 404 Not Found";
  • $s = "HTTP/1.0 404 Not Found";
  • $s = "Status: 404 Not Found";
  • $s = $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found';

followed by

header($s)

But on LiteSpeed these all seem to be ignored.

  1. Is there any option in LiteSpeed I can turn off to get Apache compatible behavior? I have access to cPanel and .htaccess
  2. Any other possible explanation and/or solution?

NOTES:

  • Problem happens on both https and http variations
  • The page returning 404 is a page used for mod_rewrites (so for URL queries where no valid content is found in database, 404 http response code should be returned)
  • Problem also happens on another domain of mine placed the server (using a popular PHP forum solution with a mod_rewrite based plugin for nice looking URLs)
  • The mod_rewrites themselves work fine so not 100% sure it is related.
  • Both sites work fine on those Apache servers I have tried through time (at least two different Apache webhosts + my localhost)

Also, on both websites I have disable LiteSpeed caching in my .htaccss file

<IfModule LiteSpeed>
RewriteRule .* - [E=Cache-Control:no-cache]
</IfModule>


Get this bounty!!!

#StackBounty: #android #gradle #protocol-buffers Register a package for the class generated from the proto file in the gradle by defaul…

Bounty: 100

In my android app I use proto files. For example, I have proto file Stats.proto

syntax = "proto3";
package com.me.test;

message Stat {
    string a = 1;
    string b = 2;
    string c = 3;
    string d = 4;
}

I need to register package in the each proto file itself, and this is uncomfortable, because I have a lot of files. I want to register default package in gradle, for example, ‘package com.me.test’, which uses each file that I create. I found solution in javanano

nano {
    proto {
      // Selects between --java_out and --javanano_out, default is 'java'
      mode 'javanano'
      // Options added to --java_out or --javanano_out
      option 'java_package=src/proto/simple-data.proto|my_package'
      option 'java_outer_classname=src/proto/simple-data.proto|OuterName'
      // Apply the 'grpc' plugin defined in protobufNativeCodeGenPluginDeps
      plugin 'grpc' {
        // Options added to --grpc_out
        option 'nano=true'
      }
    }

But I need to use javalite

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.0.0'
    }
    plugins {
        javalite {
            artifact = 'com.google.protobuf:protoc-gen-javalite:3.0.0'
        }
    }
    generateProtoTasks {
        all().each { task ->
            task.builtins {
                remove java
            }
            task.plugins {
                javalite { }
            }
        }
    }
}

And I want to have analogous logic

option 'java_package=src/proto/simple-data.proto|my_package'

like javanano in javalite

Can I implement that?


Get this bounty!!!

#StackBounty: #c++ #performance #algorithm #matrix #mathematics Determinant using Gauss Elimination

Bounty: 50

We had a question in examination to compute determinant of general square matrix.
Now I had made the normal program using Laplace Formula of determinant, ie, recursive solution.

Now I was thinking of reducing it into Upper Triangle Matrix and then the product of diagonal elements gives the determinant.

The code is following.

#include <iostream>
using namespace std;

const int N = 5;
int main()
{
    double array[N][N], det = 1;

    // initialise
    cout << "Enter " << N << "*" << N << " matrix:n";
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            cin >> array[i][j];
        }
    }

    for (int i = 0; i < N; ++i) 
    {
        bool flag = false; // flag := are all entries below a[i][i] including it zero?
        if (array[i][i] == 0) // If a[i][i] is zero then check rows below and swap
        {
            flag = true;
            for (int j = i; j < N; ++j)
            {
                if (array[j][i] != 0) {
                    det *= -1;
                    for (int k = 0; k < N; ++k) { 
                        double t = array[i][k]; // swapping
                        array[i][k] = array[j][k];
                        array[j][k] = t;
                        flag = false;
                    }
                }
            }
        }

        if (flag == true) {
            det = 0;
            break;
        }

        else {

            for (int j = i+1; j < N; ++j)
            {
                double store = array[j][i];
                for (int k = i; k < N; ++k) {
                    array[j][k] -= (array[i][k]*store)/array[i][i];

                } 
            }
            det *= array[i][i];
        }
    }

    cout << "Determinant: " << det;
    return 0;
}

The problems with this approach is that matrix needs to be of floating point datatypes. Worse, it gives wrong result for least significant place (ones digit) for all integral entries if I use datatype of entries as float. To overcome that, we can use double.

But still I :

  • need tips on improving performance of this method
  • need to know whether this method is better than Simple Laplace Formula?


Get this bounty!!!

#StackBounty: #installation Installation trouble with bioinformatics package daccord

Bounty: 50

I’m trying to install a bioinformatics tool, called daccord (on my mac).

Unfortunately my computer savvy is very limited and my trouble shooting is pretty much trial and error.

The README says:

daccord needs libmaus2 https://github.com/gt1/libmaus2.
libmaus2 needs to be built with support for the GMP library. When libmaus2 is installed in
${LIBMAUSPREFIX} then daccord can be compiled and installed in
${HOME}/daccord using

autoreconf -i -f
./configure –with-libmaus2=${LIBMAUSPREFIX}
–prefix=${HOME}/daccord
make install

I did install libmaus2 (at least I hope I did, I also installed GMP, but I have no idea whether libmaus2 was “built with support for the GMP library”.

My guess is that I have to replace ${LIBMAUSPREFIX} with the right path?
Maybe ${HOME} too.

I tried usr/local/bin because the libmaus-README said:

By default, make install installs the package’s commands under
/usr/local/bin, include files under /usr/local/include, etc.

I also tried the path of the libmaus release file.

So far the result is always:

configure: error: Package requirements (libmaus2 >= 2.0.352) were not met:
No package 'libmaus2' found
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables libmaus2_CFLAGS
and libmaus2_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.

Would be great if someone could give me a few pointers as to how to proceed.


Get this bounty!!!

#StackBounty: #php #unit-testing #phpunit #mockery Adding interface to mock with Mockery (hard dependency)

Bounty: 50

I need to mock CurrencyEnum by overload it, but it’s not the end becouse i need to add interface to this mock.
This doesn’t work:

Mockery::mock('overload:'.CurrencyEnum::class);

Error: (..) must be an instance of BaseCurrency, instance of CurrencyEnum given.
I looked at MockeryContainer::mock and I dont’t have idea how to do it.
In example I want to test TestingClass::first() method

class CurrencyEnum implements BaseCurrency
{
    /* methods */
}


class TestingClass
{
    public function first(string $currencySymbol)
    {
        $abc = 'some_string';

        return $this->second($abc, new CurrencyEnum($currencySymbol));
    }

    private function second(string $abc, BaseCurrency $currency)
    {
        /* code */
    }
}


Get this bounty!!!