text:
Q: Tailwind CSS in next.JS server isn't rendering any styles I have a basic web server using node.js, next.js, Webpack, and Tailwind CSS.
However, when I run the server, none of the Tailwind styles are applied, and so the page renders without any styling.
Expected

Actual

/styles/tailwind.css
@tailwind  base;
@tailwind  components;
@tailwind  utilities;

/package.json
{
  "name": "app",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build:css": "postcss styles/tailwind.css -o styles/main.css",
    "dev": "node server.js",
    "build": "next build",
    "start": "next start -p $PORT",
    "heroku-postbuild": "npm run build",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-cli": "^6.26.0",
    "babel-eslint": "^8.2.2",
    "classnames": "^2.2.6",
    "compression": "^1.7.4",
    "dotenv": "^7.0.0",
    "dotenv-webpack": "^1.7.0",
    "express": "^4.16.4",
    "http-proxy-middleware": "^0.19.1",
    "immutable": "^4.0.0-rc.12",
    "isomorphic-unfetch": "^3.0.0",
    "js-cookie": "^2.2.0",
    "next": "^9.0.1",
    "next-cookies": "^1.1.2",
    "next-redux-wrapper": "^3.0.0-alpha.2",
    "prop-types": "^15.7.2",
    "ramda": "^0.26.1",
    "react": "^16.8.4",
    "react-cookie": "^3.1.2",
    "react-dom": "^16.8.4",
    "react-redux": "^6.0.1",
    "react-router-redux": "^4.0.8",
    "react-timeago": "^4.4.0",
    "redux": "^4.0.1",
    "redux-immutable": "^4.0.0",
    "redux-immutable-state-invariant": "^2.1.0",
    "redux-saga": "^1.0.2",
    "redux-thunk": "^2.3.0",
    "semantic-ui-react": "^0.86.0",
    "style-loader": "^1.3.0",
    "styled-components": "^4.2.0"
  },
  "devDependencies": {
    "autoprefixer": "^9.8.6",
    "babel-plugin-styled-components": "^1.10.0",
    "css-loader": "^4.3.0",
    "postcss-cli": "^8.0.0",
    "postcss-import": "^12.0.1",
    "postcss-loader": "^4.0.3",
    "postcss-preset-env": "^6.7.0",
    "precss": "^4.0.0",
    "tailwindcss": "^1.8.12",
    "typescript": "^4.0.3",
    "webpack": "^4.44.2",
    "mini-css-extract-plugin": "^0.12.0"
  }
}

/postcss.config.js
module.exports = {
  plugins: [
    require('precss'),
    require('postcss-import'),
    require('tailwindcss'),
    require('autoprefixer'),
    require('postcss-preset-env'),
  ]
}

/tailwind.config.js
module.exports = {
  future: {},
  purge: [],
  theme: {
    extend: {},
  },
  variants: {},
  plugins: [],
}

/pages/_app.js
import '../styles/tailwind.css'
//....

/pages/sample.js
import React from "react";

import '../styles/tailwind.css'

export default function Sample() {
  return (

Next.js

        with Tailwind CSS & postcss-preset-env. Now uses tailwind purge method for
        production builds.

  );
}

/next.config.js
const { parsed: localEnv } = require('dotenv').config();
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const path = require('path');
const Dotenv = require('dotenv-webpack');

// next.config.js
module.exports = {
  target: 'serverless',
  serverRuntimeConfig: {
    // Will only be available on the server side
  },
  env: {
    //...
  },
  webpack(config) {
    config.plugins = config.plugins || [];

    const rule = {
      test: /\.css$/,
      exclude: /node_modules/,
      use: [MiniCssExtractPlugin.loader, 'css-loader']
    }

    config.module.rules.push(rule)

    config.plugins = [
      ...config.plugins,

      // Read the .env file
      new Dotenv({
        path: path.join(__dirname, '.env'),
        systemvars: true,
      }),
      new MiniCssExtractPlugin()
    ];

    return config;
  },
};

A: The generated styles are usually preferred  to be in main.css,
Try changing
import '../styles/tailwind.css'

to
import'./main.css

Hope it helps !


text:
Q: group columns in R dataframe based on values in another column Consider the following pair of lists
 ID<-c("A", "B")
 Var2<-c("T_X", "X_F", "R_X", "T_Y", "Y_F", "R_Y")

I have created the following dataframe
df2<-expand.grid(ID, Var2)

The resultant dataframe is as follows
   Var1 Var2
1     A  T_X
2     B  T_X
3     A  X_F
4     B  X_F
5     A  R_X
6     B  R_X
7     A  T_Y
8     B  T_Y
9     A  Y_F
10    B  Y_F
11    A  R_Y
12    B  R_Y

I would like to reorder the dataframe by Var1 column so that all values corresponding to A are together and likewise with B. (Note this is a toy dataset and the real number of unique values in Var1 can be much higher).
The following is the expected output
   Var1 Var2
1     A  T_X
3     A  X_F
5     A  R_X
7     A  T_Y
9     A  Y_F
11    A  R_Y
2     B  T_X
4     B  X_F
6     B  R_X
8     B  T_Y
10    B  Y_F
12    B  R_Y

I have tried df2%>% group_by(Var1). this has left the dataframe unchanged.
I request someone to help me here.

A: We can do it in reverse.  No need of any ordering afterwards or any packages
setNames(expand.grid(Var2, ID)[2:1], c("Var1", "Var2"))

-output
#    Var1 Var2
#1     A  T_X
#2     A  X_F
#3     A  R_X
#4     A  T_Y
#5     A  Y_F
#6     A  R_Y
#7     B  T_X
#8     B  X_F
#9     B  R_X
#10    B  T_Y
#11    B  Y_F
#12    B  R_Y

Or use crossing from tidyr
library(tidyr)
crossing(ID, Var2 = factor(Var2, levels = Var2))

-output
#   ID    Var2
#   <chr> <chr>
# 1 A     T_X
# 2 A     X_F
# 3 A     R_X
# 4 A     T_Y
# 5 A     Y_F
# 6 A     R_Y
# 7 B     T_X
# 8 B     X_F
# 9 B     R_X
# 10 B     T_Y
# 11 B     Y_F
# 12 B     R_Y

A: You can use tidyr's expand_grid which works as expected here.
tidyr::expand_grid(ID, Var2)

#   ID    Var2
#   <chr> <chr>
# 1 A     T_X
# 2 A     X_F
# 3 A     R_X
# 4 A     T_Y
# 5 A     Y_F
# 6 A     R_Y
# 7 B     T_X
# 8 B     X_F
# 9 B     R_X
#10 B     T_Y
#11 B     Y_F
#12 B     R_Y

However, you can always order df2 output to get output in required format.
df2 <- expand.grid(ID, Var2)
df2[order(df2$Var1), ]

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Cómo renombrar la columna nueva creada por .size()? Necesito saber como renombrar la columna que se crea después de aplicar .size()
#Productos mas vendidos
rep = Train.groupby(['product_id']).size()
rep = rep.sort_values(ascending = False)
print(rep.head(10)

Tengo esto y el resultado que me da analizando los datos es este:
    product_id
24852    18726
13176    15480
21137    10894
21903     9784
47626     8135
47766     7409
47209     7293
16797     6494
26209     6033
27966     5546
dtype: int64

Esa columna que sale a la derecha es la que quiero renombrar y no se como debería hacerlo, he leído en foros pero no me queda claro
PD: también quisiera saber como correr ese product_id para que se vea mas ordenado:(

A: pandas.DataFrame.GroupBy.size retorna una Serie en tu caso, con product_id como índice, no un DataFrame. Si lo que quieres es crear una columna con los valores de la Serie y darle un nombre puedes simplemente usar pandas.Series.to_frame:
import pandas as pd

Train = pd.DataFrame({"product_id": (24852, 13176, 21137, 21903, 47626,
                                     13176, 13176, 21903, 21903, 47626,
                                     24852, 21903, 21137, 21903, 47626,
                                     13176, 13176, 47626, 21903, 47626)})

rep = Train.groupby(['product_id']).size()
rep.sort_values(ascending=False, inplace=True)
rep = rep.to_frame("Size")

>>> rep
            Size
product_id
21903          6
47626          5
13176          5
24852          2
21137          2


text:
Q: Simulate USB keyboard from machine I want to use one PC as a USB keyboard for another PC. It has to be indistinguishable from actual USB keyboard. How can I achieve this?
A solution that works with any of Ubuntu Linux 14 and above, OS X 10.11 or Windows 10 would be acceptable. Should work with USB 2.0 or 3.0.
EDIT: the machine to receive the input should not require any specific software installed or network access. I need to use a physical USB cable and the destination machine should react as if a physical keyboard is present on that USB port.

A: You can use usbip to make USB devices (including a keyboard) on a host computer available as USB devices on a client computer over the network. As it's a USB device, it will be indistinguishable from any USB device attached locally.
Clients exist for Windows, and usbip has been a standard part of the kernel for a long time. Under Debian and Ubuntu, the usbip package contains the programs to set up and control such a connection.
Details on how to set it up can be easily googled, e.g. here
Similar questions:

*

*USB to wireless

*https://stackoverflow.com/questions/18837277/using-remote-hosts-usb-port-as-local-usb-linux-and-win

A: I have had success with etherkey, a Teensy and a UART to USB bridge.
The host computer sends commands to the Teensy through the UART bridge. The Teensy pretends it is a keyboard and presses virtual buttons on the other PC. Etherkey is the software that runs on the Teensy and forwards keys from the host computer to the virtual keyboard.
The destination computer detected the new "keyboard" immediately and didn't need any setup.
Edit: I also got Etherkey running on a ATmega32u4 development board, which is more easily available and cheaper than the Teensy.

A: You could use a Raspberry Pi Zero in USB gadget mode. In this mode, the Raspberry Pi can behave as many standard USB devices (keyboard, mouse, mass storage, etc.) and you will then be able to e.g. "inject" keystrokes from a program running on the Pi (and you can then control this program remotely as you see fit).
The Raspberry Pi Zero is not the only device allowing this; but it's cheap, it's easy to get one, and there are many documentations out there explaining how to do this, so it's (IMHO) a pretty good starting point for a project like this!

A: I'm facing the same situation (specific scenario: I need to unlock my workstation remotely from the PRE-OS BitLocker screen). I've ordered the following HW, so I'm posting this to share my research, but not my experiences
The 'source' computer has the following:

*

*USB HDMI capture device. Lower-end devices can be found on AMZN for ~$20 USD.

*USB peripheral to simulate USB HID This is $90 USD
This should provide the source machine the same functionality as this $500 USB all-in-one.

The 'target' computer has the following:

*

*HDMI splitter so I can still have console when I'm at the computer. Lower-end devices can be found on AMZN for $15 USD.

Total cost will be ( $20 + $90 + $15 ) * 2 = $250 USD so each computer in the pair can monitor and manage the other machine from POST to OS fully online (run level 5).
Wish me luck getting my admin to approve this expense!

A: Use Logitech Unifying USB receiver and emulate virtual keyboard with this: https://github.com/RoganDawes/LOGITacker
Should be about $20 total.

A: One possible solution is to add a Bluetooth dongle to the target PC, and emulate a Bluetooth keyboard from the host PC.

*

*Linux: Setup a linux computer to act as a bluetooth keyboard/mouse - Server Fault

*MacOS: Typeeto - Mac Bluetooth keyboard app for all your gadgets

A: I have the same issue, and I spotted the pikvm hardware solution which may fix the issue for you indirectly, however for my budget I was looking for something much less costly. I am still searching.

A: Given the time between the OP and now, this may be moot. However, for any others with a similar question, I propose the following solution:

*

*Buy a cheap usb keyboard, the ones that are like $5 to $20 or so.

*Disassemble it and take the controller and usb plug section, then wire-up your "controller" to the contact connections intended for the keyboard matrix. (It goes without saying, that soldering will be required.)

*Map out the pins either by examining the contact matrix, or by
program.

*Craft your control program using the mapping.

*Set your program to load and run OnBoot and off you go!

The control program can be written in any language with that supports the manner of output that will control the "key" matrix inputs of the keyboard controller, and the usb end plug, plugs into the target computer as a usb keyboard as desired.
If using a Linux based OS, Python is likely your language of choice. If using a Windows based OS, .Net is likely your language of choice (specific flavor C#, VB is up to you). It's likely even Node.js or PHP could be used if you can control GPIO or Parallel port pins.
Happy Hacking!


text:
Q: Updating a feature in GIT I currently have a feature branch in GIT. This branch was created from the develop branch.
Now certain things on the develop branch have changed and I want those changes to appear in the feature branch. I wanted to know how I can do that or what my options are

A: You can merge the features from the develop branch by first updating both branches (the feature branch and the development branch), then checking out the feature branch and merging the development branch onto the feature branch.
git fetch origin develop
git fetch origin feature/new_gadget
git checkout feature/new_gadget
git merge --no-ff develop

A: Consider the following diagram:
[master] *---*---*
                  \
[develop]          *---*---*---*---*
                            \
[feature]                    A---B---C

You have two main options:

*

*Merge the changes from develop into feature:
[master] *---*---*
                  \
[develop]          *---*---*---*---*---.
                            \           \
[feature]                    A---B---C---D

Here, D is a new merge commit. A, B and C are identical to what they were beforehand.

*Rebase your feature work on top of develop:
[master] *---*---*
                  \
[develop]          *---*---*---*---*
                                    \
[feature]                            E---F---G

Here there is no merge commit, but commits E, F and G will have different hashes from their matching A, B and C commits from before the reboase. This is only a good idea if you haven't shared your existing A, B and C commits with anybody.


text:
Q: Authentication to SharePoint Online REST API from ASP.NET Core I have an existing PHP tool which I'm rewriting in .NET Core 3.0 which browses data on SharePoint Online, Exchange Online and OneDrive.
It has an app registration which I've approve for accessing various tenants, then the tool use oAuth calls using app flow to get the access token to use in calls to read data etc.
The issue I'm having is generating an access token in .NET Core to access SharePoint online using REST. The technique of using ConfidentialClientApplicationBuilder with my client id, secret etc then calling AcquireTokenForClient seems to work for Exchange Online EWS and Graph but fails for SharePoint Online, the response containing "Unsupported app only token."
My PHP code doing the equivalent also includes a JWT as 'client_assertion' and I've found the following article which has code that appears to do very similar steps to what my PHP code does: https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-net-client-assertions (I appreciate the code is written about authentication to Azure but the construction of the claim looks so similar to the PHP construction of the JWT code. And that code I think assumes we have a certificate in a private store with a private key)
I've tried to do the equivalent using System.IdentityModel.Tokens.Jwt (not all the classes in that article are available in core) and after working around several challenges ended up being able to create a JWT token, but when used to generate an access token and make a call on the tenant, it returns a 401 access denied. It could be one of a dozen places in the code I'm using to put the token together since I don't have a solid example of exactly what I'm trying to do.
My interest is specifically in using REST with SharePoint, since it supports some operations Graph v1 doesn't support and I don't want to use Graph beta, and I'm aware there are some ports of CSOM to run on Core but prefer not to go that route.
So what I'd like to find is an example addressing the following constraints:

*

*Runs in C# as a "netcoreapp3.0" app

*Connects to SharePoint Online using the REST API

*For the certificate required to sign the JWT I have a CERTIFICATE file, PRIVATE KEY file and thumb file

*I'm trying to run operations such as 'list root site details' which are allowed by the app registration

*I already have the tenant URL, id, app registration client id and client secret


text:
Q: How do I add an internal style sheet (not inline) at run time in Angular? In my Angular 4 app, I have a page whose content is stored into a JSON (partly CSS definitions and partly HTML markup) at a certain URL on my server. So I've made a shell component to host the content in Angular.
For HTML, I had to use <div [innerHTML]="my_html"></div> in the template and this.my_html = this.sanitizer.bypassSecurityTrustHtml(my_html); in the script.
For CSS, I tried

*

*<style [innerHTML]="my_css"></style>

*<style>{{my_css}}</style>
with different combinations of sanitization but Angular
always compromise the <style> element. In particular:

*

*in this case it removes the element from the template but does'n append it to the head. The element just vanishes.

*in this case it removes the element from the template and appends it to the head like this <style>{%BLOCK%}</style>. In other words, the element is useless.

A: In the end, I had to use jQuery $('<style>').text(my_css).appendTo('head'); in the ngOnInit() handler, which works nicely, but doesn't feel... Angular.


text:
Q: Why can't my fragment shader read alpha information when I switch to an alpha-only (A8) pixelFormat? I'm creating an iOS app that uses OpenGL ES 2.0. I'm somewhat new to OpenGL, so this may be a trivial mistake.
I've created a simple shader to handle masking one texture with another, using the alpha channel. The mask texture initialized like so:

glGenTextures(1, &name);
    glBindTexture(GL_TEXTURE_2D, name);
glTexParameterf(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 768, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glGenFramebuffersOES(1, &buffer);
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, buffer);
glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, name, 0);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);

I then (later) draw some stuff to the mask texture, and link the mask texture to this fragment shader to apply it to another texture:

uniform sampler2D baseTextureSampler;
uniform sampler2D maskTextureSampler;
varying lowp vec4 colorVarying;
varying mediump vec2 textureCoordsVarying;
varying mediump vec2 positionVarying;

void main() {

      lowp vec4 texel = texture2D(baseTextureSampler, textureCoordsVarying);
      lowp vec4 maskTexel = texture2D(maskTextureSampler, positionVarying);

      gl_FragColor = texel*colorVarying*maskTexel.a;
}

This renders exactly how I want it to. However, to reduce the overhead in binding the mask texture's buffer (which seems substantial) I'm trying to use an 8-bit alpha-only pixel format for the mask texture. BUT, if I change the code from the RGBA setup:

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 768, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

...to alpha-only:

glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 1024, 768, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);

...the fragment shader fails to draw anything. Since I'm only using the alpha from the mask texture in the first place, it seems like it should continue to work. Any ideas why it doesn't?

A: The OpenGL ES 2.0 spec (or the GL_OES_framebuffer_object extension) doesn't define any renderable formats with only alpha bits, so they are NOT supported. You will have to use a RGBA format.


text:
Q: Convert an animated maya model to JSON for use with three js I have a maya model done in maya 2008. I need to be able to convert it a JSON format for use with three js. So far , I have tried
1) threeJsFileTranslator.py which is a maya plugin to export a model and is provided as a part of the threejs package.
2) MDD-OBJ-EXPORTER - with this , I was successfully able to import the animated model into blender but when I tried to export it to threejs , the js file didn't work.
I am breaking my head over this from the past 2 weeks. So please bear with me if this question is too silly but I do need help with successfully converting an animated maya model to json format.
ISSUES IMPORTING ANIMATED MODELS FROM MAYA TO BLENDER TO THREE JS
MAYA TO THREE JS WITH ANIMATION

A: It's not answered because at this point (8/2013) it's not simple :0
I have not tried it but it's been suggested that the Quake2 MD2 format offers a pathway for animated models into Three.  Theres an online MD2 > JSON converter (again, haven't tried it).  MD2 plugins for maya are hard to come by: you can build one using the source on github. Older versions of blender  (< 2.5) apparently also export md2.
The Three JSON format - at least the publicly available one on the web site - doesn't seem to have any animation support ATM.

A: You can export your model as FBX from Maya and then load it into http://Clara.io (the online 3D modeling, animation and rendering tool).  From there you can export it in the various ThreeJS JSON formats pretty easily.
http://Clara.io supports loading at least the following formats:

*

*.blend - Blender 3D

*.3ds - 3D Studio

*.dae - Collada

*.dxf - AutoCAD

*.fbx - FilmBox (Autodesk FBX)

*.irr - Irritch Scenes

*.irrmesh - Irritch Meshes

*.iv - Inventor

*.json - Three.JS Meshes

*.lwo - Lightwave Objects

*.lws - Lightwave Scenes

*.lxo - Modo Objects

*.q3d, .q3s, .md, .md2, .md3, .md4 - Quake/Doom Meshes

*.mtl/.obj - Wavefront Objects

*.ply - Polygon Type

*.pov - PovRAY

*.shp - Shape Files

*.stl - Stereolithography (3D Printing)

*.vismat, .vismatzip - VRay Vismat

*.xgl, .zgl, .wrl, .wrz - VRML X3D Scene Files

A: If you're starting with Maya you can try www.inka3d.com. You also need a newer Maya, you can get a trial at autodesk (and install it in a vm when you need to export)

A: You might be aware that THREE.js comes with an exporter for Maya, but it only works for static models.
I have created an updated version that also supports exporting rigged and animated models. It doesn't require any intermediate steps: it just outputs straight to a .JS file. We have a pull request to integrate the updated exporter with the THREE trunk, but if you want to get the new and improved exporter immediately you can get it from this repository: https://github.com/BlackTowerEntertainment/three.js/tree/maya_animation_exporter. The exporter files are in utils/exporters/maya.


text:
Q: Displaying a progress bar or wait message I want to display progress bar / wait message on any process in windows mobile. I tried displaying simple text "Please wait..." and wrote Application.DoEvents() but it is not displaying it nor progress bar.
Is there any way or other thing I need to follow to display progress bar in windows mobile device?

A: Use a Timer and place a static string in your project.
When you do not want text displayed, set the string value to null.
When a timer fires every 200 ms or so, update your message.
private static string message = null;

private void timer_Tick(object sender, EventArgs e) {
  if (String.IsNullOrEmpty(message)) {
    // clear your form values
  } else {
    // set your form values
  }
}

Of course, if you want a progress bar, you can do this too. Just make static int values for your progress bar and update your control when the timer ticks in the code snippet above.
This can be done with threads and event handlers, too, but a Timer (click to see code examples) is the simplest way.
UPDATE:
If you are doing this as inline code (as I understand from your comments), try the following:
private void Demo(int max) {
  label1.Text = String.Empty;
  progressBar1.Value = 0;
  progressBar1.Maximum = max;
  progressBar1.Refresh();
  do {
    progressBar1.Value++;
    progressBar1.Refresh();
    label1.Text = String.Format("{0}", progressBar1.Value);
    label1.Refresh();
  } while (progressBar1.Value < progressBar1.Maximum);
}

See if the code above does what you need.
NOTE: Oh, and get rid of Application.DoEvents(). It is an evil VB creation that encourages developers to have no idea what is going on.

A: The process you are running is blocking the UI thread?
Try to run your heavy processes on the thread pool.

A: Try this
    void StartLoadingPanel()
    {
        this.BeginInvoke((Action)delegate()
        {
            Cursor.Current = Cursors.WaitCursor;
            loadingPanelContainer.Visible = true;

        });
    }

where loadingPanelContainer contain the text to be displayed.


text:
Q: Extended Object.prototype function called upon page load I am trying to add a function to the Object prototype. For now, I'm simply doing this:
Object.prototype.consoleThis = function () {
    console.log(this);
};

Then embedding the code into the head. Then I try to use the new function:
var basicObject = {"name": "basicObject"};
basicObject.consoleThis();

However, in the console, a paragraph element from my HTML has been logged into the console, like so:
<p id="comment" class="ng-binding">
    This is a comment
</p>

Which is followed by the expected logging of the basicObject object. Why is this? How can I stop this from happening?
Edit: Found the source
In my JavaScript, the new function is called like so, including surrounding JavaScript:
$(document).ready(function(){
    $("#codeComments").css({height: $(".codeViewPre").height()});
    var basicObject = {
        "f": "abvc"
    };
    basicObject.consoleThis();
});

Removing the $("#codeComments").css({height: $(".codeViewPre").height()}); line removes the logged paragraph from the console. Unfortunately, I don't see why this is happening.


text:
Q: Unable to Airplay audio or video from MBP to Apple TV
*

*Apple TV Gen 4

*MBP early 2013 with Sierra (10.12.6)

I'm unable to make the MBP switch from internal speakers to Great Room, the name of my Apple TV. I click Great Room, and after a moment of silence it switches back to internal speakers. Both the MBP and the Apple TV are connected via Ethernet to a Time Capsule. They are both on the same subnet.
I can use my more recent MBP to send its audio to Great Room (using WiFi). And while connected this way, I can return to the ethernet-connected MBP, try to switch to Great Room, which knocks my newer MBP off, but still, after a moment, the old MBP switches back to internal speakers. I conclude, then, that the Apple TV and my new MBP are configured properly but the old MBP is not.
It used to work fine until the other day when I rearranged and reconnected the router and the MBP, but as far as I can tell all other connectivity is intact.
There are several system interfaces that offer "Great Room" as an option. Right-clicking the audio volume menu icon; clicking the AirPlay menu icon; the Sound System Preference panel; the Display System Preference panel. I don't know if they all accomplish the same thing, or if one is necessary for the other, or just what.
Suggestions?
UPDATE: I am able to send iTunes audio to the Apple TV. (iTunes has yet another interface for sound routing, in the iTunes toolbar). However, I'm still unable to use any of the other four interfaces to switch from internal speakers to AirPlay.


text:
Q: Is there a countable cover of $\mathbb{R}^2$ by balls $B(x_n, n^{-1/2})$? Is it possible to cover all of $\mathbb{R}^2$ using balls $\{ B(x_n,n^{-1/2})\}_{n=1}^\infty$ of decreasing radius $n^{-1/2}$? I know that if we chose e.g. radius $n^{-1}$ it could never work because $\sum \pi (n^{-1})^2 < \infty$. But in this case the balls cover an infinite amount of area, so it seems that it may be possible to construct.
Edit: It can definitely be done with balls of radius $n^{-1/2+\epsilon}$ for any $\epsilon > 0$.

A: Yes, this can be done.
Let $n\in\mathbb N$, consider $m\in\{1,\dots n\}$, and set $$a(n,m)=n^2+(m-1)n.$$ Note then that $$\sum_{k=a(n,m)+1}^{a(n,m+1)}\frac{1}{\sqrt{k}}\geq\sum_{k=a(n,m)+1}^{a(n,m+1)}\frac{1}{\sqrt{n^2+mn}}=\frac{n}{\sqrt{n^2+mn}}\geq\frac{n}{\sqrt{n^2+n^2}}=\frac{1}{\sqrt{2}}.$$ Therefore, if we consider adjacent squares, this shows that we can cover the strip $\left[0,\frac{1}{\sqrt{2}}\right]\times\left[0,\frac{1}{n\sqrt{2}}\right]$ by squares of the form $$S\left(x_{a(n,m)+1},\frac{1}{\sqrt{a(n,m)+1}}\right),S\left(x_{a(n,m)+2},\frac{1}{\sqrt{a(n,m)+2}}\right),\dots,$$$$S\left(x_{a(n,m+1)},\frac{1}{\sqrt{a(n,m+1)}}\right),$$ for any fixed $m\in\{1,\dots n\}$. If we now repeat this process for the strips $$\left[0,\frac{1}{\sqrt{2}}\right]\times\left[\frac{1}{n\sqrt{2}},\frac{2}{n\sqrt{2}}\right],\,\,\left[0,\frac{1}{\sqrt{2}}\right]\times\left[\frac{2}{n\sqrt{2}},\frac{3}{n\sqrt{2}}\right],\dots\left[0,\frac{1}{\sqrt{2}}\right]\times\left[\frac{n-1}{n\sqrt{2}},\frac{n}{n\sqrt{2}}\right],$$ this shows that we can always cover the square $\left[0,\frac{1}{\sqrt{2}}\right]^2$ by squares of the form $S(x_i,i^{-1/2})$, for $i\in\{n^2,n^2+1,\dots 2n^2\}$.
Repeating this process for all $n\in\mathbb N$ and moving the squares on $\mathbb R^2$, we actually get a covering of all of $\mathbb R^2$ in that way. We then get a covering by balls by circumscribing a ball outside each one of the squares.

A: With disks centered on an $n{+}1\times n{+}1$ grid, we can cover $[0,1]^2$ with $(n+1)^2$ disks of radius $\frac1{n\sqrt2}$.
Therefore, we can cover $[0,1]^2$ with $\left(\left\lceil\sqrt{\frac n2}\,\right\rceil+1\right)^2$ disks of radius $\frac1{\sqrt{n}}$.
For $n\ge294$, $\left(\left\lceil\sqrt{\frac n2}\,\right\rceil+1\right)^2\le\frac23n$. Thus, we have shown

For $n\ge294$, we can cover $[0,1]^2$ with at most $\frac23n$ disks of radius $\frac1{\sqrt{n}}$.

Enumerate the squares $\big\{[i,i+1]\times[j,j+1]:i,j\in\mathbb{Z}\big\}=\big\{S_k:k=1,2,3,\dots\big\}$
Cover $S_k$ with $196\cdot3^{k-1}$ disks with radii from $\frac1{\sqrt{98\cdot3^{k-1}+1}}$ to $\frac1{\sqrt{294\cdot3^{k-1}}}$.

A: It's true for any $r_n$ with $\sum r_n^2=\infty$.
Say $S(x,r)$ is the square with center $x$ and side length $r$.
It's enough to show that if $\sum r_n^2>4$ then there exist $x_n$ such
that $S(x_n,r_n)$ covers $[0,1]^2$.
For every $n$ there exists $j$ with $2^{-j}\le r_n<2^{-j+1}$. Replace $r_n$ with $2^{-j}$:
It's enough to show that if each $r_n$ is of the form $2^{-j}$ and $\sum r_n>1$ then there exist $x_n$ such that $S(x_n,r_n)$ cover the unit square.
A dyadic interval is an interval $[j2^{-n},(j+1)2^{-n}]$. A dyadic square is the product of two dyadic intervals with the same side length.
Start: If there exists $n$ with $r_n\ge1$ we're done. Suppose not. Divide $[0,1]^2$ into four dyadic squares of side length $1/2$. Call them $Q$'s.
If there are four $n$ such that $r_n=1/2$ we're done. Suppose not. Cover as many $Q$'s as possible with $S(x_n,r_n)$ with $r_n=1/2$.
Discard the $r_n$'s we just used. Note we used all the $r_n$ that equal $1/2$. Discard the $Q$'s we just covered. Divide each remaining $Q$ into four subsquares of side length $1/4$.
If there are enough $n$ with $r_n=1/4$ to cover all the reminaing $Q$'s we're done. Suppose not. Cover as many $Q$'s as possible with $S(x_n,r_n)$ where $r_n=1/4$. Note we've used all the $r_n$ that equal $1/4$. Discard those $r_n$, discard the $Q$'s we just covered. Divide each remaining $Q$ into four suubsquares of side length $1/8$.
Etc.
If at some point we're done then we're done. Suppose not. Then we've used up all the $r_n$ covering essentially disjoint subsquares of $[0,1]^2$; hence $\sum r_n^2\le 1$.


text:
Q: Unity won't build to Android (almost blank project test) So I have tried to test-publish my beginner very basic project core on Android from Unity and it failed every time I tried.. As a beginner I'm not quite sure why.
I tried to open and close Unity, publish to other platforms (OpenGL, Windows). I have downloaded Unity plug-in for Android (SDK included).
Code editor is Visual Studio (C#).
I will be glad for any help or comment :)
Logs here

A: I managed to solve it by myself.
I chose to "export" to my device (phone) and not to "build" or "build and run" options.. and that made the difference for some reason. Works fine now.


text:
Q: Please don't show "Delete" when a question can't actually be deleted Please don't show the "delete" option when a question cannot be deleted. I just tried removing a dated-issue that is no longer relevant (asked within a couple of hours) only to be alerted that I cannot delete it because it has too many answers/responses.
If I can't do it, don't let me think I can.

A: I approve of the current UI.
There are two ways to look at this:

*

*"Why can't I delete this when I can delete other things?" (if there is no delete button)

*"Why can't I delete this when the button is there?" (if there is a delete button)

Option 1. The delete button inexplicably disappears on some questions.
There are a variety of reasons why you might not be able to delete a question. I don't know them all, but there's definetly more than one. If the delete button simply disappears on those questions, we will have a frustrating user experience where you try to vote to delete, but you can't for the life of your figure out how. ("The button was here a minute ago... now where could it be?") Although this upholds the principle of not showing users options they can't do, it breaks consistency with no explanation.
Option 2. The button exists, but an error message pops up
With this option, you are led to believe that you can delete a question (and you get filled with hope) but then your hopes and dreams are rudely dashed by the red pop-up of death. In this case, you are frustrated because you can't delete (exactly as above) but you know exactly why you can't delete. So this provides better usability.
As for jinguy's suggestion that we add strikethrough and a tooltip. This incurs a performance penalty (very very minor) at pageload because SO needs to provide additional logic to determine if deletion is possible, AND you still need the pop-up because the situation might change as your page gets stale. There are also relatively few 'delete-clicks' compared to page views, so to me it makes more sense to determine a question's deletability only when it comes up, rather than all the time.

A: They could just strike out the 'delete' option.
Like this:

link | edit | delete | flag

I would also add a tooltip explaining why it is struck out.

A: If you can't outright delete your question that has gotten too many votes/answers, you should at least be able to place a delete vote.

A: See Joel Spolsky's take on this:
Don't hide or disable menu items
Similar to what devinb answered, it's basically:
'Show the option and then tell them why they can't do it' is better than 'hide/disable the option and give no explanation why'.

A: This would only generate like 7 questions of people whining because they can't see the delete link... how is it possible I can't delete my answer?
Having the link, and the message that you cannot delete it, is simpler and avoids confusion.


text:
Q: airflow saving previous task from the dag Good day,
I've faced with a problem.
I create a dag, which teakes data from airflow.models.Variable. Then i triggered task in webserver UI. All worked fine. After that i changed my variable. When i tried to access log of task that was triggered before (from UI), i got the message:
Task [my_crazy_dag.supertask] doesn't seem to exist at the moment
This task state is removed.
I would like to ask, if there a choice to save task, that it was available after i change the dag, to see it logs or run it again?


text:
Q: Routes not looking right. Missing id and index In a Rails 4.1 app I created a set of routes, to avoid severe nesting in this type of relationship:
User has_and_belongs_to_many :blogs, join_table: 'blogs_users'
User has_many :posts, through: :blogs

Blogs has_and_belongs_to_many :users, join_table: 'blogs_users'
Blogs has_many :posts

Posts has_and_belongs_to_many :tags, join_table: 'tags_posts'
Posts has_and_belongs_to_many :categories, join_table: 'categories_posts'
Posts has_many :comments
Posts belongs_to :user
Posts belongs_to :blogs

Comments belongs_to :posts

It's rather simple, how ever the rotes look as such (I was advised this was easier):
  namespace :api do
    namespace :v1 do

      resource :users, only: [:index, :show] do
        resource :blogs, only: [:index, :show]
      end

      resource :blogs, only: [:index, :show] do
        resource :posts, only: [:index, :show]
      end

      resource :posts, only: [:index, :show] do
        resource :tags
        resource :comments
        resource :categories
      end

    end
  end

The rake routes command spits out:
             Prefix Verb   URI Pattern                             Controller#Action
  api_v1_users_blogs GET    /api/v1/users/blogs(.:format)           api/v1/blogs#show
        api_v1_users GET    /api/v1/users(.:format)                 api/v1/users#show
  api_v1_blogs_posts GET    /api/v1/blogs/posts(.:format)           api/v1/posts#show
        api_v1_blogs GET    /api/v1/blogs(.:format)                 api/v1/blogs#show
   api_v1_posts_tags POST   /api/v1/posts/tags(.:format)            api/v1/tags#create

# This is just a few to keep the post clean and manageable. I can gist the whole output if you require it.

As you can see I am missing id and index I am sure my mistake is something rudimentary How ever I am lost as to what ...
I am also concerned about how the user accessing the api will create posts as I am only doing an API Key Authentication. I mean I suppose I could create a "current_user" based off that use that to pass in the user id to the posts, when one is created.
My questions are:

*

*Where is my id and index?

*Is my level of nesting (in the routes) for the types of relationships shown appropriate?

A: You should replace resource with resources.
The plural has much meaning: there can be many, hence the need for ids, the existence of index etc...
See documentation


text:
Q: How can I keep the datatable state when go to another page? I have a datatables on my page. I am for example on page 5 in my pagination and then click on a row and this links me to another page. When I click on the back button of the browser I will be directed back to the previous page and in the datatable page 5 is selected.
I try to imitate this browser back button with jquery:
 <button onclick="goBack()">Go Back</button>

<script>
function goBack() {
  window.history.back();
}
</script>

But now the datatable is refreshed and I am back at page 1. But I need the datatable to keep the page 5.

A: You can use stateSave option here. As mentioned in the docs:

When enabled aDataTables will store state information such as pagination position, display length, filtering and sorting. When the end user reloads the page the table's state will be altered to match what they had previously set up.

To enable state saving use:
$('#example').dataTable( {
  stateSave: true
});


text:
Q: How to make Designer in Visual Studio generate component using parameterize constructor How to make Visual Studio generate code using constructor with parameter?
For example:
When adding a ContextMenuStrip, this line of code is generated InitializeComponent() in MyForm.designer.cs
this.MyMenuStrip= new System.Windows.Forms.ContextMenuStrip(this.components);

Using dotPeek to reflect ContextMenuStrip doesn't give me any helpful way how I can do it.
I want to make a custom control that when it's dropped to any System.Windows.Forms.Control, the designer will call parameter constructor instead of parameter-less one.

A: From the MSDN page about the design-time features of Windows Forms, it appears that a component with a constructor that takes an IContainer as a parameter is a special case:

A component can let the designer know that it would like to be
  notified when its container goes away by implementing a public
  constructor that takes a single argument of type IContainer, as shown
  in this snippet:

class ClockComponent : Component {
    public ClockComponent(IContainer container) {
        // Add object to container's list so that
        // we get notified when the container goes away container.Add(this);
    }
    // ...
}

Notice that the constructor uses the container to add itself as a
  container component. In the presence of this constructor, the designer
  will generate code that uses this constructor, passing it a container
  for the component to add itself to.

Also, see Customizing Code Generation in the .NET Framework Visual Designers on MSDN.


text:
Q: Mock httpBackend request globally In AngularJs unittest (Jasmine/Karma), we need to put httpBackend.whenGET('/.*/').respond('')
and some other default responds in the global beforeEach().
However, we get Error: Injector already created, can not register a module! because we will also need to mock other services / import other modules in the actual tests.
Is there any way to do this?


text:
Q: Show/hide input in html form I'm trying to get the second password input only to show after the user starts typing into the first input. Also, is there are way to either "require" them both or none at all?
<form name="signUpForm">
    ...

    <input ng-modal="password" type="password" placeholder="password">
    <input ng-show="password.$dirty" class="animate-show animate-hide" type="password" placeholder="password (again)">
</form>

A: password has no property like $dirty but form controller has that one. So first of set name of input then you can access form controller with it
<form name="signUpForm">
...

    <input name="passwordNameAttr" ng-modal="password" type="password" placeholder="password">
    <input ng-show="signUpForm.passwordNameAttr.$dirty" class="animate-show animate-hide" type="password" placeholder="password (again)">
</form>

for dynamic require you can use ng-required. Just put an expresion on it and depends on condition your fields will be required or not...

A: another example using ng-show $valid required for input fields ..
html:
<form name="signUpForm">
   <input name="firstPassword" ng-model="first.password" type="password" placeholder="password" required>
   <input name="secondPassword" ng-show="signUpForm.firstPassword.$valid" ng-model="second.password" type="password" placeholder="password (again)" required>
</form>

working fiddle here: https://jsfiddle.net/vj5evgyw/2/


text:
Q: in search of a Formula for ratio where one element is 0 Very nice to meet you all. I am searching to find the value x for the given image. its a ratio that looks like this:
0: 1 = 350 : Y

but this leads if we solve for Y:
0 * Y = 350 * 1

Y = 350/0

which is undefined.

How can i get the Y value in such a case for this ratio ?
UPDATE: THE 0 in the image represents an offset start. so i am giving an offset from 0 to 1 (or if you like 0% to 100%).   the orange numbers is my new offset i have created, it runs from 350 to Y.
UPDATE2:

There is this green box that i can drag up and down...
when this green box is collapsed as it is now in the below image near                                     the bottom, the dragOffset is defined as 0. so to be clear, collapsed box has offset of 0 ALWAYS.
as the box gets dragged towards the top, the offset keeps increasing from 0 until finally it hits the top which is a max offset of 1. So to be clear, the dragging offset from collapsed to expanded is numbers between [0,1].
Here is the image so you can see the transition. how the dragOffset is being delivered to me:

I have the ability to make the greenbox 60% of the total height like this:

but when it reaches 60% the system is giving me a value such as 0.6 for the top, But at this point i can consider 60% as the FULL HEIGHT.  So the system thinks the full height is 1 but i want the full height to be at 0.6 (or 60%) mark
**so to be clear, i am searching for a way to SCALE the dragOffsets values called Y1,Y2,Y3,Y4,Yz  such that dragging from 0 to 0.6 would be the same as dragging from 0 to 1 in the system.  Hope it's clear now .

A: I think you want to map the interval $[0,1]$ to the interval $[350,Y]$.
The scale factor of your mapping is given by $\frac{Y-350}{1-0}=\frac{Y-350}{1}$, but you can't work out $Y$ without some more information about your new interval.


text:
Q: Litho, ViewPager and Tabs. How to load several Tab's layouts using Litho? I'm trying to implement a ViewPager with Tabs just like this:

The fragment's layouts are rendered with Facebook's Litho, but the problem here is that only the first item, in this case 'Look', is loaded.
See the code:
MainActivity:
public class MainActivity extends AppCompatActivity {

private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        private final Fragment[] mFragments = new Fragment[]{
                new Look(),
                new Chat(),
                new Flirt(),
                new Friends(),
                new Me(),
        };

        @Override
        public Fragment getItem(int position) {
            return mFragments[position];
        }

        @Override
        public int getCount() {
            return mFragments.length;
        }

    };
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mPagerAdapter);
    mViewPager.setOffscreenPageLimit(3);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setTabTextColors(Color.parseColor("#616161"), Color.parseColor("#ffffff"));
    tabLayout.setupWithViewPager(mViewPager);
    tabLayout.getTabAt(0).setText("LOOK");
    tabLayout.getTabAt(1).setText("CHAT");
    tabLayout.getTabAt(2).setText("FLIRT");
    tabLayout.getTabAt(3).setText("ADD");
    tabLayout.getTabAt(4).setText("ME");
    findViewById(R.id.options).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(MainActivity.this, Options.class);
            startActivity(i);
        }
    });
}
}

And, for simplicity's sake, let's assume that all the fragments (Look, Chat, ...) has the same code inside its onCreateView method:
public class Flirt extends Fragment {

public Flirt() {
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final ComponentContext contex = new ComponentContext(getContext());
    final Component component = Text.create(contex)
            .text("Hello World")
            .textSizeDip(50)
            .textColor(Color.GRAY)
            .build();
    return LithoView.create(contex, component);
}
}

It is expected that the five fragments' view be loaded when MainActivity is created, but only the first one, whichever it be, is displayed. What am I doing wrong? How could I get it?
EDIT:
If I change mViewPager.setOffscreenPageLimit(4) to (0), I get that all views get loaded, but one by one, and they are loaded everytime they're on focus, which is not desired. What I'm trying to get is that the five Pages get loaded at time, and only once.

A: Call this
public static boolean incrementalMountUsesLocalVisibleBounds = false;

before populating views in viewPager. This should do the trick.
How it works
in class IncrementalMountHelper we have the following piece of code:
// ViewPager does not give its child views any callbacks when it moves content onto the screen,
// so we need to attach a listener to give us the information that we require.
ViewParent viewParent = lithoView.getParent();
while (viewParent != null) {
  if (ComponentsConfiguration.incrementalMountUsesLocalVisibleBounds
      && viewParent instanceof ViewPager) {
    final ViewPager viewPager = (ViewPager) viewParent;
    final IncrementalMountHelper.ViewPagerListener viewPagerListener =
        new ViewPagerListener(mComponentTree, viewPager);
    ViewCompat.postOnAnimation(
        viewPager,
        new Runnable() {
          @Override
          public void run() {
            viewPager.addOnPageChangeListener(viewPagerListener);
          }
        });
    mViewPagerListeners.add(viewPagerListener);
  }

  if (viewParent instanceof LithoView && ((LithoView) viewParent).doesOwnIncrementalMount()) {
    lithoView.setDoesOwnIncrementalMount(true);
  }

  viewParent = viewParent.getParent();
}

viewPagerListener here is responsible for calling componentTree.incrementalMountComponent();
This is not getting called because ComponentsConfiguration.incrementalMountUsesLocalVisibleBounds is false by default and you have to set it true.
I yet do not know yet what all other effects will be when you set it true, but, setting it true makes your ViewPager work.


text:
Q: App Suddenly Crashing Roku Sorry if this isn't terribly descriptive, but lately my app has been crashing overnight. I usually leave it running during the day and it's just fine but if I leave it on all night and come back the next morning to check on it I find the Roku device at the home screen. The debugger doesn't offer up much information other than the following but I'm not sure how to make sense of it. I look at the lines (?) mentioned and don't see anything off in the code. Any ideas? I'm testing on the 3500X - Roku Stick software version 7.2.0 build 4100-09. Much appreciation.
BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(185)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(186)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(187)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(188)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(189)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(190)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(191)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(192)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(193)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(194)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(195)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(196)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(197)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(198)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(199)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(200)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(201)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(202)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(203)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(204)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(205)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(206)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(207)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(208)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(209)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(210)

BrightScript Debugger> Syntax Error. (compile error &h02) in $LIVECOMPILE(211)

A: The app is not "crashing suddenly". Roku kills apps that it judges inactive after a few (two?) hours. Why are you leaving app overnight, what is it supposed to do?
Never mind the console, that's confusing you - what you see is un-related, it's left-over from interactive session you had before, the error messages are from what you typed back then. Notice how mis-aligned are the diagnostics, on the same line with the prompt.

A: My guess would be a memory leak somewhere. That's pretty easy to do these days. Check if all your tasks are terminating.


text:
Q: How do you ask to know whether "reaching" a doctor's service was easily accessible? I am trying to write down a questionnaire for people (patients) on vacation, who were served by a doctor/nurse on the scene (in this example, at the hotel). I would like to ask whether the service provided by doctor/nurse was easily accessible. But it sounds a little erratic to ask as "Were you able to reach the doctor/nurse at the hotel easily?"
Any alternative which would sound more formal?

A: Your sentence looks fine. It might be a tiny bit clearer if you say, "... able to contact". Also, it's better to use "...doctor or nurse..." rather than using the / –
gotube
♦


text:
Q: LDAP user filter error at cn=%v In LDAP settings of my Gitlab, I used
user_filter : '(memberof=CN=%v,OU=groupname,DC=company,DC=local)
But it gives me an error:

malformed formed format string - %v

What should be the format that I can give the filter for a username in CN

A: As mentioned in the GitLAb LDAP man page, the syntax should follow RFC 4515 only:
  # Filter LDAP users
  #
  #   Format: RFC 4515 https://tools.ietf.org/search/rfc4515
  #   Ex. (employeeType=developer)
  #
  #   Note: GitLab does not support omniauth-ldap's custom filter syntax.
  #
  #   Example for getting only specific users:
  #   '(&(objectclass=user)(|(samaccountname=momo)(samaccountname=toto)))'
  #
  user_filter: ''

In your case, the CN should be the name of a group, not a placeholder like %v.
See as an example gitlab-ce issue 34150
You can test it with:

Try running this set of queries through the Rails console without the filter set, and then with the filter set.
  Start the Rails console with sudo gitlab-rails console.

adapter = Gitlab::LDAP::Adapter.new('ldapmain')
person = Gitlab::LDAP::Person.find_by_uid('<username>', adapter)
person.memberof


text:
Q: Should I use a platform or a custom-build solution for my business? I have an idea that involves social networking (note: it's not just a regular social networking site), and I'm wondering if I should use a social networking platform such as SocialEngine, Elgg, or some other, or get a developer and create a custom-build solution to meet my needs?

A: Make a list of your requirements and if an existing platform meets your needs (even if it needs some tailoring) then go for it. It'll get you started quickly and allow you to focus on building the online community. You can always switch over to a custom solution if the site takes off as you'll then have the money to pay for its development. Good luck in any case!


text:
Q: Cant set values of custom object I have a custom data object which I am using to store information passed from a JSON request, however when i try to set the values everything is still null.
Im still very new to iOS development and have more of a Java background so im sure I am just missing something or doing something the wrong way.
My Class:
BuildingLocation.h
#import <Foundation/Foundation.h>

@interface BuildingLocation : NSObject {
    NSString *_name;
    NSString *_description;
    NSString *_URL;
    float  _Long;
    float  _Lat;
    NSString *_Town;
    NSString *_Type;
    NSString *_Premium;
}

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *description;
@property (nonatomic, copy) NSString *URL;
@property (nonatomic) float Long;
@property (nonatomic) float Lat;
@property (nonatomic, copy) NSString *Town;
@property (nonatomic, copy) NSString *Type;
@property (nonatomic, copy) NSString *Premium;

- (id)init:(NSString *)name description:(NSString *)description URL:(NSString *)URL Long:(float)Long Lat:(float)Lat Town:(NSString *)Town Type:(NSString *)Type Premium:(NSString *)Premium;

@end

BuildingLocation.m
#import "BuildingLocation.h"

@implementation BuildingLocation

@synthesize name = _name;
@synthesize description = _description;
@synthesize URL = _URL;
@synthesize Long = _Long;
@synthesize Lat =_Lat;
@synthesize Town = _Town;
@synthesize Type = _Type;
@synthesize Premium = _Premium;

-(id)init:(NSString *)name description:(NSString *)description URL:(NSString *)URL Long:(float)Long Lat:(float)Lat Town:(NSString *)Town Type:(NSString *)Type Premium:(NSString *)Premium {
    if ((self = [super init])) {
        self.name = name;
        self.description = description;
        self.URL = URL;
        self.Long = Long;
        self.Lat = Lat;
        self.Town = Town;
        self.Type = Type;
        self.Premium = Premium;
    }
    return self;
}

@end

How I am trying to set the values in my code:
BuildingLocation *locationObject;
                locationObject.name = [location objectForKey:@"Name"];
                locationObject.description = [location objectForKey:@"Decription"];
                locationObject.URL = [location objectForKey:@"URL"];
                locationObject.Long = [[location objectForKey:@"Longitude"] floatValue];
                locationObject.Lat = [[location objectForKey:@"Lat"] floatValue];
                locationObject.Town = [location objectForKey:@"Town"];
                locationObject.Type = [location objectForKey:@"Type"];
                locationObject.Premium = [location objectForKey:@"Premium"];

                NSLog(@"Name before: %@", locationObject.name);

The NSLog gives the value of locationObject.name as (null)

A: The locationObject object is never allocated and initialized.
Try this:
BuildingLocation *locationObject = [[BuildingLocation alloc] init]; // allocate and initialize this object.
//  ...
NSLog(@"Name before: %@", locationObject.name);


text:
Q: What mechanisms does Scala have for generics and wildcards compared to Java? I am frequently pushing the limits of Java's type system through my use of Guice, TypeLiteral, generics, and wildcards.  I often run into situations where I need to perform unchecked casts, which pretty much ruins type safety--in other words, "Generics Hell."
Here's a simplified example of some of my problematic Java code.
class SquareDrawer implements ShapeDrawer<Row<Square>> {}
class Client {
   Key<SquareDrawer> SQUARE_DRAWER_KEY =
      Key.get(SquareDrawer.class, randomAnnotation());
   void bindShapeDrawer(
      Key<? extends ShapeDrawer<Row<? extends Shape>>> shapeDrawer) {}

   Client() {
      // Note Unchecked cast required below
      bindShapeDrawer(
         (Key<? extends ShapeDrawer<Row<? extends Shape>>>) SQUARE_DRAWER_KEY);
   }
}

I've been learning Scala and have been under the impression (or illusion) that it has better support for generics than Java.  Could the above code be written in Scala to avoid the unchecked casts?
Is there still a need for Guice's TypeLiteral in Scala?

A: There are a couple of things Scala offers.

*

*Higher kinded types (I hope I use the term correctly) allow you to define things like 'any type having another type as a type parameter' afaik there is no way to express that in java

*Co and Contravariant type parameters. In java you can make parameters one or the other by using wildcards in every place where they are used. In Scala you just declare them as such.

*Type witnesses (Again: Is that the correct term?) are implicit functions that demonstrate some property of type arguments, thereby defining constraints on the type. If an implicit conversion matching the declaration of the witness exists, the call will compile the condition holds.

*Path dependent types. You can have types that are elements of instances, so each instance has its own type. Again you can't do this in java afaik.

A: Scala has a form of reified types called Manifests.  They let you do things that would be quite clunky in Java due to type erasure.  Read all about them here: http://www.scala-blogs.org/2008/10/manifests-reified-types.html

A: The following (hopefully) equivalent Scala code compiles without errors. Maybe I need to state that it contains no dynamic casts. Note that I had to make Key covariant in its type argument, because SquareDrawer is only a subtype of ShapeDrawer[Row[Square]].
trait ShapeDrawer[A]
trait Row[A]
trait Shape
trait Square extends Shape
trait Key[+A]

//your code starts here
trait SquareDrawer extends ShapeDrawer[Row[Square]]

class Client{
  val SDK = new Key[SquareDrawer]{}

  bindShapeDrawer(SDK)

  def bindShapeDrawer[SD[A] <: ShapeDrawer[A],S <: Shape](shapeDrawer: Key[SD[Row[S]]]) {}
}


text:
Q: Yahoo manager error using Docker Ask timed out on [ActorSelection[Anchor(akka://kafka-manager-system/), In order to replicate this issue run docker run zookeeper then docker-compose up on the below yaml file.
I am using zookeeper latest image, wurstmeister/kafka:0.9.0.0-1 and sheepkiller/kafka-manager:latest. I ran docker-compose up and finallzy got it working but now I get the following error:

I have searched git and stack over flow with no avail. Everything looks fine until I save a cluster. In the Kafka logs I get:

[warn] o.a.z.ClientCnxn - Session 0x0 for server null, unexpected
  error, closing socket connection and attempting reconnect
  kafka-manager_1  | java.net.ConnectException: Connection refused
  kafka-manager_1  |      at
  sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
  ~[na:1.8.0_151] kafka-manager_1  |      at
  sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
  ~[na:1.8.0_151] kafka-manager_1  |      at
  org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:361)
  ~[org.apache.zookeeper.zookeeper-3.4.6.jar:3.4.6-1569965]
  kafka-manager_1  |      at
  org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1081)
  ~[org.apache.zookeeper.zookeeper-3.4.6.jar:3.4.6-1569965]

I also seen this:
INFO Got user-level KeeperException when processing sessionid:0x160fb22e9f50000 type:create cxid:0x2a zxid:0x3e txntype:-1 reqpath:n/a Error Path:/brokers/ids Error:KeeperErrorCode = NodeExists for /brokers/ids (org.apache.zookeeper.server.PrepRequestProcessor)

This can be replicated by starting zookeeper and taking the below yaml file config and running docker-compose up. I have been at this on an off for a week and am not sure why it is not working.
Yaml file:
zookeeper:
  image: confluent/zookeeper
  ports:
    - "2181:2181"

kafka:
  image: wurstmeister/kafka:0.9.0.0-1
  ports:
    - "9092:9092"
  links:
    - zookeeper:zk
  environment:
    - KAFKA_ADVERTISED_HOST_NAME
    - KAFKA_ADVERTISED_PORT=9092
    - KAFKA_DELETE_TOPIC_ENABLE=true
    - KAFKA_LOG_RETENTION_HOURS=1
    - KAFKA_MESSAGE_MAX_BYTES=10000000
    - KAFKA_REPLICA_FETCH_MAX_BYTES=10000000
    - KAFKA_GROUP_MAX_SESSION_TIMEOUT_MS=60000
    - KAFKA_NUM_PARTITIONS=2
    - KAFKA_DELETE_RETENTION_MS=1000

kafka-manager:
  image: sheepkiller/kafka-manager:latest
  ports:
    - "9000:9000"
  links:
    - zookeeper
    - kafka
  environment:
    ZK_HOSTS: zookeeper:2181
    APPLICATION_SECRET: letmein
    KM_ARGS: -Djava.net.preferIPv4Stack=true

Cluster:

More cluster settings:

Then I get:

and then:

I run docker run -it -d zookeeper, then docker-compose up on that yml file. It starts up but crashes when I create a cluster.
Docker config:

Containers: 53  Running: 2  Paused: 0  Stopped: 51 Images: 13 Server
  Version: 17.12.0-ce Storage Driver: overlay2  Backing Filesystem:
  extfs  Supports d_type: true  Native Overlay Diff: true Logging
  Driver: json-file Cgroup Driver: cgroupfs Plugins:  Volume: local
  Network: bridge host ipvlan macvlan null overlay  Log: awslogs fluentd
  gcplogs gelf journald json-file logentries splunk syslog Swarm:
  inactive Runtimes: runc Default Runtime: runc Init Binary: docker-init
  containerd version: 89623f28b87a6004d4b785663257362d1658a729 runc
  version: b2567b37d7b75eb4cf325b77297b140ea686ce8f init version:
  949e6fa Security Options:  seccomp   Profile: default Kernel Version:
  4.9.60-linuxkit-aufs Operating System: Docker for Windows OSType: linux Architecture: x86_64 CPUs: 2 Total Memory: 1.934GiB Name:
  linuxkit-00155dc95329 ID:
  YJE3:ZJKS:BJCF:TY4W:BU2Y:U7ZO:5P4B:PYMQ:SLVH:KTXD:V2OS:XKCD Docker
  Root Dir: /var/lib/docker Debug Mode (client): false Debug Mode
  (server): true  File Descriptors: 19  Goroutines: 36  System Time:
  2018-01-23T09:47:18.7698506Z  EventsListeners: 1 Registry:
  https://index.docker.io/v1/ Labels: Experimental: true Insecure
  Registries:
   127.0.0.0/8 Live Restore Enabled: false

A: Tune the below mentioned configuration and your timeout error will be fixed.

*

*kafka-manager.broker-view-thread-pool-size=< 3 * number_of_brokers>

*kafka-manager.broker-view-max-queue-size=< 3 * total # of partitions across all topics>

*kafka-manager.broker-view-update-seconds=< kafka-manager.broker-view-max-queue-size / (10 * number_of_brokers) >

*kafka-manager.offset-cache-thread-pool-size=< default is # of processors>

*kafka-manager.offset-cache-max-queue-size=< default is 1000>

*kafka-manager.kafka-admin-client-thread-pool-size=< default is # of processors>

*kafka-manager.kafka-admin-client-max-queue-size=< default is 1000>


text:
Q: How to empty data in rows except for certain row SQL command How would I empty all rows except specific ones that I want to keep in one SQL command.
I do NOT want to delete the rows. I only wan to empty all data in them.
The rows I want to keep are the ones with the following ID
23
2611
1817
322
2359
156
167
1664
901
576

All the other rows I want to empty in one SQL command.
My row ID go from 1-3000

A: If you want to set the columns to NULL then something like this:
update t
    set col1 = null,
        col2 = null,
        . . .
    where id not in (23, 2611, 1817, 322, 2359, 156, 167, 1664, 901, 576);

You have to list each column individually.

A: You might want to try something like this :
UPDATE yourTable
SET col1=null, col2=null ...
WHERE ID NOT IN (23 2611 1817 322 2359 156 167 1664 901 576)

But it will probably not work if you have NOT NULL constraints or FOREIGN KEYconstraints.


text:
Q: How to convert EDAMTimestamp to NSDate with Evernote Cloud SDK for iOS I tried Evernote Cloud SDK 2.0.6 for iOS. When I fetch the EDAMSyncChunk and the note data from Evernote service, created (and also updated and deleted) property as NSNumber type in EDAMNote instance has following values for example:

*

*1350039844000

*765020000

The former seems to be the UNIX time with milliseconds, so I can convert the value to NSDate object, getting "2012-10-12 20:04:04" (JST).
The latter, however, does not seem to be the correct UNIX time because the value cannot be converted to the acceptable time regardless of removing the last three digits:

*

*765020000 ---> "1994-03-30 18:33:20" (JST)

*765020    ---> "1970-01-10 05:30:20" (JST)

How can I get the correct time from the latter case? (I doubt that "765020000" results from something like "xxxx765020000" in 32bit environment, though I cannot check the environment now... sorry)
Please help.
Thanks.

A: on my project, I got it working like this (in swift):
let date = NSDate(EDAMTimestamp: note.created.longLongValue)


text:
Q: There is no option to Choose "Other" as mentioned under YouTube API Node.js Quickstart In the Node.js Quickstart,

Step 1, (e) says "Select the application type Other".

However there is no such entry under the options provided for "Create OAuth client ID" in the API & Services page of Google APIs. Which one to opt in that case for Node JS applications?

A: Google developer console changes faster then they change the tutorials.
select Oauth client id

Then select desktop app

The results will be the same as creating the old other type app
This will give you a client which id designed to run as a native application on your machine and not hosted on a web server.   Which is what the sample you are following is designed to show you how to do.


text:
Q: Integration by parts $\int xe^{x^2} dx$.
Find with integration by parts $$\int xe^{x^2} dx$$.

$$\int xe^{x^2} dx$$
Let $u(x) = x \ \ \ v^{'}(x) = e^{x^2}$
Now I can write the integral as $$\int xe^{x^2} dx = x \int e^{x^2} dx - \int\left(\int e^{x^2} dx \right) dx$$
Even after trying everything I am unable to solve $v^{'}(x) = e^{x^2}$ for $v(x)$.

I can do this question substitution $u = x^2$ but I told use integration by parts to do this question. What should I do ?

A: If you absolutely want to write the integration in the form of an integration by part use:
$$
v'=xe^{x^2} \quad \rightarrow \quad v=\frac{1}{2}e^{x^2}
$$
and
$$
u=1 \quad \rightarrow \quad u'=0
$$

A: Take $u=e^{x^2}$ then $du=2xe^{x^2}$ and $v=\frac{x^2}{2}$ so
$$\int xe^{x^2}dx=\frac{x^2e^{x^2}}{2}-\int x^3e^{x^2}dx$$
Take $u=e^{x^2}$ and $dv=x^3$ then
$$\int x^3e^{x^2}dx=\frac{x^4}{4}e^{x^2}-\frac{1}{2}\int x^5e^{x^2}dx$$
Similary
$$\int x^5e^{x^2}dx=\frac{x^6}{6}e^{x^2}-\frac{1}{3}\int x^7e^{x^2}dx$$
In general $$\int x^{2n+1}e^{x^2}dx=\frac{x^{2n+2}}{2n+2}e^{x^2}-\frac{1}{n+1}\int x^{2n+3}e^{x^2}dx$$
From that we can take a few terms and notice that $$\int xe^{x^2}dx=\frac{x^2}{2}e^{x^2}-\frac{x^4}{4}e^{x^2}+\frac{x^6}{12}e^{x^2}-\frac{x^8}{48}e^{x^2}+\frac{x^{10}}{240}e^{x^2}+\cdots\\\int xe^{x^2}dx=\frac{e^{x^2}}{2}\sum_{k=1}^{\infty}\frac{(-1)^{k+1}x^{2k}}{k!}$$Now with few adjustments you'll get$$e^{-x^2}=\sum_{k=0}^\infty\frac{(-1)^kx^{2k}}{k!}=1+\sum_{k=1}^\infty\frac{(-1)^kx^{2k}}{k!}=1-\sum_{k=1}^\infty\frac{(-1)^{k+1}x^{2k}}{k!}\\\int xe^{x^2}dx=\frac{e^{x^2}}{2}\left(1-e^{-x^2}\right)=\frac{e^{x^2}}{2}+C$$

A: Alternatively, with the change of variable
$$
u=e^{x^2}, \qquad du =2xe^{x^2},
$$ one has
$$
\int xe^{x^2}dx=\frac12\int du
$$ which is easy to evaluate.

A: Take $e^{x^2}$ as the first function and apply rule of by parts, you get
$\int e^{x^2}x dx =e^{x^2}\frac{x^2}{2}-\int x^3.e^{x^2}dx$.....$(A)$
Now $\int x^3e^{x^2}dx=\frac{1}{2}\int t.e^t dt$ where $x^2=t$ and $2xdx=dt$ (Assuming that your teacher didn't mean to completely reject substitution).
On integration, it gives  $\frac{1}{2}e^t(t-1)$ or $\frac{1}{2}e^{x^2}(x^2-1)$.
Substitute it in $(A)$ to get the answer.


text:
Q: Powershell not returning value if empty Using the following code
import-module activedirectory

$users = @("user1", "user2", "user3")
$results = @()

foreach($user in $users) {
    $properties = @{
        Name = (get-aduser -Identity $user).Name
        Manager = get-aduser (get-aduser -Identity $user -Properties manager).manager -properties displayName
        DirectReports = get-aduser (Get-ADUser -Identity $user -Properties directreports).directreports -properties displayName
    }
    $results += New-Object psobject -Property $properties | select Name, Manager, DirectReports
}

$results

Only user3 actually has direct reports, so it is printing his line 3 times.  But it doesn't print a line for user1 and user2.  How can I get it to print their lines, even if the DirectReports column is empty for them?

A: You have problem with the Manager and DirectReports lines, the Get-ADUser cmdlet not executed correctly, you use it three times, one for each property,
also, get-aduser (Get-ADUser...).manager or directreports may not be valid use for the identity parameter, as it use the manager as the identity, if you don't have aduser with the manager or directreports identity it will fail.
So I Suggest you to get the ADUser once, with the required properties and then use it like this,
Also the $ADUser = $null will force the reset of the variable so you will not get repeated lines for the same user.
$users = @("user1", "user2", "user3")
$results = @()

foreach($user in $users) {
    $ADUser = $null
    $ADUser = Get-ADUser $user -Properties Manager,DirectReports
    if ($ADUser) {
    $Row = "" | Select Name,Manager,DirectReports
    $Row.Name = $ADUser.Name
    $Row.Manager = $ADUser.Manager
    $Row.DirectReports = $ADUser.DirectReports
    $results += $Row
    }
}

$results


text:
Q: Change kotlin val in debugger How change val property (not method variable) in debugger?
Yes, I know that val is final analog
Breakpoint here:

Set value disabled in context menu:

Evaluate not work:

A: In the debugger select the value use the context menue on right click to select "set Value..." (default shortcut F2). The value of the variable should now be displayed in a text field. Enter the desired value and press enter to change the value. You only need to enter the value not an assignment (e.g. x = "test" is wrong, just enter the value "test"). The changed value is now applied to the field.
In the debugger it IS also possible to change values on immutable val defined values in Kotlin as it is also possible to change the value on final defined variables in Java.

A: I was able to modify val value on the fly using "evaluate and log".
Check full answer

A: You can do it using reflection.
Just open the Evaluate Expression menu, then type:
val field = Main::class.java.getDeclaredField("b")
field.isAccessible = true
field.set(b, true)


text:
Q: Better performance for kernel on ant colony optimisation I'm trying to get a better performance on my ant colony optimisation problem. In order to do so, I'm using openCL to run the update pheromones part in parallel. I have just started learning openCL and this is the kernel code I have developed. Although it runs faster than the sequential version, I still think I can achieve more performance with it, but I'm not finding other things I can do. Is there a way to improve this code even more ?
PS: I have tested this code only on the CPU, since the computer I am working on doesn't have a GPU.
#pragma OPENCL EXTENSION cl_khr_fp64 : enable

int calculateLengthOfTrail(__global int*, const int, __global int*, const int );
int edgeInTrail(const int ,const int , __global int* , const int , const int );
int indexOfCity(__global int*, const int, const int, const int);

__kernel void updatePheromones(
    __global double* pheromones,
    __global int* ants,
    __global int* distances,
    __local double* pheromones_old,
    const int numCities,
    const int numAnts,
    const double pheromoneDecreaseFactor,
    const double pheromoneIncreaseFactor
)
{
    int i = get_global_id(0);
     int k, j;

    if(i<numCities)
    {
        for(j = i +1; j<numCities; j++)
        {
          for (k = 0; k < numAnts; k++)
          {
            double size = calculateLengthOfTrail(ants,k, distances, numCities);
            double decrease = (1.0 - pheromoneDecreaseFactor) *   pheromones_old[i+numCities*j];
            double increase = 0.0;

            int edge = edgeInTrail(i, j, ants, k, numCities);

            if (edge== 1)
               increase = (pheromoneIncreaseFactor / size);

            pheromones[i+numCities*j] = decrease + increase;

            if (pheromones[i+numCities*j] < 0.0001)
               pheromones[i +numCities*j] = 0.0001;
            else if (pheromones[i + numCities*j] > 100000.0)
              pheromones[i+numCities*j] = 100000.0;

            pheromones[j+numCities*i] = pheromones[i+numCities*j];

          }
        }
     }
}

int edgeInTrail(const int cityX, const int cityY, __global int* ants, const int row, const int numCities)
{

  int lastIndex = numCities - 1;
  int indexCity = indexOfCity(ants, row, cityX, numCities);

  if (indexCity == 0 && ants[1+numCities*row] == cityY)
    return 1;
  else if (indexCity == 0 && ants[lastIndex+numCities*row] == cityY)
        return 1;
  else if (indexCity == 0)
    return 0;
  else if (indexCity == lastIndex && ants[(lastIndex-1)+numCities*row] == cityY)
        return 1;
  else if (indexCity == lastIndex && ants[row*numCities] == cityY)
    return 1;
  else if (indexCity == lastIndex)
    return 0;
  else if (ants[(indexCity-1)+numCities*row] == cityY)
        return 1;
  else if (ants[(indexCity+1)+numCities*row] == cityY)
        return 1;
  else
    return 0;
}

int calculateLengthOfTrail(__global int* ants, const int row, __global int* distances, const int numCities)
{
    int sumDistance = 0;
    int i;

    for(i =0; i<numCities-1; i++)
         sumDistance += distances[ants[i+numCities*row]+numCities*ants[(i+1)+numCities*row]];

    return sumDistance;

}

int indexOfCity(__global int* ants, int row, int city, int numCities)
{
    int i;

    for(i =0; i<numCities; i++)
    {
        if(ants[i+numCities*row] == city)
            return i;
    }

    return -1;
}


text:
Q: Spring Boot Reactive - How to convert Array response to actual DTO object? I am developing Spring Boot 2.7.0 and Reactive Microservices using Spring WebFlux.
Below is the code
public void placeOrder(OrderRequest orderRequest) {
        List<OrderLineItems> orderLineItems = orderRequest.getOrderLineItemsDtoList()
                .stream()
                .map(this::mapToDto)
                .collect(Collectors.toList());

        Order order = new Order();
        order.setOrderNumber(UUID.randomUUID().toString());
        order.setOrderLineItemsList(orderLineItems);

        List<String> skuCodes = order.getOrderLineItemsList()
                .stream()
                .map(orderLineItem -> orderLineItem.getSkuCode())
                .collect(Collectors.toList());

        // Call Inventory Service, and place order if product is in stock
        InventoryResponse[] inventoryResponsArray = webClient.get()
                .uri("http://localhost:8092/api/inventory",
                        uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
                .retrieve()
                .bodyToMono(InventoryResponse[].class)
                .block();

        boolean allProductsInStock = Arrays.stream(inventoryResponsArray)
                .allMatch(InventoryResponse::isInStock);

        if(allProductsInStock){
            orderRepository.save(order);
        } else {
            throw new IllegalArgumentException("Product is not in stock, please try again later");
        }
    }

Is there any way to combine below two codes into one?
// Call Inventory Service, and place order if product is in stock
        InventoryResponse[] inventoryResponsArray = webClient.get()
                .uri("http://localhost:8092/api/inventory",
                        uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
                .retrieve()
                .bodyToMono(InventoryResponse[].class)
                .block();

        boolean allProductsInStock = Arrays.stream(inventoryResponsArray)
                .allMatch(InventoryResponse::isInStock);

A: I can think of the simplest solution would be below:
// Call Inventory Service, and place order if product is in stock
boolean allProductsInStock = webClient.get()
                .uri("http://localhost:8092/api/inventory", uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
                .retrieve()
                .bodyToMono(InventoryResponse[].class)
                .map(e -> Arrays.stream(e))
                .block()
                .allMatch(InventoryResponse::isInStock);


text:
Q: libcouchbase not instaling on Red Hat Enterprise Linux Server release 6.6 Following the documentation for RHEL/CentOS, this is how I try to install libcouchbase:
wget http://packages.couchbase.com/releases/couchbase-release/couchbase-release-1.0-6-x86_64.rpm
sudo rpm -iv couchbase-release-1.0-6-x86_64.rpm
sudo yum install libcouchbase-devel libcouchbase2-bin gcc gcc-c++

However libcouchbase-devel and libcouchbase2-bin fail with:
Running rpm_check_debug
Running Transaction Test

Transaction Check Error:
  file /usr/lib64/libcouchbase.so.2.0.65 conflicts between attempted installs of libcouchbase-2.10.3-1.el6.remi.x86_64 and libcouchbase2-core-2.10.3-1.el6.x86_64

Error Summary
-------------

I tried installing those packages one at a time but, if I install libcouchbase-devel first it succeeds and libcouchbase2-bin fail. If I remove what I installed and do libcouchbase2-bin first it succeeds, but thenlibcouchbase-devel` fails.
This clearly points to a conflict somewhere, but I am unsure what this conflict is exactly

A: I removed all packages that have couchbase in their name: yum remove packagename
Then, yum install libcouchbase libcouchbase-devel


text:
Q: Physical interpretation of thermal 2-point function in QFT Let $\phi$ be a scalar field, $\rvert \psi_i \rangle$ a set of multiparticle states living in the Fock space of the theory indexed over the naturals, with definite 4-momentum. Let $$\rho_i = \frac{e^{-\beta E_i}}{Z}$$ be the eigenvalue of the density matrix $\rho$ when acting on one of the above states, $Z$ the partition function which normalizes, $\beta$ the inverse of the temperature of the ensemble of states $\rvert \psi_i \rangle$. Consider the $2$-point thermal correlation function
$$\langle{G(x,y)}\rangle_\beta = \sum_i \rho_i \langle \psi_i\rvert \phi(x)\phi(y)\rvert \psi_i \rangle = \mathrm{Tr} \left[\rho \phi(x)\phi(y)\right]$$
What is the physical interpretation of this quantity? Is it similar to the physical interpretation we give to the non-thermal
$$G(x,y)= \langle 0\rvert \phi(x)\phi(y)\rvert 0 \rangle$$
which is the probability amplitude for a particle of the field $\phi$ to travel from $y$ to $x$ (if $y^0 < x^0$) ?

A: At every position, $\phi(x)$ is a random variable. So the two-point correlation function $\mathrm{Tr}[\rho \phi(x) \phi(y)]$ (where the probability density $\rho$ doesn't have to be thermal) is a covariance matrix. I find the physical content of this much easier to think about than a time ordered Green's function.
Nevertheless, you are right that they are related since $e^{-\beta H}$ is the Boltzmann factor while $e^{-it H}$ is the time evolution operator. You can go from one to the other with the Wick rotation $t \mapsto i\tau$ and compactifying $\tau$ on a circle of radius $\beta$.


text:
Q: How does the scipy distance_transform_edt function work? https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.morphology.distance_transform_edt.html
I'm having trouble understanding how the Euclidean distance transform function works in Scipy. From what I understand, it is different than the Matlab function (bwdist). As an example, for the input:
[[ 0.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  0.  0.  0.  0.]]

The scipy.ndimage.distance_transform_edt function returns the same array:
[[ 0.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  0.  0.  0.  0.]]

But the matlab function returns this:
1.4142    1.0000    1.4142    2.2361    3.1623
1.0000         0    1.0000    2.0000    2.2361
1.4142    1.0000    1.4142    1.0000    1.4142
2.2361    2.0000    1.0000         0    1.0000
3.1623    2.2361    1.4142    1.0000    1.4142

which makes more sense, as it is returning the "distance" to the nearest one.

A: It is not clear from the docstring, but distance_transform_edt computes the distance from non-zero (i.e. non-background) points to the nearest zero (i.e. background) point.
For example:
In [42]: x
Out[42]:
array([[0, 0, 0, 0, 0, 1, 1, 1],
       [0, 1, 1, 1, 0, 1, 1, 1],
       [0, 1, 1, 1, 0, 1, 1, 1],
       [0, 0, 1, 1, 0, 0, 0, 1]])

In [43]: np.set_printoptions(precision=3)  # Easier to read the result with fewer digits.

In [44]: distance_transform_edt(x)
Out[44]:
array([[ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  1.   ,  2.   ,  3.   ],
       [ 0.   ,  1.   ,  1.   ,  1.   ,  0.   ,  1.   ,  2.   ,  2.236],
       [ 0.   ,  1.   ,  1.414,  1.   ,  0.   ,  1.   ,  1.   ,  1.414],
       [ 0.   ,  0.   ,  1.   ,  1.   ,  0.   ,  0.   ,  0.   ,  1.   ]])

You can get the equivalent of Matlab's bwdist(a) by applying distance_transform_edt() to np.logical_not(a) (i.e. invert the foreground and background):
In [71]: a
Out[71]:
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

In [72]: distance_transform_edt(np.logical_not(a))
Out[72]:
array([[ 1.414,  1.   ,  1.414,  2.236,  3.162],
       [ 1.   ,  0.   ,  1.   ,  2.   ,  2.236],
       [ 1.414,  1.   ,  1.414,  1.   ,  1.414],
       [ 2.236,  2.   ,  1.   ,  0.   ,  1.   ],
       [ 3.162,  2.236,  1.414,  1.   ,  1.414]])

A: Warren has already explained how distance_transform_edt works.
In your case,you could change sampling units along x and y
ndimage.distance_transform_edt(a)
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

But
>>> ndimage.distance_transform_edt(a, sampling=[2,2])
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  2.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

Or
ndimage.distance_transform_edt(a, sampling=[3,3])
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  3.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  3.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])


text:
Q: If statements not running The strings were parsed to integers, so the condition of the if statements are properly right set. Why are the if statements not running? Why there doesn't appear a MessageDialog with a response?
 class process{
     public static void whoIs(){

         JFrame frame=new JFrame("The Oldest");
            String a=JOptionPane.showInputDialog(frame, "Enter, please, the first name and age:", "QUIZ: Who is the Oldest", JOptionPane.QUESTION_MESSAGE);
           String b=JOptionPane.showInputDialog(frame, "Enter, please, the second name and age:", "QUIZ: Who is the Oldest", JOptionPane.QUESTION_MESSAGE);

            String age1=a.replaceAll("[^\\d]","");
            String age2=a.replaceAll("[^\\d]","");

            String name1=a.replaceAll("\\d","");
            String name2=b.replaceAll("\\d","");

            int age1int=Integer.parseInt(age1);
            int age2int=Integer.parseInt(age2);

            if (age1int>age2int){
                JOptionPane.showMessageDialog(frame, name1+ " is the oldest!", "QUIZ: Who is the Oldest?", JOptionPane.INFORMATION_MESSAGE);
            }

            if (age2int>age1int) {
                JOptionPane.showMessageDialog(frame, name2+ " is the oldest!", "QUIZ: Who is the Oldest?", JOptionPane.INFORMATION_MESSAGE);
            }

     }
}

A: Your both ages are same and your if condition will not match since you are not considering the equality. I think you missed this, Next time try with debugger then you can identify these kind of issues by your own.
 String age1=a.replaceAll("[^\\d]","");
 String age2=a.replaceAll("[^\\d]","");

This should change this to following.
  String age1=a.replaceAll("[^\\d]","");
  String age2=b.replaceAll("[^\\d]","");


text:
Q: JavaFx ListView doesn't show text, but working after cellFactory I have a ListView with click listener. I want add new listener on hover. I coded that new listener with CellFactory (code below). Only with this code my ListView (<String>) show items without text but both listeners works fine (click listener works fine anyway) and items properly selected.
Code of CellFactory in Controller's initialize():
myListView.setCellFactory(lv -> {
        ListCell<String> cell = new ListCell<String>() {};
        cell.hoverProperty().addListener((obs, wasHovered, isNowHovered) -> {
        if(isNowHovered) {
            handleCellHover(cell);
        } else {
            handleCellHoverEnd();
        }
    });
    return cell;
});

Code of adding elements:
// ...
ObservableList<String> data = FXCollections.observableArrayList(data); //data is List<String>
listView.setItems(data);

A: ListCell.updateItem by default does nothing but assign the item and empty properties. You need to override this method to use the item for modifying the cell's look, e.g. by setting the text property:
ListCell<String> cell = new ListCell<String>() {
    @Override
    protected void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if (empty || item == null) {
            setText("");
        } else {
            setText(item);
        }
    }
};

(The default cellFactory uses a subclass of ListCell with a similar updateItem implementation.)


text:
Q: Running a function on init in app.component.ts This might be a really stupid question, but I've noticed that the <app-root> in angular does not implement OnInit like all other components. Say I wanted to put a simple console.log('Hello World') in for a example and I wanted that to show every time the app-root was loaded (stupid I know but simple enough for this example), where in the code structure would I do this and does it need a special function name (eg. ngOnInit())? Or is the whole point of angular for this to be nothing more than just a wrapper that initialises other components.
Here's the code in it basic format as the Angular CLI installs it:
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

}

A: Yes you can add it just like the other components:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  ngOnInit() {
    console.log();
  }

}

Also, it's not that you shouldn't do it. Like anything else, there should be a reason. It just depends on what you are trying to do. That's what more accurately would determine whether or not what you are trying to do is correct/incorrect or good practice/bad practice*


text:
Q: javascript function stops browser's tab I have a problem with processing a Javascript function
in the code below a simple example
when I click the button in that code a Javascript function starts to process
that function must change the value of the progress bar while it's processing and the text area is shows when you try to type in that the page stopped and after a few seconds the browser gives a message
I intend to ensure that the function shows the value of the progress bar and I would like to do some tasks while the function is loading

       function f() {
            var i;
            for (i = 0; i < 100000; i++) {
                document.getElementById("p").innerHTML += i;
                document.getElementById("r").value += 1;
            }
        }

    <progress max="100000" value="0" id="r"></progress>
    <button onclick="f()">click here</button>
    <textarea placeholder="type here ..."></textarea>

A: The problem is that Javascript is single-threaded. The browser is fully focusing on the calculations and does not have time to redraw. To remedy this, we need to provide some time to the browser to regroup:

       function f() {
            var i = 0;
            var intervalID = setInterval(function() {
                document.getElementById("p").innerHTML += i;
                document.getElementById("r").value += 1;
                if (++i === 100000) clearInterval(intervalID);
            }, 50);
        }

    <progress max="100000" value="0" id="r"></progress>
    <button onclick="f()">click here</button>
    <textarea placeholder="type here ..."></textarea>


text:
Q: Find longest path in 2d array first increasing then decreasing I have a 2D array like this:
 3525  2227 35951  9308

42730 58974 32071 45993

41551 36086 19433 15661

60446 11397  2764 12939

I have to find the longest path in this array with numbers first increasing and then decreasing. I know the correct answer is 2764 -> 12939 -> 15661 -> 19433 -> 32071 -> 58974 -> 42730 -> 41551 -> 36086 -> 11379. All I need to know is the length (10), not the path itself. I have already tried bitonic sequence, but no luck there.


text:
Q: MVC iOS breakout game design I have the following models in my breakout like game:

*

*Ball.h

*Block.m

*GamePlay.m

*Paddle.h

*Paddle.m

I also have the following views:

*

*BallView

*BlockVIew

*PaddleView

My question is, when I change a property in the model, I have to change the property in the view also. For example:
Ball Model:
@interface Ball : NSObject
@property (nonatomic, strong) NSNumber *radius;
@property (nonatomic, strong) NSNumber *xSpeed;
@property (nonatomic, strong) NSNumber *ySpeed;
@property (nonatomic, strong) NSNumber *xDirection;
@property (nonatomic, strong) NSNumber *yDirection;
@property (nonatomic) CGPoint location;
@property (nonatomic, strong) UIColor *color;
@end

Ball View:
@interface BallView : UIView
@property (strong, nonatomic) UIColor *color;
@property (nonatomic) int radius;
@end

When the model has its properties changed, I have such as location, or color. I have to update these same properties in the view. Should I NOT track location and color in my model?

A: I think the main point in MVC is maintainability over time. If you decide you need an entirely different view of your game tomorrow, the model code can stay the same, so you can focus on modifying just the view part.
Also, if you know you need some data about the game's state, you know where you can find it - in the model. For example, you might want to transmit the ball's location over the internet to your friend, if he is interested in watching you breaking blocks.
As you can probably guess from the last two paragraphs, you should indeed store and update the location and color of the ball in the model. The view shouldn't be the owner of app state.


text:
Q: junit core java reverse string test cases can anyone please tell me how to write test case in the below code
public static String reverseWord(String str) {
    String a[] = str.split(" ");

    try {
        for (int i = a.length - 1; i >= 0; i--) {
            System.out.print(a[i] + " ");
        }

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

I have written the below test case but it is failed
@Test
public void testReverseWord() {
    assertEquals("world hello", Logic.reverseWord("hello world"));
}

A: You return exactly the same String as you get as argument, changes that you are doing are printed to the console instead of being returned.
Try this code instead. I am creating StringBuilder (you can read more about it here https://docs.oracle.com/javase/tutorial/java/data/buffers.html) which is used for String concatenation. Note that I am adding space only if it is not the last word - so that your returned String doesn't have space at the end. At the end by calling toString() on StringBuilder object I am returning new reversed String, exactly what you wanted.
public static String reverseWord(String str) {

    String a[] = str.split(" ");

    StringBuilder builder = new StringBuilder();
    try {

        for (int i = a.length - 1; i >= 0; i--) {

            builder.append(a[i]);

            if (i != 0) {
                builder.append(" ");
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return builder.toString();
}

A: Your test case is correct, but the method itself is wrong, you are splitting the string then just printing out values instead of creating a new string and concatenating those values there, so instead of System.out.print(a[i] + " "); introduce a new String outside the loop String result = "" and concatenate the values:
        String a[] = str.split(" ");
        String result = "";

        for (int i = a.length - 1; i >= 0; i--) {
                result += a[i];
                if (i != 0)
                  result += " ";
            }

        return result;

A more optimized way is using a StringBuilder since a String is immutable every time you append to it, a new instance is created - also no need for a try-catch block

A: Your function return the same input, so you need to modify it, you can easily use StringBuilder class
public static String reverseWord(String str) {
    String[] words = str.split(" ");
    StringBuilder builder = new StringBuilder(str.length());
    for (int i = words.length - 1; i >= 0; i--) {
        builder.append(words[i]).append(" ");
    }
    return builder.toString().trim();
}


text:
Q: Get single column array in database and display in laravel blade I'm trying to display values separately from a specific column "category" from my database table "order" which is an array with values like "value1,value2,value3".
I want to get those values and display them separately in laravel blade.
Something like $order->category[1]. I can't figure out how I can do it because I still want to display all values from other columns at the same time.
Here's my controller:
 public function index()

    { $orders =  DB::table('order')
        ->where('email', auth()->user()->email)
        ->get();

    return view('dashboard', [
        'orders' => $orders,

    ]);

    }

And here's my blade:
 @foreach ($orders->reverse() as $key => $order )

{{ $order->name }}

        category[1] }}" class="works-img" style="max-width: 280px">

{{ $order->category[2] }}

               @endforeach

And dd($order)
Illuminate\Support\Collection {#1374 ▼
  #items: array:1 [▼
    0 => {#1386 ▼
      +"id": 50
      +"name": "Name"
      +"email": "email@hotmail.com"
      +"mobile": 12348890
      +"category": "Personal,assets/img/personal.png,Personal Website"
      +"contact": "email"
      +"domain": null
      +"new_domain": null
      +"alojamento": null
      +"criar_email": null
      +"facebook": null
      +"instagram": null
      +"linkedin": null
      +"plan": null
      +"order_date": "2021-02-19 12:06:48"
      +"state": "Processing"
    }
  ]
}

A: @foreach ($orders->reverse() as $key => $order )

{{ $order->name }}

            category)[1] }}" class="works-img" style="max-width: 280px">

{{ $order->category[2] }}

                   @endforeach