text:
Q: Android : java.lang.RuntimeException: Unable to instantiate activity ComponentInfo: java.lang.NullPointerException I am trying to record audio, after that should play record immediately. Where I am going wrong. Please help me out. I am not getting. showing null pointer exception...
Here is the code
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

public class Audio_testActivity extends Activity {
private String LOG_TAG = null;

/* variables which are required to generate and manage the UI of the App */
// private RecordButton mRecordButton = null;
private Button recordBtn, stopBtn, playBtn;

/*
 * variables which are required for the actual functioning of the recording
 * and playing
 */
private AudioRecord recorder = null;
private AudioTrack player = null;
private AudioManager audioManager = null;
private int recorderBufSize, recordingSampleRate;
private int trackBufSize;
private short[] audioData;
private boolean isRecording = false, isPlaying = false;
private Thread startRecThread;

private AudioRecord.OnRecordPositionUpdateListener posUpdateListener;

/**
 * constructor method for initializing the variables
 */
public Audio_testActivity() {
    super();
    LOG_TAG = "Constructor";
    recorderBufSize = recordingSampleRate = trackBufSize = 0;

    // init function will initialize all the necessary variables ...
    init();

    if (recorder != null && player != null) {
        Log.e(LOG_TAG, "recorder and player initialized");
        audioData = new short[recorderBufSize / 2]; // since we r reading
                                                    // shorts

    } else {
        Log.e(LOG_TAG, "Problem inside init function ");
    }
    posUpdateListener = new AudioRecord.OnRecordPositionUpdateListener() {
        int numShortsRead = 0;

        @Override
        public void onPeriodicNotification(AudioRecord rec) {
            // TODO Auto-generated method stub
            // String LOG_TAG = Thread.currentThread().getName();
            // Log.e(LOG_TAG, "inside position listener");
            audioData = new short[recorderBufSize / 2]; // divide by 2 since
                                                        // now we are
                                                        // reading shorts
            numShortsRead = rec.read(audioData, 0, audioData.length);
            player.write(audioData, 0, numShortsRead);

        }

        @Override
        public void onMarkerReached(AudioRecord recorder) {
            // TODO Auto-generated method stub
            Log.e(LOG_TAG, "Marker Reached");
        }
    };
    // listener will be called every time 160 frames are reached
    recorder.setPositionNotificationPeriod(160);
    recorder.setRecordPositionUpdateListener(posUpdateListener);

    Log.e(LOG_TAG, "inside constructor");
}

private void init() {
    LOG_TAG = "initFunc";
    // int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
    short audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    // for (int rate : mSampleRates) {
    this.recordingSampleRate = AudioTrack
            .getNativeOutputSampleRate(AudioManager.STREAM_MUSIC);
    try {
        // Log.d(LOG_TAG, "Attempting rate " + rate + "Hz, bits: " +
        // audioFormat);
        int bufrSize = AudioRecord.getMinBufferSize(
                this.recordingSampleRate, AudioFormat.CHANNEL_IN_MONO,
                audioFormat);

        // lets find out the minimum required size for AudioTrack
        int audioTrackBufSize = AudioTrack.getMinBufferSize(
                this.recordingSampleRate, AudioFormat.CHANNEL_OUT_MONO,
                audioFormat);

        if (bufrSize != AudioRecord.ERROR_BAD_VALUE
                && bufrSize != AudioRecord.ERROR) {
            // check if we can instantiate and have a success
            if (audioTrackBufSize >= bufrSize) {
                this.recorderBufSize = audioTrackBufSize;
            } else {
                this.recorderBufSize = bufrSize;
            }

            AudioRecord rec = new AudioRecord(
                    MediaRecorder.AudioSource.DEFAULT,
                    this.recordingSampleRate, AudioFormat.CHANNEL_IN_MONO,
                    audioFormat, this.recorderBufSize);

            if (rec != null
                    && rec.getState() == AudioRecord.STATE_INITIALIZED) {

                // storing variables for future use . . .
                // this.recordingSampleRate = rate;
                // this.recorderBufSize = bufrSize;

                Log.e(LOG_TAG,
                        "Returning..(rate:channelConfig:audioFormat:recorderBufSize)"
                                + this.recordingSampleRate + ":"
                                + AudioFormat.CHANNEL_IN_MONO + ":"
                                + audioFormat + ":" + this.recorderBufSize);

                // Now create an instance of the AudioTrack
                // int audioTrackBufSize = AudioTrack.getMinBufferSize(rate,
                // AudioFormat.CHANNEL_OUT_MONO, audioFormat);

                Log.e(LOG_TAG, "Audio Record / Track / Final buf size :"
                        + bufrSize + "/ " + audioTrackBufSize + "/ "
                        + this.recorderBufSize);

                this.player = new AudioTrack(AudioManager.STREAM_MUSIC,
                        this.recordingSampleRate,
                        AudioFormat.CHANNEL_OUT_MONO, audioFormat,
                        this.recorderBufSize, AudioTrack.MODE_STREAM);

                this.recorder = rec;
                this.player.stop();
                this.player.flush();
                this.player.setPlaybackRate(this.recordingSampleRate);
                return;
            }
        }
    } catch (IllegalArgumentException e) {
        Log.d(LOG_TAG,
                this.recordingSampleRate + "Exception, keep trying.", e);
    } catch (Exception e) {
        Log.e(LOG_TAG, this.recordingSampleRate + "Some Exception!!", e);
    }
    // for loop for channel config ended here. . . .
    // for loop for audioFormat ended here. . .
    // }// for loop for sampleRate
    return;
}

private void startPlaying() {
    LOG_TAG = "startPlaying";

    Log.e(LOG_TAG, "start Playing");
}

private void stopPlaying() {
    LOG_TAG = "stopPlaying";

    Log.e(LOG_TAG, "stop Playing");
}

private void startRecording() {
    LOG_TAG = "startRecording";

    /* start a separate recording thread from here . . . */
    startRecThread = new Thread() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            android.os.Process
                    .setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
            // String LOG_TAG = Thread.currentThread().getName();
            if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
                recorder.startRecording();
            }
            // Log.e(LOG_TAG, "running" +recorder.getRecordingState());
            while (recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
                recorder.read(audioData, 0, audioData.length);
                try {

                    Thread.sleep(1000); // sleep for 2s
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    Log.e("run Method", "recorder thread is interrupted");
                    e.printStackTrace();
                }
            }
        }
    };
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    audioManager.setSpeakerphoneOn(false);
    player.flush();
    player.play();
    startRecThread.start();

    Log.e(LOG_TAG, "start Recording");
}

private void stopRecording() {
    LOG_TAG = "stopRecording";
    recorder.stop();

    if (startRecThread != null && startRecThread.isAlive()) {
        startRecThread.destroy();
        startRecThread = null;
    }

    player.stop();
    player.flush();
    Log.e(LOG_TAG, "stop Recording");
}

private void stop() {
    if (isRecording) {
        isRecording = false;
        stopRecording();
    }
    if (isPlaying) {
        isPlaying = false;
        stopPlaying();
    }
    recordBtn.setEnabled(true);
    playBtn.setEnabled(true);
}

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    LOG_TAG = "onCreate";
    // Log.e(LOG_TAG, "Create Called");
    // getting the audio service
    audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    LinearLayout ll = new LinearLayout(this);

    // creating Buttons one by one . . . .
    // button to start the recording process
    recordBtn = new Button(this);
    recordBtn.setText("Record");
    recordBtn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            recordBtn.setEnabled(false);
            playBtn.setEnabled(false);
            isRecording = true;
            startRecording();
        }
    });
    // single button to stop recording and playing as applicable
    stopBtn = new Button(this);
    stopBtn.setText("Stop");
    stopBtn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            stop();
        }
    });
    // button to play the recorded sound
    playBtn = new Button(this);
    playBtn.setText("Play");
    playBtn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            // reverse the isPlaying
            isPlaying = true;
            recordBtn.setEnabled(false);
            playBtn.setEnabled(false);
            startPlaying();
        }
    });

    ll.addView(recordBtn, new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1));

    ll.addView(playBtn, new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1));

    ll.addView(stopBtn, new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1));

    setContentView(ll);
}

@Override
protected void onDestroy() {
    // Clean up code . ..
    super.onDestroy();
    if (recorder != null)
        recorder.release();
    if (startRecThread != null && startRecThread.isAlive())
        startRecThread.destroy();
    if (recorder != null)
        recorder.release();
    if (player != null)
        player.release();
    startRecThread = null;
    recorder = null;
    player = null;
    recordBtn = null;
    stopBtn = null;
    playBtn = null;
    audioData = null;
    System.gc();
}

}

Here is the error LOGCAT file.....
05-17 09:53:01.402: E/AndroidRuntime(367): FATAL EXCEPTION: main
05-17 09:53:01.402: E/AndroidRuntime(367): java.lang.NullPointerException
05-17 09:53:01.402: E/AndroidRuntime(367):  at audio.xxx.com.Audio_testActivity.startRecording(Audio_testActivity.java:232)
05-17 09:53:01.402: E/AndroidRuntime(367):  at audio.xxx.com.Audio_testActivity.access$9(Audio_testActivity.java:194)
05-17 09:53:01.402: E/AndroidRuntime(367):  at audio.xxx.com.Audio_testActivity$3.onClick(Audio_testActivity.java:291)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.view.View.performClick(View.java:2485)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.view.View$PerformClick.run(View.java:9080)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.os.Handler.handleCallback(Handler.java:587)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.os.Handler.dispatchMessage(Handler.java:92)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.os.Looper.loop(Looper.java:123)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.app.ActivityThread.main(ActivityThread.java:3683)
05-17 09:53:01.402: E/AndroidRuntime(367):  at java.lang.reflect.Method.invokeNative(Native Method)
05-17 09:53:01.402: E/AndroidRuntime(367):  at java.lang.reflect.Method.invoke(Method.java:507)
05-17 09:53:01.402: E/AndroidRuntime(367):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-17 09:53:01.402: E/AndroidRuntime(367):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-17 09:53:01.402: E/AndroidRuntime(367):  at dalvik.system.NativeStart.main(Native Method)

Let me know where I am wrong.. Help me Please.!!!!!!!!!

A: if you are getting the "Problem inside init function" and from your code
if (recorder != null && player != null) {
        Log.e(LOG_TAG, "recorder and player initialized");
        audioData = new short[recorderBufSize / 2]; // since we r reading
                                                    // shorts

    } else {
        Log.e(LOG_TAG, "Problem inside init function ");
    }

recorder may be null. Please check that.


text:
Q: Pyinstaller No Module Tkinter I have created a python script using Tkinter and am trying to package it using a Mac with Pyinstaller.  Pyinstaller creates the executable but when I try to run it says the Tkinter module is missing.  I realize there are several similar questions like this on SO but none of the solutions have worked for me.
Here is the top of my main.py script:
#!/usr/bin/env python
import sys
import os
import traceback
import json
import time
import Tkinter

Here is my pyinstaller version:
$ pyinstaller --version
3.3.dev0+483c819

I run pyinstaller with this command:
$ pyinstaller main.py

Here is the output of that command:
30 INFO: PyInstaller: 3.3.dev0+483c819
30 INFO: Python: 3.4.3
34 INFO: Platform: Darwin-15.6.0-x86_64-i386-64bit
35 INFO: wrote /Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container/main.spec
36 INFO: UPX is not available.
38 INFO: Extending PYTHONPATH with paths
['/Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container',
 '/Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container']
38 INFO: checking Analysis
38 INFO: Building Analysis because out00-Analysis.toc is non existent
38 INFO: Initializing module dependency graph...
39 INFO: Initializing module graph hooks...
40 INFO: Analyzing base_library.zip ...
1395 INFO: Processing pre-find module path hook   distutils
2445 INFO: running Analysis out00-Analysis.toc
2452 INFO: Caching module hooks...
2454 INFO: Analyzing /Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container/main.py
2499 INFO: Loading module hooks...
2499 INFO: Loading module hook "hook-encodings.py"...
2553 INFO: Loading module hook "hook-pydoc.py"...
2553 INFO: Loading module hook "hook-xml.py"...
2753 INFO: Loading module hook "hook-distutils.py"...
2766 INFO: Looking for ctypes DLLs
2766 INFO: Analyzing run-time hooks ...
2773 INFO: Looking for dynamic libraries
2836 INFO: Looking for eggs
2836 INFO: Using Python library /Library/Frameworks/Python.framework/Versions/3.4/Python
2838 INFO: Warnings written to /Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container/build/main/warnmain.txt
2861 INFO: checking PYZ
2861 INFO: Building PYZ because out00-PYZ.toc is non existent
2861 INFO: Building PYZ (ZlibArchive) /Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container/build/main/out00-PYZ.pyz
3175 INFO: checking PKG
3176 INFO: Building PKG because out00-PKG.toc is non existent
3176 INFO: Building PKG (CArchive) out00-PKG.pkg
3185 INFO: Bootloader /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PyInstaller/bootloader/Darwin-64bit/run
3185 INFO: checking EXE
3185 INFO: Building EXE because out00-EXE.toc is non existent
3185 INFO: Building EXE from out00-EXE.toc
3185 INFO: Appending archive to EXE /Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container/build/main/main
3187 INFO: Fixing EXE for code signing /Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container/build/main/main
3192 INFO: checking COLLECT
3192 INFO: Building COLLECT because out00-COLLECT.toc is non existent
3192 INFO: Building COLLECT out00-COLLECT.toc

When I run the executable a terminal window opens with the following output:
Last login: Tue Jan  3 11:35:51 on ttys004
/Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container/dist/main/main ; exit;
[11:43:24][~]$ /Users/jonathanwilson/Documents/Projects/hr_digitization_tool/hr-records-management-tool-no-container/dist/main/main ; exit;
Traceback (most recent call last):
  File "main.py", line 7, in <module>
ImportError: No module named 'Tkinter'
Failed to execute script main
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

I have tried running the pyinstaller command with --hidden-import Tkinter but that still does not work.  I have checked the pyinstaller docs section "When Things Go Wrong" but still don't see a solution.

A: I ended up finding the problem so figured I would share.  As Bryan Oakley pointed out in the question comments, pyinstaller was using python3, I needed python2 since I was using the python2 Tkinter version (and also some other python2 modules).
I did pip uninstall pyinstaller and pip3 uninstall pyinstaller to make sure I had completely removed pyinstaller.  I then did pip2.7 install pyinstaller to install it for python2. Pyinstaller then correctly used python2 and loaded the Tkinter module with no issues (well I did have some issues related to my python2 not being added to my path, but that was unrelated to this issue).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebase Emulators HUB UI not loading in browser I recently upgraded Firebase Emulators so i can use the new auth functionalities, everything works fine, after running firebase emulators:start it shows me the following logs in the console:
firebase emulators:start

i  emulators: Starting emulators: auth, functions, firestore, hosting
!  functions: The following emulators are not running, calls to these services from the Functions emulator will affect production: database, pubsub
+  functions: Using node@12 from host.
i  firestore: Firestore Emulator logging to firestore-debug.log
i  hosting: Serving hosting files from: dist/firetest
+  hosting: Local server: http://localhost:5000
i  ui: Emulator UI logging to ui-debug.log
i  functions: Watching "C:\wamp64\www\WasteMart\firetest\functions" for Cloud Functions...

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://localhost:4000                │
└─────────────────────────────────────────────────────────────┘

┌────────────────┬────────────────┬─────────────────────────────────┐
│ Emulator       │ Host:Port      │ View in Emulator UI             │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Authentication │ localhost:9099 │ http://localhost:4000/auth      │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Functions      │ localhost:5001 │ http://localhost:4000/functions │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Firestore      │ localhost:8080 │ http://localhost:4000/firestore │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Hosting        │ localhost:5000 │ n/a                             │
└────────────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at localhost:4400
  Other reserved ports: 4500

but when I open the emulator hub at http://localhost:4000/ nothing loads up.
I opened the DevTools in Chrome and it shows these two console errors:
Uncaught SyntaxError: Unexpected token '<'
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.
DevTools failed to load SourceMap: Could not parse content for http://localhost:4000/static/js/10.e545a6ce.chunk.js.map: Unexpected end of JSON input

Im not sure what is wrong or what should I try to fix this, I try to find a way of uninstall the emulators and re-install them but i had no luck.

A: Its working now!  , I just updated firebase-tools from 9.01 to 9.10 and it downloaded emulator files ui-v1.4.1
If the error persists remove firebase-tools and install them again


text:
Q: Dell XPS 15 ubuntu 20.4.4 LTS connect to docking station display crash randomly I have an issues with Dell XPS that connect to Dell D6000s docking station that connected to 2 monitors,
the display randomly crashes and then the laptop screen turn black after a minute its lines up but happens too randomly, when disconnect and reconnect the docking station same thing happens.
I read that it's may happen because using Xorg and changing to wayland may assist,
I didn't try to change kernel.
adding some details:
echo $XDG_SESSION_TYPE says X11
bios 1.9.0 - up to date
i7-11th Gen
Nvidia 3050 - using as prime and Nvidia driver 510
kernel 5.13-0.41
Displaylink installed - left the setting to use Xorg


text:
Q: Multiple WinRT CaptureElements The CaptureElement XAML control is a cool and easy technique to preview the camera on a device in your application's canvas without having to invoke the CameraCaptureUI dialog.

But... adding more than one doesn't seem to work.
Trying this:
var _MediaCapture = new MediaCapture();
await _MediaCapture.InitializeAsync();
Cap1.Source = _MediaCapture;
Cap2.Source = _MediaCapture;
await _MediaCapture.StartPreviewAsync();

Results in this on the second 'Source' line:

{"A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)"}

Is there a technique that allows more than one CaptureElement on a single XAML canvas?


text:
Q: What is this watch expression in Angular.js Batarang? I'm trying to do performance tuning on an Angular.js application using the Angular.js Batarang Chrome extension.  One of the extension's features is that it lists all the 'watch expressions' that Angular.js checks on each $digest, and shows how long they take to evaluate.  Most of the expressions look like:
'comment.commenter_profile_url'
'comment.commenter_name'
...

However, the most expensive watch expression on the page is apparently
"function (){f=i(c);var a,b;if(L(f))if(Xa(f))
{if(e!==h)e=h,x=e.length=0,g++;a=f.length;if(x!==a)g++,e.length=x=a;
for(b=0;b<a;b++)e[b]!==f[b]&&(g++,e[b]=f[b])}else{e!==n&&(e=n={},x=0,
g++);a=0;for(b in f)f.hasOwnProperty(b)&&(a++,e.hasOwnProperty(b)?
e[b]!==f[b]&&(g++,e[b]=f[b]):(x++,e[b]=f[b],g++));if(x>a)for(b in
g++,e)e.hasOwnProperty(b)&&!f.hasOwnProperty(b)&&(x--,delete e[b])}else
e!==f&&(e=f,g++);return g}"

(line breaks are mine).  What's going on here?  My best guess is that this is some sort of compiled filtered ng-repeat.  (If I'm correct, I'd really appreciate a summary of the sort of things Angular.js does -- if any -- to make ng-repeat and filters efficient.)


text:
Q: How to place tcolorbox at bottom of page Does anyone know how set a tcolorbox textbox to appear at the bottom of a page, similar to how you can set figures to appear at the top or bottom of a page? I have looked everywhere but no answers to this specific question can be found online. I am looking for functionality equivalent to how figures will be automatically aligned with the bottom of the page they are referenced in:
\begin{figure}[!b]
... figure contents...
\end{figure}

Here is how I have my tcolorbox item set up:
\tcbset{
    noteStyle/.style={
        breakable,
        enhanced,
        outer arc=0pt,
        arc=0pt,
        colframe=noteTitleBlue,
        colback=noteBackgroundBlue!20,
        attach boxed title to top left,
        boxed title style={
            colback=noteTitleBlue,
            outer arc=0pt,
            arc=0pt, top=0pt,
            bottom=0pt
        },
        fonttitle=\sffamily
    }
}
\newtcolorbox[auto counter,number within=section]{note}[2][]{
    noteStyle,
    label=#2,
    fontupper=\footnotesize,
    title=Note~\thetcbcounter,
    overlay unbroken and first={
        \path let \p1=(title.north east),
        \p2=(frame.north east) in node[anchor=west,
        font=\sffamily,
        color=noteTitleBlue,
        text width=\x2-\x1] at (title.east) {#1};
    },
}

A: Option float converts a tcolorbox into a floating object, and floatplacement fixes positioning preferences order
\documentclass{article}
\usepackage{lmodern}
\usepackage{lipsum}
\usepackage[most]{tcolorbox}
\begin{document}
\begin{tcolorbox}[float, floatplacement=b]
\lipsum[2]
\end{tcolorbox}
\lipsum[1-3]
\end{document}


text:
Q: R ggplot2 - How do I specify out of bounds values' colour In the plot generated by the following code I would like to alter the colours so that all values < 0.6 are the same as the "low" colour and all values greater than 1 are the "high" colour.
As is stands the colour gradient stretches across the entire numeric range of the data. I have tried adding limits but that makes all out of bounds value the same colour as NA values, which is not what I want because I need missing NA values to clearly stick out and not look the same colour as out of bounds values <0.6.
I'm convinced that the answer is with the oob, breaks arguments but have had no success getting it to work.
library(ggplot2)
a = rnorm(17*17, 0.733,0.21)
qcMat = matrix(a, ncol = 17)
qcMat[qcMat> 1] = 1
#qcMat contains values between 0 and 1 and some NAs

m = melt(t(qcMat))
m$Var2 <- with(m,factor(Var2, levels = rev(sort(unique(Var2)))))
ggplot(m, aes(as.factor(Var1), Var2, group=Var2)) +
  geom_tile(aes(fill = value)) +
  geom_text(aes(fill = m$value, label = round(m$value, 2))) +
  scale_fill_gradient(low = "red", high = "green") +
  xlab("") + ylab("") + ggtitle(paste("biscuit:", biscuit_id, "- QC", sep = " "))

A: As you said youself, you want the oob argument in the scale_fill_gradient. To clamp values, you can use squish from the scales package (scales is installed when ggplot2 is installed):
library(scales)

and later
scale_fill_gradient(low = "red", high = "green", limits=c(0.6, 1), oob=squish)

A: Try changing geom_tile to below:
  geom_tile(aes(fill = ifelse(value<0.6,min(m$value,na.rm=TRUE),
                              ifelse(value>1,max(m$value,na.rm=TRUE),
                                     value))))

EDIT: Then don't use min max, so we will get 0.6-1 range:
geom_tile(aes(fill = ifelse(value<0.6,0.6,
                            ifelse(value>1,1,
                                   value))))


text:
Q: Issue with C code while making a parallel version of Odd-Even sorting I was making a C code about odd-even parallel sorting using OpenMp. The code is the following:
#include <omp.h>
#include <stdlib.h>
#include <stdio.h>

int main(){

int *A,N,i,sw=1,start=0,temp;

srand(0);

printf("Inserire la grandezza dell'array: ");
scanf("%d",&N);

A=(int *)calloc(N,sizeof(int));

for(i=0;i<N;i++){
    A[i]=rand()%100+1;
    printf("%d  ",A[i]);
    }

while(sw || start){

    #pragma omp parallel for
    for(i=start;i<N-1;i+=2){
        if(A[i]<A[i+1]){
            temp=A[i];
            A[i]=A[i+1];
            A[i+1]=temp;
            sw=1;
        }
    }
    if(start==0) start=1;
    else start=0;
}

printf("\n\n");

for(i=0;i<N;i++){
    printf("%d  ",A[i]);
    }

return 0;

}

But when I run it it will "stop" before the scanf. I used stop because it goes into the while but doing it in loop without quitting it, and also it doesn't print anything if I place a printf after the scanf.
I'm using Linux compiler gcc (Debian 10.2.0-16) 10.2.0 on a Virtual Machine


text:
Q: How do I run a program as nobody? I want a user-privileged (not root) process to launch new processes as user nobody. I've tried a straight call to setuid that fails with -1 EPERM on Ubuntu 8.04:
#include <sys/types.h>
#include <unistd.h>

int main() {
       setuid(65534);
       while (1);
       return 0;
}

How should I do this instead?

A: You will require assistance and a lot of trust from your system administrator.  Ordinary users are not able to run the executable of their choice on behalf on other users, period.
She may add your application to /etc/sudoers with proper settings and you'll be able to run it as with sudo -u nobody.   This will work for both scripts and binary executables.
Another option is that she will do chown nobody and chmod +s on your binary executable and you'll be able to execute it directly.  This task must be repeated each time your executable changes.
This could also work for scripts if you'll create a tiny helper executable which simply does exec("/home/you/bin/your-application").   This executable can be made suid-nobody (see above) and you may freely modify your-application.

A: As far as I know, you can't unless you're root or have sudo set up to allow you to switch users.  Or, you can have your executable have the suid bit set up on it, and have it owned by nobody.  But that requires root access too.

A: calife is an alternative to sudo.

Calife is small program that enable a UNIX system administrator to become root (or another user) on his/her machines without giving the root password but his/her own.

A: The 'nobody' user is still a user.  I'm not sure what your reasoning is in having the program run as nobody, it's not going to be adding any additional security.  You're more likely to open yourself to other problems.
I'd follow squadette's recommendation of using a helper application.

A: I ran across the setuid-sandbox project today while reading LWN, which does what I'm looking for the proper way.


text:
Q: vim: Join all lines in paragraph I'm trying without success to join all lines in a paragraph (block of text) using a vimscript.
I want to do this for every paragraph (block of text) and want to keep the empty lines between them.
(I don't want to use macros)
When I use the }w command to go to the first word in the next paragraph I noted that it does not recognize empty lines with spaces or multiple empty lines between paragraphs.
That's not what I want.
So I tried this:
do a search:
\(^.*\S\+.*\n\)\{2,}
do:
normal vipgJ
do above search again etc.
It works fine when I do it manually, but I can't put this in a script.
I tried this:
 function! <SID>JoinParagraphs()
   let i = 1
   normal gg
   while i <= 200
   call search("\\(^.*\\S\\+.*\\n\\)\\{2,})", "")
   normal vipgJ
    let i=i+1
   endwhile
  endfunction

Doesn't work...
I tried also to change the line call search... for
let @/ = "\\(^.*\\S\\+.*\\n\\)\\{2,})"
but that does a Join of all lines together (doesn't keep the empty lines).
What did I do wrong?

A: Click: Pragmatic approach added
much underrated command mode and :global
Update Fixed after a correct comment. It happened with whitespace-only lines containing Tab-character(s)... sry bout that.
:g#\v[^\s\t]#normal vipJ

How does that work for you? (perhaps replacing vipJ -> vipgJ if you like)
Update Here is one that not uses normal mode (inspired by Peter's comment)
The big benefit is that it reuses the same pattern in negative and positive sense; That way it can be genericized to
:let @/='\v^\s*$'
:v//.,//-1 join

Now the second line shows the simplicity of the this approach (for every nonmatching line, join up until the next matching line). The best thing is that you can use any odd search pattern instead
Of course you could write this particular task as one line, but it wouldn't quite be as elegant:
:v#\v^\s*$#.,//-1 join

A: Another approach that has been around since Berkeley UNIX, before vim existed... If you're on a linux/unix system, you can invoke the fmt command like so:
:%!fmt -w 9999
That will do it on the whole file, which might screw up stuff like numbered lists. You can do it by paragraph with:
!}fmt -w 9999
or do it from the command line outside of vi:
$ fmt -w 9999 file.txt
I like this approach because I don't have to remember to reset textwidth=80

A: as was touched on in the function the easiest way is to use
vipJ
Visual select inner paragraph join

A: Just found this answer
:set tw=1000000
gggqG

Which is the absolute winner IMHO.
It executes gq on the motion from gg (start) to G (end of document), using a textwidth of 1000000.

A: Replace all newlines followed by something other than a newline with the second matched character:
:%s/\(\S\)\n\(\S\)/\1 \2/

Another approach:
:%s/\n\([^\n]\)/\1/


text:
Q: How to speed up binary read/write I have this code
//N = 32;
//B = 27;
using (FileStream fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    using (BinaryReader br = new BinaryReader(fs))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            for (int k = B; k < N; ++k)
            {
                Console.WriteLine(k);
                long pt = 0;
                long j = 1L << k;
                for (long i = 0; i < (1L << (N - 1)); ++i)
                {
                    long b1;
                    long b2;

                    br.BaseStream.Seek(8 * (pt), SeekOrigin.Begin);
                    b1 = br.ReadInt64();
                    br.BaseStream.Seek(8 * (j - 1), SeekOrigin.Current);
                    b2 = br.ReadInt64();

                    long t1 = b1 + b2;
                    long t2 = b1 - b2;

                    bw.BaseStream.Seek(8 * (pt), SeekOrigin.Begin);
                    bw.Write(t1);
                    bw.BaseStream.Seek(8 * (j - 1), SeekOrigin.Current);
                    bw.Write(t2);

                    pt += 1;
                    if ((pt & (j - 1L)) == 0)
                    {
                        pt += j;
                    }
                    if ((i % 100000) == 0) Console.WriteLine(i);
                }
            }
        }
    }
}

What's happening is, the program reads two longs from different positions in a very large (17 GB) file, adds/subtracts them, then rewrites the new values in the same positions.
From what I can gather, the most efficient way to read data is to read a large chunk into a buffer and then work with that. However, that approach doesn't work here, because based on the values of pt and j, it could be reading from the beginning and end of the file, and of course I can't store all 17 GB in memory.
The line
if ((i % 100000) == 0) Console.WriteLine(i);

is for debugging, and it's about 2 seconds between them on my computer. I need this to be much faster. The paper I'm following said their implementation took less than 30 minutes for this loop. Is there a faster alternative for reading lots of numerical data quickly?

A: This is not really an answer per-se. However, it should give you ideas on how you can specifically speed this up
At first glance, this breaks down in to probabilities, parallelism, and chuck size.
If there is a high probability that the next/write read can be found in a larger chunk, then a large chunk size will be a performance gain. In turn it wont have to keep scanning the disk.
If you are using SSD's, you can probably load up oodles of Mbs (at a time) in a more performant manner than the default 4k chunk it is probably using .
Also, seemingly this can be broken down in to parallel workloads... Though it really is unclear what modifications you would need on the outset.
However, if you really want this fast

*

*Go an buy your self 32 gig of ram

*Create an inherited Stream Class, or even better just a custom class

*Load the entire data set into memory, broken into arrays of chunks of about a gig.

*Make use of direct pointer access

*Use parallel work loads

If you could do this, (and this is speculative) you could probably speed this up many factors faster. And for the messily cost of a couple of hundred dollars in memory and a days worth of coding.
Awesome comment by @NPras

Instead of managing the RAM caching/chunking yourself, you may also
  want to look at the concept of memory-mapped files and let the OS
  manage it for you

And from Managing Memory-Mapped Files

A: If I understand correctly, the results are written back in the locations you just read from.
So if you reverse the order of the writes, the first write will be to the same location you last read from.
That will reduce the seek time.
Further, that means the next read will also be contiguous with the other write, again reducing seek time.
Now the main loop over 'i' is obviously long, but I think you could:

*

*Break that up into medium size chunks (64M or so might be all you need)

*Do whole block of reads

*Do the second block of reads

*Do an in-memory calculation for both blocks

*Write them out


text:
Q: I need to link two of my tables together and return only the highest group average So I am trying to link two of my tables together, I have my Artist Table and my CD table. My CD Table contains a number of CD Entrys, complete with CD.cdID, CD.artID, CD.cdTitle, CD.cdPrice and CD.cdGenre. My Artist table contains, Artist.artID, Artist.artName. I am trying to return the Artist.artName which has the highest average price for all of their CDs in the CD Table.
This is my code for this so far. So far it is pulling the maximum average CD prices by CD.artID but I am not sure how to combine this so that I can display the Artist.artName name instead of CD.artID:
SELECT AVG(cdPrice) as cdPrice, artID
FROM CD
GROUP BY artID
HAVING AVG(cdPrice) = (SELECT MAX(cdPrice) FROM
(SELECT AVG(cdPrice) as cdPrice FROM CD GROUP BY artID) A)

I am using MySQL via PhpMyAdmin.

A: You can use GROUP BY after joining the tables - the same rules apply, viz all non-aggregated columns must be grouped. To find the highest averaging artist only, you can replace the having with a simple ORDER and LIMIT:
SELECT AVG(cd.cdPrice) as avgPrice, a.artName
FROM CD cd INNER JOIN Artist a
on cd.artID = a.artID
GROUP BY a.artName
ORDER BY avgPrice DESC
LIMIT 1;

SqlFiddle here


text:
Q: Running matlab script without having the required toolbox I have downloaded a matlab code for dithering the images but I don't have the Image Processing toolbox and I don't want to buy it for running this code. Is there any way for running the script?
Many thanks in advance

A: You can try Octave, or Scilab, or OpenCV, or there are many other open source, and free, alternatives.
But while you're investigating and trying those out, just make sure to measure how much time you're spending on it. If your script uses more than 20 functions from Image processing Toolbox (as you indicated in a comment) then it may be a lot of effort, and depending on how much your time is worth per hour, you may well find it would be better to just buy the toolbox. That's of course just my advice - your choice.
If you're at a university, you will likely be able to get a cheaper educational pricing, or be able to buy the Student edition of MATLAB that includes Image Processing Toolbox. It's also possible to purchase a time-limited license of MATLAB (six months or a year) for a discount, although that pricing is very unadvertised by MathWorks, and you would need to call and speak to a MathWorks account manager to request it.

A: You can download Scilab , it is a similar platform like Matlab, but it is open source,You dont have to spend your money, You can run matlab code using scilab.


text:
Q: How to mix normal canvas functions with KineticJS? In some parts I just want to draw an image or rect without the overhead of creating a complex object.
I try
var stage = new Kinetic.Stage({
    container: 'container',
    width: 400,
    height: 400});
var layer = new Kinetic.Layer();
var ctx;
layer.add(new Kinetic.Shape({x:0,y:0,drawFunc:function(context){ctx=context;}}));
stage.add(layer);
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,100,100);

But I get TypeError: ctx.fillRect is not a function
Here's the fiddle http://jsfiddle.net/qHVsu/

A: You can get the underlaying context from the layer:
var ctx = layer.canvas.context._context;
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,100,100);

JSFiddle.


text:
Q: Creating a new spreadsheet from a template I am developing code which creates a copy of a template spreadsheet whenever text is input into any row within column A. The spreadsheet needs to be named after the text entered.
Currently I have the following code, the problem is that it does not name the new spreadsheet after the text I enter.
The code is as below:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim wsNew As Worksheet
    If Target.Cells.Count > 1 Then Exit Sub

    On Error Resume Next
    If Not Intersect(Target, Range("A1:A10")) Is Nothing Then
        Set wsNew = Sheets(Target.Text)
        If wsNew Is Nothing Then
            Worksheets("Template").Copy After:=Worksheets(Worksheets.Count)
        End If
        'name new sheet code here

    End If
End Sub

A: Like this:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim wsNew As Worksheet
    If Target.Cells.Count > 1 Then Exit Sub

    On Error Resume Next
    If Not Intersect(Target, Range("A1:A10")) Is Nothing Then
        Set wsNew = Sheets(Target.Text)
        If wsNew Is Nothing Then
            Worksheets("Template").Copy After:=Worksheets(Worksheets.Count)
        End If
        'name new sheet
        Worksheets(Worksheets.Count).Name = Target.Text
    End If
End Sub

Edit:
User could empty the cell in A1:A10 which will create new tab called "Template (2)". You should also do check:
If Len(Target.Cells.Text) = 0 Then Exit Sub

A: I'd suggest something like this to create the sheet based on the template with the desired name - but after testing and cleansing the proposed sheet name first for invalid characters
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim wsNew As Worksheet
    Dim strSht As String

    If Target.Cells.Count > 1 Then Exit Sub

    If Not Intersect(Target, Range("A1:A10")) Is Nothing Then
        On Error Resume Next
        Set wsNew = Sheets(Target.Text)
        On Error GoTo 0
        If wsNew Is Nothing Then
        If ValidSheetName(Target.Value) Then
        strSht = Target.Value
        Else
        strSht = CleanSheetName(Target.Value)
        End If
        End If
        Worksheets("Template").Copy After:=Worksheets(Worksheets.Count)
        ActiveSheet.Name = strSht
    End If
End Sub

string cleaning code 1
Function ValidSheetName(strIn As String) As Boolean
    Dim objRegex As Object
    Set objRegex = CreateObject("vbscript.regexp")
    objRegex.Pattern = "[\<\>\*\\\/\?|]"
    ValidSheetName = Not objRegex.test(strIn)
End Function

string cleaning code 2
Function CleanSheetName(strIn As String) As String
    Dim objRegex As Object
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Global = True
        .Pattern = "[\<\>\*\\\/\?|]"
        CleanSheetName = .Replace(strIn, "_")
    End With
End Function


text:
Q: Multiple requests being send unintentionally I am using a PHP Script written by me with AWS (Amazon Web Service) PHP Script to send emails using SMTP
Everytime I run this script, say I have 3 user's in my database, then the first user get's mail of the first, second and third person. The second user get's mail to second and third person. And the third user get's the mail to the third person only.
I don't know why this is happening, and been pulling my hair for some time. Maybe I am missing some point, that is why adding a question here.
Pre-Requisites:
func1() = Is used to get emails from DB whom I have not send Emails Yet, return's a single value (ID) only
func2() = Is used to get the data of that particular user whose ID was found in func1()
func3() = Is used to mark "Send" to that particular ID whom we send the mail.
<?php

require 'aws-autoloader.php';
require 'vendor/autoload.php';

$mail = new PHPMailer;
$mail->isSMTP();
$mail->setFrom('myemail@address.com', 'My Company Name');
$mail->Username = 'Username';
$mail->Password = 'Password';
$mail->Host = 'email-smtp.us-west-2.amazonaws.com';

class Db {
    public function dbconnect(){
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "database";
    $conn = new mysqli($servername, $username, $password, $dbname);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        return $conn;
    }
    public function func1()
    {
    $conn=$this->dbconnect();
    $stmt = $conn->prepare("CALL func1()");
    $stmt->execute();
    $result=NULL;
    $result = $stmt->get_result();
    $item=NULL;
    while ($row = $result->fetch_array(MYSQLI_NUM))
        {
        $item[] = $row;
        }
    return $item;
    $stmt->close();
    $conn->close();
    }
    public function func2($id)
    {
    $conn=$this->dbconnect();
    $stmt = $conn->prepare("CALL func2(?)");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $item=NULL;
    while ($row = $result->fetch_array(MYSQLI_NUM))
        {
        $item[] = $row;
        }
    return $item;
    $stmt->close();
    $conn->close();
    }
    public function func3($id)
    {
    $conn=$this->dbconnect();
    $stmt = $conn->prepare("CALL func3(?)");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $item=NULL;
    while ($row = $result->fetch_array(MYSQLI_NUM))
        {
        $item[] = $row;
        }
    return $item;
    $stmt->close();
    $conn->close();
    }
}
$count=0;
$obj=new Db;
$ids=$obj->func1();
while(($ids[0][0]!=0)&&($count<1000)){
$ids=$obj->func1();
$rslt=$obj->func2($ids[0][0]);
if($rslt[0][0]!=NULL)
    {
    $idno=$rslt[0][0];
    $companyname=$rslt[0][2];
    $email=$rslt[0][16];
    $complete=NULL;
do{
    $mail->addAddress($email, $companyname);
    $mail->Subject = 'My Subject';
    $mail->Body = '
Hello
';
    $mail->AltBody = "Hello";

    $mail->SMTPAuth = true;

    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->isHTML(true);
    if(!$mail->send()) {
        echo "Email not sent. " , $mail->ErrorInfo , PHP_EOL;
    } else {
        $complete=$obj->func3($ids[0][0]);
    }
}while($complete[0][0]!=3);
}
$count=$count+1;
//if($count%10==0) Trying to give a small break after each 10 emails are send
    sleep(1);
}
$count=$count-1;
echo 'Email Send to: '.$count.' Users.
';
?>

After the function is called, I receive emails as described at the start. And all the users are marked "Send"
Any Idea what I may be doing wrong to get result like that.

A: Your code is using the same PHPMailer object for each email, and it is adding addresses using $mail->addAddress() without resetting the list of email addresses between emails hence the list of recipients is growing each time.
You can call $mail->clearAllRecipients() for each new email or you could create a new PHPMailer object for each email. Note that if you choose the former approach then you should check to see if there are any other things that also need to be reset from one email to the next.


text:
Q: Obtaining value parameter of a HTML element I am trying to obtain the value parameter of an HTML element when this element is clicked. My code is as follows:

const dothis = () => {
  var btnContainer = document.getElementById("btnContainer");

  var btns = btnContainer.getElementsByClassName("page-item");

  for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function() {
      var current = document.getElementsByClassName("active");

      if (current.length > 0) {
        current[0].className = current[0].className.replace(" active", "");
      }

      this.className += " active";

    });
  }

}

Put ABC

Put DCF

How can I obtain the value ABC from the
 tag using javascript?

A: li items support value only for ordered lists and it is the starting point for the list. (https://www.w3schools.com/tags/att_li_value.asp).
I'd recommend to use data attributes and refer to them, like:

    Put DCF

And then you refer to data-value in code, e.g.:
document.querySelector('#your_id').dataset.value

A: It's generally not a good idea to use inline event handlers. Furthermore value is a valid attribute for li, but it can only contain numbers (see MDN). You can try using data-attributes:

{
  console.log(`li.value can only be a number, so this will print '0': ${
    document.querySelector("body > ul > li:nth-child(1)").value}`);
  document.addEventListener(`click`, evt => {
      if (evt.target.classList.contains(`page-link`)) {
        console.log( evt.target.parentNode.dataset.value );
      }
  });
}

Put ABC

Put DCF

A: Several things:

*

*You called doThis onClick, which then itself added an event listener each time you clicked. That's not what you wanted I guess, so stick with one. It's recommended to not use event attributes at all, but do it all with JS alone.

*You remove the active className from the first element with that class in the whole document. Should be limited to the active page-item in the #btnContainer

*Use data-value attribute instead of value, so you can use dataset

*Use classList instead of mangling with className

*By using forEach instead of a loop, I have a local variable that is my target

!(function() {
  var btnContainer = document.getElementById('btnContainer');

  var btns = (el) => el.getElementsByClassName('page-item');
  var active = (el) => el.getElementsByClassName('active');

  Array.from(btns(btnContainer)).forEach((btn, idx, ar) => {
    btn.addEventListener("click", function(e) {
      Array.from(active(btnContainer)).forEach(el => el.classList.remove('active'))
      e.target.classList.add("active");
      console.log(btn.dataset.value)
    })

  })

}());
.active {
  color: red;
}

* {
  color: inherit;
}

Put ABC

Put DCF

A: if want obtain the value ABC from the
*
document.getElementsByClassName("page-item")[0].getAttribute("value");

A: I did the following and it worked.
const dothis = () => {
  var btnContainer = document.getElementById("btnContainer");

  var btns = btnContainer.getElementsByClassName("page-item");

  for (var i = 0; i < btns.length; i++) {
    btns[i].addEventListener("click", function(value) {
      var current = document.getElementsByClassName("active");

      if (current.length > 0) {
        current[0].className = current[0].className.replace(" active", "");
      }

      this.className += " active";

      var storage = localStorage;
      var event = value.toElement.text;

      storage.setItem("clicked_event", event);
      var stored_clicked_event = storage.getItem("clicked_event");
      console.log(stored_clicked_event);

    });
  }

}

then.. i changed HTML to:

Put ABC

Put DCF


text:
Q: How do you prompt for a sudo password using Ruby? Often I find myself needing to write scripts that have to execute some portions as a normal user and other portions as a super user. I am aware of one similar question on SO where the answer was to run the same script twice and execute it as sudo, however that is not sufficient for me.  Some times I need to revert to being a normal user after a sudo operation.
I have written the following in Ruby to do this
#!/usr/bin/ruby
require 'rubygems'
require 'highline/import'
require 'pty'
require 'expect'

def sudorun(command, password)
  `sudo -k`
  PTY.spawn("sleep 1; sudo -u root #{command} 2>&1") { | stdin, stdout, pid |
  begin
    stdin.expect(/password/) {
    stdout.write("#{password}\n")
    puts stdin.read.lstrip
                              }
  rescue Errno::EIO
  end
 }
end

Unfortunately, using that code if the user enters the wrong password the script crashes. Ideally it should give the user 3 tries to get the sudo password right.  How do I fix this?
I am running this on Linux Ubuntu BTW.

A: In my opinion, running a script that does stuff internally with sudo is wrong.  A better approach is to have the user run the whole script with sudo, and have the script fork lesser-privileged children to do stuff:
# Drops privileges to that of the specified user
def drop_priv user
  Process.initgroups(user.username, user.gid)
  Process::Sys.setegid(user.gid)
  Process::Sys.setgid(user.gid)
  Process::Sys.setuid(user.uid)
end

# Execute the provided block in a child process as the specified user
# The parent blocks until the child finishes.
def do_as_user user
  unless pid = fork
    drop_priv(user)
    yield if block_given?
    exit! 0 # prevent remainder of script from running in the child process
  end
  puts "Child running as PID #{pid} with reduced privs"
  Process.wait(pid)
end

at_exit { puts 'Script finished.' }

User = Struct.new(:username, :uid, :gid)
user = User.new('nobody', 65534, 65534)

do_as_user(user) do
  sleep 1 # do something more useful here
  exit! 2 # optionally provide an exit code
end

puts "Child exited with status #{$?.exitstatus}"
puts 'Running stuff as root'
sleep 1

do_as_user(user) do
  puts 'Doing stuff as a user'
  sleep 1
end

This example script has two helper methods.  #drop_priv takes an object with username, uid, and gid defined and properly reduces the permissions of the executing process.  The #do_as_user method calls #drop_priv in a child process before yielding to the provided block.  Note the use of #exit! to prevent the child from running any part of the script outside of the block while avoiding the at_exit  hook.
Often overlooked security concerns to think about:

*

*Inheritance of open file descriptors

*Environment variable filtering

*Run children in a chroot?

Depending on what the script is doing, any of these may need to be addressed.  #drop_priv is an ideal place to handle all of them.

A: If it is possible, you could move the stuff you want executed as root to a seperate file and use the system() function to run it as sudo, including the sudo prompt etc:
system("sudo ruby stufftorunasroot.rb")

The system() function is blocking, so the flow of your program doesn't need to be changed.

A: I do not know if this is what you want or need, but have you tried sudo -A (search the web or the man page for SUDO_ASKPASS which might have a value like /usr/lib/openssh/gnome-ssh-askpass or similar)? This is what I use when I need to present a graphical password dialogue to users in GUI environments.
Sorry if this is the wrong answer, maybe you really want to remain on the console.

A: #!/usr/bin/ruby
# ... blabla, other code
# part which requires sudo:
system "sudo -p 'sudo password: ' #{command}"
# other stuff
# sudo again
system "sudo -p 'sudo password: ' #{command}"
# usually sudo 'remembers' that you just authenticated yourself successfuly and doesn't ask for the PW again...
# some more code...


text:
Q: How to create recycler view like WhatsApp chat I have created a list view just like a whatsapp chats list which is working fine it is loading data from server and setting its view but the problem is when the device is offline it cannot show the view which was previsouly created so my question is how to save the list view offline so that when the device is online my app recieves views from server and if the device is offline then the app should show views which were previously loaded.
And if possible please share some tutorials related to this.

A: You need to save your data locally using database. The most common option is sqlite. You can try this tutorial to understand what to do: http://www.tutorialspoint.com/android/android_sqlite_database.htm there are some options like Sugar Orm (or any other ORM) which uses sqlite in the background but makes it easy to work with objects (the shortage is that you are very limited when it comes to relations between tables and such). Anyway, this is their website:  http://satyan.github.io/sugar/

A: You can try using Firebase database for your chats. You Just need one line of code to enable chats offline persistence i.e
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
For more take a look on offline-capabilities.


text:
Q: What is the use of trace captured via Profiler? I am learning about capturing trace via profiler.
I understand that the purpose of capturing trace via profiler is to log events happening on the sql server without impacting performance, because logging via the profiler GUI impacts performance.
Once I have the trace I can open it in profiler and view the events without having impact on sql server. What else can I do with the trace?

A: Don't mess around with the old trace engine. It has been deprecated for a decade now. Use Extended Events (XE) instead.
The old trace engine consists of the support in the database engine called "SQL trace"; and the GUI called "Profiler". The reason not to use Profiler for the old trace engine is because of the overhead. So, back in the days when we used the old trace engine, we used "server-side traces", where SQL Server would write to a trace file. Regardless of whether a trace file was produced by the database engine or Profiler, we can open that trace file in both Profiler, and read it from the database engine doing select from fn_trace_gettable().
There are myriad use-cases for tracing. Capturing SQL statement along with costs is only one of them.
Considering that we have Extended Events now, and the old trace engine is deprecated and haven't been worked on for a decade now should make the decision between the two pretty easy. Also, XE is so much more powerful and rich compared to the old trace engine.
XE might be somewhat more complex to get started with, which is why I wrote this blog post.
Edit: adding some examples. As for use-cases of tracing, it is essentially limitless. Tracing is IMO a troubleshooting tool allowing you to capture information when things happens in the engine. To mention just a few examples:

*

*Capture when a SQL statement was completed along with cost for performance reasons.

*When a deadlock occurs along with details info what deal to the deadlock.

*See if weird things happens in the engine, stuff you then want to narrow in on (like in my "Looking for strange" trace).

*Capture execution plans for performance analysis.

*See how frequently checkpoint happens.

*Wait stats

*Capturing when big memory grants happens.

*Long waits for client apps to consume data from SQL Server

*Tracking recompilations

*...


text:
Q: Select em entity framework com determinadas colunas Estou tentando fazer um select em uma tabela que contém várias colunas e quero que o comando sql que o EntityFramework gera contenha apenas as colunas que especifiquei.
Meu código está assim:
var clientes = (from cliente in repositoryCliente.GetAll()
    select new
    {
        cliente.Id,
        cliente.Nome,
        cliente.Email,
        cliente.Telefone
    }).ToList();

E meu repository:
public virtual IEnumerable<T> GetAll()
{
    return _dbSet;
}

Mas ao analisar o comando sql que ele faz, ele busca todos os outros campos
(Estou usando Entity Framework Profiler)
Eu quero que ele execute apenas o comando sql "Select Id,Nome,Email,Telefone from Cliente", e não com as demais colunas.

A: O Entity Framework trabalha com select tendo como padrão de comportamento selecionar todas as colunas. Se mesmo assim é desejável especificar a nível de SQL quais colunas deverão ser usadas, o método SqlQuery de DbSet cumpre essa função:
using (var entidades = new dbContext())
{
    var clientes = entidades.Clientes.SqlQuery("select Id, Nome, Email, Telefone
        from Clientes").ToList();
}

A: O problema é ao usar IEnumerable
O mesmo faz com que busque todos os campos e registros, ignorando os métodos do LINQ ou Lambda do Entity Framework.
Para contornar isso, deve-se utilizar
IQueryable
O mesmo contribui também para performance em consultas com o Entity Framework.

A: Vê se ajuda: entity-framework-select-multiple-columns
var dataset2 =
    (from recordset in entities.processlists
     where recordset.ProcessName == processname
     select new
     {
         serverName = recordset.ServerName,
         processId = recordset.ProcessID,
         username = recordset.Username
     }).ToList();


text:
Q: SANE fails to open scanner device - local IP address change possibly responsible I have a Brother DCP-7065DN multi-function device. This device includes a flatbed scanner.
Here is what scanimage -L reports for this scanner.
device `brother4:net1;dev1' is a Brother Scanner DCP-7065DN
device `brother4:net1;dev0' is a Brother DCP-7065DN DCP-7065DN
device `brother4:bus13;dev1' is a Brother DCP-7065DN USB scanner

I'm unclear on the difference between the brother4:net1;dev1 and brother4:net1;dev0. The third one is clearly the USB interface (which I don't normally use). I usually use the first one. This is a minor but irritating issue, so I'd appreciate clarifications or suggestions where to look.
This scanner has been reliable, but I tried using it just now, and SANE cannot open brother4:net1;dev1. This is likely because I recently switched from a DSL internet service to a cable internet service. When doing this, I had to add a router in front of the cable modem, since the cable modem only had one Ethernet slot. Since the cable modem has address 192.168.1.1 by default, I had to change the router to 192.168.0.1 so as to not conflict with it. The printer uses a static address. It used to be 192.168.1.20, but I changed it to 192.168.0.20. This change may be causing the problem - I had to change it in CUPS before the printer would work.
But I'm unable to discover where SANE stores IP addresses of devices. And furthermore, I don't know where it is getting the list of devices that scanimage -L is listing. I suspect this issue is easily resolved by someone who has a better understanding of how SANE works.

A: So, a little more searching, and it appears that the Brother network devices listed in the scanimage -L output shown in my question (the first two lines), are listed in (wait for it):
/opt/brother/scanner/brscan4/brsanenetdevice4.cfg

This has a symbolic link in /etc linking to this file:
root@orwell:/etc# ls -lah opt/brother/scanner/brscan4/brsanenetdevice4.cfg
lrwxrwxrwx 1 root root 49 Sep 25  2013 opt/brother/scanner/brscan4/brsanenetdevice4.cfg /opt/brother/scanner/brscan4/brsanenetdevice4.cfg

Needless to say, I found this by doing a grep. For some reason, Brother wants you to modify this file using the utility brconfig4, which is kinda bananas. I.e. the syntax to add a device is:
brsaneconfig4 -a name=Scanner model=DCP-7065DN ip=192.168.0.20

It seems that the devices brother4:net1;dev1 and brother4:net1;dev0
listed above really are redundant, because this is the contents of /opt/brother/scanner/brscan4/brsanenetdevice4.cfg with both those devices:

DEVICE=DCP-7065DN , "DCP-7065DN" , 0x4f9:0x24a , IP-ADDRESS=192.168.0.20
DEVICE=Scanner , "DCP-7065DN" , 0x4f9:0x24a , IP-ADDRESS=192.168.0.20

So I deleted the first line, corresponding to the device DCP-7065DN, using (to humor Brother)
brsaneconfig4 -r DCP-7065DN


text:
Q: How to draw 3D surface from function I am a newbie to Matlab and have a problem drawing the surface of the following inequality
Calc.S0Func(2.7,1,1,sigmaL)-Calc.S0Func(c,delta,xT,sigmaH)>0

Where Calc is a Class and S0Func(c,delta,xT,sigma) is a function with 3 unknowns (c, delta, xT)
Hope this is enough info. The S0Function is a big function which is why I have not posted it here.
Any help is very welcome
Thank you

A: I'm not sure what the surface of an inequality is supposed to be; are you by chance looking for isosurface?
[c, delta, xT] = meshgrid(-2:.1:2, -2:.1:2, -2:.1:2);
values = c.^4 + delta.^4 + xT.^2.*sin(xT);
patch(isosurface(c, delta, xT, values, 1), 'FaceColor', 'red')
view(3)


text:
Q: Python2 and Python3 DPKT appears to return different output formats The DPKT library says it supports Python3 now, but it has different behavior when I use it in Python 2.x vs 3.x.  Although, both are incorrect it appears.
For example, in Python 2.x, the example given here
with open('test.pcap') as f:
    pcap = dpkt.pcap.Reader(f)
    for ts, buf in pcap:
       eth = dpkt.ethernet.Ethernet(buf)
       print eth

Returns a format that I don't expect, an object similar to:
   ^����6#���l�m�
Q!6�(�����k����~�pO���o���N�l   �k4�'���8�9�j��@mf���5��pB�6bٌ�~p��Jf.Jܼ3H�:�ݭ�k-O7+�O��
4�(�9��^F�fb��V��t˜������\�X1��#�.�ج<�Q�!����>�^ɹDĀ�orC=bC���S�6;��SR�`�� �

ZD����j2Q���m����h��)1@��1���aw}�d�ڧn�                                          ��
0Z:�`8ຄE(�@4���}������Mu��63fP�/�
������h'7�h'7�;������

However, in Python 3, I'm forced to open the pcap file in 'rb' mode, which is fine, except for the output issues (I'm not sure 'rb' has anything to do with the issues now):
with open('test.pcap', 'rb') as f:
    pcap = dpkt.pcap.Reader(f)
    for ts, buf in pcap:
       eth = dpkt.ethernet.Ethernet(buf)
       print eth

This now returns what I believe is a bytestring, and I haven't found a way to get the data out of this that I need.  For example, if I needed the number of flags, I can easily get 17 from the above example from their site, but I can't seem to get their example to work at all:
b'\x00\x0f\x1f\x16\xd1\xcd\x00\xc0\xf0y\x9a\xfd\x08\x00E\x00\x00\x1c\xb1\xce\x00\x006\x01N\xf7\xc0\xa8\x01d\xc0\xa8\x01g\x08\x00\xd9\xd7\xb7\xc4fc'

I haven't had any luck converting this string into a human readable object.  No combination of decode, binascii or anything else I've tried has worked.  Am I using this library incorrectly?

A: One of the major differences between python2 and python3 is that in python3, str and bytes are no longer the same. Compare:
$ python2 -c 'print(b"foo" == "foo")'
True

$ python3 -c 'print(b"foo" == "foo")'
False

This explains why you must open the file with "rb" in python3. (Although it's quite likely that you would get bogus results if you didn't do so on some platforms with python2, because without the b line endings that happen to exist in the file may get expanded inappropriately.)
Another difference: in python3, print is a function, not a statement so the code you've shown above for python3 is actually a syntax error. Instead you need print(eth)
To answer your actual question: When you simply print eth, you are implicitly asking the eth object to make itself printable. That is the same as calling print(str(eth)) and so it's giving you a printable string version of the binary data buffer that contains the ethernet frame.
You need to use the facilities of dpkt to discover, then dissect the parts of the frame that you care about.
Here's a short example that decodes a pcap containing DNS packets:
import dpkt
with open("/tmp/dns.pcap", "rb") as f:
    pcap = dpkt.pcap.Reader(f)
    for ts, buf in pcap:
        l2 = dpkt.ethernet.Ethernet(buf)
        print("Ethernet (L2) frame:", repr(l2))

        if l2.type not in (dpkt.ethernet.ETH_TYPE_IP, dpkt.ethernet.ETH_TYPE_IP6):
            print("Not an IP packet")
            continue
        l3 = l2.data
        print("IP packet:", repr(l3))

        if l3.p not in (dpkt.ip.IP_PROTO_TCP, dpkt.ip.IP_PROTO_UDP):
            print("Not TCP or UDP")
            continue

        l4 = l3.data
        print("Layer 4:", repr(l4))

        if l4.dport in (53, 5353) or l4.sport in (53, 5353):
            dns = l4.data
            if not isinstance(dns, dpkt.dns.DNS):
                dns = dpkt.dns.DNS(dns)
            print("DNS packet:", repr(dns))

As for why your output looks different than the tutorial. The tutorial is out of date. Apparently at some point, the implementation of the __str__ magic method on the dpkt objects changed (when you just print an object, you get the result of its __str__ method).
Originally, __str__ returned a formatted representation of the object. Later it just returns a string representation of the raw bytes of the object. So now you need to call repr(obj) in order to get the formatted representation.

A: try open the pcap-file as binary
'with open('test.pcap','rb')'


text:
Q: firefox still showing up in bleachbit after removal I thought I had removed firefox from my system (prefer chromium) using
sudo apt-get remove firefox

however, when I open bleachbit there is still a category that allows me to clean cache/backup/cookies and whatever for firefox. But I thought I had already deleted firefox?
So did I not completely remove firefox?

A: Yes: as you suspected, BleachBit shows the Firefox section only if the Firefox configuration files exist on your system, so you can run this command to delete the Firefox user profile
rm -rf ~/.mozilla/firefox
Then you can delete the Firefox cache using BleachBit. Recent versions of Firefox have it under another directory tree.
As Soren A pointed out, removing a package normally using APT does not remove its configuration files.


text:
Q: Prevent modal close on asp:textbox enter I am trying to prevent my modal from closing when keypress enter is entered in my modal asp textbox.
I have tried to wrap the textbox in another update panel and use an asynchronous postback trigger on textchanged, but thats not quite what I'm looking for. I am trying to create a text entry part which only updates when keypress enter is pressed and not when the text changes, I have also tried adding data-dismiss="modal" to the textbox itself like other pages have suggested, but this just means when I click on the textbox it shuts the modal.
<asp:UpdatePanel ID="upd_mdl_console" runat="server" UpdateMode="Conditional">
    <ContentTemplate>

                            <asp:Label runat="server" ID="Label3" Text="DEV CONSOLE"></asp:Label>

                        <button type="button" class="close pull-right" data-dismiss="modal" aria-label="Close">
                            ×
                        </button>

                            <asp:Literal ID="devbox_line_5" runat="server" Text=""></asp:Literal>
                            <asp:Literal ID="devbox_line_4" runat="server" Text=""></asp:Literal>
                            <asp:Literal ID="devbox_line_3" runat="server" Text=""></asp:Literal>
                            <asp:Literal ID="devbox_line_2" runat="server" Text=""></asp:Literal>
                            <asp:Literal ID="devbox_line_1" runat="server" Text=""></asp:Literal>
                            <asp:UpdatePanel ID="upd_mdl_txt" runat="server" UpdateMode="Conditional">
                                <ContentTemplate>
                                    <asp:TextBox ID="txt_Devbox" class="form-control _dev_console" runat="server" autocomplete="off"></asp:TextBox>
                                </ContentTemplate>
                            </asp:UpdatePanel>

                        <asp:Label ID="Label4" runat="server" Text="Label" Visible="false"></asp:Label>
                        <%--                            <asp:Button ID="Button1" OnClick="lnk_go_Click" class="btn btn-success" runat="server" AutoPostBack="false" Text="Create"></asp:Button>--%>
                        <button type="button" class="btn btn-secondary _dev_console" data-dismiss="modal">Close</button>

    </ContentTemplate>
</asp:UpdatePanel>

A: I use the following snippet to disable enter in textboxes. This also prevents triggering of a form post when pressing enter inside a textbox. It might work for preventing the closure of the modal also.
$('input').keypress(function (e) {
    return e.keyCode !== 13;
});

If you want to disable the enter in the modal only you could do something like this
$('.modal-body input').keypress(function (e) {
    return e.keyCode !== 13;
});


text:
Q: Extra char(s) found in EDI.ISASegment When I was inbounding trading partner's X12 file using biztalk. I am required to store the ISA segment of the file in a db table.
I am using the promoted property EDI.ISA_Segment to get the ISA string.
Recently, I noticed for one trading partner. There're extra chars found in the ISA segment:
 The ISA segment shall look like this:
ISA*00*          *00*          *ZZ*########       *ZZ*#####          *150105*0606*^*00501*000000936*1*P*>~

But the ISA_segment using the promoted property was:
    ISA*00*          *00*          *ZZ*########       *ZZ*#####          *150105*0606*^*00501*000000936*1*P*>~
G

There's extra < LF >+G in the ISA segment.
The trading partner do send the X12 file with segment suffix  and it was also configed in the BizTalk Agreement correctly.
It looks BizTalk takes 2 extra chars to the ISA_segment after reached the "~", I am wondering if this is a bug or it is caused some mis-configuation?

A: You need to look at the original EDI using a good text editor such as Notepad++ so you can see exactly what those characters are.
The X12 spec allows the use of CR and/or LF as part of the Segment Terminator so it might be a side effect of changing encodings from EDI to the database.


text:
Q: Maximum power transfer and minimization of signal reflection: When should what be applied Impedance matching is the practice of designing the input impedance of an electrical load or the output impedance of its corresponding signal source to maximize the power transfer or minimize signal reflection from the load. In case of maximizing the power transfer the optimal condition we want to archieve is:
$$ Z_S=Z^*_L $$
and in case when we want to minimize
signal reflection the desired condition is
$$ Z_S=Z_L $$
The Question is can we say in in denpendence of given situation how the decide when one wants to maximize the power transfer and when to minimize signal reflection. Are there any creteria know how to decide?
Of course, if we have only a source, no transmission lines, and we want maximize the power transfer, then doubtless maximizing the power transfer is the right choice.
But what what about the case when we have a source, a load and transmission line between them:

Or even a more complicated case we have again source and load, but now two different transmission lines (ie having different impedances, being build of different materials) between them:

Or even more complicated situations which I not want to draw, and so on.
Based on which creteria we can decide with option is more important here?
The maximization of the power transfer (for \$Z_S\$ and \$Z_L\$ and ignore the \$Z_0, Z_1\$ of the transmission lines) or minimization of signal reflection (for \$Z_S, Z_0\$ and then for \$Z_S, Z_1\$ and then the same story with \$Z_L\$ instead of \$Z_S\$)? Since the two mathematical conditions on impedances are different we cannot garantee that in general both conditions are satisfied simultaneously (for example when we deal with non trivial reactant components).
How to decide which practice of the two we should do in such case?
Note also that this question is closely related to my Maximum power transfer and minimization of wave reflection: Understanding the difference on intuitive level, but there the focus was on intuitional way to distinguish between maximization the power transfer and minimization of signal reflection, while here I'm interested on understanding when should be applied/prefered what? And how is it possible to decide it?
ADDITIONAL IMPORTANT POINT: ZelmaB noticed in his answer correctly that in my question isn't adressed to a concrete rf system/application. Yes,
that's true and this is done intensionally because the main motivation in this
question to find out preferably abstract criteria when for a system
abstractly given as source, load and transmission line between them
our task is to choose a maximization of power transfer and when the
minimization of reflexion of signal waves.
If you like thinking in examples, I think ZelmaB gave below two very representative examples which also sprout the the heart of my understand problem in good way as I think, I tried to explain it below:

*

*transmitter circuit (as sourse) and output antenna (as load).
Between them we assume that the is a transmission line

*high speed signals running through a transmission line between two ICs,
one considered as source, one as load
What follows now is essentially rephrasing my comments below on ZelmaB's answer.
He wrote that for Ex 1) we have to perform maximum power transfer and for
Ex 2) the minimization of reflected signal. Clearly, this
sounds reasonable from viewpoint of our everyday experience.
But what is the precise scientific/formal reason that we chose in these two
examples as the matching technique we choose and not respectively the other one.
Let's focuss on Ex 1): Why we not perform on the minimization of signal waves reflexions caused by transmission line between the transmitter circuit and the output antenna, instead of maximizing the power transfer?
Is there a formal reason (not "everyday experience" reason!) why we take here
this choice and not the other one? Eg can we argue like that is
this case the reflexion effects due to transmission lines are here
negligible, because  ... (maybe these are to short with respect to
wave length of the signal; I don't know, that's just an idea, I'm not
sure if that's the correct reason).
But I hope that my last comments help the reader of this question
to point out the problem I have and understand for what kind of arguments I'm looking for. As a mathematician I have namely
some problems with "everyday experience" arguments, and prefer to see some
formal criteria (eg something like "that's the case when the length
of transmission line behaves so and so with respect the signal wave length, and so on)

A: I think the answer to your question depends on what your are trying to achieve.
What is you application?
For example, when doing wireless communication, usually you would want to maximize power output out of your antenna which implies matching to maximum power transfer between your transmitter and antenna.
On other case, like high speed signals between ICs, you might not care so much about power but would like to maintain your signal's integrity by matching to minimize reflections between ICs.


text:
Q: How is std::advance implemented to change behavior on iterator type? What we know about std::advance is the following:
template <class InputIterator, class Distance>
void advance (InputIterator& i, Distance n);

Purpose
Advances the iterator i by n elements.
If i is a Random Access Iterator, the function uses once operator+ or operator-, otherwise, the function uses repeatedly the increase or decrease operator (operator++ or operator--) until n elements have been advanced.

My question is the following:
How is std::advance implemented such that it recognizes if it is a Random Access Iterator or not? How does it know it can use operator+ instead of operator++?

A: I would imagine it may use std::iterator_traits::iterator_category to figure out what the type of the iterator is.
Based on that, it can decide how to advance things.

A: Through iterator_traits and tag dispatch:
template<class InputIterator, class Distance>
void advance_impl(InputIterator& i, Distance n, std::random_access_iterator_tag) {
  i += n;
}

template<class InputIterator, class Distance>
void advance_impl(InputIterator& i, Distance n, std::bidirectional_iterator_tag) {
  if (n < 0) {
    while (n++) --i;
  } else {
    while (n--) ++i;
  }
}

template<class InputIterator, class Distance>
void advance_impl(InputIterator& i, Distance n, std::input_iterator_tag) {
  assert(n >= 0);
  while (n--) ++i;
}

template<class InputIterator, class Distance>
void advance (InputIterator& i, Distance n) {
  advance_impl(i, n,
    typename std::iterator_traits<InputIterator>::iterator_category());
}

Note that iterator_category is a type (one of std::input_iterator_tag etc.), so iterator_category() is not a function call; it's an expression that constructs a temporary prvalue of that type. The appropriate overload of advance_impl is then selected by normal overload resolution. This is called tag dispatch.  Equivalently one could write:
template<class InputIterator, class Distance>
void advance (InputIterator& i, Distance n) {
  typename std::iterator_traits<InputIterator>::iterator_category the_tag;
  advance_impl(i, n, the_tag);
}

The overloads of advance_impl are receiving as their third argument an unnamed argument that is an instance of their chosen tag type.


text:
Q: Swift Scroll down should make Bar Item disappear I want that the Bar Button Item diappear when I scroll down. My problem is that I don't know how to detect the scroll? I have tried some code but nothing worked. For example:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("123")
}
(Don't work, I call the method in viewDidLoad())
Also I don't know where I have to call the method. In viewDidLoad(), viewDidAppear() or somewhere else? I am new in Swift, sorry.
Does anyone know the answer?

A: The thing is you are calling it from viewDidLoad, that gets called only once when the view is loaded. You need to place this scrollViewDidScroll
 function separately, after viewDidLoad for example, but not inside of it.
Also make sure you implemented UIScrollViewDelegate in your file. Then you can add scrollViewDidScroll method to detect when is the view scrolled and print('123') inside of it.
Also make sure to set your scrollView.delegate = self in your viewDidLoad.


text:
Q: What if I write return statement in constructor? What if I write return statement in constructor? Is it standard conformant?
struct A
{
     A() { return; }
};

The above code compiles fine, without any error at ideone. But the following code doesn't:
struct A
{
   A() { return 100; }
};

It gives this error at ideone:

error: returning a value from a constructor

I understand that returning value from constructor doesn't make sense at all, because it doesn't explicitly mention return type, and we cannot store the returned value after all. But I'm curious to know :

*

*Which statement from the C++ Standard allows the first example  but forbids the second one? Is there any explicit statement?

*Is the return type in the first example void?

*Is there any implicit return type at all?

A: Yes, using return statements in constructors is perfectly standard.
Constructors are functions that do not return a value. The family of functions that do not return a value consists of: void functions, constructors and destructors. It is stated in 6.6.3/2 in the C++ standard. The very same 6.6.3/2 states that it is illegal to use return with an argument in a function that does not return a value.

6.6.3 The return statement
2 A return statement without an
  expression can be used only in
  functions that do not return a value,
  that is, a function with the return
  type void, a constructor (12.1), or a
  destructor (12.4). A return statement
  with an expression of non-void type
  can be used only in functions
  returning a value; the value of the
  expression is returned to the caller
  of the function.

Additionally, 12.1/12 states that

12.1 Constructors
12 No return type (not even void) shall
  be specified for a constructor. A
  return statement in the body of a
  constructor shall not specify a return
  value.

Note, BTW, that in C++ it is legal to use return with an argument in a void function, as long as the argument of return has type void
void foo() {
  return (void) 0; // Legal in C++ (but not in C)
}

This is not allowed in constructors though, since constructors are not void functions.
There's also one relatively obscure restriction relevant to the usage of return with constructors: it is illegal to use return in function-try-block of a constructor (with other functions it is OK)

15.3 Handling an exception
15 If a return statement appears in a
  handler of the function-try-block of a
  constructor, the program is ill formed.

A: Perhaps the notion of having typeless return in constructors is to control the termination of constructor function.
struct A
{
// more definitions
A()
{
if( !goodToGoOn)
 return;
// the rest of the stuffs go here
}
};

A: A constructor by definition does return something.
For the code below,
#include <string>
#include <iostream>
using namespace std;

class dog{
    private:
        string _name;
        string _breed;
    public:
        //initialise private variables to those passed in
        void init(string name, string breed)
        {
            _name = name;
            _breed = breed;
        }

        void bark(){cout << "BARK! BARK! My name is " << getName() << "\n";}

        string getBreed(){return _breed;}
        string getName(){return _name;}
    };

//can run with
int main(int argc, char** argv){
    //create a dog named Sally
    dog sally;
    //Initialise its variables
    sally.init("sally", "chocolate lab");
    sally.bark();
}

Here we create a void type function that initializes our dog object, then in our main function we must call that init function on our new dog object.But if use a constructor our code looks instead like
#include <string>
#include <iostream>
using namespace std;

class dog{
    private:
        string _name;
        string _breed;

    public:
        //Dog constructor to initialize passed in variables
        dog(string name, string breed){
            _name = name;
            _breed = breed;
        }

        void bark(){cout << "BARK! BARK! My name is " << getName() << "\n";}

        string getBreed(){return _breed;}
        string getName(){return _name;}
};

//can run with
int main(int argc, char** argv){
    //create a dog named Sally
    dog sally("sally", "chocolate lab");
    sally.bark();
}

This code does essentially the same thing but it is to show that a constructor initializes the passed in variables and returns the object itself.
You cannot say
dog(string name, string breed)
    {
        _name = name;
        _breed = breed;
        return cout << "BARK! BARK! My name is " << getName() << "\n";
    }


text:
Q: ng: command not found while creating new project using angular-cli Installed angular-cli globally using (npm install -g angular-cli) but when I'm trying to create project using ng new my-project it is throwing error:

ng: command not found

A: Adding %AppData%\npm to the Win path have worked for me.
Source : https://github.com/angular/angular-cli/issues/1183 , the first comment.

A: I was facing same issue, I was using git bash terminal, I installed angular cli using this command
npm install -g @angular/cli

but when I try to create new app it was giving me error ng: command not found, I just restarted my pc and it worked, even closing and opening terminal again will also fix issue sometimes

A: First, angular-cli is deprecated and has been replaced with @angular/cli. So if you uninstall your existing angular-cli with npm uninstall angular-cli, then reinstall the package with the new name @angular/cli you might get some conflicts. My story on Windows 7 is:
I had installed angular-cli and reinstalled using npm install -g @angular/cli, but after doing some config changes to command-line tools, I started getting the ng command not found issue. I spent several hours trying to fix this but none of the above issues alone worked. I was able to fix it using these steps:
Install Rapid Environment Editor and remove any PATH entries for node, npm, angular-cli or @angular/cli. Node.js will be in your System path, npm and angular entries are in the User path.
Uninstall node.js and reinstall the current version (for me 6.11.1).
Run Rapid Environment Editor again and make sure node.js and npm are in your System or User path.
Uninstall any existing ng versions with:
npm uninstall -g angular-cli

npm uninstall -g @angular/cli

npm cache clean

Delete the C:\Users\%YOU%\AppData\Roaming\npm\node_modules\@angular folder.
Reboot, then, finally, run:
npm install -g @angular/cli

Then hold your breath and run:
ng -v
If you're lucky, you'll get some love. Hold your breath henceforward every time you run the ng command, because 'command not found' has magically reappeared for me several times after ng was running fine and I thought the problem was solved.

A: Same problem here running Windows 10 x64 / NodeJS 6.9.1 / npm 3.10.9.  After installation of Angular CLI via npm:

'ng' command cannot be found

Do the following:

*

*Uninstalled npm with npm uninstall -g npm

*Uninstalled NodeJS via control panel / programs and features

*Downloaded and ran 'old' NodeJS installer release 6.5.0 from https://nodejs.org/download/release/v6.5.0/ (node-v6.5.0-x64.msi).

*After NodeJS 6.5.0 installation completed, open powershell and npm install -g angular-cli

*Grab quick coffee

*After installation completed, ng worked OK.

HTH

A: Make sure angular-cli is installed before trying to create a project. Windows users can install angular-cli without giving permission to command but MAC users have to use sudo before executing the command as follow:
sudo npm install -g angular-cli

Type a password when asked and press enter to proceed.

A: First of all, check if your npm and node installed properly
with commands npm version and node -v.
If they are proper:

*

*Find the root global Directory of NPM npm root -g (it will
give you root of your global npm store)

*Uninstall old angular cli with npm uninstall -g angular-cli
and npm cache clean

*Reinstall new Version of angular npm install -g @angular/cli@latest

*make an Alias of Name ng:
alias ng="C:/ProgramData/npm/node_modules/@angular/cli/bin/ng"
alias ng="<ath-to-your-global-node-modules>/<angular cli path till ng>"
(from answered Oct 20 '16 at 15:30  @m.zemlyanoi )
then to check you can type ng -v

A: For Mac users:
1) Install @angular/cli globally
$ sudo npm install -g @angular/cli
/usr/local/Cellar/node/10.0.0/bin/ng -> /usr/local/Cellar/node/10.0.0/lib/node_modules/@angular/cli/bin/ng

2) Create alias for ng
alias ng="/usr/local/Cellar/node/10.0.0/lib/node_modules/@angular/cli/bin/ng"

Done

A: try this :
alias ng="~/node_modules/@angular/cli/bin/ng"

A: For mackBook OS
sudo npm uninstall -g @angular/cli
sudo npm cache verify
sudo npm install -g @angular/cli@latest

try with ng -v if not work then set alias and try
alias ng="/usr/local/Cellar/node/10.0.0/lib/node_modules/@angular/cli/bin/ng"

A: Make sure that the npm directory is in your "Path" variable.
If the module is installed properly, it may work if you start it out of your global node module directory, but your command line tool doesn't know where to find the ng command when you are not in this directory.
For Win system variable add something like:
%USERPROFILE%\AppData\Roaming\npm

And if you use a unix-like terminal (emulator):
PATH=$PATH:[path_to_your_user_profile]/path-to-npm

A: if you find this error when you are installing angular-cli,
-bash: ng: command not found try this it works,
After removing Node from your system
install NVM from here https://github.com/creationix/nvm
Install Node via NVM: nvm install stable
run npm install -g angular-cli

A: The issue is simple, npm doesn't know about ng
Just run npm link @angular/cli and it should work seamlessly.

A: the easiest solution is (If you have already installed angular) :
1 remove the ng alias if existing
unalias ng

2 add the correct alias
alias ng="/Users/<user_name>/.npm-global/bin/ng"

3 run ng serve for example and it will work.

A: This is how I made it worked for me :).
1 - npm link @angular/cli
It will return you the path of cli, which will look like this
/usr/local/Cellar/node/11.3.0_1/lib/node_modules/@angular/cli

For this part, /11.3.0_1 please replace this with your respective node version that can be found by typing node --version
2 - cd ~/
3 - open .bash_profile
In the bash profile create an alias for cli like this,
alias ng="/usr/local/Cellar/node/11.3.0_1/lib/node_modules/@angular/cli/bin/ng"
4 - source ~/.bash_profile
This is how your .bash_profile will look like once you add alias to it.

Now typing ng in the terminal will display output shown in attached snapshot.

I hope this answer will be helpful.

A: Do you install the node js package? https://nodejs.org/en/
Regards

A: According to npm, the  angular-cli has been renamed to @angular/cli you can use the following syntax to install it.
npm install -g @angular/cli

A: If you are using asdf-vm you need run adsf reshim nodejs to recreate links with global modules.
In my case this resolve my problem, I hope resolve to you all too.

A: Most likely the problem is that you are using PowerShell and not the command line. If you use Windows PowerShell run:
cmd

then next try:
ng --version

if it works run:
ng new my-project

A: For Mac run
npm install -g @angular/cli@latest
then run
alias ng="/usr/local/lib/node_modules/node/lib/node_modules/@angular/cli/bin/ng"

Check if working
ng version

A: In my case install angular cli
npm install -g @angular/cli@latest

update Nodejs to latest, then all should work fine.
...and if you still have that problem, it maybe because you run the command in shell and not in cmd (you need to run command in cmd), check this out and maybe it helps...

A: Run below commands:
npm uninstall -g angular-cli

npm uninstall -g @angular/cli

npm cache clean

npm install -g @angular/cli@latest

alias ng="C:/Users/itaas/.npm-global/ng"  ( Location of ng file in npm folder)
And finally run :
ng -v

A: If you have installed angular cli globally but ng isn't working, just do this:
echo -e "export PATH=$(npm prefix -g)/bin:$PATH" >> ~/.bashrc

source ~/.bashrc

ng --version

A: I've solved the same issue with adding an alias like:
alias ng="path-to-your-global-node-modules/angular-cli/bin/ng"

A: soluton for windows operating system only.......
first step:
install nodejs version: nodev 8.1.2
second step:
set up environment variable like: C:\ProgramFiles\nodejs
Third step:
install angular use this command: npm install -g @angular/cli
after installation whereever you have to create project like: ng new first-project......

A: For me (on MacOSX) I had to do:
nvm install stable
npm install -g angular-cli

This installed ng into:
/usr/local/lib/node_modules/@angular/cli/bin/ng

But npm did not put a link to ng into
/usr/local/bin/

Which was why it was not part of the %PATH and therefore available from the command line except via an absolute address.
So I used the following the create a link to ng:
sudo ln -sf /usr/local/lib/node_modules/\@angular/cli/bin/ng /usr/local/bin/ng

A: This worked for me:

*

*Go to C:\Users{{users}}\AppData\Roaming and delete the npm folder

*Uninstall node and install it again

*Run the command to install angular cli
npm install -g @angular/cli

A: running
export PATH=$PATH:/c/Users/myusername/AppData/Roaming/npm

helped.
Make sure your actual username is in the myusername section

A: Repairing NodeJS installation on windows resolved it for me.

A: I came here because I had the same issue on windows. The thing that baffled me most on this was I have had Node installed since Angular 4 dabbling here and there. And sure enough. That was my problem. I needed to upgrade node.
Just installing the newest version worked fine for me without having to do any of the above steps post the new install

A: Maximum time, this is a path issue conflict between npm and angular cli.
The solution that worked for me ->

*

*%USERPROFILE%\AppData\Roaming Paste this in File Explorer and delete npm folder.

*npm install -g @angular/cli@latest run this command to reinstall latest angular cli.

*npm link @angular/cli now this command can solve your path issue

Literally that three steps will fix your issue, otherwise you need to update environment variable by search and open Edit the system environment variables
Ariful Ahsan
https://arifulahsan.com

A: If you are working in windows 7 and you can not run command start with ng
please, update the angular/CLI at once and try to use ng commands
use below comman to update latest CLI
npm install -g @angular/cli@latest

A: This works to update your angular/cli
//*Global package (cmd as administrator)
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@latest

A: Firstly install '@angular/cli' by using npm as global module
sudo npm install -g @angular/cli

After that try to ping the cli by using 'ng' command from the terminal window.If any problem like

Command 'ng' not found

Then you need to manually setup the

ng

command availability.You set this step by running the following command.
ln -s path-to-your-ng-command /bin

eg:
sudo ln -s /opt/node/lib/node_modules/@angular/cli/bin/ng /bin/

A: In my case, it was happening when I restarted working on an adjacent tab. It was the npm which was not set. Please check the version of npm wither using

npm -v

or if you are having nvm then

nvm list

or

nvm current

I set it to 8.9.1 and then it started working again.
I hope it helps.

A: In my case, I was simply running the wrong node version.
I had just previously installed a new node version to play around with Angular (2).
At work we use 6.x so that is my default in nvm. After restarting the laptop ng stopped working simply because I was running node 6.x again. So for me it was simply a matter of using the version with which I was installing the Angular CLI:
nvm use node // with the node alias pointing to the right version

or
nvm use v8.11.3 // if you happen to know the version

Check your installed versions and aliases with
nvm list

A: If you have a MacOS computer (mine is MOJAVE 10.14.2), just add these lines to the end of your ~/.bash_profile file:
export ANGULAR=~/.nvm/versions/node/v10.8.0/bin/ng
export PATH=$ANGULAR:$PATH

Notice that v10.8.0 is the version of my installed Node.js. To get which version is yours, run this:
node --version

When done, reload it via your terminal/bash:
cd ~
source .bash_profile

After doing these steps you should be able to run your ng binary file.

A: If you have zsh installed add alias to .zshrc file in home directory as well.

A: If you use enterprise computer and unable to access system environments
use RapidEE to edit user variables
then add to path these
%AppData%\npm

or
%USERPROFILE%\AppData\Roaming\npm

it worked for me on windows

A: Permanently solution here for MACOS Users:
open terminal:
sudo vim /etc/Paths

add new line. (INSERT , press fn+i)
/Users/[your-user]/.npm-global/bin

press ESC , and then :wq  (exit from editor)
restart terminal (close and open terminal again..)
check the path;
~ % echo $PATH

it should be listed in path list now.. like below;
/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/[myuser]/.npm-global/bin ....

good job,  ng command now,
ng version
Angular CLI: 14.1.0

A: After trying everything here, what solved my issue was:

*

*Making sure I have the latest node.js version (re-install from here: https://nodejs.org/en/download/)

*Running the commands from the powershell

A: for me, on Linux:
you can open the .bashrc file from Home then, you will notice the following command right there:
# Load Angular CLI autocompletion.
source <(ng completion script)
comment out the "source" command that you see above by # sign then, save the file.
# source <(ng completion script)
reopen the terminal then, you could use it now.
you can now use the following command instead of ng:
open the working directory where the Angular project is there then, try this command instead:
$ npm start
you can open the package.json file and move to the line where the "scripts" key is, move to "start" key then, you will notice the ng serve that you were like to type then, you can add host and port from your choice like so:
"start": "ng serve --host 0.0.0.0 --port 4200"