text:
Q: Facebook authentication issue at Login I am using a Facebook login in my iPhone application, but when I click on the login button and the FBSession starts, it's showing an error "You are are not logged in: You are not logged in. Please log in and try again."
Here is the code I am using:
FBSession *session = [[FBSession alloc] initWithAppID:FacebookID
    permissions:[NSArray arrayWithObjects:@"publish_actions",@"read_stream",@"public_profile",@"email", nil]
    urlSchemeSuffix:nil tokenCacheStrategy:nil];
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

for (cookie in [storage cookies]) {

    [storage deleteCookie:cookie];
}

[[FBSession activeSession]handleDidBecomeActive];
[[FBSession activeSession] closeAndClearTokenInformation];
[FBSession setActiveSession:nil];
[FBSession setActiveSession:session];
FBSessionLoginBehavior behviour = FBSessionLoginBehaviorForcingWebView;
[session openWithBehavior:behviour completionHandler:^(FBSession *session1, FBSessionState status, NSError *error) {

    if (error) {
        NSLog(@"error %@",error.localizedDescription);
        [appDelegate removeHudView:nil];

    }
    if (session1.accessTokenData.accessToken) {

    }
}];

And also the screen sort of My simulator.
If anyone knows about how to handle this case, please help me.


text:
Q: How to capture powershell error in batch scripts? Currently, I'm using this script to convert a date in yyyyMMdd format to dd/MM/yyyy format.
for /f "delims=" %%a in ('powershell -Command "& {([datetime]::parseexact('%testDate%','yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture)).ToString('dd/MM/yyyy')}"') do SET testDate=%%a

When I input invalid characters/date-time structure for the %testDate% variable, in Powershell IDE, it throws an error message, "String was not recognized as a valid DateTime".
However, in batch scripts, it will only return an empty testDate variable. It also returns errorlevel = 0.
How do I return the error message from powershell in batch scripts?

Full script
@echo off
setlocal enabledelayedexpansion
REM Get user's inputs
:beginning
SET /p testDate="Please enter the date in yyyyMMdd format (e.g., 20171128)" || goto beginning
if /I "%testDate%"=="t" (
    for /f "delims=" %%a in ('powershell -Command "& get-date -format 'dd/MM/yyyy'"') do SET testDate=%%a
) ELSE (
    if /I "%testDate%"=="yt" (
        for /f "delims=" %%a in ('powershell -Command "& get-date (get-date).AddDays(-1) -format 'dd/MM/yyyy'"') do set testDate=%%a
    ) ELSE (
        for /f "delims=" %%a in ('powershell -Command "& {([datetime]::parseexact('%testDate%','yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture)).ToString('dd/MM/yyyy')}"') do SET testDate=%%a
        REM Testing
        echo !testDate!
        echo Yes!
    )
)
REM Testing
echo !testDate!
echo !errorLevel!
pause

A: The error message from [datetime]::parseexact is being returned in multiple lines of text and causing the set testData=%%a to be called multiple times. You can see this by running the command separately.
eg.
c:\Temp> for /f "delims=" %a in ('powershell -Command "& {([datetime]::parseexact('%testDate%','yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture)).ToString('dd/MM/yyyy')} "') do SET testDate=%a

output:

C:\Temp> SET testDate=Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid
  C:\Temp> SET testDate=DateTime."
  C:\Temp> SET testDate=At line:1 char:4
  C:\Temp> SET testDate=+ & {([datetime]::parseexact('Exception calling ParseExact with 3 argum ...
  C:\Temp> SET testDate=+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  C:\Temp> SET testDate=    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  C:\Temp> SET testDate=    + FullyQualifiedErrorId : FormatException
  C:\Temp> SET testDate=

To fix this you will need to control the return message when an error is encountered.
A try/catch statement can be used to achieve this:
@echo off
setlocal enabledelayedexpansion
REM Get user's inputs
:beginning
SET /p testDate="Please enter the date in yyyyMMdd format (e.g., 20171128)" || goto beginning
if /I "%testDate%"=="t" (
    for /f "delims=" %%a in ('powershell -Command "& get-date -format 'dd/MM/yyyy'"') do SET testDate=%%a
) ELSE (
    if /I "%testDate%"=="yt" (
        for /f "delims=" %%a in ('powershell -Command "& get-date (get-date).AddDays(-1) -format 'dd/MM/yyyy'"') do set testDate=%%a
    ) ELSE (
        for /f "delims=" %%a in ('powershell -Command "& {try { ([datetime]::parseexact('%testDate%','yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture)).ToString('dd/MM/yyyy') } catch { return $_.Exception.Message }} "') do SET testDate=%%a
        REM Testing
        echo !testDate!
        echo Yes!
    )
)
REM Testing
echo !testDate!
echo !errorLevel!
pause

A: if not defined testdate (echo Invalid date supplied)

or
if not defined eventdate (echo Invalid date supplied %testdate%)

or
if not defined eventdate (echo Invalid date supplied %testdate%&goto someplace)

depending on quite what the circumstances are. Are you sure that testdate is neing modified (first scenario) - I'm suspicious that actually testdate remains as-is and eventdate is simply not being set.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to turn a non-elastic IP into an elastic IP on aws? I have done some research and don't think it is possible but figured I would ask on here just to be sure.
My predecessor decided to use the public and private IP of one of our database servers in an extremely large amount of places, now that we are going to be resizing this DB server going through and changing all of those IPs over would take a large amount of time and the possibility of missing one is pretty high.
I am wondering if it is at all possible to take the current IP on the server ( which is not elastic ) and some how convert it to an elastic IP. To clarify I am not looking to add a new elastic IP to the server but rather take the IP that is currently assigned to it and make that elastic. If this is not something that I can do using the SDK / Console is it something that Amazon could do behind the scenes if we were to get support?
Thanks !

A: No, it is not possible.
The Elastic IP addresses are a separate pool from the Public IP addresses.  There is no public means to convert a public (or private) IP address to an Elastic IP.
Standard Amazon support is unlikely to be able to make such a switch for you.  While technically an Amazon network engineer can probably make such a switch, it is very unlikely that support could make that happen.

A:
If this is not something that I can do using the SDK / Console is it something that Amazon could do
  behind the scenes if we were to get support?

Amazon can create a reverse DNS record for a mail server manually and is known to implement features that users request, so I guess it might be worth asking. I would give it a try.

A: So long as you do not terminate the instance, its static IP should remain assigned to it per Amazon documentation (https://aws.amazon.com/articles/1346).

now that we are going to be resizing this DB server

You can resize the instance and keep its static IP without terminating it (and thus without losing the static IP). The moment you terminate that instance, you lose the static IP, so resize it without terminating it.


text:
Q: SQL native client data type compatibility - incompatible with SQLOLEDB We have ran into a problem with our legacy application when switching to use SQL Native Client (SQLNCLI) as the provider for ADO.
Our original connection string was:
Provider=SQLOLEDB; Server=host; Database=bob; Integrated Security=SSPI;

we changed this to:
Provider=SQLNCLI11; Server=host; Database=bob; Integrated Security=SSPI; DataTypeCompatibility=80;

What we've found is that when calling a stored procedure, using a parameter of adDBTimeStamp, Native Client appears to treat the timestamp as a smalldatetime, rather than a datetime. This is causing us problems as we use 31 Dec 9999 as a "top-end" date in some comparisons, and Native Client fails with an "Invalid date format" error where SQLOLEDB had no issues.
Now it looks like we may just be able to change from adDBTimeStamp to adDate as the datatype when creating the parameter, however I was wondering if there was something we were missing in the connection string before we go ahead and make the code change.
VBScript code to reproduce below. For the avoidance of doubt, date format is UK (dd/mm/yyyy) before someone suggests we should be using 12/31/9999 :-) But also to confirm, the CDate doesn't fail.
Set db = CreateObject("ADODB.Command")

' If Provider=SQLOLEDB then there is no error.
db.ActiveConnection = "Provider=SQLNCLI11; Server=host; Database=bob; Integrated Security=SSPI; DataTypeCompatibility=80;"
db.CommandText = "usp_FetchData"
db.CommandType = &H0004

' 135 is adDBTimeStamp
db.Parameters.Append db.CreateParameter("@screenDate", 135, 1, 20, CDate("31/12/9999"))

Set rs = CreateOBject("ADODB.RecordSet")
' Then this line fails with "Invalid date format" from SQLNCLI
rs.Open db

WScript.Echo rs.RecordCount

Winding the datetime back to 2078 (within the date range of smalldatetime) makes the error go away.
As mentioned, if a non-code-change fix can be found, that's what we'd prefer, before we go and have to change adDBTimeStamp to adDate. I'd have expected DataTypeCompatiblity=80 to behave as SQLOLEDB; unfortantly my Google-fu has failed when finding out exactly what type mapping SQLNCLI uses.

A: A solution may have finally been found: via the MSDN page Data Type Support for OLE DB Date and Time Improvements, there is this snippet towards the end:

Data Type Mapping in ITableDefinition::CreateTable
The following type mapping is used with DBCOLUMNDESC structures used
  by ITableDefinition::CreateTable:
[...table of conversions...]
When an application specifies DBTYPE_DBTIMESTAMP in wType, it can
  override the mapping to datetime2 by supplying a type name in
  pwszTypeName. If datetime is specified, bScale must be 3. If
  smalldatetime is specified, bScale must be 0. If bScale is not
  consistent with wType and pwszTypeName,DB_E_BADSCALE is returned.

In testing, it appears this need to set the scale applies to parameters to SELECT and commands as well as to CreateTable. Therefore if we change the script above to:
Set param = db.CreateParameter("@screenDate", 135, 1, 20, CDate("31/12/9999"))
param.NumericScale = 3
db.Parameters.Append param

...then the error goes away and the stored procedure is executed. We're in the early stages of testing, however welcome feedback from others if this has caused issues.


text:
Q: Implement inference bayesian network using session tensorflow I am a new with machine learning. I have a final project about prediction using two algorithms, Artificial Neural Network and Bayesian Neural Network. I want to compare the prediction result between ANN and BNN. I have finished the ANN program, but I have a problem with the BNN. I try a tutorial from this link: bayesian neural network tutorial. This is my ANN sample code to train and evaluate the model.
keep_prob = tf.placeholder("float", name="keep_prob")
x = tf.placeholder(tf.float32, [None, n_input], name="x")
y = tf.placeholder(tf.float32, name="y")

training_epochs = 5000
display_step = 1000
batch_size = 5

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=predictions, labels=y), name="cost_function")
    optimizer = tf.train.AdamOptimizer(learning_rate=0.0001, name="Adam").minimize(cost)

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in tqdm(range(training_epochs)):
            avg_cost = 0.0
            total_batch = int(len(x_train) / batch_size)
            x_batches = np.array_split(x_train, total_batch)
            y_batches = np.array_split(y_train, total_batch)

            for i in range(total_batch):
                batch_x, batch_y = x_batches[i], y_batches[i]
                _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y, keep_prob: 0.8})
                avg_cost += c / total_batch
            if epoch % display_step == 0:
                print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(avg_cost))

        print("Optimization Finished!")
        correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(y, 1), name="corr_pred")
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"), name="accuracy")
        # print('Accuracy: ', sess.run(accuracy, feed_dict={x: x_test, y: y_test}))
        print("Accuracy:", accuracy.eval({x: x_test, y: y_test, keep_prob: 1.0}))

and this is my BNN code:
# Importing required libraries
from math import floor

import edward as ed
import numpy as np
import pandas as pd
import tensorflow as tf
from edward.models import Normal, NormalWithSoftplusScale
from fancyimpute import KNN
from sklearn import preprocessing

# Read data
features_dummies_nan = pd.read_csv('csv/features_dummies_with_label.csv', sep=',')

# Function: impute missing value by KNN
def impute_missing_values_by_KNN():
    home_data = features_dummies_nan[[col for col in features_dummies_nan.columns if 'hp' in col]]
    away_data = features_dummies_nan[[col for col in features_dummies_nan.columns if 'ap' in col]]
    label_data = features_dummies_nan[[col for col in features_dummies_nan.columns if 'label' in col]]

    home_filled = pd.DataFrame(KNN(3).complete(home_data))
    home_filled.columns = home_data.columns
    home_filled.index = home_data.index

    away_filled = pd.DataFrame(KNN(3).complete(away_data))
    away_filled.columns = away_data.columns
    away_filled.index = away_data.index

    data_frame_out = pd.concat([home_filled, away_filled, label_data], axis=1)

    return data_frame_out

features_dummies = impute_missing_values_by_KNN()

target = features_dummies.loc[:, 'label'].values
data = features_dummies.drop('label', axis=1)
data = data.values

perm = np.random.permutation(len(features_dummies))
data = data[perm]
target = target[perm]

train_size = 0.9

train_cnt = floor(features_dummies.shape[0] * train_size)

x_train = data[0:train_cnt]  # data_train
y_train = target[0:train_cnt]  # target_train
x_test = data[train_cnt:]  # data_test
y_test = target[train_cnt:]  # target_test

keep_prob = tf.placeholder("float", name="keep_prob")
n_input = data.shape[1]  # D
n_classes = 3
n_hidden_1 = 100  # H0
n_hidden_2 = 100  # H1
n_hidden_3 = 100  # H2

def neural_network(X, W_0, W_1, W_2, W_out, b_0, b_1, b_2, b_out):
    hidden1 = tf.nn.relu(tf.matmul(X, W_0) + b_0)
    hidden2 = tf.nn.relu(tf.matmul(hidden1, W_1) + b_1)
    hidden3 = tf.nn.relu(tf.matmul(hidden2, W_2) + b_2)
    output = tf.matmul(hidden3, W_out) + b_out
    return tf.reshape(output, [-1])

scaler = preprocessing.StandardScaler().fit(x_train)

data_train_scaled = scaler.transform(x_train)
data_test_scaled = scaler.transform(x_test)

W_0 = Normal(loc=tf.zeros([n_input, n_hidden_1]), scale=5.0 * tf.ones([n_input, n_hidden_1]))
W_1 = Normal(loc=tf.zeros([n_hidden_1, n_hidden_2]), scale=5.0 * tf.ones([n_hidden_1, n_hidden_2]))
W_2 = Normal(loc=tf.zeros([n_hidden_2, n_hidden_3]), scale=5.0 * tf.ones([n_hidden_2, n_hidden_3]))
W_out = Normal(loc=tf.zeros([n_hidden_3, 1]), scale=5.0 * tf.ones([n_hidden_3, 1]))

b_0 = Normal(loc=tf.zeros(n_hidden_1), scale=5.0 * tf.ones(n_hidden_1))
b_1 = Normal(loc=tf.zeros(n_hidden_2), scale=5.0 * tf.ones(n_hidden_2))
b_2 = Normal(loc=tf.zeros(n_hidden_3), scale=5.0 * tf.ones(n_hidden_3))
b_out = Normal(loc=tf.zeros(1), scale=5.0 * tf.ones(1))

qW_0 = NormalWithSoftplusScale(loc=tf.Variable(tf.random_normal([n_input, n_hidden_1])),
                               scale=tf.Variable(tf.random_normal([n_input, n_hidden_1])))
qW_1 = NormalWithSoftplusScale(loc=tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
                               scale=tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])))
qW_2 = NormalWithSoftplusScale(loc=tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3])),
                               scale=tf.Variable(tf.random_normal([n_hidden_2, n_hidden_3])))
qW_out = NormalWithSoftplusScale(loc=tf.Variable(tf.random_normal([n_hidden_3, 1])),
                                 scale=tf.Variable(tf.random_normal([n_hidden_3, 1])))

qb_0 = NormalWithSoftplusScale(loc=tf.Variable(tf.random_normal([n_hidden_1])),
                               scale=tf.Variable(tf.random_normal([n_hidden_1])))
qb_1 = NormalWithSoftplusScale(loc=tf.Variable(tf.random_normal([n_hidden_2])),
                               scale=tf.Variable(tf.random_normal([n_hidden_2])))
qb_2 = NormalWithSoftplusScale(loc=tf.Variable(tf.random_normal([n_hidden_3])),
                               scale=tf.Variable(tf.random_normal([n_hidden_3])))
qb_out = NormalWithSoftplusScale(loc=tf.Variable(tf.random_normal([1])),
                                 scale=tf.Variable(tf.random_normal([1])))

sigma_y = 1.0

x = tf.placeholder(tf.float32, [None, n_input])
y = Normal(loc=neural_network(x, W_0, W_1, W_2, W_out, b_0, b_1, b_2, b_out), scale=sigma_y)

inference = ed.KLqp({W_0: qW_0, b_0: qb_0,
                     W_1: qW_1, b_1: qb_1,
                     W_2: qW_2, b_2: qb_2,
                     W_out: qW_out, b_out: qb_out}, data={x: x_train, y: y_train})

global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.05
learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,
                                           1000, 0.3, staircase=True)

optimizer = tf.train.AdamOptimizer(learning_rate)

inference.run(n_iter=5000, optimizer=optimizer, global_step=global_step)

But, I want to compare two algorithms result. So, I want to make some variables will be same between ANN and BNN, for example sum of epoch. Then I want to adapt my ANN code above for this BNN code section.
sigma_y = 1.0

x = tf.placeholder(tf.float32, [None, n_input])
y = Normal(loc=neural_network(x, W_0, W_1, W_2, W_out, b_0, b_1, b_2, b_out), scale=sigma_y)

inference = ed.KLqp({W_0: qW_0, b_0: qb_0,
                     W_1: qW_1, b_1: qb_1,
                     W_2: qW_2, b_2: qb_2,
                     W_out: qW_out, b_out: qb_out}, data={x: x_train, y: y_train})

global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.05
learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step,
                                           1000, 0.3, staircase=True)

optimizer = tf.train.AdamOptimizer(learning_rate)

inference.run(n_iter=5000, optimizer=optimizer, global_step=global_step)

I have several things that I don't understand. There is y = tf.placeholder(tf.float32, name="y") in ANN but in BNN is y = Normal(loc=neural_network(x, W_0, W_1, W_2, W_out, b_0, b_1, b_2, b_out), scale=sigma_y). Then, there is scale in BNN but not in ANN. So, can I adapt my ANN train and test sample code to BNN sample code above? I want to make inference on BNN run like in sess.run() on ANN so I can count the BNN prediction accuracy result. Can I do that?


text:
Q: Floating-point number representation difference between PostgreSQL and Java I use PostgreSQL 9.4.1 (32-bit, Windows) and have a table with a real column - quantity. When I execute the following query on pgAdmin:
SELECT quantity || ' pcs' FROM table
I get the following results:
123.234 psc
123 psc
12 psc
12.3 psc
Surprisingly, the same query through Java driver postgresql-9.4-1201.jdbc4 (and postgresql-9.2-1002.jdbc3) is different:
123.2341 psc
123 psc
12 psc
12.3000002 psc
As quantity is not returned by the query directly (but a string containing it), I don't expect such differences in the results. Can anyone suggest a solution so that Java result is the same as the one from pgAdmin.

A: It looks like pgAdmin is set to display only 3 trailing digits.
You can use a DecimalFormat object in your code to display the data in the same manner.
double numberOne = 123.2341;
double numberTwo = 123;
double numberThree = 12;
double numberFour = 12.30000002;

DecimalFormat formatter = new DecimalFormat();
formatter.setMaximumFractionDigits(3);

System.out.println(formatter.format(numberOne));   // 123.234
System.out.println(formatter.format(numberTwo));   // 123
System.out.println(formatter.format(numberThree)); // 12
System.out.println(formatter.format(numberFour));  // 12.3

A: PostgreSQL says that the real data type is an inexact, variable-precision numeric types, and that [o]n most platforms, the real type has a range of at least 1E-37 to 1E+37 with a precision of at least 6 decimal digits, because they use an IEE754 single precision representation with only 24 bits for the mantissa.
That means that in the database, 123.234 and 123.2341 are represented by the same value. I assume that you are using double datatype in Java, with a precision of about 15 decimal digits. The differences are normal.
If you want the values to be the same, you can try to use simple precision floats in Java, but you will still depend on the display modes between Java and pgAdmin.
The only foolproof way to maintain accuracy on decimal values is to use NUMERIC(precision, scale) in PostgreSQL, and BigDecimal in Java.


text:
Q: $\mathcal{H}$ is relatively compact iff every sequence in $\mathcal{H}$ has a convergent subsequence? I'm trying to prove that
Let $(Y,\rho_{Y}),(K,\rho_{K})$ a complete metric space and a compact metric space, respectively. Let, as well, $Z=\mathcal{C}^{0}(K,Y)$ the metric space of continuous fuctions, such that $K\longrightarrow Y$, with the uniform metric and $\mathcal{H}\subset Z$. $\mathcal{H}$ is relatively compact in $Z$ iff for every $\{f_{k}\}$, such that $f_{k}\in\mathcal{H}$, there is a subsequence $\{f_{k_{j}}\}$ that converges in $Z$, that is $f_{k_{j}}\rightarrow\varphi\in Z$.
The proof I'm trying reads:
Suppose $\mathcal{H}$ is relatively compact in $Z$. Then $\overline{\mathcal{H}}$ is compact. Therefore, every sequence in $\overline{\mathcal{H}}$ has a subsequence that converges in $\overline{\mathcal{H}}$. That, particularly, means that every sequence in $\mathcal{H}$, that is a sequence in $\overline{\mathcal{H}}$, has a subsequence that converges in $\overline{\mathcal{H}}$. Then, for every $\{f_{k}\}$, such that $f_{k}\in\mathcal{H}$, there is a subsequence $\{f_{k_{j}}\}$ that converges in $Z$, that is $f_{k_{j}}\rightarrow\varphi\in\overline{\mathcal{H}} \subseteq Z$.
Conversely, suppose that for every $\{f_{k}\}$, such that $f_{k}\in\mathcal{H}$, there is a subsequence $\{f_{k_{j}}\}$ that converges in $Z$, that is $f_{k_{j}}\rightarrow\varphi\in Z$. We want to show that $\mathcal{H}$ is relatively compact, or what is the same, show that $\overline{\mathcal{H}}$ is compact.
Now $\overline{\mathcal{H}}\subset Z$, but $Z$ is complete and $\overline{\mathcal{H}}$ is closed (since closure is closed), therefore $\overline{\mathcal{H}}$ is complete. Then it only remains to show that $\overline{\mathcal{H}}$ is totally bounded, for if it is then $\overline{\mathcal{H}}$ is compact.
My question is how to show this using the hypothesis that every sequence has a subsequence that converges in $Z$?

Thanks to the answers of @BrianMScott and @BenjaminLim. In the next lines I complete the proof I was doing with their useful hints, comments are welcome
Proof: Suppose $\mathcal{H}$ is relatively compact in $Z$. Then $\overline{\mathcal{H}}$ is compact. Therefore, every sequence in $\overline{\mathcal{H}}$ has a subsequence that converges in $\overline{\mathcal{H}}$. That, particularly, means that every sequence in $\mathcal{H}$, that is a sequence in $\overline{\mathcal{H}}$, has a subsequence that converges in $\overline{\mathcal{H}}$. Then, for every $\{f_{k}\}$, such that $f_{k}\in\mathcal{H}$, there is a subsequence $\{f_{k_{j}}\}$ that converges in $Z$, that is $f_{k_{j}}\rightarrow\varphi\in\overline{\mathcal{H}} \subseteq Z$.
Conversely, suppose that for every $\{f_{k}\}$, such that $f_{k}\in\mathcal{H}$, there is a subsequence $\{f_{k_{j}}\}$ that converges in $Z$, that is $f_{k_{j}}\rightarrow\varphi\in Z$. We want to show that $\mathcal{H}$ is relatively compact, or what is the same, show that $\overline{\mathcal{H}}$ is compact.
Now $\overline{\mathcal{H}}\subset Z$, but $Z$ is complete and $\overline{\mathcal{H}}$ is closed (since closure is closed), therefore $\overline{\mathcal{H}}$ is complete. Then it only remains to show that $\overline{\mathcal{H}}$ is totally bounded, for if it is then $\overline{\mathcal{H}}$ is compact. But, for that, we need only to prove that $\mathcal{H}$ is totally bounded, since closure of a totally bounded set is totally bounded.
Suppose that $\mathcal{H}$ is not totally bounded, then exists $\epsilon>0$ such that there isn't a finite covering of balls, for $\mathcal{H}$, of the form $\{B_{g_{i},\epsilon}^{\rho_{\infty}}\}$ with $g_{i}\in\mathcal{H}$. Therefore, we can choose a $f_{1}\in\mathcal{H}$ and there will be a $f_{2}\in\mathcal{H}$ such that $f_{2}\notin B_{f_{1},\epsilon}^{\rho_{\infty}}$. In the same way there will be a $f_{3}\notin B_{f_{1},\epsilon}^{\rho_{\infty}}\cup B_{f_{2},\epsilon}^{\rho_{\infty}}$ and in general there will be $f_{k}\notin\bigcup_{i=1}^{k-1}B_{f_{i},\epsilon}^{\rho}$. Hence, we have defined, inductively, a sequence that there is $\epsilon>0$ such that $\rho(f_{k},f_{\ell})\geq\epsilon$ for every $k\neq\ell$, since if $\rho(f_{k},f_{\ell})<\epsilon$ for sufficiently large $k,\ell$ therefore $f(k)\in B_{f_{\ell},\epsilon}^{\rho_{\infty}}$ which contradicts the former construction. Therefore, every subsequence is not Cauchy and therefore none of them has the chance to converge. But by hypothesis, every sequence in $\mathcal{H}$ has a convergent subsequence, and supposing that $\mathcal{H}$ was not totally bounded has led us to contradiction. Therefore $\mathcal{H}$ is totally bounded in $Z$ and, hence, $\overline{\mathcal{H}}$. It proves that, since $\overline{\mathcal{H}}$ is complete and totally bounded, $\overline{\mathcal{H}}$ is compact. Finally, $\mathcal{H}$ is relatively compact.

A: If $\mathcal{H}$ is totally bounded, then so is $\overline{\mathcal H}$, so it suffices to show that $\mathcal{H}$ is totally bounded. If not, there is some $\epsilon>0$ such that $\mathcal H$ has no finite $\epsilon$-net. That is, there is no finite subset $\mathcal F\subseteq\mathcal H$ such that for each $h\in\mathcal H$ there is some $f\in\mathcal F$ such that $\|h-f\|<\epsilon$. Use this to construct an infinite sequence $\langle h_n:n\in\Bbb N\rangle$ in $\mathcal H$ such that $\|h_m-h_n\|\ge\epsilon$ whenever $m\ne n$. Can this sequence have a subsequence that converges in $Z$?

A: Let me try to expand a little on Brian's hint above. If $\mathcal{H}$ is not totally bounded, then there is $\epsilon > 0$ such that for no finite subcollection $f_1,\ldots, f_n$ of functions in $\mathcal{H}$ does the union
$$B_{\epsilon}(f_1)  \cup \ldots \cup B_{\epsilon}(f_n)$$
cover $\mathcal{H}$. Now in particular this means the following: Choose some $f_1 \in \mathcal{H_1}$ and now choose $f_2 \in \mathcal{H}$ such that $||f_1 - f_2||\leq \epsilon$. Having chosen $f_1,\ldots,f_n \in \mathcal{H}$ it is always possible to choose $f_{n+1} \in \mathcal{H}$ such that
$$||f_{n+1} - f_i || \geq  \epsilon$$
for $1 \leq i \leq n$. Now we consider the sequence $\{f_n\}$ that lives in $\mathcal{H}$. Suppose it has a convergent subsequence $\{f_{n_j}\}$ that converges to some $\varphi \in Z$. Now this also means that for our $\epsilon$ that we chose above, the ball of radius $\epsilon/2$ about $\varphi$ must contain all but finitely many terms of your subsequence. However you have a problem because such a ball can only contain at most $1$ term of your subsequence.
To see why, say you have two terms of the subsequence $f_{n_1}$ and $f_{n_2}$. Then suppose without loss of generality that $n_1 > n_2$. Then by construction of our original sequence $\{f_n\}$ this means that $||f_{n_1} - f_{n_2}||\geq \epsilon$, i.e. that both $f_{n_1}$ and $f_{n_2}$ cannot lie in the same ball of radius $\epsilon/2$ about $\varphi$. So this explains why $B_{\epsilon/2}(\varphi)$ can only contain at most one term of your subsequence, say this term is $f_{n_k}$
But then if we now choose $B_{||\varphi -f_{n_k}||}(\varphi)$ then this will contain no point of our subsequence, contradicting the fact that $\{f_{n_j}\}$ converges to $\varphi$.
But then we have produced an example of a sequence living in $\mathcal{H}$ that has no convergent subsequence hence contradicting our hypothesis. It follows that $\mathcal{H}$ is totally bounded.


text:
Q: A class implementing an interface that takes an enum So, say I have a simple enum and a class that uses it:
enum ThingType { POTATO, BICYCLE };

class Thing {
    public void setValueType(ThingType value) { ... }
    public ThingType getValueType() { ... }
}

But, in reality, I have lots of different classes that implement setValueType, each with a different kind of enum. I want to make an interface that these classes can implement that supports setValueType and getValueType using generics:
interface ValueTypeable {
    public Enum<?> getValueType(); // This works
    public <T extends Enum<T>> setValueType(T value); // this fails horribly
}

I can't change the class model because the classes are auto-generated from an XML schema (JAXB). I feel like I'm not grasping enums and generics combined. The goal here is that I want to be able to allow a user to select from a list of enums (as I already know the type at runtime) and set the value in a particular class.
Thanks!

A: Have you tried parameterizing the interface itself.  Like:
class Thing<E extends Enum<? extends E>> {
  public E getValueType();
  public void setValueType(E value);
}

Then you have the subclass extend the one with right type:
class SomeSubClass implements Thing<ThingType> { ... }

A: enums are for when you have a fixed set of them. When you say that each implementation has its own, then you no longer have a fixed set, and how you are trying to use enums doesn't match your needs.
You might be interested in the request for Java to be able to have abstract enums.


text:
Q: Azure App Service Log Stream - Indefinite 'Welcome, you are now connected to log-streaming service' Has anyone had an issue with the Log Streams in Azure where the message 'Welcome, you are now connected to log-streaming service.' is just spammed 10 times a second constantly? I am unable to see my logs now.
2022-07-07T12:48:40  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:40  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:40  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:40  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:40  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:40  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:39  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:39  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:39  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:39  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:39  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:39  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:38  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:38  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:38  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:38  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:38  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:38  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:38  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:37  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:37  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:37  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:37  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:37  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:37  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:37  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:36  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:36  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:36  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:35  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:35  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:35  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:35  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:35  Welcome, you are now connected to log-streaming service.
2022-07-07T12:48:35  Welcome, you are now connected to log-streaming service.

A: In my experience, this happens when the app is hanging in the start phase. Below some information about how I tackled this problem.
I had the same issue. In fact not only do I have this issue in the Log Stream view, but when I run az webapp log tail I get a Python error relating to azure-cli, with urllib3.exceptions.ProtocolError: ("Connection broken: InvalidChunkLength in it.
I debugged it by:

*

*stripping my NodeJS app down to a "Hello, World" express app.

*deploying

*Log Streams loops like in the question

*calling the test endpoint until I get a response

*now Log Streams logs something useful

To be complete, this post describes a way to try to fix it by changing the logging settings: https://learn.microsoft.com/en-us/answers/questions/918228/app-service-log-stream-prints-the-welcome-message.html
The exact steps I tried from this post:

*

*restarting the app

*under monitoring > App Service Logs, disable logs and set retention to 0 and back

*restarting the app again

*repeating the last two steps several times

It had no effect. I expect these steps can help for some people because it takes enough time for the app to get out of the warm-up phase.
Deploying under different app names/resource groups also did not help for me, which in my opinion indicates that the problem lies with the code, not the environment.


text:
Q: EC2 running NGINX behind CloudFront with HTTPS? I have a CloudFront distribution already configured for an S3 bucket using Route53 domain with HTTPS enabled using a public certificate.
I want to use this CloudFront distribution with another origin (which is an EC2 instance running NGINX as a reverse proxy for an application on that same instance), but I also need to enable HTTPS.
The normal way I would enable HTTPS on EC2 with NGINX is to just setup the nginx configuration and point my domain "A record" to the instance then request a certificate with Let's Encrypt. But how should I do it when behind CloudFront? I won't use Let's Encrypt (not necessarily important to just use it) and would like to use an AWS public certificate as I did with my S3.
Could I just configure NGINX to listen on port 80 and add this EC2 instance as an origin on the CloudFront distribution then enable HTTPS and choose my public certificate there or how should this be done to work properly?
This time I am not going to use a Load Balancer, I want a direct connection between the EC2 and CloudFront. But I would also like to know how to set this up when using a Load Balancer (for the future).

A:
Could I just configure NGINX to listen on port 80 and add this EC2 instance as an origin on the CloudFront distribution then enable HTTPS and choose my public certificate there or how should this be done to work properly?

Yes you can do this, but all traffic pattern will be:
Clinet---(HTTPS)--->CF---(HTTP)--->Instance

Which means that half of your connection (CF->Instance) will be in HTTP, which may not be desired.
If you want to have HTTPs on every path, you still need to have public valid SSL cerfiicate on the instance. CF will not work with self-signed certificates.


text:
Q: Could I save pictures from different picture boxes as individual ones, with Visual Studio? If I were to load an image into VS and split it into two pieces, one in each of the two given pictureboxes, could I somehow save each split piece of the picture as an individual image? If so, how?

A: If you mean that you don't load it into VS, but into your programm and split it there the rest is simple. A picturebox can save its image like this:
pictureBox1.Image.Save(@"c:\temp\somename.jpg");


text:
Q: When is work actually done? Wikipedia says:

For example, when a ball is held above the ground and then dropped, the work done on the ball as it falls is equal to the weight of the ball (a force) multiplied by the distance to the ground (a displacement). When the force
  F
   is constant and the angle between the force and the displacement
  s
   is θ, then the work done is given by W = Fs cos θ.

From what I have learned work is only done when a force displaced something against another force. (For example if you lift something you lift it opposite to gravity). But Wikipedia doesn't agree. What is it that I have not understood correctly?

A:
From what I have learned work is only done when a force displaced something against another force

This is incorrect. Work is done whenever a force causes (or influences) displacement. That's all. It has got nothing to do with whether or not it fights against other forces. If you push a spaceship in outer space with no other forces present, then you are doing work (which the spaceship absorbs as kinetic energy). Mathematically: $$W=\int \vec F\cdot \mathrm d\vec s$$

A: $\text{Work}=\text{Force}\times\text{Distance}$, or in more formal terms $W=Fd$. Work is done when something moves from one point to another. Another way of expressing work to express this idea is $W=\Delta{E}$ where $E$ is the total energy in the system. (I hope that answers your question, because work is not opposing a force but rather when an object moves position).

A:
From what I have learned work is only done when a force displaced
  something against another force. (For example if you lift something
  you lift it opposite to gravity)

From what you are showing, Wikipedia is simply using the example of someone doing work to lift an object against gravity, and gravity doing work on the freely falling object converting the potential energy into kinetic energy according to the work- energy theorem. I don't see it saying that all work is done "against another force" (maybe you left something out?)
If you have a mass at rest on a frictionless horizontal surface and you apply a constant horizontal force $F$ through a distance $d$ in the direction of the force, the work done will equal $Fd$ and there is no opposing force (assume no air drag). This work was not done "against another force". In addition, if the mass started at rest by the time it has gone a distance $d$ it will acquire  kinetic energy according to the work-energy theorem which states that the net work done on an object equals its change in kinetic energy, or
$$\frac{mV^2}{2}=Fd cos θ$$
Hope this helps.

A: Work done by a force is defined as:-$$W=\int \vec{F}.d\vec{s}$$
I don't think any other definition of work exists.

work is only done when a force displaced something against another force.

A force will do non-zero work if its dot product with displacement is a real number.As you are also including an opposing force,then we talk about the work done by the net force and the work done by net force is equal to the algebraic sum of work done by individual forces.


text:
Q: 2 Urns and 30 balls problem needing to check answer You have 30 balls 20 black and 10 white let $X_{n}$ be the current number of white balls in urn 1 and each urn holds 15 balls, find
$P_{r}$ ($X_{n+1}$)=k |$X_{n}$=j).
You are taking a ball from urn 1 and urn 2 and placing the ball from urn 1 into 2 and the ball from urn 2 and putting it in urn 1. I should have clarified that earlier.
So I have this representation Urn 1: \begin{equation}
\frac{X_{n}\:\:\:15-X_{n}}{15};
\end{equation}
with $15-X_{n}$ representing black balls in urn 1
Urn 2:
\begin{equation}
\frac{10-X_{n}\:\:\:15-(10-X_{n})}{15};
\end{equation}
with $\frac{15-(10-X_{n})}{15}$ being the black balls and $\frac{10-X_{n}}{15}$ being the white balls in urn 2.
So would my answer be $P_{r}$ ($X_{n+1}$)=k |$X_{n}$=j)=$
\frac{15-(10-X_{n})}{15};
$
I realize that my variables might not match up at this point; but I think I'm on the right track but I am just missing something.

A: When we draw the balls from urn 1 and urn 2 there are four things that can happen. Both balls can be black or both white, in which case $X_{n+1}=X_n$, or we can draw a white ball from bin 1 and a black ball from bin 2 in which case $X_{n+1} = X_n - 1$ or we can draw a black ball from bin 1 and a white ball from bin 2 so $X_{n+1} = X_n + 1$.
Now, at time $n$, as you have observed, bin 1 has $X_n$ white balls and $15-X_n$ black balls, and bin 2 has $10-X_n$ white balls and $15 - (10-X_n)=5+X_n$ black balls.  So the probability of drawing a white ball from bin 1 and a black ball from bin 2 is $\frac{X_n}{15}\frac{5+X_n}{15}$ (we just multiply the probabilities because the two draws are simultaneous and independent.)  Similarly, the probability that we draw a black ball from bin 1 and a white ball from bin 2 is $\frac{15-X_n}{15}\frac{10-X_n}{15}$.  The probability that the two balls are the same is just 1 minus the sum or the two probabilities that they are different.  So putting it all together, we get
$$P(X_{n+1}=k | X_n=j)=\begin{cases}\frac{j^2+5j}{225}&\mbox{if }k=j-1\\\frac{-2j^2+20j+75}{225}&\mbox{if }k=j\\\frac{j^2-25j+150}{225}&\mbox{if }k=j+1\\0&\mbox{otherwise.}\end{cases}$$
Check my algebra.


text:
Q: Pandas: find matching rows in two dataframes (without using `merge`) Let's suppose I have these two dataframes with the same number of columns, but possibly different number of rows:
tmp = np.arange(0,12).reshape((4,3))
df = pd.DataFrame(data=tmp)

tmp2 = {'a':[3,100,101], 'b':[4,4,100], 'c':[5,100,3]}
df2 = pd.DataFrame(data=tmp2)

print(df)
   0   1   2
0  0   1   2
1  3   4   5
2  6   7   8
3  9  10  11

print(df2)
     a    b    c
0    3    4    5
1  100    4  100
2  101  100    3

I want to verify if the rows of df2 are matching any rows of  df, that is I want to obtain a series (or an array) of boolean values that gives this result:
0     True
1    False
2    False
dtype: bool

I think something like the isin method should work, but I got this result, which results in a dataframe and is wrong:
print(df2.isin(df))
       a      b      c
0  False  False  False
1  False  False  False
2  False  False  False

As a constraint, I wish to not use the merge method, since what I am doing is in fact a check on the data before applying merge itself.
Thank you for your help!

A: You can use numpy.isin, which will compare all elements in your arrays and return True or False for each element for each array.
Then using all() on each array, will get your desired output as the function returns True if all elements are true:
>>> pd.Series([m.all() for m in np.isin(df2.values,df.values)])

0     True
1    False
2    False
dtype: bool

Breakdown of what is happening:
# np.isin
>>> np.isin(df2.values,df.values)

Out[139]:
array([[ True,  True,  True],
       [False,  True, False],
       [False, False,  True]])

# all()
>>> [m.all() for m in np.isin(df2.values,df.values)]

Out[140]: [True, False, False]

# pd.Series()
>>> pd.Series([m.all() for m in np.isin(df2.values,df.values)])

Out[141]:
0     True
1    False
2    False
dtype: bool

A: There may be more efficient solutions, but you could append the two dataframes can call duplicated, e.g.:
df.append(df2).duplicated().iloc[df.shape[0]:]

This assumes that all rows in each DataFrame are distinct. Here are some benchmarks:
tmp1 = np.arange(0,12).reshape((4,3))
df1 = pd.DataFrame(data=tmp1,  columns=["a", "b", "c"])

tmp2 = {'a':[3,100,101], 'b':[4,4,100], 'c':[5,100,3]}
df2 = pd.DataFrame(data=tmp2)

df1 = pd.concat([df1] * 10_000).reset_index()
df2 = pd.concat([df2] * 10_000).reset_index()

%timeit df1.append(df2).duplicated().iloc[df1.shape[0]:]
# 100 loops, best of 5: 4.16 ms per loop
%timeit pd.Series([m.all() for m in np.isin(df2.values,df1.values)])
# 10 loops, best of 5: 74.9 ms per loop
%timeit df2.apply(frozenset, axis=1).isin(df1.apply(frozenset, axis=1))
# 1 loop, best of 5: 443 ms per loop

A: Use np.in1d:
>>> df2.apply(lambda x: all(np.in1d(x, df)), axis=1)
0     True
1    False
2    False
dtype: bool

Another way, use frozenset:
>>> df2.apply(frozenset, axis=1).isin(df1.apply(frozenset, axis=1))
0     True
1    False
2    False
dtype: bool

A: You can use a MultiIndex (expensive IMO):
pd.MultiIndex.from_frame(df2).isin(pd.MultiIndex.from_frame(df))
Out[32]: array([ True, False, False])

Another option is to create a dictionary, and run isin:
df2.isin({key : array.array for key, (_, array) in zip(df2, df.items())}).all(1)
Out[45]:
0     True
1    False
2    False
dtype: bool

A: Try:
df[~df.apply(tuple,1).isin(df2.apply(tuple,1))]

Here is my result:


text:
Q: getFailedLoginAttempts() function doesn't make any sense in appfoundation in Vaadin How to get failed login attempts using appfoundation? It has a function getFailedLoginAttempts() but it doesn't make any sense. I am using Vaadin 6 (6.8.12)
My code is here:
NativeButton login = new NativeButton(Lang.getMessage("login"), new ClickListener() {

         private static final long serialVersionUID = -5577423546946890721L;

         public void buttonClick(ClickEvent event) {

             username = (String) usernameField.getValue();
             String password = (String) passwordField.getValue();
            try {
                AuthenticationUtil.authenticate(username, password);
                startApp();
            } catch (InvalidCredentialsException e) {
             /* I need to get failed login attempts here but how can I do that?
I just can by doing this: AuthenticationUtil.authenticate(username, password).
getFailedLoginAttempts(),  but I need to write try and catch blocks
(so try and catch blocks in catch block) for authenticate method and this
function will never work, because user won't be authenticated and all
the time you will go to the other catch block; */
                feedbackLabel.setValue(Lang.getMessage("usernameOrPasswordIncorect"));
            } catch (AccountLockedException e) {
                feedbackLabel.setValue(Lang.getMessage("accountBlocked"));
            }
        }
    });

I wrote all the problem in the comment. I want to print a number of failed login attempts but can't get this number. Any suggestions?

A: Why the code AuthenticationUtil.authenticate(username, password).
getFailedLoginAttempts() compiles is that the authenticate method returns a User object upon successful authentication and this method can then be accessed.  However if an exception is throws then you do not have  the User object.  In their unit tests then use a FactoryFacade to retrieve the user object and check it that way.  I do not know the API well so I can not tell you whether you can get the user some other way.
see https://code.google.com/p/vaadin-appfoundation/source/browse/src/org/vaadin/appfoundation/authentication/util/AuthenticationUtil.java

A: I wrote a function for getting user in my own class.
private User getUserForUsername(String username) {
    String query = "SELECT u FROM User u WHERE u.username = :username";
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("username", username);
    return (User) FacadeFactory.getFacade().find(query, parameters);
}

And call this method in catch block.
try {
    AuthenticationUtil.authenticate(username, password);
    startApp();
} catch (InvalidCredentialsException e) {
    User user = getUserForUsername(username);
    feedbackLabel.setValue(Lang.getMessage("usernameOrPasswordIncorect"));
    attemptsLeftLabel.setValue(Lang.getMessage("attemptsLeft", 5 - user.getFailedLoginAttempts()));
} catch (AccountLockedException e) {
    feedbackLabel.setValue(Lang.getMessage("accountBlocked"));
}

All works fine.


text:
Q: The principal branch of $\sqrt{z}$ maps $\mathbb{C}-(-\infty,0]$ onto the right half plane - $\{Re(z)>0\}$ I have heard my professor say a couple of times that:

The principal branch of $\sqrt{z}$ maps $\mathbb{C}-(-\infty,0]$ onto the right half plane - $\{Re(z)>0\}$

but never realized why is that true.
Can anyone provide an explanation or a proof for that statement.

A: If $z\in\Bbb C\setminus(-\infty,0]$, then $z=re^{i\theta}$, for some $r>0$ and some $\theta\in(-\pi,\pi)$. So, $\sqrt z=\sqrt re^{i\theta/2}$. Since $\frac\theta2\in\left(-\frac\pi2,\frac\pi2\right)$, $\operatorname{Re}\sqrt z>0$.


text:
Q: accidentally deleted entire iTunes Match music library - is there a way to recover? I'm slightly panicking here.
I don't keep local copies of songs in my iTunes library, instead streaming them on demand via iTunes Match, to save space on the SSD drive.
In certain situations such as buying music from a source different than iTunes, or if i decide to download an album for listening locally, the songs end up on my disc. So whenever i feel like it, i select all the music in the library and hit delete in order to delete the local files. My music is still stored on Apple's servers.
Today though, in a hurry, i must have hit the wrong button which, in a blink, deleted my entire library from iTunes Match. It disappeared from my iOS devices and from iTunes on my Mac without a trace. Gone. Help! is there a way to undo this step?
I should add, ~99% of my collection is not bought through iTunes, so it's not a matter of re-downloading previous purchases.
update: okay, shortly before this incident, i was adding an album to iTunes in ALAC format which i had reencoded from FLACs bought from boomkat.com - this was "exotic" music not available from iTunes, and the Match status said "uploaded" from all tracks. Now, when i added these same files again to my freshly wiped library, it didn't upload them. Sure enough, the status says "uploaded", but the process took like 2 seconds. The files were definitely cached on Apple's server, so I still have a little hope..

A: Unfortunately, iTunes Match really isn't made to be a backup service in this way, and it can be really easy to loose stuff if you don't have other means of recovering it.
For those songs you purchased from iTunes, you should be able to still see them in the purchased list in the iTunes store, and re-add them to your library. Many other sources, like Amazon, will also allow you to re-download their files.
If you had a Time Machine backup, maybe your old library is stored there as well?
If you happen to have an iPod, and had any music synced to it, you could actually use that as a 'backup' and pull your songs from there using an application like iRip. This would only work though if you had a device with the files actually on there, as in a iPod classic or nano, or an iOS device you had downloaded music too.
Finally, you MAY be able to contact Apple Support and see if they have any way of helping, but this may take a very long time and not actually produce anything. I have had a hard time getting support on anything with Match, so replacing an entire library may even be harder. I would recommend calling them if possible.

A: I had this same problem. I had accidentally deleted all of the music off my iTunes library.
This website, if you are using a mac, gives an easy way to recover your library. This sadly only works if you have made no changes to your library since you deleted everything and I'm guessing you have because you posted this in march.


text:
Q: How should I move my completed Django Project in a Virtual Environment? I started learning django a few days back and started a project, by luck the project made is good and I'm thinking to deploy it. However I didn't initiate it in virtual environment. have made a virtual environment now and want to move project to that. I want to know how can I do that ? I have created requirements.txt whoever it has included all the irrelevant library names. How can I get rid of them and have only that are required for the project.

A: Django is completely unrelated to the environment you run it on.
The environment represents which python version are you using (2,3...) and the libraries installed.
To answer your question, the only thing you need to do is run your manage.py commands from the python executable in the new virtual environment. Of course install all of the necessary libraries in the new environment if you haven't already did so.
It might be a problem if you created a python3 environment while the one you created was in python2, but at that point it's a code portability issue.


text:
Q: Disable page nesting / content sections in Hugo and publish all pages at top-level? It's been 5 years since I've last used Hugo, so there is a lot I am forgetting and perhaps some things have changed as well.
I use Hugo to publish a static blog, and for some reason everything is being published under a "Post" section that you have to click into, at which point the page is title "#Posts". I do not recall this ever happening before.
I tried using --disableKinds=section to successfully stop "Post" from showing up on my main page, but the children pages disappeared as well. In addition to wanting my blog posts to show up on my main page, I want the URL structure to reflect this corrected organization; i.e., right now everything is showing up under mywebsite.com/post/article-name-here when it should just be mywebsite.com/article-name-here.]
Within my repository, my blog articles are in fact stored under content/post/article-name-here, but when I moved my articles into the content directory directly, Hugo failed to display them.
I feel like this should be a very easy fix, but I'm clearly not using the right search terms to describe what is going on.
Please let me know what other information I can provide as I am having a hard time articulating what is going on.

A: Setting the permalink

right now everything is showing up under mywebsite.com/post/article-name-here when it should just be mywebsite.com/article-name-here

When you are using a config.yaml file, you can add this to it:
permalinks:
  posts: /:filename

That will eliminate the post/ from your URL. For .toml you have to slightly alter the formatting.
The homepage solution
If you change line 8 in your layouts/index file from:
{{ $paginator := .Paginate (where .Data.Pages "Type" "post") }}

into:
{{ $paginator := .Paginate (where .Site.RegularPages "Type" "post") }}

... you will get the expected result (a list of your posts on the homepage). I tested it.

A: Here is the temporary solution I worked out thanks to Mr. Hugo's answer above/below:

*

*Set the permalink configuration in my config.toml file as Mr. Hugo noted.

*Set url = "article-name-here" inside every blog post's Markdown file.

*Publish using hugo via command line, take the index.html and index.xml files within the publish/post directory, and move them into the publish directory (i.e., overwrite the index.html and index.xml files already there).

*Manually retitle the content of the h1 tag inside index.html from "#Posts" to "Recent Articles".

Hopefully I can figure out a better answer and update this Stack Overflow question once I do.


text:
Q: Trilinear polarity from AG perspective Consider a triangle $ABC$ in the projective plane $\mathbb{P}^2.$ For a point $p  \in \mathbb{P}^2$ one can define its trilinear polar line $t(p)$ (see here). This defines a birational map to the dual plane
$$t\colon \mathbb{P}^2 \longrightarrow (\mathbb{P}^2)^{\vee}.$$
As an abstract map to a projective plane it is defined by the linear system $|2H-A-B-C|,$ but I don't see, how one can naturally understand the duality from this perspective.


text:
Q: Rotate and zoom mapview at two points I have two points on a map (MapKit), and now I want to position the map so both points are visible and aligned (one is straight above the other). I can position the map using setVisibleMapRect(rect, edgePadding: padding, animated: true) but I'm not sure how to make the rotation in the same call.
To illustrate a bit further, when the points on the map are side by side, I get this result when first using setVisibleMapRect(rect, edgePadding: padding, animated: true) and then rotating by setting mapView.camera.heading.

The end result I want is this:

The code I'm using to set the map rect is:
func centerMap() {
    let rect = MKMapRect(coordinates: [currentHole!.teeCoordinate, currentHole!.greenCoordinate])
    let padding = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
    mapView.setVisibleMapRect(rect, edgePadding: padding, animated: true)
}

extension MKMapRect {
    init(coordinates: [CLLocationCoordinate2D]) {
        let points = coordinates.map { MKMapPoint.init($0) }
        let rects = points.map { MKMapRect(origin: $0, size: MKMapSize(width: 0, height: 0)) }
        self = rects.reduce(MKMapRect.null) { result, rect in
            return result.union(rect)
        }
    }
}

Any ideas?

A: I ended up using MKMapCamera instead.


text:
Q: How to have Dapper iterate a stored procedure for inserts? I have the following Dapper command to insert values into a table using a stored procedure.
sqlConnection.Execute(
       "sp_LocationTypes_Insert"
       , parameters
       , commandType: CommandType.StoredProcedure
       );

where the parameters are created using
var parameters = new DynamicParameters();
parameters.Add("@updated", dbType: DbType.DateTime, direction: ParameterDirection.Output);
parameters.Add("@description", locationType.description);

In addition, the SP needs to be executed multiple times, once for each LocationType object in a list. I could put the list in a loop and call the Execute command for each instance. However, is there a way to have Dapper iterate the list of objects and execute the SP? I do not want to put the T-SQL as a string.

A: I have spent a while in the Dapper Source and have seen nothing in regards to dapper iterating internally like you are asking.  For this question i referenced Dapper's unit tests and i can find no example of dapper attempting to do this.  With this being said, i would assume it does not.
Here is the link to their general unit tests, if you browse up a level they have it organized into other sections.
https://github.com/StackExchange/Dapper/blob/master/Dapper.Tests/Tests.cs
I consider this to be my comprehensive guide on 'how to use' dapper.


text:
Q: Force download html to pdf using php I try to make force download html-file to pdf and use the code below
<?php
header('Content-disposition: attachment; filename=\''. basename($file) .'\'.pdf');
header("Content-type: application/pdf");

echo file_get_contents($_SERVER['DOCUMENT_ROOT'].'/index-1.html');

?>

I get some file with .pdf extention but when I try to open it, i get an error `not PDF or corrupted'. What's wrong and how to make it work?

A: Telling the browser that some data is a PDF will not magically transform the data into a PDF.
You'll need to do that yourself, e.g. using the PHP PDF library or Prince.

A: You can't just put html in a pet file and expect it to work you need to use something like dompdf to convert html to a pdf file: https://code.google.com/p/dompdf/
For even better results and support for floats I would use the following library. I got extremely good results with it. The reason why this one is working so well is because they use the WebKit browser rendering engine to render the html before converting it to pdf giving you almost 1 on 1 results when comparing it to the browser.
https://code.google.com/p/wkhtmltopdf/

A: You have to create a properly PDF file. You can do this using some PHP classes like HTML2PDF or wkhtmltopdf.


text:
Q: Sharepoint JS: upload files larger than 2mb I'm using the following code to add an attachment to a list item:
const context = new SP.ClientContext.get_current();
const attachments = context
  .get_web()
  .getFolderByServerRelativeUrl(
    `Lists/${list}/Attachments/${itemId}`
  );

const createInfo = new SP.FileCreationInformation();
const base64 = await toBase64(file);
createInfo.set_content(base64);
createInfo.set_url(file.name);

const files = attachments.get_files();
files.add(createInfo);

However, when uploading files larger than 2mb, the server throws an error.
So my question is: how to upload larger files using the Sharepoint JavaScript API?


text:
Q: Dynamically import a TypeScript type there are a lot of questions about TypeScript dynamic import, however they seem to be systematically focused on dynamically import a JavaScript object.
I'd like to be able to import a type dynamically too. Say for example that I want to import the Feature type from leaflet.
Importing leaflet is not allowed in the context of server-side rendering. Importing @types/leaflet isn't allowed either, it's considered an error by TypeScript.
So currently I must manually copy the typings in my app, and import them.
Note that I am using Next.js dynamic imports but it does not change the issue as far as I know. Related issue: https://github.com/zeit/next.js/issues/11196
Any idea how to import a TypeScript type more cleanly, without actually importing the underlying JS lib, in the context of dynamic imports?


text:
Q: SoundCloud Libraries Not Found I'm having some trouble with the SoundCloud API for iOS. I've followed the directions on their quickstart guide (here) and set my Header Search Path like so.
Xcode is finding SCUI.h and until recently wasn't getting any syntax errors. The app was running fine on the iOS Simulator and executing SoundCloud API requests (SCRequest methods). But I then went to try it on-device and encountered these errors, then when I went back to trying to test on the Simulator I started getting these errors.
After reading the error messages and checking my linked libraries (here) I'm certain it has something to do with the path that Xcode is searching for the headers. Or maybe those libraries just don't exist? I can't seem to see any them in Finder, even the .a files that are in black in my linked libraries section.
Also, I've tried cleaning the product (CMD+Shift+K). This allows the project to be run on the simulator but causes an "Assertion failure":
Assertion failure in -[NXOAuth2Client initWithClientID:clientSecret:authorizeURL:tokenURL:accessToken:tokenType:persistent:delegate:], /Users/chiliesontoast/Desktop/iOS/Projects/MobileX Labs/MXLTest App/MXLTestApp/OAuth2Client/Sources/OAuth2Client/NXOAuth2Client.m:82

And then when trying to build for a device it returns this error.
Has anybody got any suggestions for a solution? It's been really bothering me all day.
Thanks.

A: Ah, finally fixed it! It was a combination of two things.
First Issue
The first issue (here and here) was something to do with with the libraries and search paths. I did a load of different things, not sure what fixed it. I did this:

*

*Changed the Header Search Paths around from "./**" to "$PROJECT_DIR" and finally to "../**", which is what it's at now.

*Deleted all of the files downloaded for the SoundCloud API.

*Deleted the entries for the downloaded submodules in .gitmodules and .git/config and then deleted all of the API's folders from .git/modules.

*Then I removed the git cache by navigating to my project's root folder in Terminal and running:
git rm --cache ./OAuth2Client
(And repeated for each of the added submodules).
I then reinstalled the SoundCloudAPI (using git) and possibly cleaned the project (CMD+Shift+K).
Second Issue
The second issue was with a weird runtime error
Assertion failure in -[NXOAuth2Client initWithClientID:clientSecret:authorizeURL:tokenURL:accessToken:tokenType:persistent:delegate:], /Users/chiliesontoast/Desktop/iOS/Projects/MobileX Labs/MXLTest App/MXLTestApp/OAuth2Client/Sources/OAuth2Client/NXOAuth2Client.m:82

After some serious research into NXOAuth and looking at the stack trace I realised that I needed to include the following code in the function before trying to perform any SCRequest methods:
[SCSoundCloud setClientID:@"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                   secret:@"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
              redirectURL:[NSURL URLWithString:@"AppName://oauth"]];

So, that's how I went about solving it. I really hope this helps someone as I was stuck for a whole ~20 hours on this.

A: Been fighting this one for a while... hit error after error (if anyone encounters a different one to this, message me - i guarantee I've hit it)
Anyway, what worked for me is that when you click on the project file, you have a choice of checking the build settings for the project or the target. It didn't work for me until I entered $PROJECT_DIR into the project build settings header search paths instead of the target build settings (or both)


text:
Q: Initial load time is slow for a react app I am creating a web app with React which has a form component, uses Formik field and Yup schema for validation. I am also using Redux to capture some form input to render some other component. Everything works ok, but the initial render time is too slow. But once loaded it works fine and 2nd, 3rd refresh is correct very little render time. I am using create react app.
What is the solution? What should I look for? Chrome Dev Tools saying long function chain is main problem. I don't know where is this chain.
Sincerely,
I am out of clue here, component composition and image optimization is key, it is being said in multiple blogs, but not sure in this case.


text:
Q: Long Running task in android I want to do long running task, But if I use Activity or Service then it gives Timeout
exception, and if I use doInBackground(Context... params) which uses AsyncTask  class
But i want to do syncronse task
plz help if there is any other better alternate for this

A: You can't do this on the UI thread.
Your options:

*

*Good - use AsyncTask

*Not as good - use Thread
Perhaps you could explain why you need to do this synchronously and then we can help talk you off the ledge.


text:
Q: Can Qt compiled libs work with newer compilers? edit
Now i am really confused , it works , qt libs compiled with gcc 3.4 works with gcc 8.3.1
I cannot understand why

*

*End of edit*

I am using same linux qt compiled
runtime libs ,that was originally compiled with an older g++ 3.x.x compiler and it works for now on different linux systems , tested until g++4.8.5 .
Is it by chance? Am i just lucky?
Will it still work with new g++ std 20 compiler .
Or that i should compile from src for each platform...
Qt is 4.7 , can i use the same libs with c++20 compiler ,without build qt from src.


text:
Q: Issue with non-integer node positions after loading scene from a file in Xcode I have had a strange issue which I thought I would share. Although work-arounds are fairly simple, they are a bit tedious, and I was wondering whether there was a better way.
I designed a SpriteKit scene using the scene editor, loaded the scene and performed some custom logic in custom class initialisers. This involved creating some new nodes and comparing node positions and adding some integer offsets to the node positions.
Strangely, I found that although the node positions were specified throughout as integers in the scene editor, they came out as non-integer (as shown in the debugger).
Specifically, I had a node with the x value:
96.000122

This appears to be some binary fraction, so obviously a low bit is set somewhere. I say again, in the scene editor it appears as "96".
The trouble with this as I see it is two fold:

*

*Comparisons can fail.

*It is possible SpriteKit has to do unnecessary anti-aliasing of the image (if it is already pixel aligned).

Are there elegant solutions to round all the positions off in the scene file, or is it something that has to be done manually?

A: In the end, as suggested, I wrote an extension to round all of the positions:
extension SKNode {
    func fixUp() {
        for child in children {
            child.position = CGPoint(
                                 x: round(child.position.x * 4) / 4,
                                 y: round(child.position.y * 4) / 4)
            child.fixUp()
        }
    }
}

In this example, I round to quarter points, but this is arbitrary; it could be smaller as only very tiny displacements fail to show up in the scene editor.
I call this in the init function.


text:
Q: How do I apply a script in Google Sheets to all but two specific tabs? I have a script on a Google Sheet which applies a timestamp when any cell in every alternate column is edited. Currently this applies to all tabs. I would like it to apply to all EXCEPT two tabs which are named 'Tab1' and 'Tab2'. This is the script I am using:

var startingRow = 3
var startingCol = 7

function onEdit(e) {
  var range = e.range;
  var row = range.getRow();
  var colNum = range.getColumn();

  if ((row < startingRow) || (colNum < startingCol) || (colNum % 2 ==0)) {
    // Ignore
  }
  else
  {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    var dateCell = sheet.getRange(row,colNum+1);
    dateCell.setValue(new Date());
  }
}

A: I believe your goal as follows.

*

*You want to run the script when the active sheet is not Tab1 and Tab2 in the active Spreadsheet.

For this, how about this modification?
From:
function onEdit(e) {
  var range = e.range;
  var row = range.getRow();
  var colNum = range.getColumn();

To:
function onEdit(e) {
  var range = e.range;
  var row = range.getRow();
  var colNum = range.getColumn();

  // I added below script
  const ignoreTabs = ["Tab1", "Tab2"];  // Please set the tab name you want to ignore.
  if (ignoreTabs.includes(range.getSheet().getSheetName())) return;

*

*In this modification, when the active sheet name is Tab1 and Tab2, the script is finished by return.

References:

*

*getSheet()

*getSheetName()

*includes()


text:
Q: git clone issue with copssh Using copssh,I've set up my own git server whose os is windows 2012.
And I've created one git repository.
The git repository directory
As you can see in the image, there is one git repository named "vacationsabroad.git"
In my local pc, I'm gonna clone this repository.
So I use the following command.
 git clone administrator@myserverip:/cygdrive/c/cossh/home/admin/git/vacationsabroad.git

But I've gotten the fatal error:

fatal: '/cygdrive/c/cossh/home/admin/git/vacationsabroad.git' does not appear to be a git repository
  fatal: Could not read from remote repository.
Please make sure you have the correct access rights
  and the repository exists.

Error window
How could I fix this issue?

A: When using the copssh and git server, maybe you have to use the following command.
To check out a repository: git clone {username}@{servername}:{repodriveletter}:/{repopath}

So your command could be like this.
git clone administrator@myserverip:c:/cossh/home/admin/git/vacationsabroad.git

Hope it will help you. If it doesn't work, please let me know.


text:
Q: Not getting notifications when selecting myself as pull request author in the filter I'm having trouble to make azure notifications send email notification when someone is commenting on my PR.
In my organization by default notifications are turned off so I'm trying to set it up myself.
I know that the emails are going through because if I select <> in the filter for the author I do get notifications on all PRs doesn't matter who the author is.
The problem is: I don't know what should be provided as value for Pull request author for myself so I can get the emails only on PRs pushed by myself. What I've tried is using basically my account name in azure devops filter. But since that doesn't work I'm guessing something else is used ? Just not sure what.
Below is the screen of the setup I'm trying to use. After '=' there is my account name I use to log in to the system.

Edit (image of organization settings. In project settings there is nothing set for comments for pull requests):

A: So I finally got it to work. The filter works by using a Full Name not account name. Which is really weird because Full Name can be actually edited in Azure devops. So from my perspective this is a bug or bad design on Azure devops teams part.
So if anybody else has this issue instead of typing account name: john.kowalski@xx.com you need to use Full Name from profile: ie. John Kowalski.
Edit: I haven't tried it but also using [Me] keyword could work


text:
Q: Get URI VAR from SynapseXPath Variable in WSO2 ESB API I want to get a URI VAR value from request to call correct case in switch in WSO2 ESB API resource, like this:
<api name="apk" context="/apk"><resource methods="GET" uri-
template="/apk/{appName}"><inSequence><header name="App"
scope="transport" action="remove"/><switch source="get-
property('uri.var.appName')"><case regex="BEBE"><send><endpoint><http
method="GET" uri-template="http://localhost/apk/Bebe.apk></http>
</endpoint></send></case><case regex="CITAS"><send><endpoint><http
method="GET" uri-template="http://localhost/apk/Citas.apk></http>
</endpoint></send></case></switch></inSequence></resource></api>

In switch, source="get-property('uri.var.appName')" it's not correct.
Can I get this value using $url SynapseXpath valiables like $url?

A: What you have done is correct. Please try the same with a log mediator and see whether you get the value properly.
<log level="custom">
    <property name="AppName" expression="get-property('uri.var.appName')"/>
</log>

Alternatively you can assign this to a property and use that inside your switch mediator.


text:
Q: Deserializing missing type with protobuf.net I have an application with plugin architecture. The plugins have their own data containers, which all inherit from the base interface IPluginDataStorage. The DataStorage object, which is serialized to preserve state, contains a list of these subclasses along with other data. The DynamicType flag is set to true, as it's not known until run time which plugins are in use.
[Serializable]
[ProtoContract]
public class DataStorage
{
    [ProtoMember(200, DynamicType = true)]
    public List<IPluginDataContainer> PluginDataStorage { get; set; }

When serializing this setup works okay, but I'm having problems deserializing the list reliably. If I try to deserialize the object without having access to all those plugins that were used when it was serialized, I, naturally, get an exception about a missing type.

Unable to resolve type: NOSMemoryConsumptionPlugin.NOSMemoryConsumptionData, NOSMemoryConsumptionPlugin, Version=1.2.0.17249, Culture=neutral, PublicKeyToken=null (you can use the TypeModel.DynamicTypeFormatting event to provide a custom mapping)

The exception gives a hint that I could provide the format through the event, but I don't see how that could be helpful as the problem is that I don't have that type available. What I'd like to do in these cases is to completely ignore deserializing that object. The list item could even default to a dummy instance of the base class in these cases. But how to do this?

A: That (choosing to skip or default) is a fascinating use-case that I don't think I have considered fully; however, you can probably do this yourself, via:
public class NilContainer : IPluginDataContainer {}

and then subscribe to the  DynamicTypeFormatting event; if you don't recognise the type, supply typeof(NilContainer).
i.e.
RuntimeTypeModel.Default.DynamicTypeFormatting += (sender, args) =>
{
    Type type;
    if(!yourTypeMap.TryGetValue(args.FormattedName, out type))
    {
        type = typeof (NilContainer);
    }
    args.Type = type;
};

(completely untested)


text:
Q: RESPONSIVE IMAGE ON RIGHT SIDE Im trying to position my image on the right side of my screen and my text on the left, but make the image responsive as i resize my browser.

#fmap{
        position: absolute;
        right: 0%;
        margin-right: 0;
        display:block;
        margin:10px;
        width: 100%;
        height: auto;
        border: 12px double #d3d3d3;
        max-width:850px;
    }

A: Here is one way using flexbox on the parent div;

.container {
/*this makes the parent container into a flex container*/
/*divs within this parent container become responsive flex items*/
display: flex;
}

.left {
padding: 20px;
}

#facilitymap {
width: 100%;
}

img {
width: 100%;
}

@media screen and (max-width: 600px) {
.container {
/*switch to column view when screen is 600px or smaller*/
flex-direction: column;
}
}

left side text


text:
Q: Continuous extension simple question Let $f:(0,3)\rightarrow(1,2)$ be a decreasing continuous function.
Prove that $f$ is continuously extendable to a continuous function $g:[0,3]\rightarrow[1,2]$.
My try: I feel this is super easy, but I don't seem to get it.
Let $(x_n)$ be a sequence with $\lim_{n\to\infty} x_n=3$ and $x_n<3$ for all $n\in\mathbb{N}$. Then $(f(x_n))$ is bounded and decreasing, therefore convergent. Hence, $\lim_{n\to\infty} f(x_n)$ exists, and we have $\lim_{n\to\infty} f(x_n)=\lim_{x\to 3^-} f(x)$.
I don't know how to proceed.. $f$ need not be surjective, therefore I don't know what to do.


text:
Q: strange issues with JWplayer 6 and image overlaying video We are having an issue with JWplayer, that has bizarrely only just cropped up since changing our licence to the ads version.
for streaming live video this is an example of the playlist that we are passing to the player:
"playlist": [{
    "title": "a title",
    "image": "/image.png",
    "sources": [{
        "file": "http://{reacted-CDN-Link}/Playlist.m3u8",
        "width": ""
    }, {
        "file": "ramp://{reacted-CDN-Link}/rtmp-wowza-publish-point",
        "width": ""
    }]

What we are finding, is when this is playing live video the player loads, but with the image overlaying the video. (this is primarily when using the HLS stream )
If I remove the image part of the playlist then it works okay. (yes I have updated both the key and the player)
The other strange thing I am finding, is that when the player first loads (whist the live stream is loading) the control bar has the expected elements, such as full screen, level selection (HLS). However when the player starts to play, the control bar has no full screen button, and no DVR (when turned on and configured)
These issues are only happening on Live streams and not on VOD.
Has anyone else come across anything like this?

A: Just an Update, we worked out that it was an error on the configuration of the wowza server. It appeared that it was outputting the m3u8 with audio only. This caused JWPlayer to act as expected, and play back as if there was only an Audio track.


text:
Q: Using vibrations in a "custom" way I'm trying to write an app that uses vibrations as notificatons. A certain amount of vibrations means a certain thing.
I've managed to cleverly put together a method that does a series of short vibrations contionusly. But I'm having trouble just doing X# of vibrations...
Here's my code
- (void)goVibration {

    if(vCount > 1)

    {
          vCount--;
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    [self delayCallback:^{

        AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);

        [self goVibration];

    } forTotalSeconds:0.3];
    }
}

vCount = 8 before the function is called.
I only get 3 vibrates in this situation.
If I take out the if(vCount > 1) the function calls infinitely. Any ideas?
Here is my delayCallback
- (void) delayCallback: (void(^)(void))callback forTotalSeconds: (double)delayInSeconds{

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        if(callback){
            callback();
        }
    });
}

Maybe I can use the Taptic Engine?


text:
Q: How do you print the address of an http server in node.js? Here is my code:
var http = require('http');

function onRequest(req, res) {
    // do something
}

var server = http.createServer(onRequest);
server.listen(8000);
console.log("The server is now running on " + <<server.address>>);

I want the <> to be something like "http://localhost:8000". How do I do that?

A: var http = require('http');
var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080);
console.log('Server listening:', `http://${server.address().address}:${server.address().port}`);

I think you can use

server.address()#
Added in: v0.1.90 Returns the bound address, the address family name,
  and port of the server as reported by the operating system. Useful to
  find which port was assigned when getting an OS-assigned address.
  Returns an object with port, family, and address properties: { port:
  12346, family: 'IPv4', address: '127.0.0.1' }

A: This should give you your hostname and port on server startup:
var server  = require('http').createServer(onRequest);
var port = '8000';
server.listen(port, function(err) {
    console.log(err, require('os').hostname()+':'+port);
});


text:
Q: Unable to mount a gpt partitioned external USB drive in Ubuntu 19.04 I'm trying to mount an external Toshiba USB drive in Ubuntu 19.04. No entry appears in the file manager gui when the drive is plugged in. fdisk shows...
ewan@tiny:~$ sudo fdisk -l
...
Disk /dev/sdb: 698.7 GiB, 750156374016 bytes, 1465149168 sectors
Disk model: External USB 3.0
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX [redacted]

I used gdisk to partition the drive, and listing partitions shows:
Command (? for help): p
Disk /dev/sdb: 1465149168 sectors, 698.6 GiB
Model: External USB 3.0
Sector size (logical/physical): 512/512 bytes
Disk identifier (GUID): XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
Partition table holds up to 128 entries
Main partition table begins at sector 2 and ends at sector 33
First usable sector is 34, last usable sector is 1465149134
Partitions will be aligned on 2048-sector boundaries
Total free space is 2014 sectors (1007.0 KiB)
Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048      1465149134   698.6 GiB   8300  Linux filesystem

The partition changes were saved with the gdisk 'w' command.
Using lsblk shows (drive info redacted):
ewan@tiny:~$ lsblk -fa
...
loop22 squashfs                                                    0   100% /snap/gnome-system-m
loop23 squashfs                                                    0   100% /snap/gnome-characte
sda
├─sda1 vfat           XXXXXXXXX                               503.4M     1% /boot/efi
├─sda2 ext4           XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX    412.8M    34% /boot
└─sda3 crypto_L       XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  └─sda3_crypt
       LVM2_mem       XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    ├─ubuntu--vg-root
    │  ext4           XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX    110.5G    47% /
    └─ubuntu--vg-swap_1
       swap           XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX                  [SWAP]
sdb
└─sdb1

When I try to mount:
ewan@tiny:~$ sudo mount /dev/sdb /media/usb/
NTFS signature is missing.
Failed to mount '/dev/sdb': Invalid argument
The device '/dev/sdb' doesn't seem to have a valid NTFS.
Maybe the wrong device is used? Or the whole disk instead of a
partition (e.g. /dev/sda, not /dev/sda1)? Or the other way around?

Any suggestions please?

A: gdisk just modifies the partition table, it does not actually create the filesystem metadata structures into new partitions (aka "formatting" the partition). For that, you'll need some variant of the mkfs command.
As you've created a partition /dev/sdb1 and marked it as a Linux filesystem, you should now create the filesystem of the desired type on it. For example, if you choose to use the ext4 filesystem type, you should run sudo mkfs.ext4 /dev/sdb1; if you chose XFS instead, you should run sudo mkfs.xfs /dev/sdb1 instead.
After the mkfs command is successfully executed, the filesystem should be ready for mounting. And you should use the partition device (/dev/sdb1), not the whole-disk device (/dev/sdb) for mounting.


text:
Q: Remove any rows where values don't match across specific columns, except if other value(s) is NA I am looking for a way to remove any rows where the values across each variable don't match, unless the lack of a match is due to one of the values (or more) being NA.
df <- data.frame(uid = c(1, 2, 3, 4, 5, 6, 7),
                  x1 = c('a', NA, NA, 'a', 'a', 'c', 'b'),
                  x2 = c(NA, 'b', NA, NA, NA, NA, 'b'),
                  x3 = c(NA, NA, 'c', 'a', 'b', NA, 'b'),
                  x4 = c(NA, NA, NA, NA, NA, NA, 'b'),
                  x5 = c(NA, NA, NA, NA, NA, 'b', 'b'))

df
  uid   x1   x2   x3   x4   x5
1   1    a <NA> <NA> <NA> <NA>
2   2 <NA>    b <NA> <NA> <NA>
3   3 <NA> <NA>    c <NA> <NA>
4   4    a <NA>    a <NA> <NA>
5   5    a <NA>    b <NA> <NA>
6   6    c <NA> <NA> <NA>    b
7   7    b    b    b    b    b

What I am looking for is a method that would remove rows 5 and 6. I tried several methods using subset and was able to get it to work if I did:
subset(df, (x1 == x2 | is.na(x1) | is.na(x2)) & ...
           (x4 == x5 | is.na(x4) | is.na(x5)))

However, I couldn't find a method that didn't involve typing out every combination, which is already impractical with just 5 columns, but not at all practical given the actual dataset.

A: Not the cleanest solution, but I made a function that achieved the result.
Libraries
library(dplyr)
library(stringr)

Data
df <- data.frame(uid = c(1, 2, 3, 4, 5, 6, 7),
                 x1 = c('a', NA, NA, 'a', 'a', 'c', 'b'),
                 x2 = c(NA, 'b', NA, NA, NA, NA, 'b'),
                 x3 = c(NA, NA, 'c', 'a', 'b', NA, 'b'),
                 x4 = c(NA, NA, NA, NA, NA, NA, 'b'),
                 x5 = c(NA, NA, NA, NA, NA, 'b', 'b'))

Code
remove_rows <- function(string){

  if(sum(is.na(string)) >= (length(string) -1)){
    TRUE
  }else{
    string %>%
      na.omit() %>%
      str_c(.,collapse = "") %>%
      str_count(string) %>%
      max(na.rm = TRUE) > 1
  }

}

df %>%
  rowwise() %>%
  filter(remove_rows(c_across(x1:x5)))

Output
# A tibble: 5 x 6
# Rowwise:
    uid x1    x2    x3    x4    x5
  <dbl> <chr> <chr> <chr> <chr> <chr>
1     1 a     NA    NA    NA    NA
2     2 NA    b     NA    NA    NA
3     3 NA    NA    c     NA    NA
4     4 a     NA    a     NA    NA
5     7 b     b     b     b     b

A: Remove the lines where the number of unique, non-NA values in columns of interest exceeds 1:
df[ ! apply(df[-1], 1, function(x) length(unique(na.omit(x))) ) >1, ]
#--------------------
  uid   x1   x2   x3   x4   x5
1   1    a <NA> <NA> <NA> <NA>
2   2 <NA>    b <NA> <NA> <NA>
3   3 <NA> <NA>    c <NA> <NA>
4   4    a <NA>    a <NA> <NA>
7   7    b    b    b    b    b


text:
Q: DateTime.UtcNow gives different value in different server I have a dll that logs datetime in UTC using this code i.e. `DateTime.UtcNow() I am running a console application which uses this dll in two different servers. One server is in 'Easter Timezone' and the other is in 'Pacific Timezone'. Now when i launch the console application, i keep getting two different times.
e.g.
In Easter  Timezone: 11/18/2014 10:14:40 PM
In Pacific Timezone: 11/18/2014 10:13:26 PM
Difference: 1:14
I launched the console application in the server that was running in EST first. And the time difference between launching two console applications in two servers was just couple seconds. Does anyone know why there is so much difference in timezone (UTC) while running the same code in two different servers?
Thanks.
Sanjeev

A: The system clock on both servers could be slightly different.
From the spec (emphasis added):

Gets a DateTime object that is set to the current date and time on this
computer, expressed as the Coordinated Universal Time (UTC).

http://msdn.microsoft.com/en-us/library/system.datetime.utcnow(v=vs.110).aspx


text:
Q: how to preload large size image? i have certain links, on mouse over of those links I am changing <div> background image
jQuery I have used is-
function imgchange()
    {
        $('.smenu li').mouseover( function(){
        var src = $(this).find('a').attr('href');
        $('.hbg').css('background-image', 'url(' + src + ')');
        $(this).find('hbg').attr('title', 'my tootip info');
        });
    }

It is working fine but the problem is when I running it on server images takes 3-4 sec to be changed on change, but the second time I do mouse over images are getting changed instantly, I think this is because of browser stored images in cache. So I added one javascript to preload images on page onLoad() ivent -
<script language = "JavaScript">
function preloader()
{
heavyImage = new Image();
heavyImage.src = "images/soluinfo1.jpg";
heavyImage.src = "images/soluinfo2.jpg";
heavyImage.src = "images/soluinfo3.jpg";
heavyImage.src = "images/soluinfo4.jpg";
heavyImage.src = "images/soluinfo5.jpg";
heavyImage.src = "images/soluinfo6.jpg";
heavyImage.src = "images/soluinfo7.jpg";
}
</script>

<body onLoad="javascript:preloader()">
but this script has not solved my problem.what should I do?

A: You might find it easier to change your approach and use CSS sprites (and another article). Then you would just have one image referenced, and you use CSS to set which part of that image gets shown in which scenario.
This assumes that the images you're using are under your control and you can use an image editor to combine them into one large image.

A: @Richard's answer (sprites) is probably the best one for what you are after, but the reason your code is not working is that in most browsers, only the last heavyImage.src="" is given enough time to actually register with the browser as an actual request. You're creating only one Image object setting and resetting the .src attribute faster than the browser can request the files (I think modern JavaScript engines take the added step of removing all the intermediate .src statements specifically because of this).
There are a couple of ways to fix this. The easiest is to create multiple Image objects, one for each image. And the easiest way to do that is through something like this:
<script type="text/javascript">
function preloader()
{
    function doPreload(strImagePath)
    {
        var heavyImage = new Image();
        heavyImage.src = strImagePath;
    }

    var arrImages = ["images/soluinfo1.jpg","images/soluinfo2.jpg","images/soluinfo3.jpg","images/soluinfo4.jpg","images/soluinfo5.jpg","images/soluinfo6.jpg","images/soluinfo7.jpg"];
    for (var i = 0; i < arrImages.length; i++) {
        doPreload(arrImages[i]);
    }
}
</script>

By putting the heavyImage variable inside its own function (remember to use the var keyword), you're ensuring that the Image object exists inside its own dedicated scope.
Another way to do this is to attach a "load" event listener to a single heavyImage. Every time the image finishes loading, go fetch the next image. The disadvantage to this method is that your images will be loaded one at a time (bad for navigation images, but great for, say, and image gallery), whereas the first technique will fetch the images in parallel (typicallly four at a time).


text:
Q: How can one test their 1gbps server connection via ssh? My ubuntu server has a 1gbps connection. How can I test this connection via ssh terminal?

A: For a general command line Internet speed test, you could use speedtest-cli.
One-liner usage:
python3 <(curl -sL https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py)

Note: The above command assumes that you trust the Python 3 code retrieved from https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py.
Sample output:
deltik@box1 [~]$ python3 <(curl -sL https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py) --server 17394
Retrieving speedtest.net configuration...
Testing from OVH Hosting (167.114.208.99)...
Retrieving speedtest.net server list...
Retrieving information for the selected server...
Hosted by Bell Canada (Toronto, ON) [3.18 km]: 19.545 ms
Testing download speed................................................................................
Download: 2366.49 Mbit/s
Testing upload speed......................................................................................................
Upload: 689.48 Mbit/s

If you want to test the speed between your server and a client that you control, you can use iPerf3.
First, install iPerf3 on both the client and the server.  Ubuntu/Debian installation command:
sudo apt install -y iperf3

On the server, run iperf3 in server mode:
iperf3 -s

On the client, run one of these commands to test the speed:
(Replace XXX.XXX.XXX.XXX with your server's IP address.)

*

*Client to server TCP transfer:
iperf3 -c XXX.XXX.XXX.XXX

*Server to client TCP transfer:
iperf3 -R -c XXX.XXX.XXX.XXX


text:
Q: Batch convert text to audio files, retaining file names I have a folder with hundreds of text files. I'd like to batch convert them to audio files but make sure each audio file retains the file name of the text file From which it was created.
I am newer to Mac, so this is proving difficult.

A: You didn't specify an audio format but try the following in terminal in the directory containing your text files.
for f in *.txt;do say -f "$f" -o "${f%txt}aif";done

See this answer on superuser for other solutions.


text:
Q: Remove multiple sprites from stage AS3 I've created a list of sprites (to hold textfields), how would I remove all the created sprites?
creating the sprites:
    for (var i:int = 0; i < optionsArray[currentChoicePart].length; i++)
    {
        var txt:TextField = new TextField();
        txt.defaultTextFormat = new TextFormat('Verdana',15,0xFFFFFF);
        txt.text = optionsArray[currentChoicePart][i];
        txt.filters = [stroke];
        txt.autoSize = TextFieldAutoSize.LEFT;
        txt.selectable = false;
        txt.width = 400
        txt.height = 25
        var btn:Sprite = new Sprite();
        btn.mouseChildren = false;
        btn.addChild(txt);
        btn.buttonMode = true;
        btn.x = stage.stageWidth / 10
        btn.y = stage.stageHeight / 2 - 50 * (i * .5)
        btn.name = "p" + String((Number(currentPart.substring(1)) + (i+1)))
        stage.addChild(btn)
        btn.addEventListener(MouseEvent.CLICK, function m(zen:MouseEvent) // when button is clicked
        {
            choice(zen.currentTarget.name)

        }
        )
    }

A: The entire approach is all wrong and your code the way it is written is only producing more headaches for you than it really should. You only need a special way to remove those buttons because you create that situation for yourself. In reality a more simple and more efficient code would be to have your button set in a specific sprite and then simply remove all buttons from that sprite like:
var buttonHolder:Sprite = new Sprite();
stage.addChild(buttonHolder);

//for loop
for (var i:int = 0; i < optionsArray[currentChoicePart].length; i++)
//etc ...
buttonHolder.addChild(btn);
//here the button is added to his specific holder

No removing button becomes very easy
buttonHolder.removeChildren();

Adding everything to the stage directly is a clue of inexperience for a coder. Nothing really should ever be added to the stage. Instead from your document class you should add more layers (Sprite) and add to those layers depending on your needs. You end up with a very easy to manage display list and set of layers. Adding to the stage will always make your work and logic more difficult and full of headaches down the road.
EDIT:
Looping through a display list or an array in order to remove or add from it is not recommended because it's tricky and can easily produce error. If you add or remove then the number of element changes and the loop which relies on that number might end up with weird results. If you remove then the loop will terminate too soon missing some element to remove. Instead typically this is done with a while loop to avoid this problem.
while(buttonHolder.numChildren)
{
    buttonHolder.removeChildAt(0);
}

Also the removeChildren method must be called like this
removeChildren();

not like this:
removeChildren;//missing ()

A: In a nutshel, I would recommend to save links to the buttons somewhere (e.g. Vector.) and just go through the list when you need to remove all buttons.
Try this code (please, pay attention to the comments):
import flash.display.Sprite;
var btns:Vector. = new Vector.();
function init():void
{
    trace("init");

    for (var i:int = 0; i < optionsArray[currentChoicePart].length; i++)
    {
        var txt:TextField = new TextField();
        txt.defaultTextFormat = new TextFormat('Verdana',15,0xFFFFFF);
        txt.text = optionsArray[currentChoicePart][i];
        txt.filters = [stroke];
        txt.autoSize = TextFieldAutoSize.LEFT;
        txt.selectable = false;
        txt.width = 400
        txt.height = 25
        var btn:Sprite = new Sprite();
        btn.mouseChildren = false;
        btn.addChild(txt);
        btn.buttonMode = true;
        btn.x = stage.stageWidth / 10
        btn.y = stage.stageHeight / 2 - 50 * (i * .5)
        btn.name = "p" + String((Number(currentPart.substring(1)) + (i+1)))
        stage.addChild(btn)
        btn.addEventListener(
            MouseEvent.CLICK,
            function m(zen:MouseEvent) // when button is clicked
            {
                choice(zen.currentTarget.name);
            }
        )

        // Each button is put in the list,
        // to be able to work with the button after
        btns.push(btn);
    }

    trace(btns.length);
}

function reset():void
{
    trace("reset");

    var tempBtn:Sprite;
    var btnsCount:int = btns.length;
    // We just go through the list and remove all buttons from theirs parents
    for(var btnIndex:int = 0; btnIndex < btnsCount; btnIndex++)
    {
        tempBtn = btns[btnIndex];
        tempBtn.parent.removeChild(tempBtn);
    }

    btns = new Vector.<Sprite>();
}

init();
setTimeout(reset, 3000);

Also, I've tested the code above with commented lines where I don't have variables such as optionsArray, stroke, e.t.c.