text:
Q: How to build a WebRTC media server for a Twitch-like application I am trying to build an application like twitch (i.e. many-to-many real-time video streams). I want to use WebRTC because I want to make the app accessible from all platforms (I am planning to either go with Nativescript or the PWA road). My plan is to stream the camera from person A to the media server. Transcode the WebRTC stream in multiple qualities, etc. and send it to all of the subscribed users, who are also able to play WebRTC streams. In the ideal case, there will be thousands of streamers, each with thousands of real-time subscribers.
How can this be done, however? I need some kind of media server which will be responsible to take the stream, transcode it and forward it. An MVP would be to just forward the stream, without transcoding it, however, it should be possible to add that optimization in the future.
Should I go for something like Kurento, Jitsi, etc? Or is it feasible that I can build this server myself?
Is this architecture even a good idea, or should I rethink everything? The reason I am not going for RTMP or something similar is because of the amount of code and work that has to be put into developing the different client codes for native apps (iOS, Android, any ol' browser). If I can use WebRTC, this will make the client code much easier and will make the app accessible on all platforms.
Thanks a lot in advance!

A: An ambitious project, it will be complicated
First of all:
A media server is a good (even a necessary) choice, if you plan to write a large scale application. And either transcribing or making the sender send multiple video stream qualities will improve your users experience.
Now to the media servers:
You are only interested in forwarding media, ergo sfu based or similar servers.
Jitsi and Kurento both can do this (but Kurento is more often associated as a mixing server).
I cannot give you advise on which of them to use since I have not enough experience with them.
The SFU approach scales well and may be enough for your application but for a large scale service like twitch, you may also have a look at CDN supported technologies. Classically, this is DASH or HLS. Both will increase latency, but since you do not have two or multiple users speaking with each other in real time, but only one person broadcasting, this may be tolerable.
I have looked into this problem myself and found something related here which may help you.
The basic idea is sending the video to the server via webrtc (low latency but not necessarily scaling well when you reach the sfu's limits) and then encoding the video for DASH (or more optimized CMAF). Then, your content can be served by CDNs, which may allow you to scale up the service.
But why not have a look at what twitch says about itself? Here's an article where they list their services and talk briefly about how they work:
twitch engineering - an introduction and overview


text:
Q: How to fix Parallels Management Node if DHCP server filters MAC address I'm evaluating Parallels Server on Mac OS X  Lion Server, and during installation it sets up a "Management Node" VM for managing the other VMs. The problem is that my DHCP server is filtering MAC addresses, so for now the installation fails since connection can't be established.
How can I know its MAC address so that I can authorize it?

A: Actually restarting the server allowed me to see the MAC address in Management Console.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "high" vs. "tall"

*

*The chimney in the picture above is more than 20m high.

*The chimney in the picture above is more than 20m tall.
Are both high and tall proper in these sentences?
If not, why not? And when should one prefer high over tall, and vice versa?

A: Both are acceptable, but I'm sure high would be more common. People tend to use tall in reference to objects of human scale; a 200-foot chimney stack is only marginally within that category. Thus:

Everest is 29,nnn feet high 154 hits in Google Books
Everest is 29,nnn feet tall 34 hits.
Everest is the highest [mountain] 14,700 hits
Everest is the tallest [mountain] 2,050 hits

As Jim correctly comments, you can often interpret high as a reference to the "elevation" of something (i.e. - distance above ground/sea level), whereas tall is usually a reference to the "length" of something in its vertical plane.

Not directly involved here, but worth pointing out, is that because of that connection between tall and the human scale/shape, we also tend to use tall for "rod-shaped" things perpendicularly oriented, and high for things with a more "extended" top surface. Thus:

[The] wall is six feet high 1,260 hits
[The] wall is six feet tall 2 hits

A: For chimneys (like the one in the photo), towers, skyscrapers, trees, people  and anything else you can think whose height is purely vertical, native speakers will tend to prefer: tall.
For mountains, buildings that are wide as well as tall, walls, women heels, and for ground use high.

*

*The leaning tower of Pisa is only 55.86 meters tall

*I am taller than my sister.

but

*

*Six-inch high heel shoes

*A high-rise building
However, look at how both adjectives are used here. And yet fully acceptable.

*

*The world's tallest tree is hiding somewhere in California. (...) It's 369 feet high
Why did the writer prefer 369 feet high instead of tall? To avoid repetition? Because when measuring the distance from the ground, the word high just sounded
better or perhaps more authoritative? I don't know! :)

A: I would have to disagree with @FumbleFingers.  This may be a US vs. UK thing (I'm American), but I think that it sounds odd when he describes a mountain as being "high."  I would definitely say that a mountain is "tall."  If you want to use Google hits as a metric, I found these results:
"highest mountain" 412,000 results
"tallest mountain" 755,000 results
As a basic rule, I would say if both the top and bottom of something are far from the ground, then it is high (e.g. a branch in a tree is high).  If the top is high and the bottom is low, then I would describe it as tall (e.g. the tree itself is tall).
Addendum: after much discussion, the major take-away for an English Language Learner is that nobody is going to question your English proficiency based on your choice of "tall" vs. "high" in this context.  We can debate until the cows come home, but either word is perfectly acceptable here.

A: They would both be correct here. The main difference is that tall always refers to the height of something (its size), whereas high (while used this way for structures), can be (and often is) used to describe the elevation of something.

A: Regarding the original question, I think both are fine. (I'm Irish BTW.) But here's something to consider when to use "high" and when to use "tall". Imagine there is a small town with a big hill. At the bottom of this hill is a ten-story building. Every other building is a two-story building. And one of these two-story buildings sits at the top of the hill looking down on the ten-story building. In this example, I would say the building at the bottom of the hill is the tallest building in the town but the building at the top of the hill is the highest building in the town. Using this logic, I would say that it is more appropriate to say the building is tall but for a mountain, it doesn't really matter. The thing is, though, that logic and English don't always get along.

A: Tall is generally for when you are measuring the distance from the ground.
High is generally used when you don't really care about the exact distance from the ground.
However, I liked the answer above with rod vs. flat-shaped objects. There is something to that.


text:
Q: How to retrieve a message link if it contains a specific string? I tried doing something like this
ctx = message
"https://discordapp.com/channels/"+ctx.guild.id+"/"+ctx.channel.id+"/"+ctx.id
"https://discordapp.com/channels/"+guild.id+"/"+ctx.channel.id+"/"+ctx.id
Neither worked
If you're confused, Lets say if the message contains "hi" I want it to copy the message link and post it, so if someone clicks on the link it redirects them to that message
Thank you for reading.

A: @client.command()
async def keyword(ctx, *, word: str):  # Usage: !keyword hi
    messages = await ctx.channel.history(limit=200).flatten()  # Get last 200 messages

    for msg in messages:  # Iterate through all messages.
        if word in msg.content:
            await ctx.send(msg.jump_url)  # Send the jump link to the message containing the word.

A: discord.Message.jump_url

Reference:https://discordpy.readthedocs.io/en/latest/api.html?highlight=jump_url#discord.Message.jump_url


text:
Q: Batched Cross Correlation in Tensorflow I need to perform 2D cross convolution (e.g. like MATLAB's https://www.mathworks.com/help/signal/ref/xcorr2.html) across a batch of pairs of feature maps.
For clarification:
Let X be B x W1 x H1 x C and Y be B x W2 x H2 x C.
The output I want is of shape B x W2 x H2 x 1 (assuming we treat X as the "filter" we pass over Y with SAME padding) where the i-th 1 x W2 x H2 x 1 slice of the output is the cross correlation between the X[i,:,:,:] and Y[i,:,:,:] e.g. something like
tf.nn.conv2d(Y[i,:,:,:], X[i,:,:,:], [1,1,1,1], padding='SAME')

Is there an efficient way to implement this operation?
Note: if X is 1 x W1 x H1 x C and we want to cross-correlate it with Y at each slice B, this is easy:
cross_corr = tf.nn.conv2d(
    Y, tf.transpose(X, perm[1,2,3,0], [1,1,1,1], padding='SAME')

which takes advantage of the fact that Tensorflow implements conv2d as cross correlation and the fact that the we can treat the smaller tensor as essentially a filter after transposing. This does NOT solve my issue because I need to take the cross convolution of B different filters.
Maybe conv3d is a possibility?
Note2: matconvnet's vl_nnconv does this if the filter channels divides the input channels. Does Tensorflow have an equivalent?

A: You can use the tf.map function like I showed here.
I tried back then to use conv3d but didn't find a way to make it work.

A: [TensorFlow 2.x version]
I am not sure if this method was around at the time this question was asked, but you can try tf.nn.convolution:
https://www.tensorflow.org/api_docs/python/tf/nn/convolution
It looks like the method supports multiple filters, and deals with N-D convolutions, where N must be 1, 2, or 3.


text:
Q: Error Cross-compiling libfaac for Android NDK r8d on Mac OS X I am trying to cross-compile libfaac for android on an mac machine and am running into some difficulty.
The Setup

*

*Android NDK r8d

*Mac OS X 10.7.5 (64-bit)

*libfaac 1.28

I found this link: Android NDK r6b Cross-compiling libfaac for android (linking libsupc++ problems) and used that as the starting point for my script and made modifications for the more recent versions of the android ndk and processors (armv7a) that I am using.  This is my script:
#!/bin/bash
ANDROID_API=android-14
export ANDROID_NDK=${HOME}/Development/android-ndk-r8d
export ANDROID_SDK=${HOME}/Development/android-sdk-macosx
SYSROOT=$ANDROID_NDK/platforms/$ANDROID_API/arch-arm
ANDROID_BIN=$ANDROID_NDK/toolchains/arm-linux-androideabi-4.7/prebuilt/*-x86/bin/
CROSS_COMPILE=${ANDROID_BIN}/arm-linux-androideabi-
export PATH=$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools

export ARM_INC=$ANDROID_NDK/platforms/android-14/arch-arm/usr/include
export ARM_LIB=$ANDROID_NDK/platforms/android-14/arch-arm/usr/lib

DEST=${HOME}/Downloads/faac-1.28/build
CFLAGS=" -I$ARM_INC -fpic -DANDROID -fpic -mthumb-interwork -ffunction-sections -funwind-tables -fstack-protector -fno-short-enums -Wno-psabi -march=armv7-a -mtune=xscale -msoft-float -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 -DANDROID  -Wa,--noexecstack -MMD -MP "
LDFLAGS=" -nostdlib -Bdynamic -Wl,--whole-archive -Wl,--no-undefined -Wl,-z,noexecstack  -Wl,-z,nocopyreloc -Wl,-soname,/system/lib/libz.so -Wl,-rpath-link=$ARM_LIB,-L$ANDROID_NDK/sources/cxx-stl/gnu-libstdc++/libs/armeabi -L$ANDROID_NDK/toolchains/arm-linux-androideabi-4.7/prebuilt/darwin-x86/arm-linux-androideabi/lib -L$ARM_LIB  -lc -lgcc -lm -ldl  "
FLAGS="--host=arm-androideabi-linux --enable-static --disable-shared --prefix=$DEST --enable-armv7a  "

export CPPFLAGS="$CFLAGS"
export CFLAGS="$CFLAGS"
export CXXFLAGS="$CFLAGS"
export CXX="${CROSS_COMPILE}g++ --sysroot=${SYSROOT}"
export LDFLAGS="$LDFLAGS"
export CC="${CROSS_COMPILE}gcc --sysroot=${SYSROOT}"
export NM="${CROSS_COMPILE}nm"
export STRIP="${CROSS_COMPILE}strip"
export RANLIB="${CROSS_COMPILE}ranlib"
export AR="${CROSS_COMPILE}ar"

./configure $FLAGS
make clean
make -j4 || exit 1
make install || exit 1

The Problem
Unfortunately the script, as is, fails to run properly.  I receive a configure: error: C compiler cannot create executables error and the config.log file shows the following culprit:
configure:2767: $? = 1
configure:2790: checking for C compiler default output file name
configure:2817: /Users/jannon/Development/android-ndk-r8d/toolchains/arm-linux-androideabi-4.7/prebuilt/*-x86/bin//arm-linux-androideabi-gcc --sysroot=/Users/jannon/Development/android-ndk-r8d/platforms/android-14/arch-arm  -I/Users/jannon/Development/android-ndk-r8d/platforms/android-14/arch-arm/usr/include -fpic -DANDROID -fpic -mthumb-interwork -ffunction-sections -funwind-tables -fstack-protector -fno-short-enums -Wno-psabi -march=armv7-a -mtune=xscale -msoft-float -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 -DANDROID  -Wa,--noexecstack -MMD -MP   -I/Users/jannon/Development/android-ndk-r8d/platforms/android-14/arch-arm/usr/include -fpic -DANDROID -fpic -mthumb-interwork -ffunction-sections -funwind-tables -fstack-protector -fno-short-enums -Wno-psabi -march=armv7-a -mtune=xscale -msoft-float -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 -DANDROID  -Wa,--noexecstack -MMD -MP   -nostdlib -Bdynamic -Wl,--whole-archive -Wl,--no-undefined -Wl,-z,noexecstack  -Wl,-z,nocopyreloc -Wl,-soname,/system/lib/libz.so -Wl,-rpath-link=/Users/jannon/Development/android-ndk-r8d/platforms/android-14/arch-arm/usr/lib,-L/Users/jannon/Development/android-ndk-r8d/sources/cxx-stl/gnu-libstdc++/libs/armeabi -L/Users/jannon/Development/android-ndk-r8d/toolchains/arm-linux-androideabi-4.7/prebuilt/darwin-x86/arm-linux-androideabi/lib -L/Users/jannon/Development/android-ndk-r8d/platforms/android-14/arch-arm/usr/lib  -lc -lgcc -lm -ldl   conftest.c  >&5
/s/ndk-toolchain/src/build/../gcc/gcc-4.7/libgcc/config/arm/linux-atomic-64bit.c:59: error: undefined reference to '__write'
collect2: error: ld returned 1 exit status
configure:2820: $? = 1
configure:2858: result:
configure: failed program was:
| /* confdefs.h.  */
| #define PACKAGE_NAME "FAAC"
| #define PACKAGE_TARNAME "faac"
| #define PACKAGE_VERSION "1.28"
| #define PACKAGE_STRING "FAAC 1.28"
| #define PACKAGE_BUGREPORT "faac-dev@lists.sourceforge.net"
| #define PACKAGE "faac"
| #define VERSION "1.28"
| /* end confdefs.h.  */
|
| int
| main ()
| {
|
|   ;
|   return 0;
| }
configure:2865: error: C compiler cannot create executables

The Solution?
I'm not the most well-versed in the ins and outs of c/c++ compilation/linkage mechanisms, so  I really have no idea why the __write function isn't defined.  I imagine there might just be some issue with the compiler, linker, or configure flags I'm using, but maybe there is something wrong with the general setup of my environment.  I am, however, able to successfully cross-compile other projects (libx264, libmp3lame, ffmpeg).
So I am looking for pointers to get this working, or any other setup that will get libfaac compiled for android (armv7a)
Thanks!


text:
Q: Approximating a function to six terms Considering the following period function $f(x)$ with period $2\pi$ ( i.e $f(x+2\pi)=f(x))$ $$f(x) = e^x, - \pi \leq x \leq \pi.$$ I have determined the Fourier series of this given function to be, which I believe I have done correctly, $$e^x = \frac{\sinh \pi}{\pi} + \sum_{n=1}^{\infty} (-1)^n\frac{2\sinh \pi}{\pi (n^2+1)} \cos nx - (-1)^n \frac{2n \sinh \pi}{\pi(n^2+1)}\sin nx$$ $$e^x = \frac{\sinh \pi}{\pi} \big[1+2\sum_{n=1}^{\infty}\frac{(-1)^n}{n^2+1} \big](\cos nx - n\sin x)$$ I now need to approximate the function $f(x)$ with a finite Fourier series to six terms. My problem with this is I dont understand what will happen with the $x's$ in the Fourier series I have completed. So say for the first term, $n=1$ we would get, $$ \frac{\sinh \pi}{\pi} \big[1+2\frac{(-1)}{1^2+1} \big](\cos x - \sin x)$$ $$3.67608\big[ 0\big](cosx-sinx)$$ $$ = 0 $$ Then for the second term, $n=2$, $$ \frac{\sinh \pi}{\pi} \big[1+2\frac{(-1)^2}{2^2+1} \big](\cos x - \sin x)$$ $$3.67608\big[ 1.4\big](cosx-sinx)$$ So then how do I solve for the second term. Then finally once I have calculated all the terms up to $n = 6$ do I then add all of them up to approximate the function? or do I just use the value for $n = 6 $

A: Approximating a function means finding a new form of the function that is almost equivalent, but we do it to make it easier.
When doing this, the property of being a function of $x$ does not dissappear. You replaced a complicated function by a sum of six terms, and that's nice and sometimes useful.
However, the roiginal function depends on $x$. It's logical that the series depends of $x$ too. For a given $x$, you will get different values both for the original $e^x$ and the series one.
You may want to do this for certain values, or you may want to leave it like this, anallytically. The point of this approximation is converting a complicated function into an "easy" sum (which usually turns out to be hard), but a sum, after all. A sum of functions, which depend on $x$ as well, but now the functions are meant to be easier.


text:
Q: How can i manipulate data within a factor level by a subset of another factor in that level in a dataframe without loops I have a data frame made up of absorption spectra from multiple sample runs (sample a, b, c, d), where Ydata is wavelength and Xdata is absorption. I am calculating a baseline corrected absorption by subtracting the average absorption over a quiet wavelength range away from peaks of interest.
simplified dataframe:
DF <- data.frame(
  group = rep(c("a", "b", "c", "d"),each=10),
  Ydata = rep(1:10, times = 4),
  Xdata = c(seq(1,10,1),seq(5,50,5),seq(20,11,-1),seq(0.3,3,0.3)),
  abscorr = NA
)

I need to correct each sample run by subtracting the mean of a subsetted wavelength range within the run. I've been doing it this way:
for (i in 1:length(levels(DF$group))){
  sub1 <- subset(DF, group == levels(DF$group)[i], select = c(group, Ydata,
  Xdata));
  sub2 <- subset(sub1, Ydata > 4 & Ydata < 8, select = c(group, Ydata,
  Xdata));
  sub1$abscorr <- sub1$Xdata - mean(sub2$Xdata);
  DF <- rbind(sub1, DF);
}

and then tidy up all the 'NA's
DF <- na.omit(DF)

The way done above is obviously clunky with use of loops. Is there a better way to go about this task for a large dataset? perhaps dplyr?

A: Try dplyr:
DF %>%
    group_by(group) %>%
    mutate(abscorr = Xdata - mean(Xdata[Ydata < 8 & Ydata > 4]))

A: I believe this will do it.
fun <- function(x){
    x$Xdata - mean(x[which(x$Ydata > 4 & x$Ydata < 8), "Xdata"])
}
DF$abscorr <- do.call(c, lapply(split(DF, DF$group), fun))

Note that when I tested it, all.equal gave me a series of differences, namely the attributes of the two results are different. So I ran the following.
fun <- function(x){
    x$Xdata - mean(x[which(x$Ydata > 4 & x$Ydata < 8), "Xdata"])
}
DF2 <- DF
DF2$abscorr <- do.call(c, lapply(split(DF2, DF2$group), fun))

all.equal(DF[order(DF$group, DF$Ydata), ], DF2)
# [1] "Attributes: < Names: 1 string mismatch >"
# [2] "Attributes: < Length mismatch: comparison on first 2 components >"
# [3] "Attributes: < Component 2: names for target but not for current >"
# [4] "Attributes: < Component 2: Attributes: < Modes: list, NULL > >"
# [5] "Attributes: < Component 2: Attributes: < Lengths: 1, 0 > >"
# [6] "Attributes: < Component 2: Attributes: < names for target but not for current > >"
# [7] "Attributes: < Component 2: Attributes: < current is not list-like > >"
# [8] "Attributes: < Component 2: target is omit, current is numeric >"
# [9] "Component "abscorr": Modes: numeric, logical"
#[10] "Component "abscorr": target is numeric, current is logical"

As you can see there is no difference in the calculated values of abscorr, only in the attributes. Among those, there are differences in the na.omit attribute or the rownames. I wouldn't worry if I were you, since the values of abscorr are equal.
EDIT.
Note that if I sort DF and then set the problem attributes to NULL both all.equal and the much more strict identical return TRUE.
DF1 <- DF[order(DF$group, DF$Ydata), ]  # Modify a copy, keep the original
row.names(DF1) <- NULL
attr(DF1, "na.action") <- NULL

all.equal(DF1, DF2)
#[1] TRUE
identical(DF1, DF2)
#[1] TRUE


text:
Q: SQL subquery trying to find entries of main table by matching with sub table Please help me in resolving below query. Table A has EMP_NO (pk) , EMP_NAME and Table B has EMP_NO (not unique), EMP_REPORTEE , Need to query Table A info where EMP_REPORTEE does not have "CLERK"
example:
TABLE A
EMP_NO EMP_NAME
100    VICTOR
200    JOHN
300    AASIF

TABLE B
EMP_NO  EMP_REPORTEE
100     MANAGER
100     OPERATOR
200     OPERATOR
200     CLERK
300     MANAGER
300     CLERK

Resultant query must have EMP_NO 100
I tried to write subquery like below
SELECT EMP_NO, EMP_NAME
FROM TABLE A,
     TABLE B
WHERE A.EMP_NO = B.EMP_NO AND
      B.REPORTEE != 'CLERK'

A: You can chekc with a correlated subquery and EXISTS if one employee is a not a clerk
SELECT t1."EMP_NO", t1. "EMP_NAME" FROM TableA t1 WHERE NOT EXISTS(SELECT 1
  FROM TableB t2 WHERE t2."EMP_NO" = t1."EMP_NO" AND t2. "EMP_REPORTEE" = 'CLERK')


text:
Q: Can I use Insert_Row as trigger for cell.setFormula? Novice Google Apps Scripter here,
I have an IFTTT applet which adds a row to this spreadsheet via email: Data Test
Thanks to the amazing StackOverflow community, I'm now able to manually add a row which sets up the needed formulas with the correct reference, I'd like the script to automatically set those same formulas into corresponding cells of any new row that is inserted.
For example, my IFTTT.com automation will populate cells A6 and B6 with text (i.e., creating next blank row in linked spreadsheet) -- I need all of the formulas currently entered to then apply to B6 (as opposed to B2)
var ss = SpreadsheetApp.getActiveSpreadsheet();
function onOpen() {
  var items = [
    {name: 'Add Row', functionName: 'addrow'},
  ];
    ss.addMenu('Add Row', items);
    }

function addrow() {
  var ui = SpreadsheetApp.getUi();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var result = ui.prompt(
      'Enter number of Row',
      ui.ButtonSet.OK_CANCEL);

    // Process the user's response.
  var button = result.getSelectedButton();
  var rownum = result.getResponseText();
  if (button == ui.Button.OK) {
    // User clicked "OK".
  sheet.insertRowAfter(rownum);
  var cell = sheet.getRange("C" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("details",$B' + rownum +')+7,SEARCH(",",$B' + rownum +')-SEARCH("details",$B' + rownum +')-7),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("D" + rownum);
  cell.setFormula('=IFERROR(TRIM(LEFT(SUBSTITUTE(MID(B' + rownum +',FIND("$",B' + rownum +'),LEN(B' + rownum +'))," ",REPT(" ",100)),100)),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("E" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("exceed",$B' + rownum +')+7,SEARCH("%",$B' + rownum +')-SEARCH("exceed",$B' + rownum +')-6),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("F" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("due",$B' + rownum +')+3,SEARCH(";",$B' + rownum +')-SEARCH("due",$B' + rownum +')-3),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("G" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("held on",$B' + rownum +')+7,SEARCH(". Lottery",$B' + rownum +')-SEARCH("held on",$B' + rownum +')-7),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("H" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("posted by",$B' + rownum +')+9,SEARCH(". ",$B' + rownum +')-SEARCH("",$B' + rownum +')-167),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  } else if (button == ui.Button.CANCEL) {
    // User clicked "Cancel".

  } else if (button == ui.Button.CLOSE) {
    // User clicked X in the title bar.

  }
}

To be clear, what I'd like to do (instead of adding a menu to manually insert a row) is have a script that detects whenever a new row is inserted, triggering the following:
  var cell = sheet.getRange("C" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("details",$B' + rownum +')+7,SEARCH(",",$B' + rownum +')-SEARCH("details",$B' + rownum +')-7),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("D" + rownum);
  cell.setFormula('=IFERROR(TRIM(LEFT(SUBSTITUTE(MID(B' + rownum +',FIND("$",B' + rownum +'),LEN(B' + rownum +'))," ",REPT(" ",100)),100)),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("E" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("exceed",$B' + rownum +')+7,SEARCH("%",$B' + rownum +')-SEARCH("exceed",$B' + rownum +')-6),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("F" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("due",$B' + rownum +')+3,SEARCH(";",$B' + rownum +')-SEARCH("due",$B' + rownum +')-3),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("G" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("held on",$B' + rownum +')+7,SEARCH(". Lottery",$B' + rownum +')-SEARCH("held on",$B' + rownum +')-7),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
  var cell = sheet.getRange("H" + rownum);
  cell.setFormula('=IFERROR(MID($B' + rownum +',SEARCH("posted by",$B' + rownum +')+9,SEARCH(". ",$B' + rownum +')-SEARCH("",$B' + rownum +')-167),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');

Any assistance will be greatly appreciated!

A: This works anytime the spreadsheet is edited. You may have to test it as "ANYTIME" it is edited it adds the functions. Does not seem the best way to do it, however it is somewhat what you were looking for.

function onEdit(e){
    var ui = SpreadsheetApp.getUi();
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheets()[0];
    var range = e.range;
    var range2 = range.getRow();
    var destrange = range2 + 1;

    // inserts blank row after last edit.
    sheet.insertRowAfter(range2);

    // adds the formulas
    var cell = sheet.getRange("C" + destrange);
    cell.setFormula('=IFERROR(MID($B' + destrange +',SEARCH("details",$B' + destrange +')+7,SEARCH(",",$B' + destrange +')-SEARCH("details",$B' + destrange +')-7),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("D" + destrange);
    cell.setFormula('=IFERROR(TRIM(LEFT(SUBSTITUTE(MID(B' + destrange +',FIND("$",B' + destrange +'),LEN(B' + destrange +'))," ",REPT(" ",100)),100)),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("E" + destrange);
    cell.setFormula('=IFERROR(MID($B' + destrange +',SEARCH("exceed",$B' + destrange +')+7,SEARCH("%",$B' + destrange +')-SEARCH("exceed",$B' + destrange +')-6),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("F" + destrange);
    cell.setFormula('=IFERROR(MID($B' + destrange +',SEARCH("due",$B' + destrange +')+3,SEARCH(";",$B' + destrange +')-SEARCH("due",$B' + destrange +')-3),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("G" + destrange);
    cell.setFormula('=IFERROR(MID($B' + destrange +',SEARCH("held on",$B' + destrange +')+7,SEARCH(". Lottery",$B' + destrange +')-SEARCH("held on",$B' + destrange +')-7),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("H" + destrange);
    cell.setFormula('=IFERROR(MID($B' + destrange +',SEARCH("posted by",$B' + destrange +')+9,SEARCH(". ",$B' + destrange +')-SEARCH("",$B' + destrange +')-167),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');

}

A: As suggested in this related SO post - Google Script: function that insert new row copying functions/formulas from last row, try using getFormula() from previous row and setFormula() to the new row.
getFomula() code :
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];

 // This assumes we have a function in B5 that sums up
 // B2:B4
 var range = sheet.getRange("B5");

 // Logs the calculated value and the formula
 Logger.log("Calculated value: %s Formula: %s",
            range.getValue(),
            range.getFormula());

setFormula() code:
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];

 var cell = sheet.getRange("B5");
 cell.setFormula("=SUM(B3:B4)");

Hope this helps.

A: A different way to do this- Now if the last row column B is not blank it will fill in formulas. Works on each edit.

function onEdit(){
    var ui = SpreadsheetApp.getUi();
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheets()[0];
    var lastRow = ss.getLastRow();
    var lastRow2 = lastRow+1;
    var s = ss.getSheetByName('sheet1');
    var lRow = s.getRange(lastRow, 2).getValue();
    var newRow = s.getRange(lastRow2, 2).getValue();
     if(lRow != ""){

    // adds the formulas
    var cell = sheet.getRange("C" + lastRow2);
    cell.setFormula('=IFERROR(MID($B' + lastRow2 +',SEARCH("details",$B' + lastRow2 +')+7,SEARCH(",",$B' + lastRow2 +')-SEARCH("details",$B' + lastRow2 +')-7),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("D" + lastRow2);
    cell.setFormula('=IFERROR(TRIM(LEFT(SUBSTITUTE(MID(B' + lastRow2 +',FIND("$",B' + lastRow2 +'),LEN(B' + lastRow2 +'))," ",REPT(" ",100)),100)),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("E" + lastRow2);
    cell.setFormula('=IFERROR(MID($B' + lastRow2 +',SEARCH("exceed",$B' + lastRow2 +')+7,SEARCH("%",$B' + lastRow2 +')-SEARCH("exceed",$B' + lastRow2 +')-6),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("F" + lastRow2);
    cell.setFormula('=IFERROR(MID($B' + lastRow2 +',SEARCH("due",$B' + lastRow2 +')+3,SEARCH(";",$B' + lastRow2 +')-SEARCH("due",$B' + lastRow2 +')-3),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("G" + lastRow2);
    cell.setFormula('=IFERROR(MID($B' + lastRow2 +',SEARCH("held on",$B' + lastRow2 +')+7,SEARCH(". Lottery",$B' + lastRow2 +')-SEARCH("held on",$B' + lastRow2 +')-7),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
    var cell = sheet.getRange("H" + lastRow2);
    cell.setFormula('=IFERROR(MID($B' + lastRow2 +',SEARCH("posted by",$B' + lastRow2 +')+9,SEARCH(". ",$B' + lastRow2 +')-SEARCH("",$B' + lastRow2 +')-167),HYPERLINK("https://housing.sfgov.org/listings","See Housing Portal"))');
     }
}


text:
Q: Android how to sort JSONArray of JSONObjects I have made a jsonarray of jsonobjects. Now I need to sort the JSONArray on base of a value from the jsonobjects. Formerly I sorted ArrayLists of custom objects like this:
Comparators:
public class KreeftenComparatorLA implements Comparator<Kreeft> {
    public int compare(Kreeft left, Kreeft right) {
        return left.latijnseNaam.compareTo(right.latijnseNaam);
    }
}
public class KreeftenComparatorNL implements Comparator<Kreeft> {
    public int compare(Kreeft left, Kreeft right) {
        return left.naam.compareTo(right.naam);
    }
}

And then sort the arraylist:
Collections.sort(db.lijst, new KreeftenComparatorLA());

or:
Collections.sort(db.lijst, new KreeftenComparatorNL());

But when I try the same thing with the JSONArray like this (JA = my jsonarray)
Collections.sort(JA, new KreeftenComparatorNL());

the Collections.sort gives an error:

The method sort(List, Comparator) in the type Collections is not applicable for the arguments (JSONArray, ThisActicity.KreeftenComparatorNL)

Does anybody know how to sort the JSONArray?

A: Just to be clear the code above for the sort comparator is not correct.
You can't compare string like you have above as you could in a language like Ruby.
This could be written much more succinctly as follows.  Otherwise the logic is sound.
Collections.sort( jsonValues, new Comparator<JSONObject>() {
    @Override
    public int compare(JSONObject a, JSONObject b) {
        String valA = new String();
        String valB = new String();

        try {
            valA = (String) a.get("keyOfValueToSortBy");
            valB = (String) b.get("keyOfValueToSortBy");
        }
        catch (JSONException e) {
            Log.e(LOG_TAG, "JSONException in combineJSONArrays sort section", e);
        }

        return valA.compareTo(valB);
    }
});

A: The issue is that JSONArray more or less holds JSONObjects (and other JSONArrays) which ultimately are strings. Deserializing the strings entirely into POJOs, sorting those, then back into JSON is fairly heavy.
The second issue is that a JSONArray can contain:  Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object; i.e. it is mixed types, making it hard to just dump the elements into a List of some type and sort that, then pass through the list dumping sorted items back into the JSON array. the only certain way to get a common type of each element from the JSONArray is using the Object get() method.. of course then all you have is Object objects and won't be able to do any meaningful sorting on them without revisiting the serialization issue.
Assuming your JSONArray contains homogeneously structured values, you could iterate through the JSONArray, calling one of the typed get() methods on each one, dumping them into a List type, then sorting on that. If your JSONArray just holds "simple" type like String or numbers, this is relatively easy. This isn't exact code but something like:
List<String> jsonValues = new ArrayList<String>();
for (int i = 0; i < myJsonArray.length(); i++)
   jsonValues.add(myJsonArray.getString(i));
Collections.sort(jsonValues);
JSONArray sortedJsonArray = new JSONArray(jsonValues);

Of course, if you have nested objects this can get a little trickier. If the value(s) you want to sort on live in the top level, it may not be soo bad...
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < myJsonArray.length(); i++)
   jsonValues.add(myJsonArray.getJSONObject(i));

Then use a comparator like this to sort:
class JSONComparator implements Comparator<JSONObject>
{

    public int compare(JSONObject a, JSONObject b)
    {
        //valA and valB could be any simple type, such as number, string, whatever
        String valA = a.get("keyOfValueToSortBy");
        String valB = b.get("keyOfValueToSortBy");

        return valA.compareTo(valB);
        //if your value is numeric:
        //if(valA > valB)
        //    return 1;
        //if(valA < valB)
        //    return -1;
        //return 0;
    }
}

Again, this makes some assumptions about the homogeneity of the data in your JSONArray. Adjust to your case if possible. Also you will need to add your exception handling, etc. Happy coding!
edit
fixed based on comments

A: In order to fill up an Android list ArrayAdapter I needed to do just this. This is how I did it:
Activity code building a list from a JSONArray:
JSONArray kids = node.getJSONArray("contents");
kids = JSONUtil.sort(kids, new Comparator(){
   public int compare(Object a, Object b){
      JSONObject    ja = (JSONObject)a;
      JSONObject    jb = (JSONObject)b;
      return ja.optString("name", "").toLowerCase().compareTo(jb.optString("name", "").toLowerCase();
   }
});
// in my case I wanted the original larger object contents sorted...
node.put("contents", kids);

And in JSONUtil (my helper):
public static JSONArray sort(JSONArray array, Comparator c){
    List    asList = new ArrayList(array.length());
    for (int i=0; i<array.length(); i++){
      asList.add(array.opt(i));
    }
    Collections.sort(asList, c);
    JSONArray  res = new JSONArray();
    for (Object o : asList){
      res.put(o);
    }
    return res;
}

A: One example with Date field:
public class JsonObjectComparator implements Comparator<JSONObject> {
private final String fieldName;
private Class<? extends Comparable> fieldType;

public JsonObjectComparator(String fieldName, Class<? extends Comparable> fieldType) {
    this.fieldName = fieldName;
    this.fieldType = fieldType;
}

@Override
public int compare(JSONObject a, JSONObject b) {
    String valA, valB;
    Comparable newInstance_valA, newInstance_valB;
    int comp = 0;
    try {
        Constructor<? extends Comparable> constructor = fieldType.getConstructor(String.class);
        valA = a.getString(fieldName);
        valB = b.getString(fieldName);
        if (fieldType.equals(Date.class)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
            newInstance_valA = dateFormat.parse(valA);
            newInstance_valB = dateFormat.parse(valB);
        } else {
            newInstance_valA = constructor.newInstance(valA);
            newInstance_valB = constructor.newInstance(valB);
        }
        comp = newInstance_valA.compareTo(newInstance_valB);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    if(comp > 0)
        return 1;
    if(comp < 0)
        return -1;
    return 0;
  }

}

public static void main(String[] args) throws JSONException {
    JSONObject o1 = new JSONObject();
    o1.put("key1", "26-06-2014");
    JSONObject o2 = new JSONObject();
    o2.put("key1", "30-11-2011");
    JSONObject o3 = new JSONObject();
    o3.put("key1", "15-07-2014");

    JsonObjectComparator comparator = new JsonObjectComparator("key1", Date.class);
    List<JSONObject> l = new ArrayList<>();
    l.add(o1);
    l.add(o2);
    l.add(o3);

    Collections.sort(l, comparator);
 }

A: If you are going to display the data contained in the JSONArray then it may make sense to sort it in the adapter itself.  For example, the ArrayAdapter<T> class already has the requisite methods such as Insert, Remove, and of course Sort.
adapter.sort(new Comparator<JSONObject>(){

    @Override
    public int compare(JSONObject arg0, JSONObject arg1) {

        return arg0.optString("SortField", "").compareTo(arg1.optString("SortField","")) ;

    }

});

A: //My script
 //HEADER add final variables
    private final int TYPE_STRING = 1;
    private final int TYPE_INT = 2;
    private final int TYPE_DUBLE = 3;

//METHOD GET SORT JSONARRAY
public JSONArray  getSortJSONArray()
{
 JSONArray  json = new JSONArray  ([{"carid":"957502","vin":"XXXXX","carbrand":"CADILLAC","carmodel":"CTS","carname":"CADILLAC CTS седан CTS PERFORMANC 2.0L AWD AK4 2 4WD  AT-6 276 (Л.С.)","carmodificationname":" седан CTS PERFORMANC 2.0L AWD AK4 2 4WD  AT-6 276 (Л.С.)","carcolorname":"Opulent Blue Metallic - ярко-синий металлик","price":"3410000","rgb":"","volumereal":"2,00","power":"276"},{"carid":"957502","vin":"XXXXX","carbrand":"CADILLAC","carmodel":"CTS","carname":"CADILLAC CTS седан CTS PERFORMANC 2.0L AWD AK4 2 4WD  AT-6 276 (Л.С.)","carmodificationname":" седан CTS PERFORMANC 2.0L AWD AK4 2 4WD  AT-6 276 (Л.С.)","carcolorname":"Opulent Blue Metallic - ярко-синий металлик","price":"3460000","rgb":"","volumereal":"1,00","power":"272"}]");

 /*halper - My halper */
   JSONArray sorJsonArray = halper.sort(json, getComparator("power",TYPE_INT));
   return sorJsonArray;
}

private Comparator getComparator(final String tagJSON,final int type)
    {
        Comparator c =  new Comparator()
        {
            public int compare(Object a, Object b)
            {

                try
                {
                    JSONObject    ja = (JSONObject)a;
                    JSONObject    jb = (JSONObject)b;

                    switch (type)
                    {
                        case TYPE_STRING:// String
                          return ja.optString(tagJSON, "")
                                                .toLowerCase()
                                                .compareTo(jb.optString(tagJSON, "").toLowerCase());
                        case TYPE_INT:// int
                            int valA =  ja.getInt(tagJSON);
                            int valB =  jb.getInt(tagJSON);
                            if(valA > valB)
                                return 1;
                            if(valA < valB)
                                return -1;

                        case TYPE_DUBLE:// double
                            String v1 = ja.getString(tagJSON).replace(",",".");
                            String v2 = jb.getString(tagJSON).replace(",",".");

                            double valAd = new Double(v1);// ja.getDouble(tagJSON);
                            double valBd = new Double(v2);//  jb.getDouble(tagJSON);
                            if(valAd > valBd)
                                return 1;
                            if(valAd < valBd)
                                return -1;

                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                return 0;
            }
        };

        return c;
    }

//My Halper class
public class Halpe {
    public void Halpe(){}

    public static JSONArray sort(JSONArray array, Comparator c)
    {
        List    asList = new ArrayList(array.length());
        for (int i=0; i<array.length(); i++){
            asList.add(array.opt(i));
        }
        Collections.sort(asList, c);
        JSONArray  res = new JSONArray();
        for (Object o : asList){
            res.put(o);
        }
        return res;
    }}


text:
Q: Reading socket data multiple times in a row causes a connection drop My name is Michel and am trying to write a Postgres connection driver with my lovely dotnet.
Postgres message protocol is simple - [int8 opcode] [int32 length] [payload].
I am trying to read the first five bytes from a stream to detect a message type and payload length. Then I am trying to read payload, which length I have to read in the previous step, and... connection getting closed by a Postgres.
For example, we have a AuthMessage [uint8 opcode] [int32 length (always 8)] [int32 auth_type]
/// open a TCP connection, getting the stream, sending hello message
stream.Read(buffer, 0, 5);
/// parsing a buffer, creating a new one
stream.Read(buffer, 0, messageLenght - 4) // connection getting lost at this

The first packet is always the same length, so we can try to read all the 9 bytes in one step
/// open a TCP connection, getting the stream, sending hello message
stream.Read(buffer, 0, 9); // this works! no connection drop

how can I read the header packet bytes, parse them and read all the payload data in one action?


text:
Q: Detect pasted text with Ctrl+v or right click -> paste Using JavaScript how do you to detect what text the user pastes into a textarea?

A: Quite an old thread, but you might now use https://willemmulder.github.io/FilteredPaste.js/ instead. It will let you control what gets pasted into a textarea or contenteditable.

A: You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: How to get the start and end points of selection in text area?
function getTextAreaSelection(textarea) {
    var start = textarea.selectionStart, end = textarea.selectionEnd;
    return {
        start: start,
        end: end,
        length: end - start,
        text: textarea.value.slice(start, end)
    };
}

function detectPaste(textarea, callback) {
    textarea.onpaste = function() {
        var sel = getTextAreaSelection(textarea);
        var initialLength = textarea.value.length;
        window.setTimeout(function() {
            var val = textarea.value;
            var pastedTextLength = val.length - (initialLength - sel.length);
            var end = sel.start + pastedTextLength;
            callback({
                start: sel.start,
                end: end,
                length: pastedTextLength,
                text: val.slice(sel.start, end)
            });
        }, 1);
    };
}

var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
    alert(pasteInfo.text);
    // pasteInfo also has properties for the start and end character
    // index and length of the pasted text
});

A: HTML5 already provides onpaste not only <input/> , but also editable elements (
, ...)
<input type="text" onpaste="myFunction()" value="Paste something in here">

More info here

A: Works on IE 8 - 10
Creating custom code to enable the Paste command requires several steps.

*

*Set the event object returnValue to false in the onbeforepaste event to enable the Paste shortcut menu item.

*Cancel the default behavior of the client by setting the event object returnValue to false in the onpaste event handler. This applies only to objects, such as the text box, that have a default behavior defined for them.

*Specify a data format in which to paste the selection through the getData method of the clipboardData object.

*invoke the method in the onpaste event to execute custom paste code.

To invoke this event, do one of the following:

*

*Right-click to display the shortcut menu and select Paste.

*Or press CTRL+V.

Examples

Cut this Text
<INPUT ID="oTarget" TYPE="text" VALUE="Paste the Text Here"
      onbeforepaste="fnBeforePaste()"
      onpaste="fnPaste()">

Full doc: http://msdn.microsoft.com/en-us/library/ie/ms536955(v=vs.85).aspx

A: I like the suggestion for the right click
$("#message").on('keyup contextmenu input', function(event) {
  alert("ok");
});

finded here:
Source:
Fire event with right mouse click and Paste

A: Following may help you
  function submitenter(myfield,e)
  {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == //event code of ctrl-v)
    {
      //some code here
    }

  }

  <teaxtarea name="area[name]" onKeyPress=>"return submitenter(this,event);"></textarea>

A: The input event fires when the value of an , , or  element has been changed.
const element = document.getElementById("input_element_id");
element.addEventListener('input', e => {
// insertText or insertFromPaste
   if(inputType === "insertFromPaste"){
       console.log("This text is copied");
   }
   if(inputType === "insertText"){
       console.log("This text is typed");
   }

})

A: You could either use html5 oninput attribute or jquery input event

<!DOCTYPE html>

<input id="myinp" type="search" onclick="this.select()" autocomplete="off" placeholder="paste here">

Nice to meet you!


text:
Q: Delete context menu options invoked from inside the context menu itself I am trying to delete some custom command options in the context menu of Excel. I have assigned the following sub to one of the context menu buttons to do the job, however, when it gets to delete this button itself, it cannot do that. How can I achieve this, or is there a workaround such as releasing the control to another sub, etc?
Sub DeleteFromRightClickMenuOptions(sRightClickMenu As String)
    Dim ContextMenu As CommandBar
    Dim ctrl As CommandBarControl

    ' Set ContextMenu to the Cell context menu.
    Set ContextMenu = Application.CommandBars(sRightClickMenu) 'instead of "List Range Popup", "Cell" can be used for regulat cells

    ' Delete the custom controls with the Tag : My_Tag.
    For Each ctrl In ContextMenu.Controls
        If ctrl.Tag = "My_Tag" Then
            ctrl.Delete
        End If
    Next ctrl
End Sub

A: Finally, I found an easy solution for it: Application.OnTime
The function that should be assigned to the delete command in the context menu should call another function that will run the main delete function one second later:
Sub DeleteFromRightClickMenuOptions_Main()
'since this sub is invoked by a context menu item and the item itself cannot be deleted we call another function and
'release the control this way
    On Error Resume Next
    Application.OnTime Now + TimeValue("00:00:01"), "RemoveContextMenuOptions"
End Sub

where RemoveContextMenuOptions is the function that calls DeleteFromRightClickMenuOptions with proper arguments


text:
Q: fleqn and vertical space I'm writing my master thesis according to this template:
https://fenix.tecnico.ulisboa.pt/downloadFile/1407993358863322/Thesis_template_LaTeX_v7.zip
I've tried using the fleqn option right at the beginning of the Thesis.tex file, but I get huge amounts of vertical space around equations. I looked up some of the possible problems, but in the end I really can't understand what's causing this.
Can someone help?
Thanks!
% ----------------------------------------------------------------------
%  Set the document class
% ----------------------------------------------------------------------
\documentclass[10pt,a4paper,twoside,fleqn]{report}

\usepackage[utf8]{inputenc}   % <<<<< Linux
\usepackage[english]{babel} % <<<<< English

\renewcommand{\rmdefault}{phv}
\renewcommand{\sfdefault}{phv}

\def\FontLn{% 16 pt normal
    \usefont{T1}{phv}{m}{n}\fontsize{16pt}{16pt}\selectfont}
\def\FontLb{% 16 pt bold
    \usefont{T1}{phv}{b}{n}\fontsize{16pt}{16pt}\selectfont}
\def\FontMn{% 14 pt normal
    \usefont{T1}{phv}{m}{n}\fontsize{14pt}{14pt}\selectfont}
\def\FontMb{% 14 pt bold
    \usefont{T1}{phv}{b}{n}\fontsize{14pt}{14pt}\selectfont}
\def\FontSn{% 12 pt normal
    \usefont{T1}{phv}{m}{n}\fontsize{12pt}{12pt}\selectfont}

\usepackage{geometry}
\geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}

\usepackage{setspace}
\renewcommand{\baselinestretch}{1.5}
\usepackage{graphicx}
\usepackage{amsmath}  % AMS mathematical facilities for LaTeX.
\usepackage{amsthm}   % Typesetting theorems (AMS style).
\usepackage{amsfonts} %
\usepackage{subfigure}
\usepackage{subfigmat}
\usepackage{dcolumn}
\newcolumntype{d}{D{.}{.}{-1}} % column aligned by the point separator '.'
\newcolumntype{e}{D{E}{E}{-1}} % column aligned by the exponent 'E'
\usepackage{nomencl}
\makenomenclature
%
% Group variables according to their symbol type
%
\RequirePackage{ifthen}
\ifthenelse{\equal{\languagename}{english}}%
{ % English
    \renewcommand{\nomgroup}[1]{%
        \ifthenelse{\equal{#1}{R}}{%
            \item[\textbf{Roman symbols}]}{%
            \ifthenelse{\equal{#1}{G}}{%
                \item[\textbf{Greek symbols}]}{%
                \ifthenelse{\equal{#1}{S}}{%
                    \item[\textbf{Subscripts}]}{%
                    \ifthenelse{\equal{#1}{T}}{%
                        \item[\textbf{Superscripts}]}{}}}}}%
}{% Portuguese
    \renewcommand{\nomgroup}[1]{%
        \ifthenelse{\equal{#1}{R}}{%
            \item[\textbf{Simbolos romanos}]}{%
            \ifthenelse{\equal{#1}{G}}{%
                \item[\textbf{Simbolos gregos}]}{%
                \ifthenelse{\equal{#1}{S}}{%
                    \item[\textbf{Subscritos}]}{%
                    \ifthenelse{\equal{#1}{T}}{%
                        \item[\textbf{Sobrescritos}]}{}}}}}%
}%

\usepackage[number=none]{glossary}
\setglossary{gloskip={}}
\makeglossary
\usepackage{rotating}
\usepackage[pdftex]{hyperref} % enhance documents that are to be
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     Begin Document                                                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

% Set plain page style (no headers, footer with centered page number)
\pagestyle{plain}

% Set roman numbering (i,ii,...) before the start of chapters
\pagenumbering{roman}

% -----------------------------------------------------------------------------
\subsection{Equations}
\label{subsection:equations}

Equations can be inserted in different ways.

The simplest way is in a separate line like this

\begin{equation}
\frac{{\rm d} q_{ijk}}{{\rm d} t} + {\cal R}_{ijk}({\bf q}) = 0 \,.
\label{eq:ode}
\end{equation}

If the equation is to be embedded in the text. One can do it like this ${\partial {\cal R}}/{\partial {\bf q}}=0$.

It may also be split in different lines like this

\begin{eqnarray}
{\rm Minimize}   && Y({\bf \alpha},{\bf q}({\bf \alpha}))            \nonumber           \\
{\rm w.r.t.}     && {\bf \alpha} \,,                                 \label{eq:minimize} \\
{\rm subject~to} && {\cal R}({\bf \alpha},{\bf q}({\bf \alpha})) = 0 \nonumber           \\
&&       C ({\bf \alpha},{\bf q}({\bf \alpha})) = 0 \,. \nonumber
\end{eqnarray}

It is also possible to use subequations. Equations~\ref{eq:continuity}, \ref{eq:momentum} and \ref{eq:energy} form the Naver--Stokes equations~\ref{eq:NavierStokes}.

\begin{subequations}
    \begin{equation}
    \frac{\partial \rho}{\partial t} + \frac{\partial}{\partial x_j}\left( \rho u_j \right) = 0 \,,
    \label{eq:continuity}
    \end{equation}
    \begin{equation}
    \frac{\partial}{\partial t}\left( \rho u_i \right) + \frac{\partial}{\partial x_j} \left( \rho u_i u_j + p \delta_{ij} - \tau_{ji} \right) = 0, \quad i=1,2,3 \,,
    \label{eq:momentum}
    \end{equation}
    \begin{equation}
    \frac{\partial}{\partial t}\left( \rho E \right) + \frac{\partial}{\partial x_j} \left( \rho E u_j + p u_j - u_i \tau_{ij} + q_j \right) = 0 \,.
    \label{eq:energy}
    \end{equation}
    \label{eq:NavierStokes}%
\end{subequations}

% ----------------------------------------------------------------------
\end{document}
% ----------------------------------------------------------------------

A: You have
> 10.0pt plus 2.0pt minus 5.0pt.
l.82 \showthe\abovedisplayskip

?
> 0.0pt plus 3.0pt.
l.83 \showthe\abovedisplayshortskip

so as it's never possible to use the short skips with fleqn there will be 10pt extra above equation, however the spacing is wrong anyway as there should never be a blank line before a display math, as it always generates a spurious white empty line of a paragraph before the equation. Similarly don't use one equation after another, use a multi-line display such as gather
output with and without fleqn

\documentclass[10pt,a4paper,twoside,
%fleqn
]{report}

% not required in recent latex \usepackage[utf8]{inputenc}   % <<<<< Linux
\usepackage[english]{babel} % <<<<< English

\renewcommand{\rmdefault}{phv}
\renewcommand{\sfdefault}{phv}

\def\FontLn{% 16 pt normal
    \usefont{T1}{phv}{m}{n}\fontsize{16pt}{16pt}\selectfont}
\def\FontLb{% 16 pt bold
    \usefont{T1}{phv}{b}{n}\fontsize{16pt}{16pt}\selectfont}
\def\FontMn{% 14 pt normal
    \usefont{T1}{phv}{m}{n}\fontsize{14pt}{14pt}\selectfont}
\def\FontMb{% 14 pt bold
    \usefont{T1}{phv}{b}{n}\fontsize{14pt}{14pt}\selectfont}
\def\FontSn{% 12 pt normal
    \usefont{T1}{phv}{m}{n}\fontsize{12pt}{12pt}\selectfont}

\usepackage{geometry}
\geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}

\usepackage{setspace}
\renewcommand{\baselinestretch}{1.5}
\usepackage{graphicx}
\usepackage{amsmath}  % AMS mathematical facilities for LaTeX.
\usepackage{amsthm}   % Typesetting theorems (AMS style).
\usepackage{amsfonts} %
\usepackage{subfigure}
\usepackage{subfigmat}
\usepackage{dcolumn}
\newcolumntype{d}{D{.}{.}{-1}} % column aligned by the point separator '.'
\newcolumntype{e}{D{E}{E}{-1}} % column aligned by the exponent 'E'
\usepackage{nomencl}
\makenomenclature
%
% Group variables according to their symbol type
%
\RequirePackage{ifthen}
\ifthenelse{\equal{\languagename}{english}}%
{ % English
    \renewcommand{\nomgroup}[1]{%
        \ifthenelse{\equal{#1}{R}}{%
            \item[\textbf{Roman symbols}]}{%
            \ifthenelse{\equal{#1}{G}}{%
                \item[\textbf{Greek symbols}]}{%
                \ifthenelse{\equal{#1}{S}}{%
                    \item[\textbf{Subscripts}]}{%
                    \ifthenelse{\equal{#1}{T}}{%
                        \item[\textbf{Superscripts}]}{}}}}}%
}{% Portuguese
    \renewcommand{\nomgroup}[1]{%
        \ifthenelse{\equal{#1}{R}}{%
            \item[\textbf{Simbolos romanos}]}{%
            \ifthenelse{\equal{#1}{G}}{%
                \item[\textbf{Simbolos gregos}]}{%
                \ifthenelse{\equal{#1}{S}}{%
                    \item[\textbf{Subscritos}]}{%
                    \ifthenelse{\equal{#1}{T}}{%
                        \item[\textbf{Sobrescritos}]}{}}}}}%
}%

% not in texlive\usepackage[number=none]{glossary}
%\setglossary{gloskip={}}
%\makeglossary
\usepackage{rotating}
\usepackage[pdftex]{hyperref} % enhance documents that are to be
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     Begin Document                                                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}

% Set plain page style (no headers, footer with centered page number)
\pagestyle{plain}

% Set roman numbering (i,ii,...) before the start of chapters
\pagenumbering{roman}

%\showthe\abovedisplayskip
%\showthe\abovedisplayshortskip

% -----------------------------------------------------------------------------
\subsection{Equations}
\label{subsection:equations}

Equations can be inserted in different ways.

The simplest way is in a separate line like this
\begin{equation}
\frac{\mathrm{d} q_{ijk}}{\mathrm{d} t} + {\cal R}_{ijk}(\mathbf{q}) = 0 \,.
\label{eq:ode}
\end{equation}

If the equation is to be embedded in the text. One can do it like this ${\partial {\cal R}}/{\partial \mathbf{q}}=0$.

It may also be split in different lines like this
\begin{eqnarray}
\mathrm{Minimize}   && Y(\mathbf{\alpha},\mathbf{q}(\mathbf{\alpha}))            \nonumber           \\
\mathrm{w.r.t.}     && \mathbf{\alpha} \,,                                 \label{eq:minimize} \\
\mathrm{subject~to} && {\cal R}(\mathbf{\alpha},\mathbf{q}(\mathbf{\alpha})) = 0 \nonumber           \\
&&       C (\mathbf{\alpha},\mathbf{q}(\mathbf{\alpha})) = 0 \,. \nonumber
\end{eqnarray}

It is also possible to use subequations. Equations~\ref{eq:continuity}, \ref{eq:momentum} and \ref{eq:energy} form the Naver--Stokes equations~\ref{eq:NavierStokes}.

\begin{subequations}
    \begin{gather}
    \frac{\partial \rho}{\partial t} + \frac{\partial}{\partial x_j}\left( \rho u_j \right) = 0 \,,
    \label{eq:continuity}
\\
    \frac{\partial}{\partial t}\left( \rho u_i \right) + \frac{\partial}{\partial x_j} \left( \rho u_i u_j + p \delta_{ij} - \tau_{ji} \right) = 0, \quad i=1,2,3 \,,
    \label{eq:momentum}
\\
    \frac{\partial}{\partial t}\left( \rho E \right) + \frac{\partial}{\partial x_j} \left( \rho E u_j + p u_j - u_i \tau_{ij} + q_j \right) = 0 \,.
    \label{eq:energy}
    \end{gather}
    \label{eq:NavierStokes}%
\end{subequations}

% ----------------------------------------------------------------------
\end{document}


text:
Q: CSS alignment problem in IE7 I've been putting together a drupal Website for a personal project (coffee geek Website about the Rancilio Miss Silvia) and the css is working great in Firefox and Safari but not in IE.
In IE the alignment of the central section is totally screwed up and I can't seem to figure out what I'm missing.
I'm working off of the Zen theme for drupal so there's a bunch of extra tags in there to make sure it's extra confusing.
The site is: http://www.silviaschool.com
The relevant style sheet is:  http://silviaschool.com/themes/zen/zen/layout-liquid.css
Thanks for any help you can offer :)

A: problem #1:
body { width: 20%; }

That's being applied via the sidebar-left class.
problem #2:
I'm not sure if you want a fixed-width layout or not.  When I load up the page in Chrome, it appears to have fixed-width but your stylesheet applies width: 90% to #page.  If you desire fixed width, then you'll need to specify a fixed width on #page.


text:
Q: Assembling an mdadm array with "possibly out of date" disks I've recently moved house and have had some power problems after switching on my file server that's using a mdadm RAID5 set up. The file system I'm using is ext4.
It seems that at some point two (of five) disks fell out of the array almost simultaneously after a quick look with --examine. I figured that there was unlikely to be any writes to any of the disks to throw them out of parity since it's not used as the mount point for the root or home directories and wasn't being used at the time (although it may have been mounted).
So I figured this was a good time to stop the array and try

mdadm --assemble --scan --force -v

It will accept the 2nd disk to be kicked out as part of the array but will not accept the first. There doesn't appear to be anything terribly wrong with it other than the last sync date is "too far" away. To make matters worse, even though it can start the array with 4 of 5 disks the array doesn't appear to assemble correctly.
Another thing that might be worth noting is that the disks in the array appear to have changed drive letters after I booted them up again. Possibly something is wrong with the SATA controller?
I'm going to put in an order for some replacement disks to dd the current contents across just in case anything else I try ruins things further.
Fortunately I have backups for most of the contents however they're a little bit old and I'd like to avoid resorting to using them if possible.
If there's no way around this does anybody have a suggestion for a file recovery tool that would deal with this sort of scenario? I know how that should be impossible, but it can't hurt to ask right?

A: (This is probably too late, but in case anyone else stumbles across this...)
Something similar happened to me recently on a RAID10 array.  A drive was accidentally removed for a few weeks (don't ask...).  When I re-inserted it, mdadm --add and mdadm --re-add both failed.  I had to do mdadm --zero-superblock on the drive, then mdadm --add worked fine.
If you have 4 out of 5 working disks and are using persistent superblocks the array should start in degraded mode; I'm not sure exactly what you mean by "doesn't appear to assemble correctly".  If the shutdown was unclean then --force would probably be necessary, which you are already using.
There's also a bunch of information about RAID recovery at https://raid.wiki.kernel.org/index.php/RAID_Recovery.


text:
Q: How to read multiple large sas data files into R, filter rows and save subset datasets as .rds I have 30 sas-files (dataset1.sas7bdat through dataset30.sas7bdat, approx. 10 GB per file) in a folder, and need to analyse a subset of rows in these data files (all rows where the character variable A begins with 10).
Thus, I need to read each of the sas-files into R, filter a subset with grep on variable A and then save each of these filtered datasets as a .rds-file.
I'm trying to achieve this using a for loop of list.files() and the Haven package to read the sas-file. In order to avoid going out-of-memory, I need to remove the imported dataset on each iteration after the subset has been filtered and saved as .rds.
Though not elegant nor satisfying, I could hard-code it manually 30 times over like this, copy/pasting and incrementing the suffixes by 1 each time:
dt1 <- haven::read_sas("~/folder/dataset1.sas7bdat")
dt1 <- data.table::as.data.table(dt1)
dt1 <- dt1[grep("^10", A)]
saveRDS(dt1, "~/folder/subset1.rds")

dt2 <- haven::read_sas("~/folder/dataset2.sas7bdat")
dt2 <- data.table::as.data.table(dt2)
dt2 <- dt1[grep("^10", A)]
saveRDS(dt2, "~/folder/subset2.rds")
etc.

While the following for loop technically works to read the files into memory, it is never going to finish due to massively going out of memory, so it does not allow me to filter the data:
folder <- "~/folder/"
file_list <- list.files(path = folder, pattern = "^dataset")
for (i in 1:length(file_list)) {
 assign(file_list[i], Haven::read_sas(paste(folder, file_list[i], sep='')))
}

Is there a way to - on each iteration in the loop - filter the dataset, remove the unfiltered dataset and save the subset in a .rds-file?
I can't seem to come up with a way to incorporate this into my approach of using the assign() function.
Is there a better way to go about this?

A: You could potentially look at freeing up memory by clearing the memory after each load and filter via
rm(list=ls())

A: I slept on it, and woke up with a working solution using a function to do the work, and a loop to cycle through filenames. This also enables me to save the output in a different folder (my raw data folder is read-only):
library(haven)
library(data.table)
fromFolder <- "~/folder_with_input_data/"
toFolder <- "~/folder_with_output_data/"
import_sas <- function(filename) {
dt <- read_sas(paste(fromFolder, filename, sep=''), NULL)
dt <- as.data.table(dt)
dt <- dt[grep("^10", A)]
saveRDS(dt, paste(toFolder,filename,'.rds.', sep =''), compress = FALSE)
remove(dt)
}

file_list <- list.files(path = fromFolder, pattern="^dataset")
for (filename in file_list) {
import_sas(filename)
}

I haven't tested this with the full 30 files yet. I'll do that tonight.
If I encounter problems, I will post an update tomorrow. Otherwise, this question can be closed in 48 hours.
Update: It worked without a hitch and completed the 297GB conversion in around 13 hours. I don't think it can be optimized to accomplish the task much faster; the vast majority of computing time is spent on opening the sas-files, which I don't think can be done faster by other means than Haven. Unless someone has an idea to optimize the process, this question can be closed.


text:
Q: Best practice for storing object in multiple containers I want to store an object in both a priority_queue but also in an unordered_map. Is there a best practice for doing something like this? I've considered storing the objects in a separate container (say array), and then relinquishing the pointers to the other two containers.
I'm hesitant to do this though, because that would mean I would have to write some additional comparitors to handle the fact that the containers would be storing pointers, rather than actual objects. In addition there is addition work managing ownership of the objects I'd like to not have to deal with.
So, I'm wondering if there isn't already an established best way to do this?

A: You've seen that you have to store a reference (of some sort) to the object if you want 1 thing to appear in 2 places. Whilst you once would have used a pointer, today we have shared_ptr.
This wraps the pointer so you don't have to manage lifetime ownership- the pointer will only get delete'd when the reference count of the shared_ptr drops to 0, ie when everyone holding the shared_ptr has relinquished it. You use the shared_ptr object as a real object so it's easy to manage in your containers.
If you don't have a C++11 compiler, you can use the boost version (that comes with an example of storing shared_ptr objects in both a vector and a set)


text:
Q: Python Generate a big text file Using Python 3.8, I am trying to generate a big text file filled by random alphabets and or letters.
Here is the code that does not do anything, and I am not too sure why.
def generate_big_random_letters(filename,size):

    import random
    import string

    chars = ''.join([random.choice(string.letters) for i in range(size)]) #1

    with open(filename, 'w') as f:
        f.write(chars)
    pass

if __name__ == '__main__':
    generate_big_random_letters("temp_big_letters.txt",1024*1024)

A: Use string.ascii_letters and string.digits:
import random
import string

def generate_big_random_letters(filename, size):
    chars = ''.join([random.choice(string.ascii_letters + string.digits) for i in range(size)])  # 1

    with open(filename, 'w') as f:
        f.write(chars)

if __name__ == '__main__':
    generate_big_random_letters("temp_big_letters.txt", 1024 * 1024)


text:
Q: In statistics, is an uppercase x-bar used as a notation for something? I was reading someone's answer and I came across him using the uppercase x-bar as a notation:
"Technically, the standard error is the standard deviation of an estimator. Most commonly, this refers to sample mean $\bar X$ as an estimator of the population mean .
So the 'standard error of the mean' is ($\bar X$)=/√. If  is unknown, it is estimated as the sample standard deviation . This means that the '(estimated) standard error' is /$\sqrt 2$."

A: If your sample is $X_1, \ldots, X_n$, then $\overline{X} := \frac{1}{n} \sum_{i=1}^n X_i$. Sometimes lowercase $x$ is used in place of $X$. See the Wikipedia page for more detail.


text:
Q: How to setup a domain name for my website hosted on ubuntu? I have created a django website and instead purchasing a hosting service, i have hosted the website on my own PC having public IP. Hence now i can access my website through my IP address.
Next step is to assign a domain name to my IP and hence everyone on internet can access my website through the domain name instead of IP. I know, there is a lot of sites for purchase a domain name but i don't want to purchase.
Is it possible to run a dns server on my system or anyother system connected to internet and set up a domain name for my website so that it can be accessed on internet?

A: No , it is not possible.
As domain entry has to present in tld authoritative dns servers , which only registrar authorised by ICANN can insert via EPP protocol or some other way which tld provides like API, phone call, email, etc..
Explanation :
Whenever client will enter domain in his/her browser , it will do a DNS query , query will reach the root server and then tld server, but because tld server doesn't have any entry , client will not be able to get IP address and hence won't be able to reach you web server.
If you are thinking why anyone has to pay for the domian registration, there is a good explanation on this stackexchange answer .
Terms :
EPP protocol : a different protocol from DNS , to deal with name registration and provisioning
ICANN : a nonprofit organization responsible for coordinating the maintenance and procedures of several databases related to the namespaces of the Internet, ensuring the network's stable and secure operation


text:
Q: Confusion about power source/supply on the STM32F103C8T6 Blue Pill I am attempting to program and STM32F103C8T6 Blue Pill board using an ST-LINK V2 debugger, i have the 4 pins connected to SWDIO, SWCLK, 3.3V and GND, and then connected into the 4 pin header on the board itself. I am using the Arduino IDE to program it, and I can run the "Blink" program to flash PC13, but i modified the code to the following to try and flash an external LED:
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(PC13, OUTPUT);
  pinMode(PA7, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(PC13, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(PA7, HIGH);
  delay(1000);                       // wait for a second
  digitalWrite(PC13, LOW);    // turn the LED off by making the voltage LOW
  digitalWrite(PA7, LOW);
  delay(1000);                       // wait for a second
}

However this doesn't flash the LED in PA7 at all. Further, i would assume that plugging an LED into the 3.3V/5V and Ground on the blue pill would power it up, however it doesn't light up at all.
Am I doing something wrong is my board possibly broken? It doesnt seem to be outputting at all, other than the onboard LED.


text:
Q: 403 error in accessing an URL but works fine in browsers String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false";

        URL google = new URL(url);
        HttpURLConnection con = (HttpURLConnection) google.openConnection();

and I use BufferedReader to print the content I get 403 error
The same URL works fine in the browser. Could any one suggest.

A: HTTP 403 is a Forbidden status code. You would have to read the HttpURLConnection.getErrorStream() to see the response from the server (which can tell you why you have been given a HTTP 403), if any.

A: This code should work fine. If you have been making a number of requests, it is possible that Google is just throttling you. I have seen Google do this before. You can try using a proxy to verify.

A: The reason it works in a browser but not in java code is that the browser adds some HTTP headers which you lack in your Java code, and the server requires those headers.  I've been in the same situation - and the URL worked both in Chrome and the Chrome plugin "Simple REST Client", yet didn't work in Java. Adding this line before the getInputStream() solved the problem:
                connection.addRequestProperty("User-Agent", "Mozilla/4.0");

..even though I have never used Mozilla. Your situation might require a different header. It might be related to cookies ... I was getting text in the error stream advising me to enable cookies.
Note that you might get more information by looking at the error text. Here's my code:
        try {
            HttpURLConnection connection = ((HttpURLConnection)url.openConnection());
            connection.addRequestProperty("User-Agent", "Mozilla/4.0");
            InputStream input;
            if (connection.getResponseCode() == 200)  // this must be called before 'getErrorStream()' works
                input = connection.getInputStream();
            else input = connection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            String msg;
            while ((msg =reader.readLine()) != null)
                System.out.println(msg);
        } catch (IOException e) {
            System.err.println(e);
        }

A: Most browsers automatically encode URLs when you enter them, but the Java URL function doesn't.
  You should Encode the URL with URLEncoder URL Encoder

A: I know this is a bit late, but the easiest way to get the contents of a URL is to use the Apache HttpComponents HttpClient project:  http://hc.apache.org/httpcomponents-client-ga/index.html

A: you original page (with link) and the targeted linked page are not the same domain.
original-domain and target-domain.
I found the difference is in request header:
with 403 forbidden error,
         request header have one line:
                        Referer: http://original-domain/json2tree/ipfs/ipfsList.html

when I enter url, no 403 forbidden,
                          the request header does NOT have above line referer: original-domain
I finally figure out how to fix this error!!!
on your original-domain web page, you have to add
              <meta name="referrer" content="no-referrer" />

it will remove or prevent sending the Referer in header,  works both for links and for Ajax requests made


text:
Q: C string functions error I'm working on an assignment, but I'm having trouble with my code :
int is_ascii_match(const char c1[], const char c2[], char res[MAX_STRING_SIZE]) {
....

    if (val_c1 == val_c2) {
        strcpy(res, strcat(strcat(c1, '&'),c2));
    }
    else
        return 0;

I'm getting an error :

Access violation reading location

Do I pass the parameters wrong or..?

A: strcat expects a non-const char*. You passed a const that's why compiler complained.
Also the second parameter would be "&". (Earlier you passed a char).
From standard §7.24.3.1
char *strcat(char * restrict s1, const char * restrict s2);

The strcat function appends a copy of the string pointed to by s2
  (including the terminating null character) to the end of the string
  pointed to by s1.

So s1 will be modified (the first parameter) that's why it should be non-const.

A: '&' is a character literal, which is a small integer. The second argument of strcat is a const char*, which is a pointer to a character (more precisely, a pointer to the first character in a contiguous NUL-terminated array of chars).
You presumably intended "&", which is a two-byte array.
Attempting to interpret a small integer as a pointer leads to precisely the problem indicated by the error.
If it were not for the problem reading the second argument, you might be presented with an error when strcat attempts to modify the string pointed to by its first argument, which is const and thus conceivably in read-only memory. (Modifying the first argument seems semantically incorrect, as well.)
If you compile with warnings enabled, you should see a warning about the types of the argument.
For this particular problem, consider the use of snprintf(res, MAX_STRING_SIZE, "%s&%s", c1, c2), which avoids modifying c1 and protects against buffer overflow. (You should compare the return value with MAX_STRING_SIZE if you care about truncation.)


text:
Q: How do I render a custom object to Android in linearLayout? I am new to Android development.  I have created a custom object in java.  How do I render it to screen?  I look around and is really confused about the whole Android rendering process.
My object is not a list.  It is a tree.  I also read about Adapter, Layout and View, but don't understand it.  Here is my code:
public class GeoArea {

    public String id;
    public String name;
    public String searchLocation;
    public static String searchTerm;
    public List<GeoArea> subGeoAreas;
    public GeoArea parentGeoArea;

    public GeoArea(String id) {
        this.id = id;
        name = id;
        searchLocation = "";
        subGeoAreas = new LinkedList<GeoArea>();
    }

    @Override
    public String toString() {
        return name;
    }

    public int size(){
        int result = 0;
        for(GeoArea curGeoArea:subGeoAreas){
            result += curGeoArea.size();
        }
        return result + 1;
    }
}

And here is the Layout I have:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Activity_GeoAreas" >

    <TextView
        android:id="@+id/textMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Choose Suburb"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <LinearLayout
        android:id=""@+id/geoAreasLayout""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textMain"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

So the idea is to render the main GeoArea into geoAreasLayout, and since it is a tree, each subGeoArea will get rendered in turn.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_geo_areas);

    GeoArea.searchTerm =  "Bar & Grill";

    GeoArea torontoArea = new GeoArea("cityOfToronto");
    torontoArea.name =  "City of Toronto";
    torontoArea.searchLocation =  "Toronto, ON";

    GeoArea testGeoArea = null;

    testGeoArea = new GeoArea("DownTownCore");
    testGeoArea.name =  "Down Town Core";
    testGeoArea.searchLocation =  "Downtown Core, Toronto, ON";
    testGeoArea.parentGeoArea = torontoArea;
    torontoArea.subGeoAreas.add(testGeoArea);

    testGeoArea = new GeoArea("AlexandraPark");
    testGeoArea.name =  "Alexandra Park";
    testGeoArea.searchLocation =  "Alexandra Park, Toronto, ON";
    testGeoArea.parentGeoArea = torontoArea;
    torontoArea.subGeoAreas.add(testGeoArea);

    // what's next?

    }

}

I try to write an Adapter, but I am not even sure what it's for or how to use it:
public class GeoAreaAdapter extends BaseAdapter implements Filterable{
    private Context _context;
    private int resource;
    private GeoArea _myGeoArea;

    public GeoAreaAdapter(Context context, int resource, GeoArea myGeoArea) {
        _context = context;
        _myGeoArea = myGeoArea;
    }

    public int getCount() {
        return _myGeoArea.size();
    }

    public Object getItem(int position) {
        return _myGeoArea;
    }

    public long getItemId(int position) {
        return _myGeoArea.id.hashCode();
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        LinearLayout GeoAreaView;
        if (convertView == null) {
            GeoAreaView = new LinearLayout(_context);
            LayoutInflater li = LayoutInflater.from(_context);
            convertView = li.inflate(R.layout.layout_geo_area, null);
        }
        else {
            GeoAreaView = (LinearLayout) convertView;
        }

        TextView name = (TextView) GeoAreaView.findViewById(R.id.txtGeoAreaName);
        name.setText(_myGeoArea.name);

        return convertView;
    }

    static class ViewHolder {
        TextView name;
        RelativeLayout childContainer;
    }

    @Override
    public Filter getFilter() {
        return null;
    }
}

A: Firstly your class must be extends from one of Views or ViewGroups classes to render and use it in LinearLayout.like this:
public class GeoArea extends View{

According to this issue after that you can use it in xml Layout file like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.example.YourClassName
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/mapview"
        ></com.example.YourClassName>
</LinearLayout>

as you see you must use package name to render your new object in xml layout file.


text:
Q: QA on MS word Run-time Error 4248 I am writing a VB script on MS word. The program is fine when I ran the program on my computer. But it is failed when the document is opened in protected mode.
Since the ms word will enter the protected view mode if the files are downloaded from the Internet and my word file is generated on the server side.
After  opening the word in protected mode and clicking the "Enable Editing" button , the word is existed from the "protected view mode" and change to "Compatibility Mode". And the ms word start to execute the VBA program.
Here is the program.
Private Sub Document_Open()
  If Application.ActiveProtectedViewWindow Is Nothing Then
        createButtonFunction (ActiveDocument.Tables.Count)
    End If
End Sub

The program keep on saying that "ActiveDocument" is not found. But the number of activate document is 1.
How can I set the "ActiveDocument" properties back again after the word is change from "protected view mode" and change to "Compatibility Mode" ????


text:
Q: Finding An Isosceles Triangle Can we always find an isosceles triangle of the same area as the original scalene triangle?
If so, could you please provide a compass straight edge proof?

A: Sketch of a construction:  Let the original triangle be $\Delta ABC$ and let $h$ be the height from $C$.  Then of course the area is $\frac 12 h\,\overline {AB}$.  Let $M$ be the midpoint of segment $AB$.  Construct the perpendicular bisector, $\mathscr P$, to $AB$.  Draw the line, $\mathscr L$ parallel to $AB$ through $C$ and let $X$ be the intersection of $\mathscr L$ and $\mathscr P$.  Then the triangle $\Delta ABX$ does the job.

A: Draw a line parallel to the base through the third vertex of the triangle, and draw the perpendicular bisector of the base to meet the parallel line. This point is now the third vertex of the isosceles triangle whose area is the same as the original.


text:
Q: FCM heads up notification Tried all forums, but still can't make it work. Heads up notification is not working.
Tried max and high priority and vibrate full screen content, nothing is working. Using Android-Moto 5.1 version.
notificationBuilder.setDefaults(Notification.DEFAULT_ALL);
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);

A: Finally, i found the solution. In cordova-fcm plugin MyFireBaseMessagingService.java file onMessageReceived method - below line is commented(send notification).
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), remoteMessage.getData());

Hope it helps someone. I uncommented this line and added the priority it works fine.


text:
Q: Confusion about the definition of $f(n) \in O(g(n))$ I learned in my Algorithmics course that that :
$f(n) \in O(g(n))$ can be written as $f(n) \leq cg(n)$.
My confusion is about what $c$ is. Is it a constant that can be any value? Is it a constant that can be changed depending on which value of $f(n)$ or is it a value that must make the inequality hold true for every f(n) and g(n).

A: It should read something like:
$f(n)=\mathcal{O}(g(n))$ (or $\in$) if there exists a positive constant $c$ and natural number $N$, such that for all $n\ge N$, $f(n)\le cg(n)$. That is, $c$ does not depend on $n$.
There are slightly varying definitions, such as $|f(n)|$ replacing $f(n)$, and another definition based on limits.


text:
Q: Sharing Android Phone's WiFi connection with OSX Is it possible to tell OSX to connect to an Android phone (Sony Xperia Z2) via BlueTooth / USB and use the WiFi connection that's setup on the Android phone?
I've tried to setup Bluetooth PAN on the phone seeing as OSX can connect to a Bluetooth PAN, but the phone doesn't seem to support Bluetooth PAN.
My friend has access to the WiFi via his phone, his roommate set it up for him, but he's away for a few months. I've tried plugin a cable into the router, but there seems to be Mac filtering setup on the router - so the only way I can connect to the WiFi is via his phone unless I know the WiFi password, which I don't.

A: First things first, enable bluetooth on your phone, pair it with OSX.
Now on the phone (this is on Android Lollipop), go to
Settings -> Wireless & networks -> More -> Tethering & portable hotspot -> enable Bluetooth tethering.

On OSX, create a new Bluetooth PAN, you will be presented with the device you paired earlier

Then whatever means the phone is using to connect to the internet, in this case WiFi, will be shared to your Laptop.


text:
Q: Java UUID compareTo not working correctly for Type1 UUIDs While working on a use case where the data needs to be sorted on UUID which are all Type 1 or timebased and generated using Datastax Cassandra Java driver library (UUIDS.timebased()), i found that UUID.compareTo is not sorting some of the UUIDs correctly.
The logic in compareTo is
    /**
 * Compares this UUID with the specified UUID.
 *
 * <p> The first of two UUIDs is greater than the second if the most
 * significant field in which the UUIDs differ is greater for the first
 * UUID.
 *
 * @param  val
 *         {@code UUID} to which this {@code UUID} is to be compared
 *
 * @return  -1, 0 or 1 as this {@code UUID} is less than, equal to, or
 *          greater than {@code val}
 *
 */
public int compareTo(UUID val) {
    // The ordering is intentionally set up so that the UUIDs
    // can simply be numerically compared as two numbers
    return (this.mostSigBits < val.mostSigBits ? -1 :
            (this.mostSigBits > val.mostSigBits ? 1 :
             (this.leastSigBits < val.leastSigBits ? -1 :
              (this.leastSigBits > val.leastSigBits ? 1 :
               0))));
}

I had the below 2 UUIDs generated using the datastax cassandra driver for java.
UUID uuid1 = java.util.UUID.fromString("7fff5ab0-43be-11ea-8fba-0f6f28968a17")
UUID uuid2 = java.util.UUID.fromString("80004510-43be-11ea-8fba-0f6f28968a17")
uuid1.timestamp() //137997224058510000
uuid2.timestamp() //137997224058570000

From the above, it is evident that uuid1 is smaller than uuid2, but when we compare them using UUID compareTo method, we get different output. We should get output as -1 as it is supposed to be less than but we get answer as 1 which shows that this uuid1 is greater than uuid2
uuid1.compareTo(uuid2) //output - 1

On further analysing this, found out that the msb for uuid2 transforms to a negative number where as msb for uuid1 is positive number. Because of this the logic in compareTo is returning the value of 1 instead of -1.
u_7fff5ab0 = {UUID@2623} "7fff5ab0-43be-11ea-8fba-0f6f28968a17"
mostSigBits = 9223190274975338986
leastSigBits = -8090136810520933865

u_80004510 = {UUID@2622} "80004510-43be-11ea-8fba-0f6f28968a17"
mostSigBits = -9223296100696452630
leastSigBits = -8090136810520933865

Is this behaviour normal with UUID and their comparison with each other ?
If so then how do we handle sorting of such timebased UUIDs?
Thank you

A: Please note that comparing time based UUIDs need special care, From the docs:

Lastly, please note that Cassandra's timeuuid sorting is not compatible with UUID.compareTo(java.util.UUID) and hence the UUID created by this method are not necessarily lower bound for that latter method.

Time based UUIDs should not be compare with the java.util.UUID#compareTo. To compare the two time based UUID, you should compare the time; within these two UUID contains. you need a custom Utility method implementation or just compare two timesstamps. Here is an example how to do it:
// must be timebased UUID
int compareTo(UUID a, UUID b){
   return Long.compare(UUIDs.unixTimestamp(a),UUIDs.unixTimestamp(b));
}

To learn more, go through this DOCS.


text:
Q: Sending a message from webpage to webcontrol Goal:
Display a message in the Webcontrol. The message's will be started in the default.aspx
Problem:

I don't know how to send a message (string test = "testing testing")
  from Default.aspx to the WebUserControl.ascx by using C# code

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="~/WebUserControl1.ascx" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <Acme:AdRotator id="Control1" runat="server" />
</asp:Content>

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>

namespace WebApplication1
{
    public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}

// Fullmetalboy

A: Not sure I fully understand the question. You can expose a public property on the Bag control that lets you set/get the Coffee instance.
If you don't have a direct handle to the Bag control you can always pass it in the current HttpContext Items cache.
However if you really want to move to loose coupling and dependency injection then implement the MVP pattern in WebForms.
Edit: Based on your updated question add a property to your webcontrol like this.
public partial class WebUserControl1 : System.Web.UI.UserControl
{
    public string MyProperty
    {
       get;set;
    }
}

Then set the property from the page like this:
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Control1.MyProperty = "Testing Testing";
    }
}

Or like this:
<Acme:AdRotator id="Control1" runat="server" MyProperty="Testing Testing" />


text:
Q: Elastic Search: URI Search is inaccurate I am searching via Webbrowser Firefox with the following URI:

http://localhost:9200/xyz-leads/lead/_search?q=datetimeHour:22_09_2015__12&&deliveryType:EMAIL

But I only get hits with deliveryType:RVS, not EMAIL.
If I search for deliveryType:RVS I get 3 hits.
I know there are 3 results for RVS and 0 for EMAIL with the datetimeHour above, in total.
I guess the standard behaviour of ElasticSearch is, that it ignores the second search value 'deliveryType' and uses only the first 'datetimeHour' if there are no results for both.
If I search for deliveryType:Email, then I want no hits in the response.
Do I need to set some additional ElasticSearch parameters?
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-uri-request.html
_source: {
country: "DEU",
brand: "A",
leadGroup: "TEST",
leadID: 108798,
deliveryType: "RVS",
datetime: 1442916913000,
datetimeFormatted: "22.09.2015 12:15:13",
datetimeHour: "22_09_2015__12",
datetimeDay: "22_09_2015"
}

A: The query string query you stuff into your URL (i.e. in the q=... parameter) needs to be well-formed according to the query string query syntax
Try this instead (i.e. using AND instead of &&)
http://localhost:9200/xyz-leads/lead/_search?q=datetimeHour:22_09_2015__12%20AND%20deliveryType:EMAIL


text:
Q: Upgrading Ubuntu to 12.04 stuck
Possible Duplicate:
Upgrade from 11.10 to 12.04 stalled

While upgrading from 11.10 to 12.04, I'm stalled at the step:
Installing new version of config file /etc/init/udevtrigger.conf
The Terminal in the Distribution Upgrade window is expanded, there is no prompt for user input. I've hit enter a few times but it doesn't change anything but add a blank line after the last print statement. It's been sitting for ~6 hours at this stage.
No other windows or dialog boxes are open. The upgrade has progressed through "Preparing to Upgrade", "Setting new software channels", and "Getting new packages". Under the progress bar (which estimates 1 day 2 hours remaining, and has for some time), it says Preparing to configure libpcap0.8. I'd take a screen-shot, but it won't let me save the file anywhere. The progress bar is about 1/3 complete.

A: As a last resort, boot into Ubuntu using a live cd copy whatever files you need and also your package list and perform a fresh install. Using your package list you can reinstall programs pretty easily.


text:
Q: sudo command sudo: /etc/sudoers is world writable sudo: no valid sudoers sources found, quitting sudo: unable to initialize policy plugin I have run this command by mistake chmod -R 777 ./*
Now not able to use sudo and can't open folders as root.
sudo: /etc/sudoers is world writable
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin


text: Q: How to build component to play videos using angular 4 I have created Rest webservices to get list of Contents using spring-boot. Content has a field for videoURL of Content. On frontend I'm using angular4. Now I want to build a component to show this videoURL and play that video. What is the best way to build this component.