Q: PowerShell: Difference between (ConvertTo-* | Set-Content) and (Export-*)? I'm new to PowerShell, and trying to learn things the write way, I noticed in this case that I can export data in many different manners, what I want to ask about is this case,
Get-Process | ConvertTo-Csv | Set-Content -Path .\Process.txt

and :
 Get-Process | Export-Csv -Path .\Process.txt

Both exports the list of the processes into a CSV file on my desktop, and give the same result.
The first one :
Converts the processes to CSV first then it writes it onto the file.
The second one :
Exports the Processes directly to the file.
What's really the difference between the two cases, is there performance difference, time execution difference, or anything else I'm not aware of ?

A: They are pretty much the same. There shouldn't be any big difference when it comes to performance and time:
Measure-Command { Get-Process | ConvertTo-Csv | Set-Content -Path .\Process.txt }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 2
Milliseconds      : 880
Ticks             : 28801761
TotalDays         : 3,33353715277778E-05
TotalHours        : 0,000800048916666667
TotalMinutes      : 0,048002935
TotalSeconds      : 2,8801761
TotalMilliseconds : 2880,1761

Measure-Command { Get-Process | Export-Csv -Path .\Process2.txt }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 2
Milliseconds      : 772
Ticks             : 27724661
TotalDays         : 3,20887280092593E-05
TotalHours        : 0,000770129472222222
TotalMinutes      : 0,0462077683333333
TotalSeconds      : 2,7724661
TotalMilliseconds : 2772,4661

This is because Export-CSV and ConvertTo-CSV run 90% of the same code. They share the same helper-class Microsoft.PowerShell.Commands.ExportCsvHelper to create the header and convert objects to csv. The only difference is that ConvertTo-CSV writes the CSV-object(string) to the pipeline using WriteObject(), while Export-CSV directly writes it to a file using a StreamWriter.
To find this yourself, you could look inside Microsoft.PowerShell.Commands.Utility.dll. I won't be posting the code directly because I'm not sure if it's legal or not. :-)
If you need the CSV-output to be displayed or sent through a third-party API etc., then use ConvertTo-CSV. If you need the data stored in a CSV-file, then you should use Export-CSV.


Q: How to test mp3 upload in Django DRF, via PUT? I try to test mp3 modification (hence PUT). I have the following so far:
client = Client()
with open('my_modified_audio.mp3', 'rb') as fp:
    response = client.put(
            f"/resource/{resource_id}/",
            data={'audio': fp})

However, I get response.status_code == 415 because the serializer line in DRF's ModelViewSet
serializer = self.get_serializer(instance, data=request.data, partial=partial).
fails with
rest_framework.exceptions.UnsupportedMediaType: Unsupported media type "application/octet-stream" in request.
I have tried setting format="multipart", setting the content type to json or form-encoded, nothing helped so far. The Resource model uses FileField:
class Resource(models.Model):
    audio = models.FileField(upload_to='uploads')

How can I make this put request work?

A: I think that the following will work:
The client:
import requests
...

client = Client()
files = [('audio': open('my_modified_audio.mp3', 'rb'))]
url = f"/resource/{resource_id}/"

# response = client.put(url, data=None, files=files)
# You can test it using the `requests` instead of Client()
response = requests.put(url, data=None, files=files)

The serializer:
class AudioSerializer(serializers.Serializer):
    """ AudioSerializer """
    audio = serializers.FileField(...)

    def create(self, validated_data):
        ...

    def update(self, instance, validated_data):
        ...

The view:
from rest_framework.generics import UpdateAPIView

class AudioView(UpdateAPIView):
   ...
   parser_classes = (FormParser, MultiPartParser)
   serializer_class = AudioSerializer
   ...

A: Inspired by @athansp's answer, I compared the source code of client.post and client.put and it turns out, put's implementation slightly differs from post, so a workable way of submitting files with put is:
from django.test.client import MULTIPART_CONTENT, encode_multipart, BOUNDARY

client = Client()
with open('my_modified_audio.mp3', 'rb') as fp:
    response = client.put(
        f"/resource/{resource_id}/",
        data=encode_multipart(BOUNDARY, {
            'other_field': 'some other data',
            'audio': fp,
        }),
        content_type=MULTIPART_CONTENT
    )

Lol.


Q: Change element tag name Mootools I am at the end , sooo many posts and Fiddle examples on how to change tag name of all elements on page with Jquery but NONE with mootools. Is there any way to do it? I need to convert all tr to div, not able to change the actual page html, must do it with Moo. Please help.
i have 15 tr's in a div , crazy huh!

...

I need to convert them to divs but keep all attributes and html within tr's in tact. PLEASE help! Thank you!

A: Replacing elements in mootools is easy, as long as the markup is not invalid as above.
http://jsfiddle.net/dimitar/4WatG/1/
document.getElements("#mydiv span").each(function(el) {
     new Element("div", {
        html: el.get("html")
    }).replaces(el);
});

this will replace all spans for divs in the above markup (use spans instead of trs).
as stated up, http://jsfiddle.net/dimitar/4WatG/ -> firefox strips invalid markup of TR not being a child of a table which makes it hard to target.

A: I'm just going to leave this floating here.
Element.implement({'swapTagName': function(newTagName) {
    return new Element(newTagName, {html: this.get('html')}).replaces(this);
}});

Usage:
//cleaning HTML3.2 like it's 2012
target.getElements('font[size=5pt],b').swapTagName('h2').addClass('header_paragraphs');
target.getElements('font').swapTagName('p');


Q: Find the area of the triangular region $ABC$ in the figure bellow For reference:

In the figure below, the quadrilaterals $AMNB, AEFC$ and $APQR$ are squares; $S_1=9\ \mathrm{m^2}$, $S_2(BRE)=6\ \mathrm{m^2}$, calculate the area of the triangular region $ABC$. (Answer: $15\ \mathrm{m^2}$)

Here is a trigonometric solution
Let $a=AC$.
Considering $△ABC$:
$AB=a\sin(α)⟹\tan(α)=\dfrac{PB}{AB}$
$⟹PB=a\sin(α\tan(α)$
$S_1=a^2\sin^2(α)-\dfrac{a^2}{2}\sin^2(α)\tan(α)$
$S_{ARE}=S_2+S_{ABE}+S_{ABR}$
$S_{ARE}=\dfrac{a⋅a⋅\tan α}{2}$
$S_{ABR}=\dfrac{(a\tan(α))⋅(a\sin(α)\cos(α))}{2}=\dfrac{a^2\sin^2(α)}{2}$
$S_{EAB}=\dfrac{a⋅a⋅\sin2(α)}{2}=S_{ABR}$
$\therefore S_2=\dfrac{a^2}{2}(\tan(α)−2\sin^2(α)))$
$\therefore  \tan(α)=1−\sqrt{\dfrac{2}{5}}$
From the equations above,
$\implies 12=a^2(1−\sqrt{\dfrac{2}{5}}−\dfrac{1}{26}(22−5\sqrt{10})))$
$\implies a^2=\dfrac{12⋅130}{20−\sqrt{10}}=4⋅(20+\sqrt{10})$
$S_{ABC}=\dfrac{a^2}{2}\sin(α)\cos(α)=\dfrac{a^2}{2}\dfrac{\sin^2(α)}{\tan(α)}=\dfrac{a^2}{2}\dfrac{(20−\sqrt{10})}{52}$
$=\dfrac{2}{52}(20^2−10)=15$
But there must be a better solution
simple...???
The solution would be to combine the two areas...

A: Drop perp $~RH$ from $R$ to $AB$. Also as $\angle MAP = \angle BAC$ and $AB = AM$, $M, N, E~$ are collinear.

Notice $~\triangle ARH \cong \triangle PAB~$ (by $A$-$S$-$A$) and hence $RH = AB$. So,
$[ARB] = [AMN] \tag1$
Also, $~\triangle APB \sim \triangle EPN \implies \frac{PB}{AB} = \frac{PN}{EN}$,
$PB \cdot EN = AB \cdot PN \implies [EPB] = [MPN] \tag2$
Adding $(1)$ and $(2)$,
$[ARB] + [EPB] = S1$
$[ARB] + [EPB] + [ERP] = S1 + S2$
But also,
$[ARB] + [EPB] + [ERP] = [ARE] - [ABP]$
$ = [ACP] - [ABP] = [ABC]$


Q: Spin connection on Ricci-flat anti-self-dual 4-manifolds During a talk I heard it was claimed (without proof) that the canonical connection $\nabla^{S^-}$ on the bundle $S^-\to X^4$ of negative chirality spinors over a spin, Ricci-flat, anti-self-dual (ASD) 4-manifold $(X^4,g)$ is flat. Why is this true, i.e. why does the ASD Weyl curvature $W^-$ not contribute to the curvature of $\nabla^{S^-}$?
I think it should depend on $W^-$: by Ricci-flatness and anti-self-duality of $g$, the curvature operator $R:\Lambda^2\to \Lambda^2$ of $g$ is equal to $W^-$. Thus for any $v,w\in \Gamma(TX)$ and $\psi\in \Gamma(S^-)$,
\begin{align}
\mathcal{R}^{S^-}_{v,w}\cdot\psi
&=\frac{1}{2}\sum_{i<j}\langle R_{v,w} e_i,e_j\rangle e_i\cdot e_j \cdot \psi \\
&=\frac{1}{2}\sum_{i<j}\langle W^-_{v,w}e_i,e_j\rangle e_i\cdot e_j \cdot \psi,
\end{align}
which (as far as I can tell) is nonzero provided $W^-\neq 0$ and $v\wedge w \in \Lambda^{2,-}$ is a an ASD 2-form. Where is my mistake?
Thanks for your help.


Q: распарсить с помощью регулярок qt определенное выражение здравствуйте, нужно выдрать с помощью регулярок из запроса scgi выражение content_length и 27, только их, и все(если это вообще возможно)... естественно content_length может быть не 27 :
 auto f = QString("\"CONTENT_LENGTH\"<00>\"27\"<00>"
                  "\"SCGI\"<00>\"1\"<00>"
                  "\"REQUEST_METHOD\"<00>\"POST\"<00>"
                  "\"REQUEST_URI\"<00>\"/deepthought\"<00>\",\""
                  "\"What is the answer to life?\"");
 QRegExp rx("(\"+[a-zA-Z_/0-9]+\")");
 QStringList list1;
 int pos1 = 0;
 while ((pos1 = rx.indexIn(f, pos1)) != -1) {
    list1 << rx.cap(1);
    pos1 += rx.matchedLength();
 }

выводит это: "CONTENT_LENGTH" "27" "SCGI" "1" "REQUEST_METHOD" "POST" "REQUEST_URI" "/deepthought"...
хотел как-нибудь через
QRegExp rx("(\"+[a-zA-Z_/0-9]+\")(\\d+)");

и далее использовать rx.cap(2), то в итоге не удается...

A: Если вам нужно получить значение только CONTENT_LENGTH, тогда именно его и вытаскивайте:
QRegExp rx("\"(CONTENT_LENGTH)\"<00>\"(\\d+)\"<00>");

Для получения всех пар ключ-значение используйте это выражение:
QRegExp rx("\"([\\w]+)\"<00>\"([\\w|/]+)\"<00>");

Соответственно имя ключа получите через rx.cap(1), а значение через rx.cap(2).


Q: Passing data from bootstrap model I am trying to pass the data from bootstrap model and display it on a table. However, the problem here is I am unable to pass the data and the column only display null values. I am a newbie, so I need some help on how to pass the data Day and Session?

        Day

        Type

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Select A Day:

          <select class="selectpicker" data-style="btn-info" multiple data-max-options="1" data-live-search="true">
            <optgroup label="Day">
              <option>Monday</option>
              <option>Tuesday</option>
            </optgroup>
          </select>

Select A Session:

          <select class="selectpicker" data-style="btn-info" multiple data-max-options="1" data-live-search="true">
            <optgroup label="Session">
              <option>Morning</option>
            </optgroup>
          </select>

        <button id="addrow" type="button" class="btn btn-primary">Add
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

A: *

*You haven't closed the  tag correctly for the "#addrow" button.

*You can extract the values from the modal like so (after you give the <select> elements a proper id:
var dayPickerSelect1 = $("#daypicker-select1").val();
var dayPickerSelect2 = $("#daypicker-select2").val();

*You can then pass the extracted values to the table like so:
<input type="text" class="form-control" name="Day' + counter + '" value="' + dayPickerSelect1 + '"/>
<input type="text" class="form-control" name="Session' + counter + '" value="' + dayPickerSelect2 + '"/>


Q: Pass null arguments to native module in React-Native android I have a react-native NativeModule with a single method
@ReactMethod
public void sendEvent(String message, Integer code) {
  ...
}

I want to be able to pass null for the code argument in js, but when I do e.g.
TestModule.sendEvent('this is a test', null);

I get
com.facebook.react.bridge.NativeArgumentsParseException: TypeError: expected dynamic type `double', but had type `null' (constructing arguments for TestModule.sendEvent at argument index 1)

How can null be passed as an argument?

A: You can't pass null in Integer values.
public void sendEvent(String message, Integer code) {
Here Integer code return invalid either pass 0 or change it to String code
So now you can pass null values.


Q: Heroku nodejs Procfile never picked up It seems that my nodejs application is never deploying on Heroku. While my build successfully completes with the following message:
[154] ./server.ts 2.1 kB {0} [built]
[238] ./src 160 bytes {0} [built]
[244] (webpack)/buildin/module.js 517 bytes {0} [built]
[259] ./dist/server/main.bundle.js 76.1 kB {0} [built]
+ 301 hidden modules
Node server listening on http://localhost:5000

I'm only just seeing Heroku's Blank app:

Other symptoms:
My builds never end:

And no dynos are being instantiated:

This is despite the fact that I'm providing a Procfile, like so:
web: npm start

See my package.json:
{
  "name": "vivonslagrasse-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "node dist/server.js",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "universal": "ng build --prod --aot && ng build --prod --app ssr --output-hashing=false && webpack --config webpack.server.config.js --progress --colors && node dist/server.js",
    "postinstall": "npm run universal"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/platform-server": "^5.2.9",
    "@angular/router": "^5.2.0",
    "@nguniversal/module-map-ngfactory-loader": "^5.0.0-beta.8",
    "@ngx-translate/core": "^9.1.1",
    "@ngx-translate/http-loader": "^2.0.1",
    "@nicky-lenaers/ngx-scroll-to": "^0.6.0",
    "ngx-cookie": "^2.0.1",
    "core-js": "^2.4.1",
    "foundation-sites": "^6.4.4-rc1",
    "rxjs": "^5.5.6",
    "ts-loader": "^3.5.0",
    "xmlhttprequest": "^1.8.0",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular/cli": "~1.7.0",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/jquery": "^3.3.1",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  },
  "engines": {
    "node": "7.7.4",
    "npm": "5.6.0"
  }
}

Note that I need to run a node server since this is an angular universal app and the initial page's contents need to be server-generated.
EDIT: I'm adding my server.ts file (the generated server.js is too long to be reproduced here)
// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';

import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';

(global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 5000;
const DIST_FOLDER = join(process.cwd(), 'dist');

// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main.bundle');

const {provideModuleMap} = require('@nguniversal/module-map-ngfactory-loader');

app.engine('html', (_, options, callback) => {
  renderModuleFactory(AppServerModuleNgFactory, {
    // Our index.html
    document: template,
    url: options.req.url,
    // DI so that we can get lazy-loading to work differently (since we need it to just instantly render it)
    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP)
    ]
  }).then(html => {
    callback(null, html);
  });
});

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render(join(DIST_FOLDER, 'browser', 'index.html'), {req});
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node server listening on http://localhost:${PORT}`);
});

Needless to say, this setup works perfectly on my development machine...
Your help will be highly appreciated. I already spent 2,5 hours on this.

A: Use process.env.port in server.js to listen
const port = process.env.port || 5000;
app.listen(port);


Q: Multivariate Jensen's inequality in a probabilistic setting: When does equality hold? I am having trouble understanding the concept of Jensen's inequality in a probabilistic setting with multiple variables. Specifically, I am interested in cases where equality holds. I understand that in the univariate case
\begin{equation}
f(\text{E}[X])\leq \text{E}[f(X)]
\end{equation}
for an integrable, real-valued random variable $X$ and a convex function $f$, and that equality holds if $X$ is constant almost surely or $f$ is linear on some set $A$ such that $\text{P}(X \in A) = 1$ (according to wikipedia and some answered questions on this site).
I am trying to find a similar condition for the multivariate case with independent random variables. For example, consider the function $g(X, Y) = XY$ for two independent, integrable, real-valued random variables $X$ and $Y$ (e.g. normal distributed). In that case
\begin{equation}
\text{E}[g(X, Y)] = \text{E}[XY] = \text{E}[X]\text{E}[Y] = g(\text{E}[X],\text{E}[Y])
\end{equation}
which suggests to me that $g$ has some property that causes equality. However, if my understanding is correct, $g$ is not linear (it is for example not homogeneous of degree 1). I assume that the paragraph about general inequality in a probabilistic setting on wikipedia is relevant to my question, but it is far above my level of understanding.
Is there a condition for equality in the multivariate case besides almost surely constant random variables (and specifically how does $g$ above meet this condition) or do I have a serious misunderstanding about the applicability of Jensen's inequality on this case?

A: Your function $\ g\ $ is neither convex nor concave, so Jensen's inequality isn't applicable. If $\ x=\Big(\frac{1}{2},\frac{-1}{2}\Big)\ $ and $\ y=\Big(\frac{-1}{2},\frac{1}{2}\Big)\ $, for instance, then
\begin{align}
g\Big(\frac{1}{2}x+\frac{1}{2}y\Big)&=g((0,0))\\
&=0\\
&> \frac{-1}{4}\\
&= \frac{1}{2}g(x)+\frac{1}{2}g(y)\ ,
\end{align}
so $\ g\ $ isn't convex.  On the other hand, if $\ u=\Big(\frac{1}{2},\frac{1}{2}\Big)\ $ and $\ v=\Big(\frac{-1}{2},\frac{-1}{2}\Big)\ $, then
\begin{align}
g\Big(\frac{1}{2}u+\frac{1}{2}v\Big)&=g((0,0))\\
&=0\\
&< \frac{1}{4}\\
&= \frac{1}{2}g(u)+\frac{1}{2}g(v)\ ,
\end{align}
so $\ g\ $ isn't concave either.


Q: solr: Adding content-disposition to SolrQueryResponse I have a custom request handler that is extending RequestHandlerBase.
The purpose of this handler is to search the index for the given user query. Instead of omitting the results on the browser at client side, the response data should be downloaded as a file. Here is my handleRequestBody function code
@Override

public void handleRequestBody(final, SolrQueryRequest req,final SolrQueryResponse res) {
    tempFile = File.createTempFile(UUID.randomUUID().toString(),".tmp", new File(FILE_PATH));
    writeSearchResultstoFile(tempFile);
    ContentStreamBase outConentStream = new ContentStreamBase.FileStream(tempFile);
    outConentStream.setContentType("application/download");
    rsp.add(RawResponseWriter.CONTENT, outConentStream);
}

The problem is the file is being downloaded with .part file at client side.
rsp.getResponseHeader().add("Content-Disposition", "filename=data.csv");
didn't help much. Could some please tell me how to set the Content-Disposition.

A: Since I see that you are formatting your results as CSV I am curious as to whether you have looked at the CSVResponseFormat that Solr has supported since release 3.1


Q: Can regressors be considered as random variables? In the linear regression model $$y = \beta_1 X_1 + \cdots + \beta_p X_p + \varepsilon \, ,$$ can the regressors $\{X_i\}_{i \in \{1, \ldots, p\}}$ be considered as random variables?
I know that what we really have is $n$ observations of the relationship between the dependent variable and the regressors, i.e., $$y_i = \beta_{i1} x_{i1} + \cdots +\beta_{ip} x_{ip} + \varepsilon_i \, ,$$ but does it make sense to see things like $\Pr[X_1 = 0]$, where $X_1$ is the same $X_1$ as in the first equation? Would that be equal to $\frac{1}{n} \sum_{i = 1}^n [x_{i1} = 0]$ or does it refer to the probability according to a theoretical distribution?

A: Yes, it is meaningful to imagine the regressors are sampled from a theoretical distribution. The quantity $P(X_1=0)$ would then refer to the theoretical distribution for $X_1$, not to the observed values $x_{1,1},\ldots,x_{1,p}$ of $X_1$. Note that in elementary treatments of regression we assume the regressors are non-random, i.e., they are known constants (equivalently, we are conditioning on the the values of the regressors).


Q: Trying to understand packets captured with tcpdump So I have intercepted a packet being sent from my android device to an apps server. I want to understand what my phone is sending to the server.
I have rooted the phone, and install tcpdump on it. I have used adb shell to run:
tcpdump -n -i wlan0 -w OUTPUT_FILE src host IP_ADDRESS and greater 200

I have gotten the packet on my pc and run it through wireshark.

I have been told that the long list of "........" prevalent in the ascii section is because there is no ascii representation of the specific HEX.
Is that true?
I have been able to determine the packet is not encrypted, because I can see clear text strings in the ascii that I type in the app.
I am guessing the data is either binary OR base64 encoded JSON, converted to hex and sent to the server. Is there any step I can take to further understand the structure of the data sent from my device to the remote server?
Any other tips, or random insights would be super helpful.

A:
Is that true?

Yes.

Is there any step I can take to further understand the structure of the data sent from my device to the remote server?

The captured packet includes an Ethernet Ⅱ header and an IPv4 header and a UDP header as follows:
Ethernet Ⅱ: from 20:e5:2a:4f:b9:4f (NETGEAR) to 44:80:eb:ea:ef:9b (Motorola)
IPv4: from 169.55.244.58 to 192.168.1.12, not fragmented
UDP: from port 14242 to port 48818, payload length=1406 bytes

The right chunk of the 3rd line (i.e. bb 19 43 4f 02 c8 2b a3) is the start of the application data.
To analyze the application data, you need to know what protocol the application used to send the packet and to learn the protocol.


Q: Keras TensorFlow Hub: Getting started with simple ELMO network I'm trying to get a simple ELMO model working from TensorFlow hub but, it's turning out to be a challenge.
When I run the my code, I'm getting the error: "Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_69:0' shape=(None, 10) dtype=string>]"
I think I'm messing up the sequence_length args or the inputs. Can anyone please help me?
import tensorflow as tf
import tensorflow_hub as hub
import re

from tensorflow import keras
import tensorflow.keras
from tensorflow.keras.layers import Input, Dense,Flatten
import numpy as np
import keras.callbacks
import io
from sklearn.model_selection import train_test_split

i = 0
max_cells = 51 #countLines()
x_data = np.zeros((max_cells, 10, 1), dtype='object')
y_data = np.zeros((max_cells, 3), dtype='float32')
seqs = np.zeros((max_cells), dtype='int32')

with io.open('./data/names-sample.txt', encoding='utf-8') as f:
    content = f.readlines()
    for line in content:
        line = re.sub("[\n]", " ", line)
        tokens = line.split()

        for t in range(0, min(10,len(tokens))):
            tkn = tokens[t]
            x_data[i,t] = tkn

        seqs[i] = len(tokens)
        y_data[i,0] = 1

        i = i+1

def build_model():
    tokens = Input(shape=[10,], dtype=tf.string)
    seq_lens = Input(shape=[], dtype=tf.int32)

    elmo = hub.KerasLayer(
        "https://tfhub.dev/google/elmo/3",
        trainable=False,
        output_key="elmo",
        signature="tokens",
    )
    out = elmo({"tokens": tokens, "sequence_len": seqs})

    model = keras.Model(inputs=[tokens, seq_lens], outputs=out)
    model.compile("adam", loss="sparse_categorical_crossentropy")
    model.summary()

    return model

x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.70, shuffle=True)

model = build_model()
model.fit(x_train, y_train,validation_data=(x_test, y_test),epochs=1,batch_size=32)

Full Error:

TypeError: An op outside of the function building code is being passed
a "Graph" tensor. It is possible to have Graph tensors leak out of the
function building context by including a tf.init_scope in your
function building code. For example, the following function will fail:
@tf.function   def has_init_scope():
my_constant = tf.constant(1.)
with tf.init_scope():
added = my_constant * 2 The graph tensor has name: input_69:0
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\temp\Simon\TempElmoNames.py", line 66, in
model = build_model()
File "C:\temp\Simon\TempElmoNames.py", line 56, in build_model
out = elmo({"tokens": tokens, "sequence_len": seqs})
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py",
line 891, in call
outputs = self.call(cast_inputs, *args, **kwargs)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_hub\keras_layer.py",
line 229, in call
result = f()
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py",
line 1081, in call
return self._call_impl(args, kwargs)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py",
line 1121, in _call_impl
return self._call_flat(args, self.captured_inputs, cancellation_manager)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py",
line 1224, in _call_flat
ctx, args, cancellation_manager=cancellation_manager)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\function.py",
line 511, in call
ctx=ctx)
File
"C:\ProgramData\Anaconda3\lib\site-packages\tensorflow_core\python\eager\execute.py",
line 75, in quick_execute
"tensors, but found {}".format(keras_symbolic_tensors))
_SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_69:0' shape=(None, 10)
dtype=string>]

Here are the versions I'm working with:
Keras: 2.3.1
TF: 2.0.0
TH-hub: 0.12.0
UPDATE 1:
I upgraded Keras (2.6.0) TF (2.6.0) & TF Hub(0.12.0) and changed the build_model method on how the seqs and seq_lens are passed.
def build_model():
    tokens = Input(shape=[10,], dtype=tf.string)
    seq_lens = Input(shape=[], dtype=tf.int32)

    elmo = hub.KerasLayer(
        "https://tfhub.dev/google/elmo/3",
        trainable=False,
        output_key="elmo",
        signature="tokens",
    )
    out = elmo({"tokens": tokens, "sequence_len": seq_lens})

    model = keras.Model(inputs=[tokens, seqs], outputs=out)
    model.compile("adam", loss="sparse_categorical_crossentropy")
    model.summary()

    return model

Now I'm getting the error:

ValueError: Input tensors to a Functional must come from
tf.keras.Input. Received: [3 3 2 2 3 3 3 5 3 3 3 2 7 2 2 2 3 2 2 3 3
3 3 3 3 2 3 2 3 2 3 3 2 3 3 2 3  2 2 2 2 3 2 2 3 3 5 3 3 3 0] (missing
previous layer metadata).

A: I don't believe it is a bug rather TF gives us freedom in choosing each method. While we can mix match the layer subclass with keras functional api, I guess we can't make the model subclass work with the Model api of keras. This is where, in my opinion the distinction between eager execution and keras graph mode comes into conflict giving rise to this "SymbolicException".
Making TF aware beforehand what mode it should execute solves it.

A: Ok finally got it working. The first I did it upgraded:
Keras: 2.2.4
TF: 1.15.0
TF: 0.12.0

Next changed my code to use the right version of ELMO model:
import tensorflow_hub as hub
import tensorflow as tf

elmo = hub.Module("https://tfhub.dev/google/elmo/3", trainable=False)

from tensorflow.keras.layers import Input, Lambda, Bidirectional, Dense, Dropout, Flatten, LSTM
from tensorflow.keras.models import Model

def ELMoEmbedding(input_text):
    return elmo(tf.reshape(tf.cast(input_text, tf.string), [-1]), signature="default", as_dict=True)["elmo"]

def build_model():
    input_layer = Input(shape=(1,), dtype="string", name="Input_layer")
    embedding_layer = Lambda(ELMoEmbedding, output_shape=(1024, ), name="Elmo_Embedding")(input_layer)
    BiLSTM = Bidirectional(LSTM(128, return_sequences= False, recurrent_dropout=0.2, dropout=0.2), name="BiLSTM")(embedding_layer)
    Dense_layer_1 = Dense(64, activation='relu')(BiLSTM)
    Dropout_layer_1 = Dropout(0.5)(Dense_layer_1)
    Dense_layer_2 = Dense(32, activation='relu')(Dropout_layer_1)
    Dropout_layer_2 = Dropout(0.5)(Dense_layer_2)
    output_layer = Dense(3, activation='sigmoid')(Dropout_layer_2)
    model = Model(inputs=[input_layer], outputs=output_layer, name="BiLSTM with ELMo Embeddings")
    model.summary()
    model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])
    return model
elmo_BiDirectional_model = build_model()

import numpy as np
import io
import re
from tensorflow import keras

i = 0
max_cells = 300
x_data = np.zeros((max_cells, 1), dtype='object')
y_data = np.zeros((max_cells, 3), dtype='float32')

with tf.Session() as session:
    session.run(tf.global_variables_initializer())
    session.run(tf.tables_initializer())
    model_elmo = elmo_BiDirectional_model.fit(x_data, y_data, epochs=100, batch_size=5)
    train_prediction = elmo_BiDirectional_model.predict(x_data)


Q: Where is defined the TgtOutFormat type in PDFtoolkit VCL library? I have a problem to set watermark image format in the TgtImageWatermarkTemplate component (which is part of the Gnostice PDFtoolkit VCL library). I have the following code:
var
  Watermark: TgtImageWatermarkTemplate;
begin
  ...
  // create and set watermark properties
  Watermark := TgtImageWatermarkTemplate.Create;
  Watermark.ImageFormat := ofJPEG; // <- this line fails the compilation
  ...
end;

But it fails to compile with the following error:

[DCC Error] Unit1.pas(186): E2003 Undeclared identifier: 'ofJPEG'
  [DCC Fatal Error] Project1.dpr(5): F2063 Could not compile used unit 'Unit1.pas'
  Failed Elapsed time: 00:00:01.5

In which unit is the ofJPEG identifier declared (I think it's member of the TgtOutFormat enumeration)? Which unit should I add to my uses clause?

A: Please include gtCstPDFDoc unit in your PAS file. The enumeration TgtImageFormat is from that.
UPDATE: The enumeration values start with if and so it is ifJPEG.


Q: PWA create custom origin for custom project I having an issue with create custom origin it doesn't seem to be reading .env file from my project folder but I have a .env file and it's all set.
Create Project REF: https://magento.github.io/pwa-studio/pwa-buildpack/reference/buildpack-cli/create-project/
yarn buildpack create-custom-origin package/custom-pwa
$ /Users/juliano/Sites/pwa-sites/pwa-studio/node_modules/.bin/buildpack create-custom-origin package/custom-pwa ⓧ  Missing required environment variables: MAGENTO_BACKEND_URL: Connect to an instance of Magento 2.3 by specifying its public domain name. (eg. "https://master-7rqtwti-mfwmkrjfqvbjk.us-4.magentosite.cloud/") CHECKOUT_BRAINTREE_TOKEN: Specify a Braintree API token to direct the Venia storefront to communicate with your Braintree instance. You can find this value in Braintree's Control Panel under Settings > API Keys > Tokenization Keys. (eg. "sandbox_8yrzsvtm_s2bg8fs563crhqzk") ⓧ  Error: Missing required environment variables: MAGENTO_BACKEND_URL: Connect to an instance of Magento 2.3 by specifying its public domain name. (eg. "https://master-7rqtwti-mfwmkrjfqvbjk.us-4.magentosite.cloud/") CHECKOUT_BRAINTREE_TOKEN: Specify a Braintree API token to direct the Venia storefront to communicate with your Braintree instance. You can find this value in Braintree's Control Panel under Settings > API Keys > Tokenization Keys. (eg. "sandbox_8yrzsvtm_s2bg8fs563crhqzk") ⓧ  Error: Error: Missing required environment variables: MAGENTO_BACKEND_URL: Connect to an instance of Magento 2.3 by specifying its public domain name. (eg. "https://master-7rqtwti-mfwmkrjfqvbjk.us-4.magentosite.cloud/") CHECKOUT_BRAINTREE_TOKEN: Specify a Braintree API token to direct the Venia storefront to communicate with your Braintree instance. You can find this value in Braintree's Control Panel under Settings > API Keys > Tokenization Keys. (eg. "sandbox_8yrzsvtm_s2bg8fs563crhqzk")
All of the above is specified in inside project package/custom-pwa/.env
any ideas what could be ?

A: Found out I was missing .  Sounds a bit stupid even thought I cd custom-pwa folder It's required to specify . E.G:
yarn buildpack create-custom-origin package/custom-pwa .


Q: Using Bonferroni’s inequality to prove the following: Let $A_k(1\leqslant k \leqslant \infty)$ be events from sample space $\Omega$, such that $P(A_k)=1 (1\leqslant k \leqslant \infty)$.
Prove that: $P(\bigcap \limits _{k=1}^{\infty}A_{k}) = 1$
I was wondering how to prove with only $P(\bigcap \limits _{k=1}^{\infty}A_{k}) = 1$ instead of $\geqslant 1$.

A: One way of doing this is noting that $P(A\cap B)=P(A)+P(B)-P(A\cup B)$, and so the intersection of two events with probability one has probability 1 as well. By induction any finite intersection of such events also has probability 1. Now consider $B_n=\cap_{k=1}^n A_k$, which is a decreasing sequence of events such that $\cap_{n=1}^\infty A_n = \cap_{n=1}^\infty B_n$, and $P(\cap_{n=1}^\infty B_n) =1$ by continuity from above of $P$.

A: Bonferroni's inequality immediately implies that a countable union of events with probability $0$ also has probability $0$. Thus $\mathbb{P}(\bigcup\limits_{n=1}^\infty A_n^c)=0$, and so the probability of the complement $\bigcap\limits_{n=1}^\infty A_n$ is $1$. You really don't need anything else.


Q: How to add custom header to AFNetworking on a JSONRequestOperation Hi, I have the following code accessing a URL:
NSString * stringURL = [NSString stringWithFormat:@"%@/%@/someAPI", kSERVICE_URL, kSERVICE_VERSION];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]];

AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    completionHandler(JSON, nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    completionHandler(nil, error);
}];

But I want to pass the user token as a parameter on HEADER, like X-USER-TOKEN.
Cant find it on AFNetworking documentation, should I change the operation type?

A: I did this :)
[manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"];

A: Use AFHTTPClient or subclass it!
You can set default headers with -setDefaultHeader:value: like this :
[self setDefaultHeader:@"X-USER-TOKEN" value:userToken];

You can check the documentation

A: If you have a layer of abstraction, let's say APIManager,
then you should do the following inside a particular method
 [[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:@"X-Register"];

A: NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];

[request setValue: @"X-USER-TOKEN"  forHTTPHeaderField:@"< clientToken >"];

[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]


Q: Making a android button’s background translucent, Is there a way to make an android button’s background translucent within xml code,
So the button has no background drawable?

A: android:background="@android:color/transparent"

You can also set your own colors:
android:background="#80000000"

The first two hex characters represent opacity. So #00000000 would be fully transparent. #80000000 would be 50% transparent. #FF000000 is opaque.
The other six values are the color itself. #80FF8080 is a color I just made up and is a translucent sort of pinkish.

A: Set the background to the standard android transparent color.
In Code:
myButton.setBackground(getResources().getColor(android.R.color.transparent));

In xml:
android:background="@android:color/transparent"

A: The best way is to create a selector.


Q: autossh options to open a port through a jumpbox I'm connecting to a DB in a private subnet through a bastion host:
ssh -N -M -i ${PEM_FILE} -L 3306:${DB_HOST}:3306 ec2-user@${BASTION_PUBLIC_IP}

But the connection drops very quickly. Is there a way to use autossh in this scenario do maintain the connection alive?

A: Have you considered -o ServerAliveInterval=30?
I recommend making a ~/.ssh/config host name for this server with all its configation options.


Q: AppDelegate.swift line 0 type metadata accessor for _ContiguousArrayStorage crash There is a strange crash happening in my code when I try upgrade the app version.
Here is the crash report for the crash :-
  Crashed: com.apple.root.user-initiated-qos
  0  libswiftCore.dylib             0x102f6f95c specialized _assertionFailure(_:_:file:line:flags:) + 164
  1  Quickride                      0x1011b02f8 type metadata accessor for _ContiguousArrayStorage<String> (AppDelegate.swift)
  2  Quickride                      0x1011a1cfc closure #1 in closure #1 in AppDelegate.persistentContainer.getter (AppDelegate.swift)
  3  Quickride                      0x1015196cc thunk for @callee_owned (@owned NSPersistentStoreDescription, @owned Error?) -> () (UserDataCache.swift)
  4  CoreData                       0x184f3d6d0 -[NSPersistentStoreCoordinator _doAddPersistentStoreWithDescription:privateCopy:completionHandler:] + 920
  5  CoreData                       0x184f3d8a0 -[NSPersistentStoreCoordinator addPersistentStoreWithDescription:completionHandler:] + 172
  6  CoreData                       0x18500100c -[NSPersistentContainer loadPersistentStoresWithCompletionHandler:] + 484
  7  Quickride                      0x1011a1c6c AppDelegate.persistentContainer.getter (AppDelegate.swift:670)
  8  Quickride                      0x10123a72c specialized static  CoreDataHelper.getNSMangedObjectContext() (CoreDataHelper.swift:18)
  9  Quickride                      0x101131664 specialized static ContactPersistenceHelper.clearAllContacts() (ContactPersistenceHelper.swift:113)
  10 Quickride                      0x10123efd0 specialized UserModuleSessionManager.clearUserPersistentStore() (UserModuleSessionManager.swift:103)
  11 Quickride                      0x1010417d4 specialized QRSessionManager.performSessionChangeOperationOnModule(moduleSessionHandler:sessionChangeOperationId:) (QRSessionManager.swift)
  12 Quickride                      0x10103df24 QRSessionManager.callSessionChangeOperationOnAllModules(sessionChangeOperationId:isShutdownSequence:) (QRSessionManager.swift:256)
  13 Quickride                      0x10103d410 QRSessionManager.onResumeUserSession() (QRSessionManager.swift:159)
  14 Quickride                      0x1013125b0 SessionManagerController.resumeUserSession(sessionChangeCompletionListener:) (SessionManagerController.swift:82)
  15 Quickride                      0x10128b0c8 closure #1 in AppStartupHandler.resumeUserSessionAndNavigateToAppropriateInitialView() (AppStartupHandler.swift:38)
  16 Quickride                      0x100ee5784 thunk for @callee_owned () -> () (RideManagementModuleSessonHandler.swift)
  17 libdispatch.dylib              0x181e50aa0 _dispatch_call_block_and_release + 24
  18 libdispatch.dylib              0x181e50a60 _dispatch_client_callout + 16
  19 libdispatch.dylib              0x181e5ddfc _dispatch_root_queue_drain + 924
  20 libdispatch.dylib              0x181e5d9fc _dispatch_worker_thread3 +       120
  21 libsystem_pthread.dylib        0x182183fac _pthread_wqthread + 1176
  22 libsystem_pthread.dylib        0x182183b08 start_wqthread + 4

Any help guys on whats this strange crash all about ? Tried a lot but couldn't figure you..... Thanks in advance


Q: Problems after Importing an android project from github into Eclipse I'm trying to tinker with this project and am having some issues importing it.
https://github.com/HoloAddict/FeedEx
I'm a beginner still, and have made a couple of test projects from scratch, but I think I'd learn a little faster by going through working code in a larger project. Just can't get rid of errors to even build the existing code. These are the steps I have taken:

*

*imported it in as a Git project (file - Import - Git - Projects from Git)

*gen folder error (does not exist or not source) - right clicked on gen, Buld path - Use as a source folder. This made that particular error go away

*all the src files were listed as src.net.fred... packages, so all the imports were errors. Right click - build path - configure build path - added Feedex/src in build path, got rid of those errors.

*have the R.java problem... tried many clean-build approaches, no luck. Also tried taking one from a clean project, creating package net.fred.feedex in gen, creating file R.java, and putting code in from a clean project, but no luck. It did make the import R go away, but of course left many errors where the res class references are broken, again because that R file is missing (I think).

So that's where I am. It seems like I have an R.java problem, but I may have messed up on one of the other steps. Either way, thanks for the help.

A: When you imported the project did you check the "Copy projects into workspace"?
If not import your project again and see if this problem still continues.


Q: utilizar props.match.params em uma classe Gostaria de utilizar uma função que está dentro de uma classe, porém gostaria que esta função utilizasse o props.match.params para resgatar a id do produto na URL, para saber qual é o produto que a função irá manipular e etc.
class Exemplo{

    exemplo(){
        const id = props.match.params
        return console.log(id)
    }
}
export default new Exemplo()

Quando tento executar um código semelhante a este, da erro do tipo "props undefined"


Q: RES_NOT_FOUND after login using JAAS I am using JAAS to authenticate users accessing the protected area of my web application. The login page looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <meta http-equiv="Content-Type" content="text/html; UTF-8" />
    <title>Test</title>
</h:head>
<h:body>
    <ui:composition template="template/common/commonLayout.xhtml">
        <ui:define name="content">
            <form name="loginForm" method="post" action="j_security_check">

                        Login to the your application:

                        Select something:
                        <h:selectOneMenu>
                                <f:selectItems value="#{loginScreenBean.listSomething}" />
                            </h:selectOneMenu>

                        Name:
                        <input type="text" name="j_username" />

                        Password:
                        <input type="password" name="j_password" />

                        <input type="submit" value="Go" />

            </form>
        </ui:define>
    </ui:composition>
</h:body>

My web-xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>patchit</display-name>
  <welcome-file-list>
    <welcome-file>test.html</welcome-file>
  </welcome-file-list>
  <security-role>
    <role-name>admin</role-name>
  </security-role>
  <security-constraint>
    <display-name>Example Security Constraint</display-name>
    <web-resource-collection>
      <web-resource-name>Protected Area</web-resource-name>
      <url-pattern>/protected/*</url-pattern>
      <http-method>DELETE</http-method>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
      <http-method>PUT</http-method>
    </web-resource-collection>
    <auth-constraint>
      <role-name>admin</role-name>
    </auth-constraint>
  </security-constraint>
  <login-config>
    <auth-method>FORM</auth-method>
    <realm-name>Example Form-Based Authentication Area</realm-name>
    <form-login-config>
      <form-login-page>/login.xhtml</form-login-page>
      <form-error-page>/login-error.xhtml</form-error-page>
    </form-login-config>
  </login-config>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
</web-app>

my jaas config looks like this:
CustomLogin {
    de.kungfuzius.test.security.SimpleLoginModule
    sufficient;
};

so when I open a page in the protected area like contextpath/protected/test.xhtml I am presented the login.xhtml with the login form. Once I hit the submit button the user is authenticated, but instead of being forwarded/redirected to the initially requested page I am redirected to contextpath/protected/RES_NOT_FOUND. To check if the user is really authenticated I tried to access contextpath/protected/test.xhtml again at it worked.
Any help is greatly appreciated.
Thanks!

A: wow, interesting behavior. I had a look at the requests using fiddler and I found a request to context/protected/RES_NOT_FOUND. This request came from a css file which was referenced in my template, but did not exist yet.
When I remove this reference to the style sheet it works!!!


Q: Reasons for GLM ('identity') performing better than GLM ('gamma') for predicting a gamma distributed variable? I am investigating different methods for fitting my target variable (observed wind speed: positive, real, with small values being most probable) using generalized linear modeling (GLM) and -  in a first instance - a single predictor (wind speed output from a numerical weather prediction model).
I found that a GLM based on the 'identity' link function (for normal distributions, equal to ordinary least squares regression) performs better than a GLM based on the 'reciprocal' link function (for gamma distributions): 1/mu=Xb. I also tried 'inverse Gaussian: 1/mu^2=Xb.
As a measure of model performance I use skill scores calculated as SS= 1-mse/mse_(ref); where mse is the cross-validation squared error of the GLM and mse_(ref) is the cross-validation squared error of the reference model, with the reference model being the mean value of the observed wind speed.
I tried calculating SS using the expectation value of the gamma distribution as the reference model (E(y)=omega*phi, with omega and phi being the estimated shape and scale parameters of a gamma distribution fitted to Y), but found out that this is exactly the mean of Y.
While all three gamma, inverse Gaussian and Gaussian - based GLMs show significant prediction skill, the Gaussian option shows definitely the highest skill. What could be the reasons why a gamma GLM does not improve, but even lower the model performance?

A: Your outcome variable is measured wind speed, while the predictor is wind speed calculated from a numerical weather forecast model. So, input and output has the same units of measurement, and, assuming the forecasting model is good, the result of the model should be some small adjustment (maybe also depending on some other predictors).
The identity link than says that expectation of wind speed is a linear function of forecasted wind speed, which seems natural. The log link would imply that the expectation of wind speed is the exponential of a linear function of forecasted wind speed, which seems unnatural.
Note that you can use identity link function also with a gamma model, there is no need to use the (canonical) inverse link. It is not clear from your post if you did try that!


Q: using font-awesome in fnCreatedCell Recently learned a new way to use data-attributes within a datatable.
Previously, I would code the columns in this manner (please note the font-awesome tags):
 "columns": [{
    "data": "",
    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
    {
      $(nTd).html("<a href='#' title='Edit Account' class='modAccount'
      data-voyid='"+oData.VOYID+"' data-servicename='"+oData.SERVICE_NAME+"'
      data-vesselname='"+oData.VESSEL_NAME+"' data-voyage='"+oData.VOYAGE+"'
      data-bound='"+oData.BOUND+"' data-cargoweek='"+oData.CARGO_WEEK+"'
      data-cargoyear='"+oData.CARGO_YEAR+"' data-allocation='"+oData.ALLOCATION+"'
      data-importvoyage='"+oData.IMPORT_VOYAGE+"' data-adddate='"+oData.ADD_DATE+"'
      data-adduser='"+oData.ADD_USER+"' data-moddate='"+oData.MOD_DATE+"'
      data-moduser='"+oData.MOD_USER+"'> ");
    },

The method I just learned follows this format:
"columns": [{
    "data": "",
    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol)
    {
       $('', {
       'href': '#',
       'title': 'Edit Account',
       'class': 'modAccount',
       'data-voyid': oData.VOYID,
       'data-servicename': oData.SERVICE_NAME,
       'data-vesselname': oData.VESSEL_NAME,
       'data-voyage': oData.VOYAGE,
       'data-bound': oData.BOUND,
       'data-cargoweek': oData.CARGO_WEEK,
       'data-cargoyear': oData.CARGO_YEAR,
       'data-allocation': oData.ALLOCATION,
       'data-importvoyage': oData.IMPORT_VOYAGE,
       'data-adddate': oData.ADD_DATE,
       'data-adduser': oData.ADD_USER,
       'data-moddate': oData.MOD_DATE,
       'data-moduser': oData.MOD_USER,
       'text': ' ' <-- does not work
       }).appendTo(nTd);
     }
   },

I had no problem bringing in the font-awesome icon with the first piece of code.
The second piece of code is where I need the icons now.
If  you'll notice in the 'text' section in the second piece of code, I tried to pull in the font-awesome icons there.  But on screen, I only see the code, not the icon.
How can I fix this to include the font-awesome icons?
Thank you.

A: You're adding HTML so you supply the string to the html property, instead of text in the object initialiser:
'html': ' '


Q: Decrypting a string to Byte array I was doing encrypting a array of string containing only 0s and 1s like this :
public String[] binaryToText1(String[] binary1, int lengthofshares) {
    String[] encrptedfinally = new String[lengthofshares];
    for(int tt = 0; tt < lengthofshares; tt++) {
        String ss2 = "";
        String ss = binary1[tt];
        String mynextChar;
        ss2 = new java.math.BigInteger(ss, 2).toString(16);
        encrptedfinally[tt] = ss2;
    }
    return encrptedfinally;
}

Here lengthofshares is just the size of string array binary1.But i got stuck when i tried to convert it back to an String array of 0 and 1
I was not able to come up with a solution.
Function of decryption is somewhat like this :
public String[] textToBinary(String[] alpha, int myK) {
    String[] ans = new String[myK + 3];
    for(int t = 0; t < myK; t++) {
        String s = alpha[t];
        byte bytes[] = new byte[s.length()];
        char c[] = s.toCharArray();
        int i;
        for(i = 0; i < s.length(); i++) {
            bytes[i] = (byte) c[i];
        }
        StringBuilder binary = new StringBuilder();
        for(byte b : bytes) {
            int val = b;
            for(i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
        }
        ans[t] = binary.toString();
    }
    return ans;
}

But results are different.Please help.Am not able to get the reason for it being wrong

A: Unfortunately, I don't really understand your code, and I also couldn't figure out if you just want plain String-to-byte conversion or if you also want to do some naive encrypting.
In any case, I think the code below does most of what you want. It uses bitmasks to extract the bits from a 0 to 255 integer representing a char (char + 127).
Similary, it uses bitwise OR to convert the binary String[] representation of the String back to chars and finally, back to a String.
public static void main(String[] args)
{
    String test = "Don't worry, this is just a test";
    List<String> binary = stringToBinary(test);
    System.out.println(binary);
    System.out.println(binaryToString(binary));
}

public static List<String> stringToBinary(String input)
{
    LinkedList<String> binary = new LinkedList<String>();
    char[] input_char = input.toCharArray();
    for (int c = input_char.length - 1 ; c >= 0; c--)
    {
        int charAsInt = input_char[c] + 127; // Char range is -127 to 128. Convert to 0 to 255
        for (int n = 0; n < 8; n++)
        {
            binary.addFirst((charAsInt & 1) == 1 ? "1" : "0");
            charAsInt >>>= 1;
        }
    }
    return binary;
}

public static String binaryToString(List<String> binary)
{
    char[] result_char = new char[binary.size() / 8];
    for (int by = 0; by < binary.size() / 8; by++)
    {
        int charAsInt = 0;
        for (int bit = 0; bit < 8; bit++)
        {
            charAsInt <<= 1;
            charAsInt |= binary.get(by * 8 + bit).equals("1") ? 1 : 0;
        }
        result_char[by] = (char) (charAsInt - 127);
    }
    return new String(result_char);
}


Q: click returns only the first item value in jQuery I have many products with the same class name and I want a user click on the item to return only the clicked item values but my code is returning the value of the first product only.one more thing i want when user click on images the record stores in the cart but here in my case when user click on image the selected product value returned and again when user click on another image the previous value get replace with this one i dont want to replace it i want to add in other li how it can be done. Here is my code:

bellle belle belle 25cl

2 Unit(s) at PKR 0.8/Unit(s)

          PKR 1.6

          processor amd 8-core

           PKR 1980.0

 processor amd 8-core

           PKR 1980.0

Total:PKR 1993.0

Taxes:PKR 0.0

pkr 800.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 700.0

Beverges

pkr 800.0

Beverg

The script i have written for it is here.

A: You need too use this, this inside a JQuery event handler is the DOM element that has the handler attached.
Use
  var price=$(this).find("p").html();
  var product=$(this).find("h1").html();

instead of
  var price=$(".box2 p").html();
  var product=$(".box2 h1").html();

A: Use
$(this).find('p') //or  $(this).find('h1')

Instead of
$(".box2 p").html()

A: $(document).ready(function() {
  $('.box2').click(function(){
      var price=$( this).find('p').html();
      var product=$( this).find('h1').html();
      $(".add li:first-child").text(product+ price);

  });
});

Your jquery should looks like
Demo

A: You can use like this (A faster way):
$('.box2').click(function(){
      var price=$(".box2 p", this).html();
      var product=$(".box2 h1", this).html();
      $(".add li:first-child", this).text(product);
      $(".add li:nth-child(2)", this).text(price);
  });

A:

A: try
  var price=$( this).find('p').html();


Q: comparing extended objects private List<Fruit> myFruit = new Vector<Fruit>();

ok so if I have a list of different types of fruit objects how could I go through the list and compare the different objects.
public class Fruit{
 String type;
 String color;

 }

 public class Grape extends Fruit{
  int seedCount;

   public Grape(Attributes attributes){
    this.type = attributes.getValue("type");
    this.color=attributes.getValue("color");
    this.seedCount=attributes.getValue("seedCount");

 }

 public class Banana extends Fruit{
    String color;

   public Banana(Attributes attributes){
    this.type = attributes.getValue("type");
    this.color=attributes.getValue("color");

 }

public load(localName name, Attributes attributes){
if (name.equalsIgnoreCase("grape"){
 Grape grape = new Grape(attributes);
 myFruit.add(grape);
  }
if (name.equalsIgnoreCase("banana"){
   Banana banana = new Banana(attributes);
   myFruit.add(banana);
  }
 }

So how would I go about sorting through the list of Fruit and displaying specific properties of these objects based on what type of object they are. Ie. if type=Grape display seedCount.

A: *

*If you want to sort Fruit, you need to implement the Comparable interface for the Fruit class.

*If you want to display attributes, have an abstract method in Fruit class and provide the implementations in the subclass.
This way depending on the instance of the Fruit , it will show the corresponding properties.
public abstract class Fruit implements Comparable{
    public abstract void displayProperties();

    @Override
    public int compareTo(Fruit otherFruit){
        return 0;
    }

}

public class Banana extends Fruit {
    private int seedCount;
    @Override
    public void displayProperties() {
        // TODO Auto-generated method stub
        System.out.println(seedCount);
    }

}

public class Grape extends Fruit{
    private String color;
    @Override
    public void displayProperties() {
        // TODO Auto-generated method stub
        System.out.println(color);
    }

}

A: You could add an abstract method to Fruit displayProperties()
You would then be forced to impliment the method for all types  of fruit, then in your for loop you would just call displayProperties()

A: This isn't recommended, but you could use
if(object instanceof Class) {
    Class temp = (Class) object
    //operate on object
}

But what you should do is create a Fruit interface that gives access to the important info related to all fruit, in general you shouldn't cast down to get extra information.
While downcasting isn't evil, it could mean you aren't taking full advantage of polymorphism. To take advantage of polymorphism one should ensure that the supertype the subtypes share has methods to get as much info or behavior as necessary.
For example, lets say you have a list of HousePets, and the HousePets consist of the subtypes Dog and Cat. You loop over this list and want to wag all of the tails of the HousePets that can wag their tails. For simplicity there are two ways to do this, either only the Dog has the method 'wagTail()' (since Cats don't wag tails), or HousePets has a method called 'wagTail()' that is inherited by Cats and Dogs (but the Cat's version does nothing). If we choose the first example the code would look something like this:
 for(HousePet pet : petList)
     if(pet instanceof Dog) {
         ((Dog)pet).wagTail();
     }

And for the second example it would look like this:
 for(HousePet pet : petList)
     pet.wagTail();

The second example takes a little less code and is a little more streamlined. In the worst case scenario, if we go with the first option, we will need an if-block for each new subtype of HousePet, which will make the code bulkier/uglier/etc. Better yet we could have a HousePet method called "showHappiness", and the Dog would wag its tail while the cat purred.

A: I think you need an instanceof operator. It allows you to check object type.
if (list.get(0) instanceof Grape) {
    // list.get(0) is Grape
}


Q: Redux dispatch inside Meteor.call or get Meteor.call value My project works with Meteor and react-redux
For redux to work, one must be able to access the dispatch function in the this.props of the component.
However when I use Meteor.call the callback's this property does not contain the redux function dispatch as is expected.
So this is my Meteor.call:
var testing;

Meteor.call('seed', mergedobj, function(err, seed){
      if(err){
        console.log('ERROR ERROR ERROR: when calling seed err', err);

        if(err.error === 'SWE_RISE_TRANS_NEGATIVE'){
        }
      }else{
        console.log('return of seed', seed)
        console.log('this', this)
        //this.props.dispatch(seedAction(seed))
        testing = seed

      }
    })
console.log('testing', testing) //'INITIAL' and not seed!!

I either need to change the this of the callback so I can call this.props.dispatch inside of the callback or I need to get the value of seed outside of the callback.....
How do I achieve this?
How do I get the value of seed inside variable that is outside of the callback's scope?

A: How about using this syntax:
const dispatch = this.props.dispatch;
Meteor.call('seed', mergedobj, function(err, seed){
      if(err){
        // error handling here.
      }else{
        dispatch(seedAction(seed));
      }
})

So you don't have to deal with this keyword.


Q: What's the difference between config fonts in /etc/fonts/conf.d and gnome-tweak-tool? I can change the hinting and sub-pixel settings from /etc/fonts/conf.d or gnome-tweak-tool. What's the difference of those two methods?
It seems to me that google-chrome and gnome-terminal changes more obviously from /etc/fonts/.


Q: Tabulator getElement is not a function I currently have a tabulator table of 100 elements in the array. When I call the function to grab the specific cell, it manages to grab the first 25 rows and change the color of the specific cell that I want.
The problem is that the ones after isn't changing color when everything else is the same. How do I get around it?
Here is the code that I am using to generate the background color. It works for the first 25 rows but it wasn't able to grab the next 75 rows
var allRowData = table.getRows();

    // loops the entire row
    allRowData.forEach(x => {

        // using the row data, grab the columns and compare with a condition
        scope.columns.forEach(y => {

            if (y.priority == 3) { // checks for the priority number to add a color to it
                var rowCell = x.getCell(`${y.fieldName}`);
                rowCell.getElement().style.backgroundColor = "#F00";
            }
        });
    });

A: You should not be trying to directly manipulate the layout of the table from outside of Tabulator.
Tabulator uses a virtual DOM which means that it will create and destroy elements of the table as needed, which means that you can only style elements that are currently visible, when these elements are updated any previous formatting can be lost without notice.
If you wish to style cell elements you must use the formatter function in the column definition or the rowFormatter function on the table which are called when the rows/cells are redrawn.
Full details of these can be found in the Formatter Documentation
If you are wanting to change the state of rows based on something outside of the table, then your formatters should reference this external variable and when you update the external state you should trigger the redraw function on the table to retrigger the formatters


Q: No equivalent of Yes yes command in linux prints y infinitely on the console. This is helpful to respond to few interactive commands with y. For e.g. yes | cp A/*.txt B automatically overwrites all files in destination directory.
Is there an equivalent command in linux that prints n infinitely?

A: yes accepts an argument, y is just the default value.
You can use:
yes n | command

How cool is that?

Pro tip:
# Use this and see what happens
yes maybe | command

Note: Not every command implements maybe.


Q: cmd type without printing filenames I have a makefile that concatenates two files to create a small kernel.
I am using the following command:
type boot_sect.bin kernel.bin > os-image

Unfortunately, type still shows something on the cmd:
boot_sect.bin

kernel.bin

Is there a way to not show the filenames with type?

A: You can try the following command:
copy /y /b boot_sect.bin+kernel.bin os-image > nul

The /y switch is to automatically overwrite the destination file in case it already exists and /b is for binary copy.


Q: :dependent => :destroy isn't calling the destroy method before the deletion? I have a note model, with the following association
note.rb
has_many :note_categories, :dependent => :destroy
has_many :categories, :through => :note_categories

The NoteCategory model was created to function as a join table between notes and categories. Initially it was just a model/table, but I've created a controller to do some custom stuff when someone is removing a category from a note.
note_categories_controller.rb
def destroy
    p "in notes_categories_controller destroy"
    note_category_to_delete = NoteCategory.find(params[:id])
    #some custom stuff
    note_category_to_delete.destroy
    respond_to do |format|
        format.html { redirect_to(notes_url }
        format.xml  { head :ok }
    end
end

This works fine, because I can use this link to create a button which will remove a category from a note:
<%= button_to 'Remove', note_category, :confirm => 'Are you sure?', :controller => :note_categories, :method => :delete %>

and it works fine.
The problem is, when I delete a note, the note_category rows the belonged to the note are getting deleted, but the destroy method isn't being run. I know this because the custom code isn't being run, and the terminal output in the first line doesn't show up in the terminal. Here is the terminal output:
Note Load (0.7ms)   SELECT * FROM "notes" WHERE ("notes"."id" = 245)
NoteCategory Load (0.5ms)   SELECT * FROM "note_categories" WHERE ("note_categories".note_id = 245)
NoteCategory Destroy (0.3ms)   DELETE FROM "note_categories" WHERE "id" = 146
Note Destroy (0.2ms)   DELETE FROM "notes" WHERE "id" = 245

I thought that by using :dependent => :destroy, the destroy method in the NoteCategories Controller should run before it's deleted. What am I doing wrong?

A: :dependent => :destroy will call the destroy method on the model not the controller.
From the documentation:

If set to :destroy all the associated objects are destroyed alongside this object by calling their destroy method.

That is, if you want something custom to your note_categories before being destroyed, you'll have to either override the destroy method in your NoteCategory model, or use an after_destroy/before_destroy callback.
Either way, using :dependent => :destroy will never execute code contained within your controller, which is why you're not seeing the output of the puts statement in the terminal.


Q: Navbar contents, icons, and card body? (HTML, bootstrap) So I have 3 issues:

*

*The contents of my navbar after the navbar-brand area will not show up for some reason. I am trying to add a home button, about section with a drop-down menu containing: 'Our mission', 'our team', 'faq;' a contact button, etc. (see picture for reference)

*The icon in my card footers will not appear

*How do I make the gray part of the cards a transparent gray color that also shows the body background?

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
  <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@700&display=swap" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="app3.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  <title>Quarantine Blog</title>

      Quarantine Pal

            Home (current)

            Link

Home

                About

                Our Mission

                Our Team

                FAQ

Contact

Our Founder

Press

Sign Up

Login

Quarantine State of Mind

Exploring the 'New Normal'

    Sign Up
    Login

Self-Care and Burn Out

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

        Download

Help Fight Coronavirus

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

        Download

Pandemic Socializing

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

        Download

CSS:
#header {
    background-color: transparent;
    background-position: center bottom;
}

h1 {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.navbar-brand {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.navbar.bg-dark.navbar-dark {
    background-color: transparent !important;
}

body {
    background-image: url('https://images.unsplash.com/photo-1588774210246-a1dc467758df?ixlib=rb-1.2.1&auto=format&fit=crop&w=1934&q=80')

}

.card-body {
    font-family: 'Source Sans Pro',
}

.lead {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.card-body {
    background-color: gray;
    opacity: 80%;
}

.card-title {
    color: white;
    font-family: 'Source Sans Pro', sans-serif;
}

.card-text {
    color: white;
    font-family: 'Source Sans Pro', sans-serif;
}

A: *

*I have fixed your navigation issue. You may need to change the style of the navigation items.

*I also fix your icon display issue, you need to use Font Awesome 4 style. fa fa-heart-o

*Finally, I also add in CSS code to make the background of the card body becomes 80% transparent. Class .card background-color need to set to transparent and class card-footer background-color need to set to white.

.card {
  background-color: transparent !important;
}
.card-body {
    background-color: gray;
    opacity: 80%;
}
.card-footer {
  background-color: #fff !important;
}

#header {
    background-color: transparent;
    background-position: center bottom;
}

h1 {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.navbar-brand {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}

.navbar.bg-dark.navbar-dark {
    background-color: transparent !important;
}

body {
    background-image: url('https://images.unsplash.com/photo-1588774210246-a1dc467758df?ixlib=rb-1.2.1&auto=format&fit=crop&w=1934&q=80')

}

.card-body {
    font-family: 'Source Sans Pro',
}

.lead {
    color: white;
    text-shadow: 0px 4px 3px rgba(0, 0, 0, 0.4),
                0px 8px 13px rgba(0, 0, 0, 0.1),
                0px 18px 23px rgba(0, 0, 0, 0.2);
    font-family: 'Source Sans Pro', sans-serif;
}
.card {
  background-color: transparent !important;
}
.card-body {
    background-color: gray;
    opacity: 80%;
}
.card-footer {
  background-color: #fff !important;
}
.card-title {
    color: white;
    font-family: 'Source Sans Pro', sans-serif;
}

.card-text {
    color: white;
    font-family: 'Source Sans Pro', sans-serif;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

  Quarantine Pal

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

Home

                About

          Our Mission

          Our Team

          FAQ

Contact

Our Founder

Press

Sign Up

Login

Quarantine State of Mind

Exploring the 'New Normal'

  Sign Up
  Login

Self-Care and Burn Out

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

        Download

Help Fight Coronavirus

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

        Download

Pandemic Socializing

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

        Download


Q: connect to Apple Watch through node.js I am looking to try to connect a workout from my Apple Watch to my node.js application. I am not using react or anything, I just specifically want to connect to the Apple Watch through node.js and grab the data.
Is it possible through an Api, without using swift?

A: You can use any API provided by apple to use it in your React app. You can find the documentation here.


Q: Can't add compiler options for nvcc in nsight eclipse How do I add options to my nvcc using nsight eclipse. I tried to modify the command option Under Project->Properties->Build->Settings->Tool Settings-> NVCC Compiler. I changed it from "nvcc" to "nvcc --someoption". However when it compiles I see this output "/usr/local/cuda-7.0/bin/nvcc -O3 -ccbin gcc-4.9 -std=c++11 -gencode arch=compute_35,code=sm_35 -gencode arch=compute_52,code=sm_52 -odir "." -M -o "binomial.d" "../binomial.cu"
Notice that --someoption in not in it. How can I add an option in eclipse?  I also noticed that I can change the command from nvcc to some gibberish and it still compiles so I think that option does not affect anything.  If so how can I add compiler options which eclipse does not include in its gui.

A: I would recommend using the -optf switch that is selectable under Project Settings... Build ... Settings...Tool Settings...Miscellaneous and add your own file to the project that contains whatever compiler switches you want to add.
I think most compiler switches are already covered in the GUI, however.


Q: runtime error : return value gets lost I'm working on this project : https://github.com/zsteve/zebra-zmachine-interpreter
which is supposed to be an interpreter for z-machine story files, but I'm still working on it.
Anyway, the error I'm having is within ztext.cpp and ZDictionary's unit test main.cpp.
zChartoDictionaryZCharString() is supposed to return a pointer to a string/array of zwords.
It is creating/calculating that array properly, but is strangely failing to return it properly...
the error occurs at line 499 of ztext.cpp :
[code]  return (outWord);[/code]
Right at this point, outWord points to an array of zwords : {15 25, 28 ab} allocated by new[]
Once it returns to line 42 in https://github.com/zsteve/zebra-zmachine-interpreter/blob/master/zdictionary/zdictionary/main.cpp ,
the returned zword* now points to {50 00, 00 00}, which shouldn't happen.
I spent an hour debugging the entire thing until I figured out that this was where it went wrong.
So my question is : what causes this problem in my program?
I suspect it's either unmatched new[]/delete[] (could this cause it?) or the std::vector objects in zChartoDictionaryZCharString().
Here is the code :
in main.cpp (/zdictionary/zdictionary/main.cpp) from line 40:
// error occurs here :
// at this point : tmp == {15 25 28 ab}
zword* tmp=zChartoDictionaryZCharString(tmp_);

in ztext.cpp (/ztext/ztext/ztext.cpp) from line 502:
zword* zChartoDictionaryZCharString(zword* zstring)
{
// converts a normal zchar string to a dictionary zchar string
// returns a zword* to either a 2 or 3 zword array.
    std::vector<zchar> vector1=expandZChars(zstring);
    std::vector<zchar> vector2(0);
    if(zVersion<=3){
        // for versions 1 to 3, dictionary word length is 4 bytes (6 zchars)
        int done=0;
        for(int i=0; i<vector1.size() && i<6; i++, done++)
        {
            vector2.push_back(vector1[i]);
        }
        if(done<6)
        {
            for(int i=done; i<6; i++)
            {
                vector2.push_back(5);
            }
        }
        // now we need to pack them to 2x zwords.
        zword* outData=new zword[2];
        zchar* zcharArray=new zchar[vector2.size()];
        for(int i=0; i<vector2.size(); i++) zcharArray[i]=vector2[i];
        outData[0]=endianize(packZChars(zcharArray));
        outData[1]=endianize(packZChars(zcharArray+3)|128);
        delete[] zcharArray;
        vector1.clear();
        vector2.clear();
        return outData;
    }else if(zVersion>3){
        // for versions 4 and up, dictionary word length is 6 bytes (9 zchars)
        int done=0;
        for(int i=0; i<vector1.size() && i<9; i++, done++)
        {
            vector2.push_back(vector1[i]);
        }
        if(done<9)
        {
            for(int i=done; i<9; i++)
            {
                vector2.push_back(5);
            }
        }
        // now we need to pack them to 3x zwords.
        zword* outData=new zword[3];
        zchar* zcharArray=new zchar[vector2.size()];
        for(int i=0; i<vector2.size(); i++) zcharArray[i]=vector2[i];
        outData[0]=packZChars(zcharArray);
        outData[1]=packZChars(zcharArray+3);
        outData[2]=packZChars(zcharArray+6);
        outData[2]|=128;
        for(int i=0; i<3; i++) outData[i]=endianize(outData[i]);
        delete[] zcharArray;
        return outData;
    }
}

Any help on fixing this would be greatly appreciated.
Thanks!


Q: java array casting? How can it be that i get a class cast exception when i try to do:
PrioritetArraySorteret<String> p = new PrioritetArraySorteret<String>();

the error is in the constructor?
public class PrioritetArraySorteret<E> implements PrioritetADT<E> {
private int capacity = 5;
private Entry S[];
private int size;

public PrioritetArraySorteret() {
    S = (Entry[]) new Object[capacity];
    size = 0;
}

private class Entry implements Comparable<Entry> {
    private int key;
    private E value;

    public Entry(int key, E value) {
        this.key = key;
        this.value = value;
    }

    public int getKey() {
        return key;
    }

    public E getValue() {
        return value;
    }

}

A: You really are declaring an array of type Object and trying to cast it, which doesn't work. Instead, in your constructor, do:
S = new Entry[capacity];

A: Why do you do a cast in
S = (Entry[]) new Object[capacity];

and not just
S = new Entry[capacity];

That would probably solve the problem.

A: Your error appears to be attempting to mix generics with something that can't handle this use of generics - namely, arrays.
Changing the definition of S to List<Entry<E>>, and the instantiation to new ArrayList<Entry<E>>(capacity) allows your program to run (given the limited sample).
Some other random notes, given your sample:

*

*You've named your array-to-sort S.  Please follow the standard naming conventions (other people will expect you to), and give it a meaningful name.  It doesn't help that it may look similar to 5 (depends on font, I'll admit).

*capacity is an instance variable used for initialization for every instance of the class (and nowhere else).  Change this to a final static variable and/or change the name of the variable to reference why this is the case

*You define size - Likely, you should be returning S.size() regardless, unless you have some (unstated) specific need.

*Your use of the terms key and value suggests you are attempting to use (or maybe implement) a HashMap.


Q: Invert "Gravitational" Force Function or Solve an Intersection Recall "gravitational"-type force functions, by which I mean anything of the form:
$f(x,y,z) = \frac{k}{((x-x_0)^2+(y-y_0)^2+(z-z_0)^2)^p}, p\in\Re_{>0}, k\in\Re, (x,y,z) \neq(x_0,y_0,z_0)$
(e.g., for gravity, $p=1,k=G m_1 m_2$)
Define a function $g(x,y,z) = f_1(x,y,z) + f_2(x,y,z) + f_3(x,y,z) +\cdots+f_n(x,y,z)$ (a sum of several force functions, presumably each with different $k$ (though probably not $p$).
I have two points $(x_1,y_1,z_1)$ and $(x_2,y_2,z_2)$ such that $g(x_1,y_1,z_1)<a$ and $g(x_2,y_2,z_2)>a$.  My problem is to find the location $(x_3,y_3,z_3)$ such that $g(x_3,y_3,z_3)=a$ where $(x_3,y_3,z_3)$ lies on the straight line between $(x_1,y_1,z_1)$ and $(x_2,y_2,z_2)$.  If it helps, I know that exactly two of the xs, ys, and zs are equal.
I'm currently solving this numerically, but it will eventually be solved on an OpenCL kernel where I would very much like a closed form solution.
However, I am having trouble getting such a solution.  I'm not even sure it's possible.  I tried inverting $g$, but got basically nowhere.  Ideas?  Thanks.

A: Let us consider an extremely simplified version of the problem: $p=1$ and just two terms centered at $(0,\bar y_1,0)$ and $(\bar x_2,\bar y_2,0)$, with the line on which the unknown point lies being $y_1 = y_2 = 0$ and $z_1 = z_2 = 0$. Then you want to solve the equation
$$\frac{k_1}{x^2+\bar y_1^2} + \frac{k_2}{(x-\bar x_2)^2+\bar y_2^2} = a,$$
which expands to the fourth-degree polynomial equation in $x$,
$$k_1\big((x-\bar x_2)^2+\bar y_2^2\big) + k_2\big(x^2+\bar y_1^2\big) = a\big(x^2+\bar y_1^2\big)\big((x-\bar x_2)^2+\bar y_2^2\big).$$
Mathematica finds an analytical solution that I cannot reproduce here because its $\LaTeX$ code has 11887 characters in it. If you have more than two terms, of course, you'll get a polynomial equation of degree greater than five, and those are known to have no analytical solutions in general.


Q: onBlur for lightning:input Trying to implement logic for lightning:input on onBlur case. I need to close this input, when it lose focus, and if I click related buttons for this lightning:input(Confirm/Cancel), want to have some custom validation logic for value in input, and if validation is ok, do something and just then close. If not, don't let input to close and show problem from input.
<lightning:input aura:id="editName"
                 maxlength="255"
                 label="Enter New name here"
                 messageWhenBadInput="bad input length"
                 onchange="{!c.onChange}"
                 onblur="{!c.onBlur}"
                 value="{!v.bufferName}"/>

In current version I'm closing input & buttons just with time delay, but it will not work ok with this additional custom validation(input will show problem, but will be close in any validity
onChange: function(component) {
    var input = component.find("editName");
    var newName = component.get("v.bufferName");
    if (newName.length > 254) {
        input.setCustomValidity("You can't type over 255-symbols name");
        input.reportValidity();
    } else {
        input.setCustomValidity("");
        input.reportValidity();
    }
},
onBlur: function(component, event, helper) {
    window.setTimeout(
        $A.getCallback(function() {
            helper.closeCardEditionForm(component); //closing part with input and buttons
        }), 100
    );
}

Any suggestion how to solve this problem or how to build all logic with this input from begining?


Q: How do I make it so my code displays a cerrtain amount of lines (like it does) but backwards So when I enter 4, instead of say 4 bottles of beer etc, It will start with 100 and go to 96 and then stop (ending with the final line)
import java.util.Scanner;

public class ThreeDotNine {
  public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.print("How many Verses would you like to print:  ");
      String num = sc.nextLine();
      int num2 = Integer.parseInt(num);
      String s = " ";

      for (int x = num2; x > 0; x--) {
          System.out.println(x + " bottles of beer on the wall " + x + " bottles of beer");
          System.out.println("Take one down, pass it around, " + (x - 1) + " bottles of beer on the wall.\n");
      }
      System.out.print("Go to the store, buy some more, ");
      System.out.println("99 bottles of beer on the wall.\n");

  }
}

A: there is nothing wrong with the program. It works fine, Just check it again
How many Verses would you like to print:  4
4 bottles of beer on the wall 4 bottles of beer
Take one down, pass it around, 3 bottles of beer on the wall.

3 bottles of beer on the wall 3 bottles of beer
Take one down, pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall 2 bottles of beer
Take one down, pass it around, 1 bottles of beer on the wall.

1 bottles of beer on the wall 1 bottles of beer
Take one down, pass it around, 0 bottles of beer on the wall.

Go to the store, buy some more, 99 bottles of beer on the wall.

A: I would try it like that:
for ( int x = 0; x <= num2; x++ ) {
  int y = 100 - x;

  System.out.println(y + " bottles of beer on the wall " + y + " bottles of beer");
  System.out.println("Take one down, pass it around, " + (y - 1) + " bottles of beer on the wall.\n");
}

It's easier to understand if you define a second variable.
Now you have your output with
100
99
98
97
96


Q: How to deserialize derived class with other derived class as property I have 2 projects. One is a WPF application and second is my "toolkit" with predefined WPF control, XML deserialization and some base configuration classes.
In my toolkit I have a ConfigurationBase class:
public class ConfigurationBase : XmlDeserializeConfigSectionHandler
{
      public GuiConfigurationBase GuiConfiguration { get; set; }
}

This is GuiConfigurationBase
public class GuiConfigurationBase
{
    public int LogLineCount { get; set; }
}

My toolkit contains predefined View for in app log messages. So my LogViewModel constructor requires a ConfigurationBase which should contain GuiConfiguration with LogLineCount property.
This is because I don't want to implement in app log for every application.
Then I have a WPF project. It contains a class Config which is derived from ConfigurationBase. It's extended with some other props which are not important.
I also needed to extend GuiConfigurationBase so I have class called GuiConfiguration which derives from GuiConfigurationBase.
public class Config : ConfigurationBase
{
    public string AppName { get; set; }
}

public class GuiConfiguration : GuiConfigurationBase
{
    public int TextSize { get; set; }
}

I am also using XmlSerializer for deseserializing my XML file. I need to fill both of my derived classes.
How I can achieve this please?
I tried some abstraction for base classes but with no success.
Thank you for any suggestion.

A: I found a solution.
It's necessary to use XmlAttributeOverrides.
Because I have two projects I had to use reflection to retrieve classes which derive from GuiConfigurationBase. (I don't know anything about project where is my toolkit project referenced)
Then add new XmlElementAttribute for each class (in my case it should be enough to use Linq First() method) - This should be same as XmlIncludeAttribute(Type)
And finaly add XmlAttributeOverrides for ConfigurationBase class's property GuiConfiguration
Here is my deserialize method:
 public T Deserialize<T>(string input) where T : class
    {
        //Init attrbibutee overrides
        XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
        XmlAttributes attrs = new XmlAttributes();

        //Load all types which derive from GuiConfiguration base
        var guiConfTypes = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies()
                            from lType in lAssembly.GetTypes()
                            where typeof(GuiConfigurationBase).IsAssignableFrom(lType) && lType != typeof(GuiConfigurationBase)
                            select lType).ToArray();

        //All classes which derive from GuiConfigurationBase
        foreach (var guiConf in guiConfTypes)
        {
            XmlElementAttribute attr = new XmlElementAttribute
            {
                ElementName = guiConf.Name,
                Type = guiConf
            };

            attrs.XmlElements.Add(attr);
        }

        //Add Attribute overrides for ConfigurationBase class's property GuiConfiguration
        attrOverrides.Add(typeof(ConfigurationBase), nameof(ConfigurationBase.GuiConfiguration), attrs);

        XmlSerializer ser = new XmlSerializer(typeof(T), attrOverrides);

        using (StringReader sr = new StringReader(input))
        {
            return (T)ser.Deserialize(sr);
        }
    }

I hope it will help someone else :-)


Q: Solving SVM without QP solver I've consulted three textbooks on support vector machines, and it is unclear to me how to solve such a problem without a QP solver (which is something my professor has asked us to to). Can anyone help me see the workings through a toy example?
Given toy data:
$$X = \begin{bmatrix} 0 & 0\\ 2 & 3\end{bmatrix} \qquad\qquad y = \begin{bmatrix} -1\\ 1\end{bmatrix}$$
My understanding proceeds as follows:
$$\min_w w^Tw \ \ \ \ \ s.t. \ \ y_i(w^Tx_i + b) \ge 1$$
Express the previous constrained problem as an unconstrained problem:
$$L(w,b,\alpha) = \frac{1}{2}w^Tw - \sum_i\alpha_i[y_i(w^Tx_i + b)-1]$$
Dual problem is equivalent to but easier than the primal problem:
$$\min_w  \max_{\alpha \ge 0} \frac{1}{2}w^Tw - \sum_{i}\alpha_i[y_i(w^Tx_i+b)-1] = \max_{\alpha \ge 0} \min_w \frac{1}{2}w^Tw - \sum_{i}\alpha_i[y_i(w^Tx_i+b)-1]$$
Start by minimizing $w$ in terms of $\alpha$:
$$\frac{\delta L}{\delta w} = 0 = w - \sum_i\alpha_iy_ix_i \implies w = \sum_i\alpha_iy_ix_i$$
Plug this value for $w$ into the Lagrangian from earlier:
$$L(w,b,\alpha) = \frac{1}{2}(\sum_i\alpha_iy_ix_i)(\sum_i\alpha_iy_ix_i) - \sum_ja_j[y_j[(\sum_i\alpha_iy_ix_i)x_j + b]-1]$$
Simplify:
$$= \frac{1}{2}\sum_{i,j}\alpha_i\alpha_jy_iy_jx_ix_j - \sum_{i,j}a_ia_jy_iy_jx_ix_j + b\sum_ia_iy_i+\sum_i\alpha_i$$
The third term equals zero because:
$$\frac{\delta L}{\delta b} = 0 = -\sum_i\alpha_iy_i$$
Ergo:
$$L(w,b,\alpha) = \sum_i\alpha_i - \frac{1}{2}\sum_{i,j}\alpha_i\alpha_jy_iy_jx_ix_j$$
Plug in $X$ and $Y$:
$$= a_i + a_2 - \frac{1}{2}[ (-1)(-1)a_1^2(0) + (-1)(1)a_1a_2(0) + (-1)(1)a_2a_1(0) + (1)(1)a_2^2(13) ]$$
$$= a_1 + a_2 - \frac{13}{2}a_2^2$$
I imagined that my goal now was to solve for values of $a_i$ that maximize the foregoing equation. I thought I would take partial derivatives with respect to $a_i$ and set the derivatives to zero, but that can't be right because I would end up with $\frac{\delta L}{\delta a_1} = 0 = 1$

A: We have the quadratic program (QP) in $\mathrm w \in \mathbb R^2$ and $b \in \mathbb R$
$$\begin{array}{ll} \text{minimize} & w_1^2 + w_2^2\\ \text{subject to} & - (0 w_1 + 0 w_2 - b) \geq 1\\ & + (2 w_1 + 3 w_2 - b) \geq 1\end{array}$$
which can be written as follows
$$\begin{array}{ll} \text{minimize} & w_1^2 + w_2^2\\ \text{subject to} & b \geq 1\\ & 2 w_1 + 3 w_2 \geq b + 1\end{array}$$
If $b \geq 1$, then $b + 1 \geq 2$. Thus,
$$\begin{array}{ll} \text{minimize} & w_1^2 + w_2^2\\ \text{subject to} & b \geq 1\\ & 2 w_1 + 3 w_2 \geq 2\end{array}$$
Decoupling $\mathrm w$ and $b$, we solve the QP in $\mathrm w$
$$\begin{array}{ll} \text{minimize} & w_1^2 + w_2^2\\ \text{subject to} & 2 w_1 + 3 w_2 \geq 2\end{array}$$
and then choose a $b \geq 1$. Rewriting the inequality constraint as an equality constraint, we then have the least-norm problem
$$\begin{array}{ll} \text{minimize} & w_1^2 + w_2^2\\ \text{subject to} & 2 w_1 + 3 w_2 = 2\end{array}$$
whose solution is
$$\bar{\mathrm w} := \dfrac{2}{13} \begin{bmatrix} 2\\ 3\end{bmatrix}$$


Q: Capture time difference between values of two regular expression reference names in Jmeter I defined regular expressions in my JMeter test plan and I'm able to capture the values in simple variables in user.variables. But I'm trying to calculate the time difference between two variables as follows in Beanshell post processor and I'm not getting any result in my report.
import javax.xml.bind.DatatypeConverter;

vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", "succeededDate");
vars.put("old_date_running", "runningDate");

Calendar cal_s =       DatatypeConverter.parseDateTime(vars.get("old_date_submitted"));
Calendar cal_c = DatatypeConverter.parseDateTime(vars.get("old_date_succeeded"));
Calendar cal_r = DatatypeConverter.parseDateTime(vars.get("old_date_running"));

Date new_date1 = cal_s.getTime(); // submitted Time
Date new_date2 = cal_c.getTime(); // succeeded Time
Date new_date3 = cal_r.getTime(); // running Time

long new_date1_ms = new_date1.getTime(); // submitted Time
long new_date2_ms = new_date2.getTime();
long new_date3_ms = new_date3.getTime();

log.info("Date in milliseconds: " + new_date1_ms);

long delta1 = new_date2_ms - new_date1_ms; //calculate the difference (succeededDate - submittedDate)
long delta2 = new_date3_ms - new_date1_ms; //calculate the difference (runningDate - submittedDate)
vars.put("delta1", String.valueOf("delta1")); // store the result into a JMeter Variable
vars.put("delta2", String.valueOf("delta2")); // store the result into a JMeter Variable

A: This bit:
vars.put("old_date_submitted", "submittedDate"); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", "succeededDate");
vars.put("old_date_running", "runningDate");

seems odd to me. Given:

submittedDate, succeeddedDate and runningDates are regular expr. reference names

My expectation is that you should be using JMeter Variables instead of hardcoded strings there, so you should change your code to look like:
vars.put("old_date_submitted", vars.get("submittedDate")); // submittedDate, succeeddedDate and runningDates are regular expr. reference names
vars.put("old_date_succeeded", vars.get("succeededDate"));
vars.put("old_date_running", vars.get("runningDate"));

So most likely your code is failing at DatatypeConverter.parseDateTime.
Next time you face any problem with your Beanshell scripts consider the following troubleshooting techniques:

*

*Check jmeter.log file - in case of Beanshell script failure the error will be printed there

*Add debug(); directive to the very beginning of your Beanshell script - it will trigger debugging output to stdout

*Put your Beanshell code in try/catch block like:
try {
    //your code here
}
catch (Throwable ex) {
    log.error("Something went wrong", ex);
    throw ex;
}

This way you get more "human-friendly" stacktrace printed to jmeter.log file.
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using Beanshell in JMeter tests.