text:
Q: Increasing Number Of Treads Cause The Longer Loop Duration I have a method with some logic that take ~40ms
When I am call this method more times (parallel)- each loop duration takes more time (a lot).
For example:
1 call - ~40ms (avg)
5 calls - ~63ms (avg)
10 calls - ~120ms (avg)
100 calls - ~1200ms (avg)
and so on...
Code:
int numberOfExecution = 100;
ExecutorService executor = Executors.newFixedThreadPool(numberOfExecution);
for (int i = 0; i < numberOfExecution; i++) {
    executor.execute(new Runnable() {
        @Override
        public void run() {
            MyObject obj1 = readBytesFromFile(1);
            MyObject obj2 = readBytesFromFile(2);
            MyObject obj3 = readBytesFromFile(3);
            MyObject obj4 = readBytesFromFile(4);

            final Map<Integer, MyObject> objects = new TreeMap<>();
            objects.put(0, obj1);
            objects.put(1, obj2);
            objects.put(2, obj3);
            objects.put(3, obj4);

            Foo foo = new Foo(objects);

            long startTime = System.currentTimeMillis();
            Thread.sleep(40); // sleep for 40ms to demonstrate my 40ms logic
            long endTime = System.currentTimeMillis();
            float durationMs = endTime - startTime;

            System.out.println("Foo.bar() duration: " + durationMs);
        }
    });
}

executor.shutdown();
while (!executor.isTerminated()) { }

Console:
Foo.bar() duration: 41.0
Foo.bar() duration: 40.0
Foo.bar() duration: 43.0
Foo.bar() duration: 41.0
Foo.bar() duration: 40.0
Foo.bar() duration: 41.0
Foo.bar() duration: 41.0
Foo.bar() duration: 48.0
Foo.bar() duration: 62.0
Foo.bar() duration: 48.0
Foo.bar() duration: 48.0
Foo.bar() duration: 48.0
Foo.bar() duration: 48.0
Foo.bar() duration: 49.0
Foo.bar() duration: 48.0
Foo.bar() duration: 49.0
Foo.bar() duration: 40.0
Foo.bar() duration: 40.0
Foo.bar() duration: 40.0
Foo.bar() duration: 40.0
Foo.bar() duration: 40.0
Foo.bar() duration: 40.0
Foo.bar() duration: 40.0
Foo.bar() duration: 41.0
Foo.bar() duration: 40.0
Foo.bar() duration: 41.0
Foo.bar() duration: 41.0
Foo.bar() duration: 42.0
Foo.bar() duration: 49.0
Foo.bar() duration: 40.0
Foo.bar() duration: 40.0
Foo.bar() duration: 49.0
Foo.bar() duration: 74.0
Foo.bar() duration: 40.0
Foo.bar() duration: 70.0
Foo.bar() duration: 40.0
Foo.bar() duration: 50.0
Foo.bar() duration: 43.0
Foo.bar() duration: 40.0
Foo.bar() duration: 43.0
Foo.bar() duration: 56.0
Foo.bar() duration: 63.0
Foo.bar() duration: 45.0
Foo.bar() duration: 40.0
Foo.bar() duration: 41.0
Foo.bar() duration: 43.0
Foo.bar() duration: 43.0
Foo.bar() duration: 48.0
Foo.bar() duration: 41.0
Foo.bar() duration: 58.0
Foo.bar() duration: 59.0
Foo.bar() duration: 55.0
Foo.bar() duration: 42.0
Foo.bar() duration: 40.0
Foo.bar() duration: 42.0
Foo.bar() duration: 70.0
Foo.bar() duration: 40.0
Foo.bar() duration: 41.0
Foo.bar() duration: 75.0
Foo.bar() duration: 40.0
Foo.bar() duration: 43.0
Foo.bar() duration: 40.0
Foo.bar() duration: 41.0
Foo.bar() duration: 67.0
Foo.bar() duration: 59.0
Foo.bar() duration: 40.0
Foo.bar() duration: 57.0
Foo.bar() duration: 42.0
Foo.bar() duration: 40.0
Foo.bar() duration: 41.0
Foo.bar() duration: 43.0
Foo.bar() duration: 41.0
Foo.bar() duration: 40.0
Foo.bar() duration: 41.0
Foo.bar() duration: 42.0
Foo.bar() duration: 41.0
Foo.bar() duration: 40.0
Foo.bar() duration: 42.0
Foo.bar() duration: 42.0
Foo.bar() duration: 41.0
Foo.bar() duration: 45.0
Foo.bar() duration: 44.0
Foo.bar() duration: 40.0
Foo.bar() duration: 42.0
Foo.bar() duration: 41.0
Foo.bar() duration: 40.0
Foo.bar() duration: 40.0
Foo.bar() duration: 45.0
Foo.bar() duration: 41.0
Foo.bar() duration: 40.0
Foo.bar() duration: 44.0
Foo.bar() duration: 41.0
Foo.bar() duration: 42.0
Foo.bar() duration: 40.0
Foo.bar() duration: 42.0
Foo.bar() duration: 41.0
Foo.bar() duration: 42.0
Foo.bar() duration: 42.0
Foo.bar() duration: 43.0
Foo.bar() duration: 43.0

Run on MacBook Pro i9
What am I missing?

A: The number of cores in a machine is fixed. As we increase the number of threads that needs to be executed parallelly there will be context switching between Threads.
Please check https://www.javamex.com/tutorials/threads/context_switch.shtml .
Also, there can be resource contention between Threads. The maximum number of threads which can run in parallel will depend on the Machine Cores.
In short, just increasing the thread count will not increase the code execution performance.


text:
Q: Animate CAShapeLayer as Timer runs I have a round button with a CAShapeLayer that is on the outside of it. I also have timer that runs as a video plays. As the timer runs, I want to update the CAShapeLayer as if it were a progress indicator. The problem is as the timer runs, the animation on the shapelayer starts jumping around, it isn't smooth. I tried updating it on the mainqueue but that didn't work either.
Where am I going wrong at?
lazy var roundButton: UIButton = {
    // create button
}()

var seconds = 15
weak var videoTimer: Timer?
let shapeLayer = CAShapeLayer()
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")

func addCAShapeLayerToButton() {

    // there is another shapelayer that is gray used as the outer circle background layer

    let circularPath = UIBezierPath(arcCenter: roundButton.center, radius: (roundButton.frame.width / 2) + 10, startAngle: -.pi/2, endAngle: 3 * .pi/2, clockwise: true)
    shapeLayer.path = timerCircularPath.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.fillColor = fillColor
    shapeLayer.lineWidth = lineWidth
    shapeLayer.strokeEnd = 0
    view.layer.addSublayer(shapeLayer)

    basicAnimation.fillMode = CAMediaTimingFillMode.forwards
    basicAnimation.isRemovedOnCompletion = false
    shapeLayer.add(basicAnimation, forKey: nil)
}

func startTimer() {

    videoTimer?.invalidate()
    videoTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] _ in
        self?.timerIsRunning()
    })
    if let videoTimer = videoTimer {
        RunLoop.current.add(videoTimer, forMode: RunLoop.Mode.common)
    }
}

@objc fileprivate func timerIsRunning() {

    if seconds != 0 {
        seconds -= 1

        let recordingProgress: CGFloat = CGFloat(seconds) / CGFloat(15)
        shapeLayer.strokeEnd = recordingProgress // tried updating on the mainqueue

        /*
          I also tried
          basicAnimation.fromValue = 0
          basicAnimation.toValue = 1
          basicAnimation.duration = CFTimeInterval(recordingProgress)
        */

    } else {

        videoTimer?.invalidate()
    }
}

The red shapeLayer is going to fill the outer gray circle as the timer runs. It's supposed to indicate how much time the user has left to record because there isn't a label that shows the timer as it runs.

A: This sample progress wheel involves a subclass of UIView and a subclass of NSObjet.  The former creates a wheel view while the latter executes Energizer bunny in animation until the user stops it.
StrokeView.swift
import UIKit

class StrokeView: UIView {
    var shapeLayer = CAShapeLayer()
    var strokeColor: UIColor // strokeColor
    var start: CGFloat
    var end: CGFloat
    var radius: CGFloat // radius
    var weight: CGFloat // weight
    var view: UIView // view

    init(frame: CGRect, strokeColor: UIColor, start: CGFloat, end: CGFloat, radius: CGFloat, weight: CGFloat, view: UIView){
        self.strokeColor = strokeColor
        self.start = start
        self.end = end
        self.radius = radius
        self.weight = weight
        self.view = view
        super.init(frame: frame)
        self.isOpaque = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let bounds = self.bounds
        let centerPoint = CGPoint(x: bounds.width/2, y: bounds.height/2)
        let circlePath = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: start, endAngle: end, clockwise: true)
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = weight
        self.layer.addSublayer(shapeLayer)
    }
}

RotateMe.swift
import UIKit

class RotateMe: NSObject {
    var myView = UIView()

    var strokeColor0: UIColor
    var start0: CGFloat
    var end0: CGFloat

    var strokeColor1: UIColor
    var start1: CGFloat
    var end1: CGFloat

    var strokeColor2: UIColor
    var start2: CGFloat
    var end2: CGFloat

    var rect: CGRect
    var radius: CGFloat
    var weight: CGFloat
    var slowness: Double
    var view: UIView

    init(rect: CGRect, strokeColor0: UIColor, start0: CGFloat, end0: CGFloat, strokeColor1: UIColor, start1: CGFloat, end1: CGFloat, strokeColor2: UIColor, start2: CGFloat, end2: CGFloat, radius: CGFloat, weight: CGFloat, slowness: Double, view: UIView) {
        self.rect = rect
        self.strokeColor0 = strokeColor0
        self.start0 = start0
        self.end0 = end0
        self.strokeColor1 = strokeColor1
        self.start1 = start1
        self.end1 = end1
        self.strokeColor2 = strokeColor2
        self.start2 = start2
        self.end2 = end2
        self.radius = radius
        self.weight = weight
        self.slowness = slowness
        self.view = view
    }

    func circleMe() {
        let minSize = min(rect.width, rect.height)
        let myRect = CGRect(origin: CGPoint(x: (view.frame.width - minSize)/2.0, y: (view.frame.height - minSize)/2.0), size: CGSize(width: rect.width, height: rect.height))
        myView = UIView(frame: myRect)
        let strokeView0 = StrokeView(frame: rect, strokeColor: strokeColor0, start: start0, end: end0, radius: radius, weight: weight, view: view)
        let strokeView1 = StrokeView(frame: rect, strokeColor: strokeColor1, start: start1, end: end1, radius: radius, weight: weight, view: view)
        let strokeView2 = StrokeView(frame: rect, strokeColor: strokeColor2, start: start2, end: end2, radius: radius, weight: weight, view: view)
        myView.addSubview(strokeView0)
        myView.addSubview(strokeView1)
        myView.addSubview(strokeView2)
        //myView.backgroundColor = UIColor.blue.withAlphaComponent(0.4)

        let start = 0.0
        let end = start + 2 * Double.pi
        let dur = slowness as Double
        let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotateAnimation.duration = dur
        rotateAnimation.repeatCount = .infinity
        rotateAnimation.fromValue = start
        rotateAnimation.toValue = end
        //rotateAnimation.removedOnCompletion = true;
        rotateAnimation.fillMode = CAMediaTimingFillMode.forwards;
        rotateAnimation.autoreverses = false
        rotateAnimation.isCumulative = true // if set it to no, the view won't rotate and will only move in an awkward way
        myView.layer.add(rotateAnimation, forKey: "rotationAnimation")
        view.addSubview(myView)
    }

    func stopRotation() {
        myView.removeFromSuperview()
    }
}

How to run a progress wheel through a view controller

In this case, the user is presented with the start button.  When they tap it, a progress wheel will appear.

import UIKit

class ViewController: UIViewController {
    // MARK: - Variables

    // MARK: - IBOutlet
    @IBOutlet var rotateView: RotateMe?
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var endButton: UIButton!

    // MARK: - IBAction
    @IBAction func startTapped(_ sender: UIButton) {
        startButton.isEnabled = false
        endButton.isEnabled = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
            self.makeProgress()
        }
    }

    @IBAction func endTapped(_ sender: UIButton) {
        startButton.isEnabled = true
        endButton.isEnabled = false
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
            self.rotateView?.stopRotation()
        }
    }

    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func makeProgress() {
        let selfFrame = view.frame
        let minFloat = min(selfFrame.size.width, selfFrame.size.height)
        let rect = CGRect(x: 0.0, y: 0.0, width: minFloat, height: minFloat)
        let color0 = UIColor.orange
        let start0 = CGFloat(-120.0).degreesToRadians()
        let end0 = CGFloat(0.0).degreesToRadians()
        let color1 = UIColor.purple
        let start1 = CGFloat(0.0).degreesToRadians()
        let end1 = CGFloat(120.0).degreesToRadians()

        let color2 = UIColor.green
        let start2 = CGFloat(120.0).degreesToRadians()
        let end2 = CGFloat(-120.0).degreesToRadians()

        rotateView = RotateMe(rect: rect, strokeColor0: color0, start0: start0, end0: end0, strokeColor1: color1, start1: start1, end1: end1, strokeColor2: color2, start2: start2, end2: end2, radius: 80.0, weight: 30.0, slowness: 2.0, view: view)
        rotateView?.circleMe()
    }
}

extension CGFloat {
    func degreesToRadians() -> CGFloat {
        return self * .pi / 180.0
    }

    func radiansToDegrees() -> CGFloat {
        return self * (180.0 / .pi)
    }
}

In your case, run Timer and time 15 seconds.  Then simply call
rotateView?.stopRotation()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copying a range of columns within a row instead of entire row to another sheet? I'm pretty clueless on this stuff, just starting to play with it.  I have a code I got from a website, I customized it and it works great.  It looks at a value in column 12 (a numeric value) on a master sheet, in my case "invoice2" and then copies that entire row based on the column 12 value to the pre-created sheet matching that value in my workbook.  What I'd like is for it to only copy the row from columns A to H, not the entirety of columns A to L.  I cannot for the life of me figure out where to adjust that in this code.  Can anyone assist?
'<<<<  Create a new sheet for every Unique value or paste it below the existing data if the sheet exists  >>>>>

'This example copy all rows with the same value in the first column of
'the range to a new worksheet. It will do this for every unique value.
'The sheets will be named after the Unique value.
'If the sheet already exists the data will be pasted below the existing data on that worksheet.

'Note: this example use the function LastRow and SheetExists in the ModReset module

Sub Copy_To_Worksheets_2()
'Note: This macro use the function LastRow and SheetExists
Dim My_Range As Range
Dim FieldNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
Dim DestRange As Range
Dim Lr As Long

'Set filter range on ActiveSheet: A11 is the top left cell of your filter range
'and the header of the first column, D is the last column in the filter range.
'You can also add the sheet name to the code like this :
'Worksheets("Sheet1").Range("A11:D" & LastRow(Worksheets("Sheet1")))
'No need that the sheet is active then when you run the macro when you use this.
Set My_Range = Range("A12:L" & LastRow(ActiveSheet))
My_Range.Parent.Select

If ActiveWorkbook.ProtectStructure = True Or _
   My_Range.Parent.ProtectContents = True Then
    MsgBox "Sorry, not working when the workbook or worksheet is protected", _
           vbOKOnly, "Copy to new worksheet"
    Exit Sub
End If

'This example filters on the first column in the range(change the field if needed)
'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
FieldNum = 12

'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False

'Change ScreenUpdating, Calculation, EnableEvents, ....
With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .EnableEvents = False
End With
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
ActiveSheet.DisplayPageBreaks = False

'Add a worksheet to copy the a unique list and add the CriteriaRange
Set ws2 = Worksheets.Add

With ws2
    'first we copy the Unique data from the filter field to ws2
    My_Range.Columns(FieldNum).AdvancedFilter _
            Action:=xlFilterCopy, _
            CopyToRange:=.Range("A1"), Unique:=True

    'loop through the unique list in ws2 and filter/copy to a new sheet
    Lrow = .Cells(Rows.count, "A").End(xlUp).Row
    For Each cell In .Range("A2:A" & Lrow)

        My_Range.Parent.Select
        'Filter the range
        My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
                                                        Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")

        'Check if there are no more then 8192 areas(limit of areas)
        CCount = 0
        On Error Resume Next
        CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
                 .Areas(1).Cells.count
        On Error GoTo 0
        If CCount = 0 Then
            MsgBox "There are more than 8192 areas for the value: " & cell.Value _
                 & vbNewLine & "It is not possible to copy the visible data." _
                 & vbNewLine & "Tip: Sort your data before you use this macro.", _
                   vbOKOnly, "Split in worksheets"
        Else
            'Add a new worksheet or set a reference to a existing sheet
            If SheetExists(cell.Text) = False Then
                Set WSNew = Worksheets.Add(After:=Sheets(Sheets.count))
                On Error Resume Next
                WSNew.Name = cell.Value
                If Err.Number > 0 Then
                    ErrNum = ErrNum + 1
                    WSNew.Name = "Error_" & Format(ErrNum, "0000")
                    Err.Clear
                End If
                On Error GoTo 0
                Set DestRange = WSNew.Range("A1")
            Else
                Set WSNew = Sheets(cell.Text)
                Lr = LastRow(WSNew)
                Set DestRange = WSNew.Range("A" & Lr + 1)
            End If

            'Copy the visible data to the worksheet
            My_Range.SpecialCells(xlCellTypeVisible).Copy
            With DestRange
                .Parent.Select
                ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
                ' Remove this line if you use Excel 97
                .PasteSpecial xlPasteValues
                .PasteSpecial xlPasteFormats
                Application.CutCopyMode = False
                .Select
            End With
        End If

        ' Delete the header row if you copy to a existing worksheet
        If Lr > 1 Then WSNew.Range("A" & Lr + 1).EntireRow.Delete

        'Show all data in the range
        My_Range.AutoFilter Field:=FieldNum

    Next cell

    'Delete the ws2 sheet
    On Error Resume Next
    Application.DisplayAlerts = False
    .Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

End With

'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False

If ErrNum > 0 Then
    MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
         & vbNewLine & "There are characters in the name that are not allowed" _
         & vbNewLine & "in a sheet name or the worksheet already exist."
End If

'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = CalcMode
End With

End Sub

Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
                        After:=sh.Range("A1"), _
                        Lookat:=xlPart, _
                        LookIn:=xlValues, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row
On Error GoTo 0
End Function

Function SheetExists(SName As String, _
                 Optional ByVal WB As Workbook) As Boolean
'Chip Pearson
On Error Resume Next
If WB Is Nothing Then Set WB = ThisWorkbook
SheetExists = CBool(Len(WB.Sheets(SName).Name))
End Function

A: I have changed your code slightly :) Now it yields what you wanted.
The current version of code:
'<<<<  Create a new sheet for every Unique value or paste it below the existing data if the sheet exists  >>>>>

'This example copy all rows with the same value in the first column of
'the range to a new worksheet. It will do this for every unique value.
'The sheets will be named after the Unique value.
'If the sheet already exists the data will be pasted below the existing data on that worksheet.

'Note: this example use the function LastRow and SheetExists in the ModReset module

Sub Copy_To_Worksheets_2()
'Note: This macro use the function LastRow and SheetExists
Dim My_Range As Range
Dim Filter_Range As Range
Dim FieldNum As Long
Dim CalcMode As Long
Dim ViewMode As Long
Dim ws2 As Worksheet
Dim Lrow As Long
Dim cell As Range
Dim CCount As Long
Dim WSNew As Worksheet
Dim ErrNum As Long
Dim DestRange As Range
Dim Lr As Long

'Set filter range on ActiveSheet: A11 is the top left cell of your filter range
'and the header of the first column, D is the last column in the filter range.
'You can also add the sheet name to the code like this :
'Worksheets("Sheet1").Range("A11:D" & LastRow(Worksheets("Sheet1")))
'No need that the sheet is active then when you run the macro when you use this.
With ActiveSheet
    Set My_Range = .Range("A12:H" & LastRow(ActiveSheet))
    Set Filter_Range = .Range("L12:L" & LastRow(ActiveSheet))
    .Select
End With

If ActiveWorkbook.ProtectStructure = True Or _
    My_Range.Parent.ProtectContents = True Then
    MsgBox "Sorry, not working when the workbook or worksheet is protected", _
        vbOKOnly, "Copy to new worksheet"
    Exit Sub
End If

'This example filters on the first column in the range(change the field if needed)
'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
FieldNum = 12

'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False

'Change ScreenUpdating, Calculation, EnableEvents, ....
With Application
    CalcMode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .EnableEvents = False
End With
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
ActiveSheet.DisplayPageBreaks = False

'Add a worksheet to copy the a unique list and add the CriteriaRange
Set ws2 = Worksheets.Add

With ws2
    'first we copy the Unique data from the filter field to ws2
    Filter_Range.AdvancedFilter _
        Action:=xlFilterCopy, _
        CopyToRange:=.Range("A1"), Unique:=True

    'loop through the unique list in ws2 and filter/copy to a new sheet
    Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
    For Each cell In .Range("A2:A" & Lrow)

        My_Range.Parent.Select
        'Filter the range
        Filter_Range.AutoFilter Field:=1, Criteria1:="=" & _
            Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")

        'Check if there are no more then 8192 areas(limit of areas)
        CCount = 0
        On Error Resume Next
        CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
                 .Areas(1).Cells.Count
        On Error GoTo 0
        If CCount = 0 Then
            MsgBox "There are more than 8192 areas for the value: " & cell.Value _
                 & vbNewLine & "It is not possible to copy the visible data." _
                 & vbNewLine & "Tip: Sort your data before you use this macro.", _
                   vbOKOnly, "Split in worksheets"
        Else
            'Add a new worksheet or set a reference to a existing sheet
            If SheetExists(cell.Text) = False Then
                Set WSNew = Worksheets.Add(After:=Sheets(Sheets.Count))
                On Error Resume Next
                WSNew.Name = cell.Value
                If Err.Number > 0 Then
                    ErrNum = ErrNum + 1
                    WSNew.Name = "Error_" & Format(ErrNum, "0000")
                    Err.Clear
                End If
                On Error GoTo 0
                Set DestRange = WSNew.Range("A1")
            Else
                Set WSNew = Sheets(cell.Text)
                Lr = LastRow(WSNew)
                Set DestRange = WSNew.Range("A" & Lr + 1)
            End If

            'Copy the visible data to the worksheet
            My_Range.SpecialCells(xlCellTypeVisible).Copy
            With DestRange
                .Parent.Select
                ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
                ' Remove this line if you use Excel 97
                .PasteSpecial xlPasteValues
                .PasteSpecial xlPasteFormats
                Application.CutCopyMode = False
                .Select
            End With
        End If

        ' Delete the header row if you copy to a existing worksheet
        If Lr > 1 Then WSNew.Range("A" & Lr + 1).EntireRow.Delete

        'Show all data in the range
        Filter_Range.AutoFilter 'Field:=FieldNum

    Next 'cell

    'Delete the ws2 sheet
    On Error Resume Next
    Application.DisplayAlerts = False
    .Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

End With

'Turn off AutoFilter
My_Range.Parent.AutoFilterMode = False

If ErrNum > 0 Then
    MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
         & vbNewLine & "There are characters in the name that are not allowed" _
         & vbNewLine & "in a sheet name or the worksheet already exist."
End If

'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = CalcMode
End With

End Sub

Function LastRow(sh As Worksheet) As Long
    LastRow = sh.Range("A1").SpecialCells(xlCellTypeLastCell).Row
End Function

Function SheetExists(SName As String, Optional ByVal WB As Workbook) As Boolean
'Chip Pearson
On Error Resume Next
If WB Is Nothing Then Set WB = ThisWorkbook
SheetExists = CBool(Len(WB.Sheets(SName).Name))
End Function

Changes are basically related to the newly added Filter_Range. My_Range remains, but while the subroutine is processing, fields are no longer filtered according to the 12th column of My_Range. Now filter works on the first (the only) column of Filter_Range. In the code you can see assigned values for both of them.
Set My_Range = .Range("A12:H" & LastRow(ActiveSheet))
Set Filter_Range = .Range("L12:L" & LastRow(ActiveSheet))

LastRow function was also changed, now it has only one line:
Function LastRow(sh As Worksheet) As Long
    LastRow = sh.Range("A1").SpecialCells(xlCellTypeLastCell).Row
End Function

Try it out, it works! :)


text:
Q: Sum of uniform random variables on simplex Let $X,X'$ be two independent uniform random variables on $n$-dimensional simplex $\Delta_n= \{(x_1,\ldots,x_n):x_i \geq 0, \sum x_i \leq 1\}$. I am trying to find the probability distribution of their sum
$$
Y= X+X'
$$
More specifically I am interested in finding the differential entropy of their sum, $h(Y)$.
$$
h(Y)= -\int f_Y(y) \log(f_Y(y)) \ dy
$$
The convolution integrals are tending to be too messy. I couldn't find any other trick apart from convolution.

A: A very crude asymptotic:
Consider first the entropy of $X$. Because it's uniform inside the $n-$ simplex, with volume $1/n!$, its entropy is $$H(X)=-\log(n!) \tag{1}$$
The density of the sum $S=\sum{X_i}$ is a beta density $f(S)=n S^{n-1}$, which means that $X$ tends to concentrate around $\sum X_i=1$ for large $n$. Further, over this region, the (multivariate) $X$ is asympotically equivalent to a set of $n$ iid exponential variables (lets call them $Z_i$)  with mean $1/n$ (or $\lambda = n$).
Indeed, the density of these $Z$ variables is $$H(Z)=n H(Z_i)=n (1-\log(n))\tag{2}$$
which agrees (asympotically) with $(1)$. This gives some (non rigorous) support to the following approximation: given that $X\sim Z$,
 instead of $Y = X+X'$, let's consider $W=Z+Z'$. Then $W_i$ (sum of two exponentials with parameters $\lambda=n$) follows a gamma distribution $(2,1/\lambda)$, with mean $E(W_i)=2/n$ and entropy
$$H(W_i)=1-\log(n)+\gamma$$
Hence $$H(W)=n(1-\log(n)+\gamma)$$
We can then conjecture
$$H(Y) \approx n(1-\log(n)+\gamma)$$
or perhaps
$$H(Y) = -\log(n!) + n \gamma + o(n)$$

Update (from OP comment): By the same reasoning, we can approximate $H(X-X')$:
The difference of two exponentials with paramenter $\lambda$ is a zero mean laplacian with scale $\lambda^{-1}$; and its entropy is $\log(2/\lambda)+1$
Hence $$H(X-X')\approx n (1+ \log(2) - \log(n))\approx -\log(n!) + n \log(2)$$
And
$$\frac{H(X-X')+\log(n!)}{H(X+X')+\log(n!)} \approx \frac{n \log(2) + o(n)}{n \gamma + o(n)} \to \frac{\log(2)}{\gamma}\approx 1.2008461$$
Remember that this approximation is only expected (by me at least) to work for large $n$. Further, the $o(n)$ term has probably a leading $O(\log(n))$ term, so the convergence can be slow.
I'd like to know if this fits your empirical results (if you have them), or the context.

A: Let $Z=X+Y$ and $Z'=X-Y$. Since $X$ and $Y$ are i.i.d on $\Delta_n$, the densities of $Z$ and $Z'$ are given by:
\begin{align*}
f_Z(z) &=\int_{\Delta_n \cap \left(-\Delta_n+z \right)} dx\\
f_Z'(z) &=\int_{\Delta_n \cap \left(\Delta_n+z \right)} dx\\
\end{align*}
and the entropies of $Z$ and $Z'$ are similarly given by:
\begin{align}
h(Z) &= \int_{\Delta_n + \Delta_n} f_Z \log \frac{1}{f_Z}\\
h(Z') &= \int_{\Delta_n -\Delta_n} f_{Z'} \log \frac{1}{f_{Z'}}\\
\end{align}
After using Monte Carlo integration to compute the required integrals I obtained the following results for the ratio $\frac{h(Z')+\log n! }{ h(Z)+\log n!}$:


text:
Q: .NET web application on Windows 2008 R2 Webserver only able to address 16 GB RAM, not 32 - why? We are trying to run a .NET 4 web application (on an 8 GB, 8 core Windows 2008 R2 64bit Webedition server) that creates Word mailmerge documents, using Spire.doc. Everything works fine up to around 5.000 records. If we try to merge more, physical as well as virtual memory both consume all they can, around 8 GB each.
Question: according to http://msdn.microsoft.com/en-us/library/aa366778%28v=vs.85%29.aspx#physical_memory_limits_windows_server_2008_r2, Windows 2008 R2 64bit would give you 32 GB.
So how can I make the application use more virtual memory?
Here's the code, but I think the question is rather generic (and yes, creating Word documents with 10.000 pages may seem ridiculous, but this is what the customer desires, and yes, we will talk him out of it):
    private static void Merge(DataTable recipients, string template, string saveAs)
    {
        Document document = new Document();
        document.LoadFromFile(template);

        document.MailMerge.Execute(recipients);

        document.ViewSetup.DocumentViewType = DocumentViewType.PrintLayout;
        document.SaveToFile(saveAs, FileFormat.Doc);
    }

A: You could try to compile your web application in in x64 mode.


text:
Q: Why are these Python processes stepping on each other? I have a simulation that runs on multiple processes. They get their input (a NumPy array containing just integers - no nested objects or other arrays) from a queue, and often report results through another queue. The parent process does this:
1 - populates the input queue with a cope of the data for each process:
        output_queue = multiprocessing.Queue()
        input_queue = multiprocessing.Queue()

        for _ in range(parallel_populations):
            new_input = {
                'data': np.copy(data_source),
            }
            input_queue.put(new_input)

2 - starts each process:
        processes = []
        for i in range(parallel_populations):
            process = multiprocessing.Process(target=run_population,
                                              args=(
                                                  input_queue,
                                                  output_queue
                                              ))
            process.start()
            processes.append(process)

3 - then, indefinitely, listens to the outputs coming from the output_queue and kills all processes, and restarts them with the new data:
while True:
    # kill all processes
    result = output_queue.get(True)
    for i in range(len(processes)):
        processes[i].kill()

    # populate input_queue again with new data:
    for _ in range(parallel_populations):
        new_input = {
            'data': np.copy(result),
        }
        input_queue.put(new_input)

    # finally, start the processes again
    processes = []
    for i in range(parallel_populations):
        process = multiprocessing.Process(target=run_population,
                                          args=(
                                              input_queue,
                                              output_queue
                                          ))
        process.start()
        processes.append(process)

Note that every time I put that data array in the input_queue, I make a np.copy so that each process has its own copy. The processes modify the data.
If I run only one process at a time, it runs well indefinitely. But if I launch more than one, they corrupt the data in the array as if i had not made copies before putting in the input_queue.
Doesn't np.copy create a full copy of the ndarray? Since they have just numbers, I thought this was sufficient.
I also tried using data = data[:] before putting into the queue to make a copy, but same results. Lastly, I tried using copy.deepcopy even though shouldn't be needed. Same results.
I also tried starting the processes with forkserver as well as spawn to see if memory isolation improved, but same results.
I can't seem to figure out why are they stepping on each other. I'm on Python 3.8.
Any pointers are greatly appreciated!


text:
Q: sql query fails every time

<form action="login_process.php" method="post">
SID: <input type="text" name="sid">

Password: <input type="text" name="pw">

<input type="submit" value="Login">
</form>

login_process.php FILE

<?php
include ("connection.php");

$sid = $_POST['sid'];
$pw = $_POST['pw'];

setcookie("username", "$sid". time()+86400);

$result = mysqli_query($con, "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'") or die('Query failed');

if(!$result){
    echo "Failed";
    } else {
        echo "success". $_COOKIE['username'];
        $_SESSION['username'] = $sid;
        }
?>

I have data in my student_table. But no matter what input i give it says success. even if i click login button without any input it still says success. please help.

A: You should use quotes when you assign values in sql queries .
SELECT
    SID
FROM
    student_table
WHERE
    SID = '$sid' and password = '$pw'

Also look forward Prepared Statements to protect yourself from sql injections.You should also add the code below to fetch selected row :
while ($row = mysqli_fetch_array($result)) {
   $_SESSION['username'] = $row['SID'];
}

A: Start learning basic debugging:
When a query fails bad, just do this:
Instead of running it  (mysql_query, or mysqli_query or whatever you have), ECHO it:
echo "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'";

After you submit the form, you will be shown the query that runs, go to phpmyadmin or whatever  you use and run the query manually. See if there are errors and also see easier what's going on. Advisable when you do work like this, FIRST try the queries in phpmyadmin then apply them in the code, after you are confident they are ok.

A: This is not really an answer but more about how to find out what is going wrong when you code does not work as you expect.
First, always put you SQL into a variable by itself. Why, so you can 'var_dump' it and see what is happening. So, try this:
$sql = "SELECT SID FROM student_table WHERE SID=$sid and password=$pw";

var_dump($sql, 'my_query'); // you will see what PHP created.

then try the answer provided:
$sql = "SELECT
    SID
FROM
    student_table
WHERE
    SID = '$sid' and password = '$pw'";

At least you will see what is likely to be incorrect.
var_dump($sql, 'the answer_query'); // you will see what PHP created.

$result = mysqli_query($con, $sql) or die('Query failed');
The outer quote marks must be " (double quote) not " ' " (single quote) both of which are perfectly valid PHP. the former allows variables to be replaced in strings.
    The latter will treat eveything as a literal string.


text:
Q: wxWidgets: Periodically redraw image in wxFrame I have a MainFrame and to set a background image I have implemented my own OnPaint() function.
OnPaint(wxPaintEvent& roEvent)
{
    if (!m_oBackgorund1.IsOk() || !m_oBackgorund2.IsOk())
        return;
    wxPaintDC paintDC(this);

    switch (roEvent.GetId())
    {
    case 0:
        paintDC.DrawBitmap(m_oBackgorund1, 0, 0);
        break;
    default:
        paintDC.DrawBitmap(m_oBackgorund2, 0, 0);
        break;
    }
}

The two bitmaps are correctly loaded previously. When starting my application the image m_oBackgorund2 is set as a background because the event's GetId() returns -201.
After that I start a thread that fires an event with either 0 or 1 as Id
{
    nId = !nId;
    wxPaintEvent oPaintEvent;
    oPaintEvent.SetId(nId);
    wxPostEvent(GetParent(), oPaintEvent);
}

The OnPaint is called correnty by that event and the bitmap is set according to the Id. However, the changes do not show in the UI.
If I call Refresh() in the OnPaint() the background image is painted voer everything else.
How can I update the Backgorund image of the wxFrame without having it paint over all other UI elements?
Thanks!

A: You need to change your approach because what you're doing is not going to work.
The basic problem is that you can't post paint events (or any other event processed by the underlying GUI layer) from your own code. These events are generated by the GUI library you use itself (i.e. Windows, GTK+ or Cocoa) and the windows have to be repainted when they get them, but artificially creating such events doesn't make the window repaint itself. The only way to do this is to call Refresh() on it and Refresh(), like all the GUI functions, can only be called from the main GUI thread.
So if you really want to use threads (and for what you're doing a timer would seem like a much more natural choice), you must post a custom event to the main thread which would then refresh the window which would then repaint itself.


text:
Q: Apex:Component not rerendering I know that there is a similar question from a while ago but...
I have a component that is not rerendering
<apex:actionFunction status="waiting" name="refreshTable" action="{!refresh}" rerender="learnComnt" oncomplete="reloadTable();"/>
<div>
    <c:Learning_Reviews_Component id="learnComnt" assignmentid="{!AssignmentID}" li="{!learningItemID}" type="{!LIType}"/>
</div>

This component is used to display reviews in a few places. It is shown on a description page on which is a button to create a new review.
<apex:commandButton id="Review" value="Rate it!" onclick="openedWindow = openRateWindow('{!$Page.Review}?type={!LIType}&Lid={!learningItemID}');" title="Submit a Review" />

the javascript in the description page:
function openRateWindow(link) {
    window.open(link, "_blank","fullscreen=no, scrollbars=no, resizable=no, titlebar=no, status=no, height=650, width=800, top=100, left=100");
}

On the review page is a javascript function that is called when the save button processes.
function MyCloseWindow() {
        var status = document.getElementById('{!$Component.pg.createReview.pb.pbs.statusMsg}');
        if(status.value == "Saved"){
            window.opener.refreshTable();
            window.close();
            self.close();
        }

So - the page opens, saves and closes as expected but

*

*When the review page is opened, the URL on the description page is altered (do not know how) and drops the last two items in the query string
(apex/Details?id=000000000000000&type=Module&asnmt=000000000000000000) turns to (apex/Details?id=000000000000000)

*When the page refreshes, the component empties

*If I replace the rerender on the actionFunction to bufferTableResult (name of the outputPanel in the component) then the old results double up so I get 2 lists of data that do not include the new review.

Any ideas as to what I am doing wrong??
EDIT:
I wrapped the component call in an actionRegion and it made no discernible difference. When I rerender the actionRegion there is no change to the behaviour.
<apex:actionRegion id="actioRegion">
    <apex:outputPanel layout="block" id="componentPanel">
        <c:Learning_Reviews_Component id="learnComnt" assignmentid="{!AssignmentID}" li="{!learningItemID}" type="{!LIType}"/>
    </apex:outputPanel>
</apex:actionRegion>

new version below
<apex:actionFunction status="waiting" name="refreshTable" action="{!refresh}" oncomplete="reloadTable();" rerender="actioRegion"/>

Rerendering on anything other than bufferTableResult causes no results to display. Rerendering on bufferTableResult causes a duplication effect with all of the previous reviews in list form... (review 1,2,3,4 followed by review 1,2,3,4)
I also checked the debug logs and the messages in the controller of the component are not showing

A: Try doing this:
<apex:actionFunction status="waiting" name="refreshTable" action="{!refresh}" rerender="componentPanel" oncomplete="reloadTable();"/>
<apex:outputPanel layout="block" id="componentPanel">
    <c:Learning_Reviews_Component id="learnComnt" assignmentid="{!AssignmentID}" li="{!learningItemID}" type="{!LIType}"/>
</apex:outputPanel>

Instead of rendering the component try rendering the panel and component inside panel will automatically rerender.
Hope this will  help.


text:
Q: How to setup plus / minus button on input type = number? https://www.w3schools.com/tags/att_input_type_number.asp
We've an input type number. If a user types "23" and presses enter, page 23 shows up. I handle it with a keydown function that checks value of input field = $("#pageFld").
But I'm having problems setting up the +/i buttons. We handled this before with on "input". But adding this also adds functionality to input field .
Example, if I try to type "23" again, it scrolls when '2' is entered. We also want scroll to only happen on input field when enter is pressed.
How to separate between code that handle input field and handle +/i buttons?
Code that handle enter key pressed.
$(document).keydown(function(e){
    switch (e.which){
        case 13:    //enter key (for Page scroll)
            $("#bookComponent").turn("page", $("#pageFld").val());
            break;
    }
});

Code that should handle +/- button but currently also effect input field:
    $("#pageFld").on('input', function(){
        $("#bookComponent").turn("page", $(this).val());
    });

A: You can change the input to the combination of change and mouseup event.
$("#pageFld").keydown(function(e){
    switch (e.which){
        case 13:    //enter key (for Page scroll)
            $("#bookComponent").turn("page", $("#pageFld").val());
            break;
    }
});

 $("#pageFld").on('change.mouseup', function(){
        $("#bookComponent").turn("page", $(this).val());
 });

In this scenario, I have changed the selector from document to that input id and it will detect on mouseup and the value is changed.


text:
Q: Subtract values from running total using DAX I have the following table:
Date        Measure1    Measure2    Output
11-02-2019  8           0.4         8
12-02-2019  8           0.4         7.6
13-02-2019  8           0.4         7.2
14-02-2019  8           0.4         6.8
15-02-2019  8           0.4         6.4
16-02-2019  8           0.4         6
17-02-2019  8           0.4         5.6

I want to subtract the value from previous row in power bi. How to update the value of measure in or value of variable.

*

*Measure1 - Holds one value which will change if some filter is changed.

*Measure 2 - Holds the value and depend upon filter for change.

*Measure 3 (Output) - This is based on calculation,Want to subtract the value from previous row.

measure1 = measure1 - measure2

A: Here's the kind of dax that will let you do something that looks like a running total.  I leave it to you to straighten up the column and table names.
RunningTotal =
CALCULATE(
   FIRSTNONBLANK(Table1[StartingVal], TRUE()) - SUM(Table1[Change])
   , FILTER(ALLSELECTED(Table1)
      , [DayOfMonth] <= MAX(Table1[DayOfMonth])
   )
)

This takes advantage of the filter portion of the 'CALCULATE' function to sum values in the field [Change] that are on rows whose value in [DayOfMonth] are less than or equal to the value of [DayOfMonth].  The resulting sum is subtracted from the first value in the column [StartingVal] that is part of our context.  In the strictest sense, this is not a running total.  The measure has no 'look back' capabilty to find a value in a previous row because the very concept of row is quite unreliable in DAX.  There are only subtables and filtered contexts.


text:
Q: SPSS Syntax to R for discriminant analysis I have been working in SPSS and need to know how to run a discriminant analysis in R. I imagine my syntax which look like this in SPSS
> GET DATA /TYPE=XLSX
>/FILE='C:\Users\Downloads\Initial Diabetics Data 10000.xlsx'
>/SHEET=name 'Initial Diabetics Data 10000.xl'
>/CELLRANGE=full   /READNAMES=on
>/ASSUMEDSTRWIDTH=32767.
>EXECUTE.
>DATASET NAME DataSet1 WINDOW=FRONT.
>
>
>
> DELETE VARIABLES weight.
>
>
> DISCRIMINANT
>/GROUPS=readmitted(0 1)
>/VARIABLES=age
> admission_type_id discharge_disposition_id admission_source_id
> lengthofstay num_lab_procedures num_procedures num_medications number_outpatient
> number_emergency number_inpatient number_diagnoses
>/ANALYSIS ALL
>/SAVE=CLASS
>/METHOD=WILKS
>/FIN=3.84
>/FOUT=2.71
>/PRIORS EQUAL
>/HISTORY
>/STATISTICS=CORR TABLE
/PLOT=CASES
/CLASSIFY=NONMISSING POOLED.

Should look something like below in R? What is the syntax for a basic discriminant analysis in R using wilks lambda and saving the predicted groups?
> library(readxl)
> Initial_Diabetics_Data_10000 <- read_excel("C:/Users/Downloads/Initial Diabetics Data 10000.xlsx")
> View(Initial_Diabetics_Data_10000)

>df <-df Initial_Diabetics_Data_10000 select(-weight)

>DISCRIMINANT
  ?


text:
Q: How to over come from Database Locked Exception? I am implementing an app where I make database calls frequently.
I open the database using following code:
public DataBaseHelper open() throws SQLException {

      mDbHelper = new DatabaseHelper(this.mCtx);
      this.mDb = mDbHelper.getWritableDatabase();
      return this;
 }

but I get database locked exception in the following line:
 this.mDb = mDbHelper.getWritableDatabase();

Please help me fix this exception.
Thanks in advance

A: this problem arises when you use several connections with your database.
try to avoid creating multiple connections to the database and use the one with all your functions
Database locked exception


text:
Q: "URI is not hierarchical" + private key I just started using Jsch for an SSH connection in my Java program (made for Windows 7). I am running into an issue incorporating a private key into my program. I use the following code:
URL keyFileURL = Main.class.getResource("auth/public_key_1");
URI keyFileURI = keyFileURL.toURI();
jsch.addIdentity(new File(keyFileURI).getAbsolutePath());

Where "auth" is a folder in the same package. The good news is that everything works fine when running it in Eclipse, however it fails when running it as a jar. The error that is given is: "IllegalArgumentException: URI is not hierarchical".
I know the error has to do with pathnames and using URI as a File, but I don't know how else to reference a resource within the jar file without externally importing it (i.e. from file in same folder as jar) AND still have it compatible with Jsch.
Can someone help me with the code to appropriately reference a resource in the program and still have Jsch accept it as a key.
Thank you in advance for any and all help.
Update:
I tried @bmargulies recommended code:
    String authfile;

     URL resUrl = Resources.getResource(Main.class, "auth/public_key_1");
     File tempFile = File.createTempFile("key", ".key");
     ByteSink sink = Files.asByteSink(tempFile);
     try (OutputStream os = sink.openStream()) {
         Resources.copy(resUrl, os);
         authfile = os.toString();
         jsch.addIdentity(authfile);
     }

But it gives me error: "java.io.FileOutputStream (The system cannot find the file specified)". Is there anything I should fix in the code or any other suggestions?

A: That's not how you read a resource. You can't get a File for a resource, only a stream. The URL's for resources don't correspond to files.
If jsch can handle a stream, pass it the results of getResourceAsStream.
If jsch can handle an array of bytes, pass it the results of reading the stream into an array of bytes.
If it must have a file, create a temp file.
In the third case, I'd incorporate Guava and write the code like:
URL resUrl = Resources.getResource(Main.class, "auth/public_key1");
File tempFile = File.createTempFile("key", ".key");
ByteSink sink = Files.asByteSink(tempFile);
try (OutputStream os = sink.openStream()) {
    Resources.copy(resUrl, os);
}

and pass the File's path to jsch.


text:
Q: Difference beetween http://www.app.in and http://app.in What is the difference between http://www.app.com and http://app.com
and how it affects to cross-domain policy of Ajax
I mean i added ajax request in app
                 $.ajax({
                      type: "POST",
                      url: "http://app.in/getToken",
                      contentType: "text/html",
                      success: function(msg) {
                               alert(msg);
                          }
                    });

it works in chrome but not in firefox
Whats the issue?
Thanks

A: See the Same Origin Policy chapter of Michal Zalewski's Browser Security Handbook. www.example.com is a different domain than example.com under same-origin policy.
As Deanna points out, scripts can communicate with each other through iframes or separate windows if the subdomain sets its document.location to the higher domain. However, setting document.location has no effect on XMLHttpRequests; the domain and subdomain cannot send XMLHttpRequests directly to each other.

A: They are different sites.
IIRC, there is a tag you can add to each site saying "this is the same site" for XSS but I can't remember detaisl or how standard it was.
As for a solution, use relative URLs.


text:
Q: Infinispan Distributed Cache Communication Issue in Jboss Multiple Nodes I have a multiple nodes of Jboss on different VMs running in standalone mode. I am using Distributed Infinispan Cache.
Below is the code which I'm using currently.
JChannel jchannel = new JChannel();
jchannel.setDiscardOwnMessages(false);
jchannel.setName("losci_qa");
JGroupsTransport transport = new JGroupsTransport(jchannel);

manager = new DefaultCacheManager(GlobalConfigurationBuilder.defaultClusteredBuilder()
          .transport().transport(transport).nodeName(cacheClusterName+"-node").clusterName(cacheClusterName)
          .build());

ConfigurationBuilder c = new ConfigurationBuilder();
c.clustering().cacheMode(CacheMode.DIST_SYNC).hash().numOwners(numOwners).numSegments(numSegments).capacityFactor(capacityFactor).build();
c.invocationBatching().enable();
c.transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC);
manager.defineConfiguration(DIST, c.build());

The above code is running successfully on individual node.
Issue is, when I want to communicate this cache with both the nodes its not working. When I run above code its print below logs.
Server 1 Logs:
2020-09-24 12:16:45,637 INFO  [org.infinispan.factories.GlobalComponentRegistry] (default task-1) ISPN000128: Infinispan version: Infinispan 'Infinity Minus ONE +2' 9.4.11.Final
2020-09-24 12:16:45,823 INFO  [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (default task-1) ISPN000078: Starting JGroups channel losci_qa
2020-09-24 12:16:45,839 INFO  [stdout] (default task-1)
2020-09-24 12:16:45,839 INFO  [stdout] (default task-1) -------------------------------------------------------------------
2020-09-24 12:16:45,840 INFO  [stdout] (default task-1) GMS: address=losci_qa, cluster=losci_qa, physical address=10.100.101.82:60774
2020-09-24 12:16:45,840 INFO  [stdout] (default task-1) -------------------------------------------------------------------
2020-09-24 12:16:47,845 INFO  [org.jgroups.protocols.pbcast.GMS] (default task-1) losci_qa: no members discovered after 2003 ms: creating cluster as first member
2020-09-24 12:16:47,858 INFO  [org.infinispan.CLUSTER] (default task-1) ISPN000094: Received new cluster view for channel losci_qa: [losci_qa|0] (1) [losci_qa]
2020-09-24 12:16:47,865 INFO  [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (default task-1) ISPN000079: Channel losci_qa local address is losci_qa, physical addresses are [10.10.10.82:60774]

Server 2 Logs:
2020-09-24 17:17:07,686 INFO  [org.infinispan.factories.GlobalComponentRegistry] (default task-1) ISPN000128: Infinispan version: Infinispan 'Infinity Minus ONE +2' 9.4.11.Final
2020-09-24 17:17:07,936 INFO  [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (default task-1) ISPN000078: Starting JGroups channel losci_qa
2020-09-24 17:17:07,958 INFO  [stdout] (default task-1)
2020-09-24 17:17:07,958 INFO  [stdout] (default task-1) -------------------------------------------------------------------
2020-09-24 17:17:07,958 INFO  [stdout] (default task-1) GMS: address=losci_qa, cluster=losci_qa, physical address=10.100.101.83:39828
2020-09-24 17:17:07,958 INFO  [stdout] (default task-1) -------------------------------------------------------------------
2020-09-24 17:17:09,966 INFO  [org.jgroups.protocols.pbcast.GMS] (default task-1) losci_qa: no members discovered after 2007 ms: creating cluster as first member
2020-09-24 17:17:09,981 INFO  [org.infinispan.CLUSTER] (default task-1) ISPN000094: Received new cluster view for channel losci_qa: [losci_qa|0] (1) [losci_qa]
2020-09-24 17:17:09,989 INFO  [org.infinispan.remoting.transport.jgroups.JGroupsTransport] (default task-1) ISPN000079: Channel losci_qa local address is losci_qa, physical addresses are [10.10.10.83:39828]

no members discovered by infinispan cache.
Network Domain is same, cluster name is same.
What I am doing wrong here? How can i make a cluster of both the nodes ? how can i communicate with each node?
TIA

A: First problem could be a firewall. Disable firewalls on both nodes and test without them (you should start them again after fixing the rules).
With no-arg JChannel constructor you default to udp.xml; The PING protocol multicasts hello messages by default on 228.8.8.8:45588; check that multicasts are routed correctly on your machine (e.g. using netcat/nc).
If this won't help, enable TRACE logging to get more insight.


text:
Q: Wamp error in opening .error showing again I have installed Wamp server but not able to use PHP admin my button shows green but not able to login to PHP admin the port which I am using is it whenever I open the localhost it goes to 8080 so once i in the address bar change it to a t from 8080 to 80 in(already in  httpd.conf changes to 80 still 8080 opens up) it opens up  and connects  to the database.but when I try to open a PHP admin want to see my files in database can't login
Where m i going wrong


text:
Q: Bluetooth UUID for car handsfree devices Can anyone help me with the UUID for car handsfree peripheral connections, so I can call scanForPeripherals withServices: [SOME UUID] instead of nil, and only return handsfree. Is there a UUID or CBUUID for this? I hope this can be done at a service level and does not need to look at characteristics. Thanks in advance if you can help me.
func centralManagerDidUpdateState(_ central: CBCentralManager) {

    if central.state == .poweredOn {
        self.centralManager.scanForPeripherals(withServices: [UUID HERE] , options: nil)
    } else {
        print("central not powered on")
    }
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

    print("peripheral discovered")
    peripheralLabel.text = peripheral.name
}

A: Handsfree devices implement the Bluetooth Hands Free Protocol (HFP). This is not a Bluetooth Low Energy GATT service and so does not have a service UUID. They cannot be discovered using Core Bluetooth.


text:
Q: New Relic with Mixpanel When my website was only protected by a login pwd gate, Mixpanel was not showing New relic pings on the Live View but I know it was pinging as it was showing when my website was down. Now for some reason, since we remove the "gate" meaning the website is public, new relic every 20 seconds pings are showing on the Mixpanel Live View. This is terrible. Both new relic and mixpanel have been integrated with Ruby.
Any idea what could cause this?
Thanks
class ApplicationController < ActionController::Base

http_basic_authenticate_with name: "xxxx", password: "xxx", if: Proc.new{ Rails.env.staging? }

# before_filter :check_beta_user
  before_filter :get_tracker

  before_filter :verify_account_existance, :except => [:destroy]
   include SimpleCaptcha::ControllerHelpers

  def check_beta_user
#    return if Rails.env == "development"
    return true unless Rails.env.production?
    session[:beta] = true if request.referrer && request.referrer == "http://signup.mawwell.com/"
    return redirect_to "http://xxxxxx.com/" unless session[:beta]
  end

  def get_tracker
    @tracker =  Mixpanel::Tracker.new(MIXPANEL_CONFIG[:key])

    if current_user
      @user_tracker_id = current_user.email
    else
      if !session[:anonymous_uid]
        session[:anonymous_uid] = SecureRandom.uuid
      end
      @user_tracker_id = session[:anonymous_uid]
    end

  end

  def verify_account_existance
    if I18n.locale == :ar
        I18n.locale = :ar
        cookies['googtrans'] =""
        cookies['googtrans']="/ar"
      elsif I18n.locale == :en
        I18n.locale = :en
        cookies['googtrans'] = ""
        cookies['googtrans']="/en"
      end
    if params.present? and params['action'] == "change_language" and params['controller'] == "users"
      if I18n.locale == :ar
        I18n.locale = :en
        cookies['googtrans'] =""
        cookies['googtrans']="/en"
      elsif I18n.locale == :en
        I18n.locale = :ar
        cookies['googtrans'] = ""
        cookies['googtrans']="/ar"
      end
    end
      if user_signed_in? && !current_user.is_active?
        sign_out(current_user)
        return redirect_to new_user_session_path, :alert => "Your account has been deactivated"
      end
  end

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, :alert => exception.message
  end

end

A: Since the New Relic pinger sends a standard GET or HEAD request and is only reporting if the responding URL returns a 200, it would be interesting to find out if you are seeing the same behavior with other external GET or HEAD requests. Was Mixplanel monitoring external GET or HEAD requests that hit the password gateway? If not, that could explain why you are seeing the pings now. You may want to check with Mixpanel to investigate why the pinger notifications started appearing after removing the password gate.
https://discuss.newrelic.com/t/issue-new-relic-pings-showing-mixpanel/1089/2

A: I found a solution and basically in the Mixpanel tracker, I added a small code saying to ignore new relic pings on the landing page


text:
Q: Optional Parameters in Sanic Server I want to take some optional body parameters in sanic server, just like we do in python.
Example in Python:
def func(a, b=1098):
    return a+b

print(func(2, 2))
print(func(1))

The same thing, I would like to do with sanic server request parameters. For now, I just simply use try block but would like to know a more efficient approach of it.
try:
    data = request.form['data'][0]
except Exception:
    data = 5

Thanks :)

A: Just like you would with any other dict object.
data = int(request.form.get("data", 5))

https://sanic.dev/en/guide/basics/request.html#body
FYI - I wrapped it inint because form data usually will be a string otherwise.


text:
Q: How to Import CSV File and Text File In Type Script
All I need help i'm new on angular-6. My question is how to `import the csv or text file in typescript` like below example for json i import file

1) Example:-
I store the json file in folder under the app folder like
file name login.json
{
    "email": "nabeel.amd9@gmail.com",
    "password": "Balc"
}

and declare the module like json.d.ts

This will allow you to load .json files from disk

declare module "*.json" {
    const value: any;
    export default value;
}

and import this file json file as
//# json import
import jsonData from '../common/json/jsondata.json';
export const JsonResouce = <IJsondata> jsonData;

export interface IJsondata {
    email: string;
    password: string;
}

that above example work for me while the same process i use for parse the csv and text file but it's sow error

ERROR in ./src/app/common/text/info.txt Module parse failed:
Unexpected token (1:9) You may need an appropriate loader to handle
this file type. | Pakistan zindabad
ERROR in ./src/app/common/csv/latlong.csv Module parse failed: Unexpected token
(2:4) You may need an appropriate loader to handle this file type. |
name, lat, long | Pir Mahal, Toba Tek Singh, Punjab, Pakistan
30.767956       72.437813

My Code for both csv and text file are :-
// # csv file
import csvData from './latlong.csv';
//# text import
import textData from '../common/text/info.txt';
//# json import
import jsonData from '../common/json/jsondata.json';

export const TextResource = textData; // not-work
export const JsonResource = <IJsondata> jsonData; // work
export const CsvResource = <ILatLong[]> csvData; // not-work

export interface IJsondata {
    email: string;
    password: string;
}

export interface ILatLong {
    name: string;
    lat: any;
    long: any;
}

declare module "*.txt" {
    const content: string;
    export default content;
}

declare module '*.csv' {
    const value: any;
    export default value;
}

is for csv|txt import file possible in that way?

A: For some files, you might need to configure a special loader in your bundler (Webpack).
JSON files might work out of the box.
Check this CSV loader: https://www.npmjs.com/package/csv-loader
You can try require if the declaration files don't manage to attach the types correctly:
const textData = require('../common/text/jsondata.json') as IJsondata;


text:
Q: Creating files from a list of csv in a directory I have the folder "TEST AIS Florent/test division/division2014/testexport/testloop" with 4 csv files in it: testexport_1;  testexport_2; testexport_3 and testexport_4.
I would like to filter each file and export them to different csv: one for testexport_1, a second one for testexport_2, etc.
For now, my script is
rm(list = ls())
setwd("D:/TEST AIS Florent/test division/division2014/testexport/testloop")
fileList <- list.files(pattern="testexport_.*\\.csv", recursive=TRUE)
#lenghtlist<-as.numeric(length(fileList))

for (file in fileList) {

data2014<-read.table(file, header=F, fill=T, quote="\"", na.strings=c(""," ", "null", "NA"), sep=",")

#########filtering the data here

write.csv(data2014,   file = "data.csv",sep = ";", quote= F, col.names=T, row.names=F)
}

The problem is when I write the csv in my working directory, R is only creating one output file data.csv and is writting over and over this file.
I would like to have
 for testexport_1 --> the output data_1
 and for testexport_2 --> the output data_2,
etc.
Thank you!

A: Construct the file string on the fly by replacing main part of the string with "data".
...
write.csv(data2014,   file = gsub("testexport", "data", file),sep = ";", quote= F, col.names=T, row.names=F)
...


text:
Q: Change URL hash on scroll and keep back button working On a one page layout with fixed top menu and anchor navigation I have a "scrollspy" in place that changes the fragment identifier on scroll, gives the menu link an active class depending on scroll position and animates the scrolling to the anchor with Velocity.js.
Unfortunately what it also does, when clicking the browser back button it takes me through all the steps of the scrolled way, meaning I load the site and scroll down and up a tiny bit and then hit the back button frequently the browser will also scroll down and up but won't go to either the last visited id or back in browser history actually.
Here is the jsfiddle.
// jQuery on DOM ready

// In-Page Scroll Animation with VelocityJS
// ------------------------------------------------ //
// https://john-dugan.com/fixed-headers-with-hash-links/
$('.menu-a').on('click', function(e) {
    var hash  = this.hash,
        $hash = $(hash)

        addHash = function() {
            window.location.hash = hash;
        };

      $hash.velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], complete: addHash });

    e.preventDefault();
});

// ScrollSpy for Menu items and Fragment Identifier
// ------------------------------------------------ //
// https://jsfiddle.net/mekwall/up4nu/
$menuLink           = $('.menu-a')

var lastId,
    // Anchors corresponding to menu items
    scrollItems = $menuLink.map(function(){
    var item = $($(this).attr("href"));
        if (item.length) { return item; }
    });

$(window).scroll(function(){
    // Get container scroll position
    var fromTop = $(this).scrollTop()+ 30; // or the value for the #navigation height

    // Get id of current scroll item
    var cur = scrollItems.map(function(){
        if ($(this).offset().top < fromTop)
        return this;
    });

    // Get the id of the current element
    cur = cur[cur.length-1];
    var id = cur && cur.length ? cur[0].id : "";
    if (lastId !== id) {
        lastId = id;

        // Set/remove active class
        $menuLink
        .parent().removeClass("active")
        .end().filter("[href='#"+id+"']").parent().addClass("active");
    }

    // If supported by the browser we can also update the URL
    // http://codepen.io/grayghostvisuals/pen/EtdwL
    if (window.history && window.history.pushState) {
        history.pushState("", document.title,'#'+id);
    }
});

With the above code the following works fine:

*

*The hash or fragment identifier updates fine when clicked on the menu link using VelocityJS for the scrolling animation.

*The active class is given to the corresponding menu link on scrolling.

*The fragment identifier also updates fine when scrolling instead of clicking the menu link.
Question
Part 1: When you scroll a tiny bit on the fiddle and then hit the back button you will see that the scrollbar "travels" the exact same way, remembering the scrolling that was done.
I need the back button to work like it normally does.
a) Either go back in browser history and return to the page/site you were on and
b) when having clicked an anchor link (i) and then anchor link (ii) and then the back button the page should go back to anchor link (i).
Part 2: Since history.pushState is not supported in IE8 I am looking for a way to use window.location.hash = $(this).attr('id'); instead. No matter what I have tried towards the end of the code I simply cannot get window.location.hash = $(this).attr('id'); to work. I don't really want to use HistoryJS or something for this but am interested to learn this and write it myself.
Apart from the back button broken behaviour all the other behaviour that I want is already there, now I just need to fix the back button behaviour.
edit
I think I might have found a solution here, will test and then reply in detail if I get this to work.
Related:
smooth scrolling and get back button with popState on Firefox - need to click twice
jQuery in page back button scrolling
Modifying document.location.hash without page scrolling
How to Detect Browser Back Button event - Cross Browser

A: To answer the first part of your question, if you don't want to pollute the browser's history, you can use history.replaceState() instead of history.pushState(). While pushState changes the URL and adds a new entry to the browser's history, replaceState changes the URL while modifying the current history entry instead of adding a new one.
There is also a good article including differences between pushState and replaceState on MDN.

A: For older browsers I decided to include https://github.com/devote/HTML5-History-API and with this in place I got the desired behaviour (more or less).
This answers has:
- a scroll spy for the menu items and sets and active class to those on scroll
- the scroll spy also works for the URL hash, setting the correct hash depending on the section that is currently scrolled to
- a scroll stop function that checks when the user has stopped scrolling and then takes the value form the currently active menu item and sets that as the current URL hash. This is done on purpose to not catch the sections' anchors while scrolling but only the anchor of the section that the user scrolls to.
- a smooth scroll with Velocity.js when clicking on the menu links as well as when using the back and forward buttons
- functions that reacts to loading and reloading the page, meaning if you enter the page with a specific URL hash for a section it will animate the scroll to that section and if the page is reloaded it will animate the scroll to the top of the current section
The code is a rough sketch and could possibly use a few tweaks, this is just for demo purpose. I think I am still a beginner to please point out obvious errors so that I can learn from those. All links to where code snippets come from are included as well.
// In-Page Scroll Animation to Menu Link on click
// ------------------------------------------------ //
// https://john-dugan.com/fixed-headers-with-hash-links/
// https://stackoverflow.com/questions/8355673/jquery-how-to-scroll-an-anchor-to-the-top-of-the-page-when-clicked
// http://stackoverflow.com/a/8579673/1010918
// $('a[href^="#"]').on('click', function(e) {
$('.menu-a').on('click', function(e) {

    // default = make hash appear right after click
    // not default = make hash appear after scrolling animation is finished
    e.preventDefault();

    var hash  = this.hash,
        $hash = $(hash)

    $hash.velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], queue: false });
});

// In-Page Scroll Animation to Hash on Load and Reload
// ----------------------------------------------------------- //
// https://stackoverflow.com/questions/680785/on-window-location-hash-change
// hashchange triggers popstate !
$(window).on('load', function(e) {

    var hash  = window.location.hash;
    console.log('hash on window load '+hash);
    $hash = $(hash)

    $hash.velocity("scroll", { duration: 500, easing: [ .4, .21, .35, 1 ], queue: false });

    // if not URL hash is present = root, go to top of page on reload
    if (!window.location.hash){
        $('body').velocity("scroll", { duration: 500, easing: [ .4, .21, .35, 1 ], queue: false });
    }
});

// In-Page Scroll Animation to Hash on Back or Forward Button
// ---------------------------------------------------------- //
$('.menu-a').on('click', function(e) {
    e.preventDefault();
    // keep the link in the browser history
    // set this separately from scrolling animation so it works in IE8
    history.pushState(null, null, this.href);
    return false
});
$(window).on('popstate', function(e) {
    // alert('popstate fired');
    $('body').append('
popstate fired
');
    $('.console1').delay(1000).fadeOut('slow');

    if (!window.location.hash){
        $('body').append('
no window location hash present
');

        $('body').velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], queue: false });

        $('.console2').delay(1000).fadeOut('slow');
    }

    console.log('window.location.hash = '+window.location.hash);
    var hash  = window.location.hash;
    $hash = $(hash)

    $hash.velocity("scroll", { duration: 700, easing: [ .4, .21, .35, 1 ], queue: false });
});

// ScrollSpy for Menu items only - gives selected Menu items the active class
// ------------------------------------------------------------------------ //
// Does not update fragment identifier in URL https://en.wikipedia.org/wiki/Fragment_identifier
// https://jsfiddle.net/mekwall/up4nu/
    var lastId,

    // Anchors corresponding to menu items
    scrollItems = $menuLink.map(function(){
        var item = $($(this).attr("href"));
        // console.table(item);
        if (item.length) { return item; }
    });

    // Give menu item the active class on load of corresponding item
    function scrollSpy () {

        // Get container scroll position
        var fromTop = $(this).scrollTop()+ $menuButtonHeight;

        // Get id of current scroll item
        var cur = scrollItems.map(function(){
            if ($(this).offset().top < fromTop)
            return this;
        });

        // Get the id of the current element
        cur = cur[cur.length - 1];
        var id = cur && cur.length ? cur[0].id : "";

        if (lastId !== id) {
            lastId = id;
            // Set/remove active class
            $menuLink
            .parent().removeClass("active").end()
            .filter("[href='#"+id+"']").parent().addClass("active");
        }

        // Active Menu Link href Attribute
        activeMenuLinkHref = $('.menu-li.active > .menu-a').attr('href');
        // console.log('activeMenuLinkHref '+activeMenuLinkHref);
    }
    scrollSpy()

    $(window).scroll(function(e){
        scrollSpy()
    });

// On Stop of Scrolling get Active Menu Link Href and set window.location.hash
// --------------------------------------------------------------------------- //

// Scroll Stop Function
//---------------------//
// https://stackoverflow.com/questions/8931605/fire-event-after-scrollling-scrollbars-or-mousewheel-with-javascript
// http://stackoverflow.com/a/8931685/1010918
// http://jsfiddle.net/fbSbT/1/
// http://jsfiddle.net/fbSbT/87/

(function(){
    var special = jQuery.event.special,
        uid1 = 'D' + (+new Date()),
        uid2 = 'D' + (+new Date() + 1);
    special.scrollstart = {
        setup: function() {
            var timer,
                handler =  function(evt) {
                    var _self = this,
                        _args = arguments;
                    if (timer) {
                        clearTimeout(timer);
                    } else {
                        evt.type = 'scrollstart';
                        // throws "TypeError: jQuery.event.handle is undefined"
                        // jQuery.event.handle.apply(_self, _args);
                        // solution
                        // http://stackoverflow.com/a/20809936/1010918
                        // replace jQuery.event.handle.apply with jQuery.event.dispatch.apply
                        jQuery.event.dispatch.apply(_self, _args);
                    }
                    timer = setTimeout( function(){
                        timer = null;
                    }, special.scrollstop.latency);
                };
            jQuery(this).bind('scroll', handler).data(uid1, handler);
        },
        teardown: function(){
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid1) );
        }
    };
    special.scrollstop = {
        latency: 250,
        setup: function() {
            var timer,
                    handler = function(evt) {
                    var _self = this,
                        _args = arguments;
                    if (timer) {
                        clearTimeout(timer);
                    }
                     timer = setTimeout( function(){
                        timer = null;
                        evt.type = 'scrollstop';
                        // throws "TypeError: jQuery.event.handle is undefined"
                        // jQuery.event.handle.apply(_self, _args);
                        // solution
                        // http://stackoverflow.com/a/20809936/1010918
                        // replace jQuery.event.handle.apply with jQuery.event.dispatch.apply
                        jQuery.event.dispatch.apply(_self, _args);
                    }, special.scrollstop.latency);
                };
            jQuery(this).bind('scroll', handler).data(uid2, handler);
        },
        teardown: function() {
            jQuery(this).unbind( 'scroll', jQuery(this).data(uid2) );
        }
    };

})();

// Scroll Stop Function Called
//----------------------------//

$(window).on("scrollstop", function() {

    // window.history.pushState(null, null, activeMenuLinkHref);
    // window.history.replaceState(null, null, activeMenuLinkHref);

    // http://stackoverflow.com/a/1489802/1010918 //
    // works best really
    hash = activeMenuLinkHref.replace( /^#/, '' );
    console.log('hash '+hash);
    var node = $( '#' + hash );
    if ( node.length ) {
      node.attr( 'id', '' );
      // console.log('node.attr id'+node.attr( 'id', '' ));
    }
    document.location.hash = hash;
    if ( node.length ) {
      node.attr( 'id', hash );
    }
});

CSS
.console1{
    position: fixed;
    z-index: 9999;
    top:0;
    right:0;
    background-color: #fff;
    border: 2px solid red;
}

.console2{
    position: fixed;
    z-index: 9999;
    bottom:0;
    right:0;
    background-color: #fff;
    border: 2px solid red;
}

I will also supply a jsfiddle in due time. ;)


text:
Q: How can I place includegraphics in the margin such that it lines up with text? I want to place small things, mostly images (hence \includegraphics) in the outer margin of a page in a way that I can line it up with a piece of text (e.g. heading) or another \includegraphics in the text.

A: Images have their reference point on the bottom edge, so that aligns with the text baseline in a standard \marginpar

\documentclass{article}

\usepackage{graphicx}
\setlength\marginparsep{1pt}% moved closer to show alignment
\begin{document}

One two three four five six seven eight.
One two three four five six seven eight.
\includegraphics[height=.7em]{example-image}
Red yellow blue green black white brown.%
\marginpar{\includegraphics[height=.7em]{example-image-a}}
One two three four five six seven eight.
One two three four five six seven eight.
One two three four five six seven eight.
Red yellow blue green black white brown.
Red yellow blue green black white brown.
Red yellow blue green black white brown.
One two three four five six seven eight.%
\marginpar{\includegraphics[height=.7em]{example-image-a}}
One two three four five six seven eight.
Red yellow blue green black white brown.
Red yellow blue green black white brown.
One two three four five six seven eight.

\end{document}


text:
Q: Knockout js + dropdown(select) value binding + IE browsers family It is a badly known issue when selects in IE show only the first letter after dynamical initialization. (See this SO question)
But what is the best way to re-render dropdowns after data binding via knockout?

A: I hadn't seen this bug before. You could do something like.
<select data-bind="options: youroptions, value: somevalue, visible: !loading()"
</select>

Then in your code
self.loading(true);
doAjax(function(result) {
    self.youroptions(result);
    self.loading(false);
});

This would do as the fix suggests. Not very elegant.
Hope this helps.


text:
Q: How can I hide a  arrow in Firefox 30+? This hack used to work in <= Firefox 29 to remove a <select> arrow:
text-overflow: '';
text-indent: 0.01px;
-moz-appearance: none;

It no longer works in Firefox 30. Arrow is back.

*

*Codepen for hack that works in Firefox 29

*Related bug (now fixed in Fx 35b)

Does anyone know a way to achieve the same effect?
Note1: I'm not interested in solutions that overlay the arrow with another element, or solutions that nest the select element and do a overflow:hidden.
Note2: I tried all -moz-appearance possibilities. They either add default styling I cannot override, don't allow custom styling (border and background, specifically), or the arrow is still visible.
Update: it works again in Firefox 35 (currently in beta) using -moz-appearance: none, making this look consistent in all latest browsers (Tested in IE11, Firefox 35b, Chrome 39, Safari 8): http://jsfiddle.net/phd5pu9x/

A: I fixed my this issue by giving some style to div and select individually.
Anyone can change his width and other style properties a/c to needs. :)
Here is the js fiddle for it. JSFIDDLE

<select id="select" class="common-dropdown-project-select">
    <option>
        apple
    </option>
    <option>
        blackberry
    </option>
    <option>
       pumpkin
    </option>
</select>

.common-dropdown-small-div{
border: 1px solid rgb(208, 208, 208);
overflow: hidden;
width: 220px;  }

.common-dropdown-project-select{
  width: 100% !important;
background-image: url("http://upload.wikimedia.org/wikipedia/en/f/f1/Down_Arrow_Icon.png");
background-position: 97% 60%, 0 0 ! important;
 background-repeat: no-repeat;
background-size: 25px 16px;
border: none  ! important;
outline : medium none !important;
display: inline-flex !important;
height: 33px !important;
vertical-align: top;
-webkit-appearance: none; }

select::-ms-expand {
display: none;}

A: Put the select in another container which has overflow: hidden;, make the select wider than the container. If you want a border, add it to the container.
An example is the select at the bottom of this page:
https://mozillians.org/en-US/

A: You can use this solution for firefox, using vendor pseudo class :-moz-any() and pointer events only for mozilla and do not affect other browsers, because both is valid since version 3.6.
here is a jsbin example http://jsbin.com/pozomu/4/edit

A: /* For mozilla Firefox 30.0+ I used the following to coverup the reappearing arrow: */
@-moz-document url-prefix() {
.yourClass:after {
    position: absolute;
    margin-left: -25px;
    border-radius: 4px;
    content: url('../images/pathToYourDownArrowImage.svg');
    pointer-events: none;
    overflow: hidden;
}

/* I still use this to move the text over */
.yourClass select {
    text-overflow: '';
    text-indent: -1px;
    -moz-appearance: none;
    background: none;
}

}

A: Firefox > 29 -moz-appearance:none; working, But have a problem with width, we extend the width of select from 100 to 110% to hide, but it affects the design of a forms, So i just hide it with a div and over come it,
Check the codepen version
http://codepen.io/ssbalakumar/pen/jgLEq

A: As @mircea c alluded to ...
If your HTML looks like this:

   <select>
     <option>Here is the first option</option>
     <option>The second option</option>
     <option>The thrid option</option>
   </select>

Then you can remove the dropdown arrow in Firefox 30+
.styled-select {
  overflow: hidden;
  width: 200px;
}

@-moz-document url-prefix(){
  .styled-select select { width: 110%; }
}

Working demo: codepen
FYI: The same technique works in IE 8 & 9, just use a conditional comment instead of @-moz-document url-prefix()


text:
Q: Edit (every page of a) Postscript file manually I want to (manually) insert additional postscript commands in a postscript file that was converted from a PDF file via ghostscript's pdf2ps. For the purpose of testing I created a PDF file from the following file using pdflatex:
\documentclass[a4paper]{article}
\begin{document}
Mostly empty.
\end{document}

In the converted postscript file I make the following edit:
...
%%Page: 1 1
%%PageBoundingBox: 0 0 595 841
%%BeginPageSetup
4 0 obj
<</Type/Page/MediaBox [0 0 595.28 841.89]
/Parent 3 0 R
/Resources<</ProcSet[/PDF]
/Font 8 0 R
>>
/Contents 5 0 R
>>
endobj
%%EndPageSetup
% BEGIN MANUAL EDIT
0 setgray 0 0 moveto 595 841 lineto stroke
% END MANUAL EDIT
5 0 obj
<</Length 257>>stream
q 0.1 0 0 0.1 0 0 cm
0 G
0 g
q
10 0 0 10 0 0 cm BT
/R6 9.9626 Tf
1 0 0 1 139.746 706.129 Tm
[(M)-0.699638(os)-0.399443(t)-0.900585(l)-0.798886(y)-333.819(e)-0.400668(m)-0.300195(p)-0.599165(t)26.0974(y)83.192(.)-0.800112]TJ
154.421 -615.691 Td
(1)Tj
ET
Q
Q

endstream
endobj
pagesave restore
%%PageTrailer
%%Trailer
end
%%EOF

Instead of producing a diagonal line the postscipt/PDF file remains (seemingly) unchanged. However, if I alter the page dimensions from A4 to letter size the line is shown:
%%Page: 1 1
%%PageBoundingBox: 0 0 612 792
%%BeginPageSetup
4 0 obj
<</Type/Page/MediaBox [0 0 612 792]
...

I am obviously missing something here (which is not surprising given my rudimentary knowledge of postscript). My question is: How can I make the line appear while keeping the page dimensions unchanged?
P.S.: A comment I stumbled across mentioned that pdftops (from poppler-utils) is in some sense superior to pdf2ps. Indeed, inserting commands into the converted postscript file immediately before the showpage command (which is not there at all when using pdf2ps) worked fine. So I have probably already found a solution to my problem. However, I would like to learn what the page dimensions have to do with it when using pdf2ps.

Solution
Thanks to KenS's advice and referring to his answer to this question I was able to achieve the desired effect by adding an EndPage procedure to the postscript file:
<<
/EndPage
{
  exch pop 2 lt
  {
    gsave
    0 0 translate
    0 setgray 0 0 moveto 596 842 lineto stroke
    grestore
    true
  }{false} ifelse
} bind
>> setpagedevice

(This assumes the page size is a4.)

A: PostScript is a write-only language :-)
Seriously, its a programming language. In order to understand what's going on, you need to understand the program, which in the case of the output from Ghostscript's ps2write device, is distinctly non-trivial.
The syntax is basically PDF, with a prolog program which interprets it in PostScript terms.
The program will use showpage, it does it when the procedure EndStream is executed, which is (basically) when the endobj keyword is encoutnered in a page stream. You'll see that it looks like:
ET
Q
Q
Q

endstream
endobj
%%Page: 2 2

You could place anything you like between the endstream and the endobj, but you need to be aware that the graphics state at that point is determined by whatever operations have already taken place. This can include scaling, oration, skeing, flipping the vertical axis, etc. So simply inserting some PostScript into there is unlikely to work. You could do an initgraphics which would at least reset the graphics state to a known setup.
As a test I ran Ghostscript'sd ps2write device like this:
gs -sDEVICE=pdfwrite -o out.ps -c "showpage" -f
which produces a PostScript program where the (effective) content is:
%%EndResource
%%EndProlog
%%Page: 1 1
%%PageBoundingBox: 0 0 595 842
%%BeginPageSetup
4 0 obj
<</Type/Page/MediaBox [0 0 595 842]
/Parent 3 0 R
/Resources<</ProcSet[/PDF]
>>
/Contents 5 0 R
>>
endobj
%%EndPageSetup
5 0 obj
<</Length 23>>stream
q 0.1 0 0 0.1 0 0 cm
Q

endstream
endobj
%%Trailer
end
%%EOF

I then modified this more or less as you suggested:
%%EndPageSetup
0 setgray 0 0 moveto 595 842 lineto stroke
5 0 obj
<</Length 23>>stream
q 0.1 0 0 0.1 0 0 cm
Q

endstream
endobj
%%Trailer

For me this produced the expected stroke from bottom left to top right. Obviously without the PostScript file you originally produced I can't tell you why your experience is different. (no I'm not in a position to run latex to produce such a thing, and even if I did I have no way to know which version of Ghostscript and the other tools you used).
My guess would be that 'something' in your PDF file overwrote the entire page, its not entirely uncommon.


text:
Q: How to guarantee that a function is inlined in C++ in C++, a function can be defined to be inline using inline key word. It is like the programmer has requested from the compiler to insert the complete body of the function in every place that the function is called.
But as I know compilers are not obligated to respect this request. So is there any way to guarantee that a function is inlined?

A: Nope. Actually inlining a function is a complete implementation detail, and many functions cannot be inlined. This makes the existence of an inline forcing mechanism impossible. Even compilers that offer keywords like __forceinline (VC++) won't inline functions with that qualifier under some circumstances. And the page carries a very apt warning about misusing this qualifier.

A: Use __forceinline in VC++ and __attribute__((always_inline)) in g++

A: As this isn't covered by the standard, it depends on the compiler you're using. The compiler's documentation will tell you if there is a feature for forcing a function to be inlined, and how to use it. The documentation should also tell you the limits of that feature, such as for recursive calls in a non-tail position.

A: If you are using a Microsoft compiler, you may use __forceinline, as explained here:
http://msdn.microsoft.com/en-us/library/z8y1yy88%28v=vs.71%29.aspx
I do not know of a way to force inlining in g++ or other compilers.

A: By putting the definition of a function right into its declaration in the header, the function gets the highest chances to be inlined.
class TheClass
{
public:
    static void DoSomething () // declaration
    {
        // the function's code (definition) goes here
    };
};

// in the same header..

void DoOtherThings () // declaration
{
    // the function's code (definition) goes here
}

In any case, there is no strong guarantee, perhaps even if you use the compiler-specific keyword for inline forcing.
A 100% percent guarantee would be transforming your function into a C++ macro and using the macro instead of referring to the function. If you function has multiple lines, place a \ (a space followed by a backslash) where you want to have a line break in your "macro-function".

A: I cannot imagine that there´s a way to do that. It is mainly dependant on the compiler. Another solution would be to use #define macro to define your function


text:
Q: TLS mutual authentication on a spefic subdomain I'm not sure if this is the best place to ask this question, or if perhaps it's to vague, but here goes anyway.
I have a web server (Apache) which hosts a personal wiki (dokuwiki), as well as a blog (Wordpress). The wiki is located at "wiki.example.com", whereas the blog is just located at "www.example.com". I'm about implement one way TLS/SSL encryption across the example, however I would also like to set up two way TLS/SSL encryption (client authentication) on only the "wiki.example.com" subdomain so that only specific users with the certificate can access it.

*

*www.example.com - Anyone can access this

*wiki.example.com - only users with a certificate can access this

Is this possible, and if it is, does anyone have any resources explaining how you would go about setting it up?

A: Yes, it is possible.
Create two different virtual hosts for both the websites
But for two-way authentication, the virtual host should contain this two parameters enabled
SSLVerifyClient require
SSLCACertificateFile
You can get free SSl related support on this website www.ssl.support


text: Q: Martian tries to understand High heels I remember excellent story where alien (might not have been Martian) reports back on viewing earthlings and the description of half of them shackled in torturous footwear. And brilliant descriptions of pushchair pushing too. But I cannot find it. Anyone any clues? I think it was circa '79? Because I was at uni and link it with 'a Martian sends a postcard home' poem by Craig raine but it's not that. Want to publish an excerpt of it as postcard for Leeds Postcards. Hope someone might guide me in right direction. Thanks for reading


text:
Q: How to prevent default Shortcut alt+b by Firefox and IE via JS? I need to implement a shortcut alt+b, calling a function. My problem is, that everytime i press this shortcut, a Firefox and an IE open a Menu-Bar "Edit". Is there any solution to prevent this default behavior? Or maybe it is possible to close this menu-bar after calling a function?
What i have tried but without success
     $(document).keydown(function(e) {

         if (e.keyCode == 18 || e.which==18)
         {
            e.preventDefault();
         }
      });

A: Try this, it will only run the console.log() if you hit Alt+B. Replace the console with anything you want.

$(window).keydown(function(event) {
  if(event.altKey && event.keyCode == 66) {
    event.preventDefault();
    console.log("Hey! alt+B event captured!");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: This seems to work for me:
$(document).keydown(function(e) {

    // check for alt+b
    if (e.keyCode == 66 && e.altKey === true) {
        e.preventDefault();
    }
});

You need to check the press of b, not alt.


text:
Q: Загрузить контент страницы через Ajax Мне нужно загрузить статью на сайт с помощью Ajax, в инете есть следующий пример:
Создадим 3 файла.
index.html

   Какой-то контент...

Какой-то контент...

блок вывода с AJAX:

блок вывода с AJAX:

ajax.js
(function($) {
$(function() {
  $("#blockajax").load("text-dlya-ajax.html");
})
})(jQuery)

text-dlua-ajax.html
Этот текст будет выведен через AJAX

Но данный пример не работает, возможно кто-то подскажет в чем дело. Сайт находиться локально на компе

A: Сделайте запрос на backend с идентификатором статьи, найдите её в бд, сформируйте представление(view) и сделайте append в блок. Пример ниже
$.ajax({
  method: "POST",
  url: "your-backend-url",
  data: { id: your-article-id}
  success: function(response) {
      //response is rendered view
     $('#your-block-id-where-to-render').append(response);
  }
})

В Вашем случае:
var html = $.get("text-dlya-ajax.html", function(data){
    $(this).children("div:first").html(data);
});

$("#blockajax").append(html);


text:
Q: How to effectively set up MySQL Users and Roles in the production server WITHOUT Visual Studio? So far I have been using the WebSite Administration Tool built in Visual Studio 2010 to manage Users and Roles along with MySQL Membership and Roles Provider.
Now, I have deployed the application to the production server and I am getting the following error:

Even if I tried to copy one of the roles and one of the users from my local DB to the one used by the production server, it didn't quite work and I keep getting the same error. At least, I'm sure that's the cause of the error because I did a remote debugging which led me to find it.
At this point I am very confused on how to get it working properly. So, any help or guidance would be really appreciated.
EDIT: At this point the User has been already authenticated in the login page using the connectionString to the production DB server. For that reason, I have dismissed any kind of problems related to the connectionString. I get this error while loading the masterPage where the role is needed in order to choose which menu to display.

A: The exception message says it all: It cannot connect to the database. Verify that your production DB server is running, that the connection string is correct and that you have network connectivity (including name resolution) from the web server to the DB server.

A: The solution for this problem was to create the mysql_aspnet_membership provider by granting full access through the machine.config and autogenerating the schema, instead of manually creating the membership tables in the database, which I though there could have been a valid way to create the db.
Afterwards, this didn't break anymore.


text:
Q: Doesn't Isotope play nice with Flexbox, or is it just me? I have a basic layout with flexbox.
CSS:
.grid {
    display: flex;
    flex-wrap: wrap;
}
.element-item {
    flex-direction: row;
    width: calc(100% / 2);
}
.element-item img {
    width: 100%;
    height: 16em;
    object-fit: cover;
}

HTML:

Title

Taxonomy

    ...

All good, the button filter navigation is working too. But when I init Isotope in my .js file, the whole layout collapses, the images disappear and everything is stacked on top of each other.
jQuery::
// init Isotope
var $grid = $('.grid').isotope({
    // options
    itemSelector: '.element-item',
});

// filter items on button click
$('.filter-button-group').on( 'click', 'button', function() {
    var filterValue = $(this).attr('data-filter');
    $grid.isotope({ filter: filterValue });
});

Doesn't Isotope "work" well with Flexbox? Or am I missing some Isotope jQuery option. Or haven't I been precise enough with the Flexbox properties?
Thanks.
jsfiddle by request https://jsfiddle.net/Lyqdguvz/

A: As far as I can tell the later versions of isotope play nicely with flex (I am currently using it with a flexbox project), but you need to add the layout mode option to your js:
// init Isotope
var $grid = $('.grid').isotope({
    // options
    itemSelector: '.element-item',
    layoutMode: 'fitRows'
});

There is also other layout mode options available - check out this resource:
http://isotope.metafizzy.co/layout-modes.html

A: Okay I solved it.
What I forgot to include was that I had a .grid parent container #main set to display: flex and flexwrap: wrap. Removing that containers display properties solved it.


text:
Q: How can I animate a histogram of occurrences using Plotly Python? I want to animate a histogram over a DataFrame index, so that as the index increases, the bins fill up. My DataFrame is structured like this:

Index
Ingredient

1
Onions

2
Onions

3
Garlic

4
Onions

5
Tomato

6
Tomato

7
Onions

At the beginning of the animation, all bins should be initialized at 0, and fill up as the index increases. I have tried the following using plotly.express.histogram.
idx = df.index
fig = px.histogram(df, x="Ingredient",
    animation_frame=idx, animation_group=idx, cumulative=True,
)

The result I get is an animated histogram with only one bin that switches between the ingredient names as it goes through the DataFrame, with the height of the bin staying constant at 1.

A: *

*approach is to prepare a dataframe that is ready for animation

*then it's simple to create an animated bar to create figure you have defined

import pandas as pd
import plotly.express as px
import io

df = pd.read_csv(
    io.StringIO(
        """Index,Ingredient
1,Onions
2,Onions
3,Garlic
4,Onions
5,Tomato
6,Tomato
7,Onions"""
    )
)

ings = df["Ingredient"].value_counts()
df2 = pd.concat(
    [
        pd.DataFrame({"Ingredient": ings.index})
        .merge(
            df.loc[df["Index"].le(i)].groupby("Ingredient", as_index=False).size(),
            on="Ingredient",
            how="left",
        )
        .assign(Index=i)
        .fillna(0)
        for i in range(df["Index"].min(), df["Index"].max() + 1)
    ]
)

px.bar(df2, x="Ingredient", y="size", animation_frame="Index").update_layout(
    yaxis={"range": [0, ings.max()]}
)