Q: Windows Command Line - List Network Adapter Components I'm looking for a way to, in a batch file, get a list of the components (such as NDIS drivers) in use by each network adapter on the system. Here's a screenshot of the info I want in the network adapter properties:
Screenshot of network adapter properties:

I have looked through a lot of the data I can get from WMIC, and while I can find a lot of network adapter information I'm not able to find exactly what I'm looking for.
Is anyone aware of a way to get this information from the regular Windows command line without using third-party utilities?

A: Powershell:
Get-NetAdapterBinding -IncludeHidden -AllBindings

VBScript (using WMI):
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\StandardCimv2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM MSFT_NetAdapterBindingSettingData",,48)
Wscript.Echo "Name,DisplayName,ComponentId,Enabled"
For Each objItem in colItems
    Wscript.Echo objItem.Name & "," & objItem.DisplayName & "," & objItem.ComponentId & "," & objItem.Enabled
Next

WMIC:
wmic /namespace:\\root\StandardCimv2 Path MSFT_NetAdapterBindingSettingData Get Name,DisplayName,ComponentId,Enabled

A: How do I get a list of the components used by each network adapter on the system.
You can use nvspbind (a Microsoft Technet application) to retrieve exactly the information you are asking for.

nvspbind is a tool for modifying network bindings from the command line. It is especially useful in Server Core environments with the Hyper-V role enabled.

...

There are three variations:

*

*Microsoft_Nvspbind_package.EXE is the standard 64 bit version for server core.

*32bit_Nvspbind_package.EXE is a 32 bit version that works on Vista and newer.

*XP_Nvspbind_package.EXE is a reduced functionality 32 bit version that works on XP and newer.

Source Hyper-V Network VSP Bind (nvspbind)
I've tested the Microsoft_Nvspbind_package.EXE version on Windows 7 64 bit with the following results:
F:\temp>nvspbind.exe "Local Area Connection 2" > lan2.txt

F:\temp>type lan2.txt

Hyper-V Network VSP Bind Application 6.1.7725.0.
Copyright (c) Microsoft Corporation. All rights reserved.

Adapters:

{37C93C8F-EE9C-4268-A33F-DD199D18748E}
"usb\class_e0&subclass_01&prot_03"
"Remote NDIS based Internet Sharing Device"
"Local Area Connection 2":
   enabled:  ms_netbios       (NetBIOS Interface)
   disabled: ms_server        (File and Printer Sharing for Microsoft Networks)
   enabled:  ms_pacer         (QoS Packet Scheduler)
   disabled: ms_ndiscap       (NDIS Capture LightWeight Filter)
   enabled:  ms_wfplwf        (WFP Lightweight Filter)
   enabled:  inspect          (COMODO Internet Security Firewall Driver)
   disabled: ms_msclient      (Client for Microsoft Networks)
   enabled:  ms_tcpip6        (Internet Protocol Version 6 (TCP/IPv6))
   enabled:  ms_netbt         (WINS Client(TCP/IP) Protocol)
   enabled:  ms_smb           (Microsoft NetbiosSmb)
   enabled:  ms_tcpip         (Internet Protocol Version 4 (TCP/IPv4))
   enabled:  ms_lltdio        (Link-Layer Topology Discovery Mapper I/O Driver)
   enabled:  ms_rspndr        (Link-Layer Topology Discovery Responder)
   enabled:  ms_pppoe         (Point to Point Protocol Over Ethernet)
   enabled:  ms_ndisuio       (NDIS Usermode I/O Protocol)

cleaning up...finished (0)

F:\temp>

A: As an update, and to provide an example for anyone else who may need to know this, I wanted to post that I've found a way to take the suggestion given by DavidPostill by downloading NVSPBind with BITSAdmin (BITS Administration Utility). Apparently BITSAdmin was never removed from Windows (it is still in Windows 10, and still performs this function as expected).
I start by making a folder in %TEMP% to save the downloaded files in, sort of like this:
MD "%TEMP%\NVSPBind"

Some ECHO commands can go here to inform the user about the download, but we'll skip that in the example and go right to using BITSAdmin to download NVSPBind (note that the priority needs to be "foreground" in order for the download to run immediately):
BITSADMIN.EXE /TRANSFER "NVSPBind" /DOWNLOAD /PRIORITY FOREGROUND "https://gallery.technet.microsoft.com/Hyper-V-Network-VSP-Bind-cf937850/file/117119/1/32bit_Nvspbind_package.EXE" "%TEMP%\NVSPBind\32bit_Nvspbind_package.exe"

Next I have the batch file extract the NVSPBind files:
"%TEMP%\NVSPBind\32BIT_NVSPBIND_PACKAGE.EXE" /Q /T:"%TEMP%\NVSPBind"

Now we can run NVSPBind, and have it output a list of network adapters and installed components to our log (we'll assume the log is being saved to the user's Desktop):
"%TEMP%\NVSPBind\NVSPBIND.EXE" *>>%UserProfile%\Desktop\Diagnostic_Log.txt

Then, of course, I have the batch file clean up after itself and delete the TEMP folder we created and the NVSPBind files:
RD /S /Q "%TEMP%\NVSPBind"

Altogether the above code would look like this:
MD "%TEMP%\NVSPBind"
BITSADMIN.EXE /TRANSFER "NVSPBind" /DOWNLOAD /PRIORITY FOREGROUND "https://gallery.technet.microsoft.com/Hyper-V-Network-VSP-Bind-cf937850/file/117119/1/32bit_Nvspbind_package.EXE" "%TEMP%\NVSPBind\32bit_Nvspbind_package.exe"
"%TEMP%\NVSPBind\32BIT_NVSPBIND_PACKAGE.EXE" /Q /T:"%TEMP%\NVSPBind"
"%TEMP%\NVSPBind\NVSPBIND.EXE" *>>%UserProfile%\Desktop\Diagnostic_Log.txt
RD /S /Q "%TEMP%\NVSPBind"

The final log would look something like the following:
Hyper-V Network VSP Bind Application 6.1.7725.0.
Copyright (c) Microsoft Corporation. All rights reserved.

Adapters:

{9C5B16F9-78E6-4434-BE8E-81D6903EB907}
"*teredo"
"Teredo Tunneling Pseudo-Interface"
"Local Area Connection* 9":
   enabled:  ms_netbios       (NetBIOS Interface)
   enabled:  ms_server        (File and Printer Sharing for Microsoft Networks)
   enabled:  ms_msclient      (Client for Microsoft Networks)
   enabled:  ms_netbt         (WINS Client(TCP/IP) Protocol)
   enabled:  ms_smb           (Microsoft NetbiosSmb)
   enabled:  ms_tcpip6        (Internet Protocol Version 6 (TCP/IPv6))
   enabled:  ms_tcpip6_tunnel (Microsoft TCP/IP version 6 - Tunnels)

{F1C945CA-D4B9-4E09-90D1-66C5E85CC22E}
"*isatap"
"Microsoft ISATAP Adapter"
"isatap.{120652A1-8BD2-4435-BD9B-73B23DF7044B}":
   enabled:  ms_netbios       (NetBIOS Interface)
   enabled:  ms_server        (File and Printer Sharing for Microsoft Networks)
   enabled:  ms_msclient      (Client for Microsoft Networks)
   enabled:  ms_netbt         (WINS Client(TCP/IP) Protocol)
   enabled:  ms_smb           (Microsoft NetbiosSmb)
   enabled:  ms_tcpip6        (Internet Protocol Version 6 (TCP/IPv6))
   enabled:  ms_tcpip6_tunnel (Microsoft TCP/IP version 6 - Tunnels)

{120652A1-8BD2-4435-BD9B-73B23DF7044B}
"pci\ven_8086&dev_100f"
"Intel(R) PRO/1000 MT Network Connection"
"Local Area Connection":
   enabled:  ms_netbios       (NetBIOS Interface)
   enabled:  ms_server        (File and Printer Sharing for Microsoft Networks)
   enabled:  ms_pacer         (QoS Packet Scheduler)
   disabled: ms_ndiscap       (NDIS Capture LightWeight Filter)
   enabled:  ms_wfplwf        (WFP Lightweight Filter)
   enabled:  ms_msclient      (Client for Microsoft Networks)
   enabled:  ms_tcpip6        (Internet Protocol Version 6 (TCP/IPv6))
   enabled:  ms_netbt         (WINS Client(TCP/IP) Protocol)
   enabled:  ms_smb           (Microsoft NetbiosSmb)
   enabled:  ms_tcpip         (Internet Protocol Version 4 (TCP/IPv4))
   enabled:  ms_lltdio        (Link-Layer Topology Discovery Mapper I/O Driver)
   enabled:  ms_rspndr        (Link-Layer Topology Discovery Responder)
   enabled:  ms_pppoe         (Point to Point Protocol Over Ethernet)
   enabled:  ms_ndisuio       (NDIS Usermode I/O Protocol)

...


Q: Permission ATTR{idVendor} for USB devices on linux mint to use table mobii protab2 XXL I am using linux mint, and consulting VendorIds from http://developer.android.com I don't know how to detect my tablet device correctly. My tablet device is Mobii protab 2 XXL, fabricated by Point of view.
I have created 50-android.rules at /etc/udev/rules.d/ and added line:
SUBSYSTEM=="usb|usb_device", SYSFS{idVendor}==”0955″, MODE=”0666″
But adb devices throw:
List of devices attached  ????????????  no permissions

Does anyone know which idvendor do I have to use???
usb:

    lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 007 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 008 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 058f:6362 Alcor Micro Corp. Flash Card Reader/Writer
Bus 002 Device 002: ID 05e3:0608 Genesys Logic, Inc. USB-2.0 4-Port HUB
Bus 002 Device 005: ID 1058:1003 Western Digital Technologies, Inc.
Bus 007 Device 002: ID 1a34:0203
Bus 007 Device 003: ID 06f8:3008 Guillemot Corp.
Bus 008 Device 002: ID 046d:c050 Logitech, Inc. RX 250 Optical Mouse
Bus 002 Device 007: ID 0a81:0101 Chesen Electronics Corp. Keyboard
Bus 002 Device 008: ID 18d1:0003 Google Inc.

And I put in udev last time:
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1:0003", SYMLINK+="android_adb", MODE="0666" GROUP="plugdev"

It worked the first time, but when I restart the PC, the permissions are denied. I have tried to restart:
sudo service udev restart
adb kill-server
adb start-server

But it didn't work.
NOTE:
Some devices don't work propertly doing this process. If you still having problems, try execute

sudo adb start-server

It works with Point of view device.

A: On 51-android.rules:
SUBSYSTEMS=="usb", ATTRS{idVendor}=="18b1", ATTRS{idProduct}=="0003", MODE="0666".
And use chmod command to have permission 666 (the number of the beast, muahahhaha) on adb or will not work.
Good luck.

A: SUBSYSTEMS=="usb",
ATTRS{idVendor}=="0bb4",
ATTRS{idProduct}=="XXXX",
MODE="0660",
OWNER="`<your user name>`"

and try using upper case and lower case because in linux a lot of people are having problems to add permissions.

A: Following from the Arch Linux Wiki page I would create /etc/udev/rules.d/51-android.rules
SUBSYSTEM=="usb", ATTR{idVendor}=="18D1", MODE="0666"
SUBSYSTEM=="usb",ATTR{idVendor}=="18D1",ATTR{idProduct}=="0003",SYMLINK+="android_adb"
SUBSYSTEM=="usb",ATTR{idVendor}=="18D1",ATTR{idProduct}=="0003",SYMLINK+="android_fastboot"

Then as root run udevadm control --reload-rules
You may need to replace 18D1 with 18d1. That is what I have done and it works great. You don't necessarily need the username as long as you give permission (MODE="0666") to everyone. If you require more security look at adding the OWNER tag. Again these are rules that I have used on Arch, they should work on Mint.
Good luck!

A: *

*Connect your device.

*Run lsusb.

*Disconnect your device and run it again.

*Find your device hex by comparing both lsusb results:Bus 001 Device 013: ID xxxx:2765 and note the xxxx

*Create a new rule:sudo nano /tmp/android.rules

*Insert:SUBSYSTEM=="usb", ATTRS{idVendor}=="xxxx", MODE="0666"

*Copy the rule:sudo cp /tmp/android.rules /etc/udev/rules.d/51-android.rules

*Change permissions:sudo chmod 644   /etc/udev/rules.d/51-android.rulessudo chown root. /etc/udev/rules.d/51-android.rules

*Retstart ADB:sudo service udev restartsudo killall adb

*Reconnect your device.

*Test ADB: adb devicesList of devices attachedxyzxyzxyz  device
Source: pts.blog: How to fix the adb no permissions error on Ubuntu Lucid

A: As suggested by Ethan, look at "lsusb" to locate the Mobii vendor ID. In the example below, 046d is the ID for Logitech. "0955" belongs to nVidia.
Bus 001 Device 006: ID 046d:c52b Logitech, Inc. Unifying Receiver

Also, don't forget to restart udev after you've changed the 50-android.rules file.


Q: CLIENT_MISSING_INTENTS' enter image description here
i need help with that error when first coding discord bot
here code
const client = new Discord.Client()

client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on("message", msg => {
  if (msg.content === "ping") {
    msg.reply("pong");
  }
})

client.login(process.env.TOKEN)

i try many way on internet but it still not sold ;.;
pls help me
this is error
 throw new TypeError('CLIENT_MISSING_INTENTS');
      ^

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
    at Client._validateOptions (E:\bot\node_modules\discord.js\src\client\Client.js:544:13)
    at new Client (E:\bot\node_modules\discord.js\src\client\Client.js:73:10)
    at Object.<anonymous> (E:\bot\src\bot.js:2:16)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47 {
  [Symbol(code)]: 'CLIENT_MISSING_INTENTS'

A:
To specify which events you want your bot to receive, first think about which events your bot needs to operate. Then select the required intents and add them to your client constructor, as shown below.
All gateway intents, and the events belonging to each, are listed on the Discord API documentation. If you need your bot to receive messages (MESSAGE_CREATE - "messageCreate" in discord.js), you need the GUILD_MESSAGES intent. If you want your bot to post welcome messages for new members (GUILD_MEMBER_ADD - "guildMemberAdd" in discord.js), you need the GUILD_MEMBERS intent, and so on.

Example:
const client = new Discord.Client({
    intents: [
        Discord.Intents.FLAGS.GUILDS,
        Discord.Intents.FLAGS.GUILD_MESSAGES
    ]
});

A: The issue is exactly what the error says it is; your client is missing intents. You need to specify what events and data your bot intends to work with (e.g. guild member presences, messages, etc).

i try many way on internet but it still not sold

I don't know what tutorials or guides you're looking at, but only discord.js v11 and under can work without intents. Discord.js v12 and the latest version (v13) require intents to be specified. What intents you need to specify depends on what you want your bot to do. Does your bot need to detect messages and respond to them? Then enable the GUILD_MESSAGES intent. If your bot does not need to, for example, track guild member presences, you do not need to enable a GUILD_PRESENCES intent.
Before continuing, I would highly suggest you check out the official discord.js guide on how to create a bot on the latest version, which should have been the first place you looked for this information.
Here is a simple way to solve your issue based on the code on that guide, if you are using discord.js v13:
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

Here is another way of doing it, if you are on discord.js v12 (this may also work in v13):
// Require the necessary discord.js classes
const { Client } = require('discord.js');

// Create a new client instance
const client = new Client({ intents: ["GUILDS", "GUILD_MESSAGES"], ws: {intents: ["GUILDS", "GUILD_MESSAGES"]} });

Note that the intents I specified in the above examples may not be enough for you, depending on what your bot is supposed to do in the future. But I believe those examples will be enough to get your current code working without the error you are experiencing.
For a full list of intents, check the discord developer docs here.


Q: Error 10038 (Socket operation on invalid socket) when trying to send a string from Winsock2 C program I'm trying to make a C library that mimics Python socket library.
When i run my main function, an error occurs on simplesend(sucket, "foo");
the whole main function:
int main(){
    struct SIMPLESOCKET sucket;

    simpleinit(sucket);

    simpleconnect(sucket, "ip", "port");

    simplesend(sucket, "foo");

    simpleclose(sucket);

    return 0;
}

this is the definition of the SIMPLESOCKET struct:
#include <winsock2.h>
#include <ws2tcpip.h>

struct SIMPLESOCKET{
    WSADATA wsaData;
    int iResult;
    struct addrinfo *result;
    struct addrinfo *ptr;
    struct addrinfo hints;
    SOCKET ConnectSocket;
};

I get error 10038, which is "socket operation on invalid socket". But when i check s.ConnectSocket, it isn't equal to INVALID_SOCKET.
the simplesend function body:
int simplesend(struct SIMPLESOCKET s, char* msg){

    s.iResult = send(s.ConnectSocket, msg, (int) strlen(msg), 0);
    if (s.iResult == SOCKET_ERROR) {
        printf("send failed: %d\n", WSAGetLastError());
        closesocket(s.ConnectSocket);
        WSACleanup();
        return 1;
    }
}

and the only part of the code that does stuff to s.ConnectSocket doesnt give any errors, here it is:
int simpleconnect(struct SIMPLESOCKET s, char* ip, char* port){
    memset(&s.hints, 0, sizeof(s.hints));
    s.iResult = getaddrinfo(ip, port, &s.hints, &s.result);
    if (s.iResult != 0) {
        printf("getaddrinfo failed: %d\n", s.iResult);
        WSACleanup();
        return 1;
    }
    s.ConnectSocket = INVALID_SOCKET;
    s.ptr=s.result;
    s.ConnectSocket = socket(s.ptr->ai_family, s.ptr->ai_socktype, s.ptr->ai_protocol);
    if (s.ConnectSocket == INVALID_SOCKET) {
        printf("Error at socket(): %ld\n", WSAGetLastError());
        freeaddrinfo(s.result);
        WSACleanup();
        return 1;
    }

    //connect
    s.iResult = connect(s.ConnectSocket, s.ptr->ai_addr, (int)s.ptr->ai_addrlen);
    if (s.iResult == SOCKET_ERROR) {
        printf("1977\n");
        closesocket(s.ConnectSocket);
        s.ConnectSocket = INVALID_SOCKET;
    }

    freeaddrinfo(s.result);
    if (s.ConnectSocket == INVALID_SOCKET) {
        printf("unable to connect to server\n");
        WSACleanup();
        return 1;
    }
}

So, i really don't understand why i get an invalid socket error since i even get the successfull connection on my python server.


Q: Destroying file after HTTP response in Django I'm now making website that downloads certain images from other website, zip files, and let users download the zip file.
Everything works great, but I have no way to delete zip file from server, which has to be deleted after users download it.
I tried deleting temp directory that contains zip file with shutil.rmtree, but I couldn't find way to run it after HTTPResponse.
Here is my code in views.py.
    zipdir = condown(idx)#condown creates zip file in zipdir
    logging.info(os.path.basename(zipdir))
    if os.path.exists(zipdir):
        with open(zipdir, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="multipart/form-data")
            response['Content-Disposition'] = 'inline; filename=download.zip'
            return response
    raise Http404

Thanks in advance.

A: You should looks to Celery project. It allows to schedule delayed function calls (after response generated).
So you can read that file to a variable and schedule task to remove that file.
# views.py
def some_view(request):
    zipdir = condown(idx)#condown creates zip file in zipdir
    logging.info(os.path.basename(zipdir))
    response = HttpResponseNotFound()
    if os.path.exists(zipdir):
        with open(zipdir, 'rb') as fh:
            response = HttpResponse(fh.read(), content_type="multipart/form-data")
            response['Content-Disposition'] = 'inline; filename=download.zip'

    task_delete_zipfile.delay(zipdir)
    return response

# tasks.py
import os
from webapp.celery import app

@app.task
def task_delete_zipfile(filePath):
    if os.path.exists(filePath):
        os.remove(filePath)
    else:
        print("Can not delete the file as it doesn't exists")


Q: Omniauth localization in ruby on rails How do omniauth localize in ruby on rails project?
I want use :ru localization.
In my project I use:
gem 'omniauth-twitter'
gem 'omniauth-facebook'
gem 'omniauth-vkontakte'
gem 'omniauth-mailru'
gem "omniauth-google-oauth2"

A: I'm not sure that omniauth allows you to provide translations for the messages that come out of it.  There don't seem to be any en.yml files in omniauth, omniauth-facebook or omniauth-twitter anyway.
I've only used omniauth with devise and devise provides a couple of omniauth-related messages which can be overridden, but they contain the untranslated error messages which come out of omniauth:
en:
  devise:
    omniauth_callbacks:
      failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
      success: "Successfully authenticated from %{kind} account."

These can be overridden in an app using devise by providing an en translations file containing these in config/locales in your app.  You can of course also provide a ru translations file and set config.default_locale = :ru in application.rb or use some other way to decide which locale to use.  You can see how devise builds an error message from an omniauth failure here:
https://github.com/plataformatec/devise/blob/master/app/controllers/devise/omniauth_callbacks_controller.rb
You could use the same approach in your app without using devise, but as I say, the problem is that %{reason} would be the untranslated error (often an exception.message I think) from omniauth.
For general internationalisation, if you haven't read it already: Rails i18n
EDIT:
It sounded like you were asking about omniauth itself, but in case, as Ashitaka wondered in their comment, you were (also) asking about telling the services you call which locale to use, you've probably seen in the docs, but just for the sake of completeness it does indeed vary by service.  For example, omniauth-facebook lets you add a locale parameter to the facebook call (e.g. locale=ru_RU) and omniauth-twitter lets you add a lang parameter to the twitter call (e.g. lang=ru).

A: If you browse under app/config/locales dir, there is a file en.yml. It is for english locale. If you would like to add other languages, just create (in your case) ru.yml file and place translations there.
This Rails guide is a nice staring point.
Recently I have tried another interesting approach : phrasing gem.


Q: How do I deal with old collected metrics in Prometheus? I am using a Gauge Vector in my application for collecting and exposing a particular metric with labels from my application in the Prometheus metrics format. The problem is that once I have set a metric value for a particular set of labels, even if that metric is not collected again it will be scraped by Prometheus until the application restarts and the metric is removed from memory. This means that even if that metric is no longer valid anymore (hasn't been set again for a day say) Prometheus will still be scraping it as if it's a fresh metric.
Is it possible to either set an expiry time for collected metrics or to remove the collected metric completely? Or are problems like this dealt with on the Prometheus server side?

A: These are the correct semantics. Prometheus deals with metrics and metrics don't go away just because they haven't changed in a while. What you should be doing is keeping the gauge up to date.
It sounds like you might want a logs-based monitoring system, such as provided by the ELK stack.


Q: Nested query with aggregation in Mongo I have a document in MongoDB:
{
        "_id" : ObjectId("111111111111111111111111"),
        "taskName" : "scan",
        "nMapRun" : {
                ...
                "hosts" : {
                        ...
                        "distance" : {
                                "value" : "1"
                        },..
}

I'm interested in the field: nMapRun.hosts.distance.value
How do I get ten maximum values of the field .
Could you give an example of a Java?

A: The aggregation operation in shell:
db.collection.aggregate([
{$sort:{"nMapRun.hosts.distance.value":-1}},
{$limit:10},
{$group:{"_id":null,"values":{$push:"$nMapRun.hosts.distance.value"}}},
{$project:{"_id":0,"values":1}}
])

You need to build the corresponding DBObjects for each stage as below:
    DBObject sort = new BasicDBObject("$sort",
                    new BasicDBObject("nMapRun.hosts.distance.value", -1));
    DBObject limit = new BasicDBObject("$limit", 10);
    DBObject groupFields = new BasicDBObject( "_id", null);
    groupFields.put("values",
                    new BasicDBObject( "$push","$nMapRun.hosts.distance.value"));
    DBObject group = new BasicDBObject("$group", groupFields);
    DBObject fields = new BasicDBObject("values", 1);
    fields.put("_id", 0);
    DBObject project = new BasicDBObject("$project", fields );

Running the aggregation pipeline:
    List<DBObject> pipeline = Arrays.asList(sort, limit, group, project);
    AggregationOutput output = coll.aggregate(pipeline);
    output.results().forEach(i -> System.out.println(i));


Q: R Logistic Regression using summary table Can I run multiple logistic regression in R using data not from whole database, but only using summarized values?
In other words, can I still run the logistic regression and build a model only when I have a table like this:

Age Group
No outcome
Outcome

female, 18-39
130
9

female, 40-59
156
22

female, 60 and older
165
18:

male, 18-39
234
44

male, 40-59
156
34

male, 60 and older
90
5

A: Adding to my comment: You can do this by using the definiton of comparing 2 columns described in ?glm.
data <- data.frame(AgeGroup = c('female, 18-39', 'female, 40-59', 'female, 60 and older', 'male, 18-39', 'male, 40-59', 'male, 60- and older'),
           NoOutcome = c(130, 156, 165, 234, 156, 90),
           Outcome = c(9, 22, 18, 44, 34, 5))
fit <- glm(cbind(Outcome, NoOutcome) ~ AgeGroup, data = data, family = binomial)

This is equivalent to expanding each group to individual rows and doing a binary regression:
data_long <- do.call(rbind, lapply(split(data, data$AgeGroup),
       \(data)data.frame(AgeGroup = data[, 1], outcome = rep(c(0, 1), c(data[,2], data[,3])))))
fit_long <- glm(outcome ~ AgeGroup, family = binomial, data = data_long)
summary(fit_long)
summary(fit) # identical


Q: Kubernetes: Tasks that need to be done once per cluster or per statefulset or replicaset So i heard about initConainers which allow you to do pre-app-container initialization. However, i want initialization which are done either at the cluster level or statefulset, or even the whole pod.
For instance, I want to perform a one time hadoop namenode format on my persistent volumes and be done with that. After that is done my namenode statefulset and my datanode replicasets can proceed each time
Does kubernetes have anything to accommodate this?
How about its Extensions?

A: Kubernetes itself provides Jobs for ad hoc executions. Jobs do not integrate very tightly with existing Pods/Deployments/Statefulsets.
Helm is a deployment orchestrator and includes pre and post hooks that can be used during an install or upgrade.
The helm docco provides a Job example run post-install via annotations.
metadata:
  annotations:
    # This is what defines this resource as a hook. Without this line, the
    # job is considered part of the release.
    "helm.sh/hook": post-install
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": hook-succeeded

If you have more complex requirements you could do the same with a manager or Jobs that query the kubernetes API's to check on cluster state.
Helm 3
A warning that helm is moving to v3.x soon where they have rearchitected away a lot of significant problems from v2. If you are just getting started with helm, keep an eye out for the v3 beta. It's only alpha as of 08/2019.


Q: disable YUM mirrorlist checking I have a machine which is not connected to the internet. I still want to execute some yum commands from time to time.
YUM does like to update the mirrorlist every so often, resulting in errors like:

Could not retrieve mirrorlist http://mirrorlist.centos.org/?release=6&arch=x86_64&repo=os error was' from yum-dump.py! Please check your yum configuration.

Is there a parameter in yum.conf or elsewhere to make yum stop updating the mirrorlist?

A: You can use -C flag in yum. As per YUM's man page:
-C, --cacheonly
        Tells yum to run entirely from system cache - does not
        download or update any headers unless it has to to perform the
        requested action.  If  you’re  using  this as a user yum will not
        use the tempcache for the user but will only use the system cache in
        the system cachedir.

and also please check this question

A: I believe this behavior is governed by this parameter:

metadata_expire
Duration in seconds after which the metadata will expire. So if the
  current metadata downloaded is some seconds younger, then yum will not
  update the repository metadata. If you think that yum is not
  downloading the update information as often as you wish, reduce the
  value of this parameter. You can also change the default format in
  seconds to days, hours or minutes adding d,h or m to the specified
  value. The default is 1.5 hours, for running yum-updatesd every hour.
  You can also use the word never meaning that the metadata will never
  expire.

So I'd try either a 0d, -1, or set the value to something that's really long, 1000d (1000 days).
Example
metadata_expire=99999999

You can then update the cache when you do have access to the internet:
$ sudo yum makecache

References

*

*YUM Configuration

A: Besides the idea of changing the metadata age, you can simply remove the configuration for the repositories which are not reachable. Yum does not need configured repositories to work properly - it can actually run with no configured repository at all. In such case, you are of course bound to only work with packages you have locally installed.
If you have more than one machine cut off from the Internet, it might make sense to create an internal mirror of the CentOS repos and point yum towards these.


Q: Is it possible to initiate SCCM 2007 updates from the command line or powershell on client's computer? Current Process:
1. RDP to client's machine
2. Install updates that are advertised in User Interface
3. Reboot
Issues:
1. We have to remote into one machine at a time, which is a nightmare.
2. We are not allowed to have these updates run automatically.
3. We are not allowed to download foreign software, but we can write it.
What would be the recommended way for remoting into multiple machines at a time and running the updates that are cached in the temporary folder? I've been researched this all night and it seems this problem is unique because of our limitations, most normal networks would just have the users automatically download the updates.


Q: How to reference an assembly in GAC I'm trying to deploy an assembly in GAC, I did that successfully using Gacutil.exe utility.
Now, when I try to add a reference for it from Visual Studio - Add Reference - .Net tab, I don't find it!!
Any help!

A: I had this problem, the GAC'ed dlls arent included in the references.
Check out this post I made:
Add Reference in Framework 4 Application is not showing assemblies in GAC registered with GACUtil V 4
To make things easier, the link to the msdn article:
http://msdn.microsoft.com/en-us/library/wkze6zky(VS.100).aspx
And to paraphrase, create an entry along the lines of the following:
[HKEY_CURRENT_USER\SOFTWARE\Microsoft.NETFramework\v4.0.30319\AssemblyFoldersEx\MyMagicAssemblies] and then set the (Default) value to be a string with the value being the path you want searched. Look at your registry for examples of how this is set up (so the default value becomes: c:\dlls\
v4.0.30319 would be replaced with the framework version you want the dlls to show up against.
because your dlls are in the GAC it will use those as the actual reference and not the files you are showing in the reference list.  Only if the version number of the dlls are different will it use your local version.

A: I've created a sexy visual studio extension that will help you to achieve your goal. Muse VSReferences will allow you to add a Global Assembly Cache reference to the project from Add GAC Reference menu item.

Regards...
Muse Extensions


Q: Is it possible to drive a 3x3 videowall with HDMI + an i7 notebook? Yesterday I saw a 3 by 3 video wall display, in which the only connection between the LED TVs are by HDMI cable from one i7 notebook.
I asked the operator how he did it, and his answer sounded to me kind of tricky and misleading. He connects the notebook to the #1 LED TV in the 'input' HDMI (or something like that). Then, from the 'output' HDMI in that TV, he connects to the #2 input HDMI, and from it to the 3rd and so on... all in series and with HDMI cables.
All of them work with the i7 notebook with one and only HDMI cable plugged in it (connected to the 1st TV) and with some software I can't recognize at first view. He says there's no need to use anything else.
I saw it working. Is it really possible, or has he somehow tricked me?
And if it is possible, why is something like the 'iVu4 stand alone video wall controller' and others like it needed anymore?
Anyone knows anything about this?

A: I'm not sure about HDMI, but you can do that with DisplayPort if your monitors support daisychaining. You can connect up to 6 1366x768 screens or 4 FullHD screens with only one cable plugged into graphics card. To use more screens you'd need another card and one more cable.

A: pretty sure it was DisplayPort MST
read more here
https://www.displayport.org/cables/driving-multiple-displays-from-a-single-displayport-output/

A: Assuming that specialized hardware was in use, then yes, that would be possible.  Normal HDMI displays have no output port.
You did not say what resolutions were in use.  HDMI cannot drive very high resolution from one cable.  Maybe the video wall was not using too many pixels to make it possible.

A: Probably a displayport daisychain, since with displayport the signal processing chips are on the monitor side which lets you get around the usual "two display limit" imposed by even high-end GPUs (even a GTX 980 has only two RAMDACs). There is no way I'm aware of that would allow him to do this with HDMI.
ED: And those adapters / splitters are used for people who are repurposing displays without displayport chaining, displayport input, etc. A lot of them expose the grouped monitors as a single "monitor" to Windows, necessitating Display Fusion or similar software to split them back up again. A lot cheaper than buying 3-6 new screens though.


Q: MAX IF INDEX Function? Currently, I have a table like the one below.
               Jan-16   Feb-16  Mar-16  Apr-16  May-16  Jun-16  Jul-16  Aug-16  Sep-16  Oct-16  Nov-16  Dec-16
Forecast       5        8       7       -       -       -       -       -       -       -       -       -

The monthly forecast figure is set to populate only once that month closes.
In my dashboard, I am attempting to capture the most recent Forecast number in this table so the output would look something like...
Current Forecast    7

I would assume that to achieve this, Current Forecast would require a series of IF, INDEX, MATCH, and MAX (for max date) functions but I'm unable to figure this out.
From deleted comments:
Sorry I didn't clarify. That's correct-- the "-" are zeros with the number format applied.

A: I haven't tested this, but looks like it'll do what you're looking for.
=INDEX(B$2:M$2,MATCH(TRUE,INDEX(B2:M2<>"-",),0))

Modified from here
As Dirk pointed out, this actually returns the first match.

A: if there are no empty dates between the values then, then this formula will do:
=INDEX(B2:M2,COUNTIF(B2:M2,"<>-"))

and having empty dates inbetween then this array-formula will do
=INDEX(B2:M2,MAX(ISNUMBER(B2:M2)*COLUMN(A:L)))

Needs to be confirmed with Ctrl + Shift + Enter

A: The first question would be if those are real dates across row 1 or text-that-look-like-dates. Let's say those are real dates formatted as mmm-yy because that is the better method.
The second question is whether the inactive numbers in row 2 are showing hyphens because they are zeroes with an accounting style number format or if you have actually put hyphens in the cells. Let's say they are zeroes with an accounting style number format because that is the better way to do it.
=INDEX(B2:M2, MATCH(AGGREGATE(14, 6, (B1:M1)/(B2:M2<>0), 1), B1:M1, 0))
' for pre xl2010 systems w/o AGGREGATE
=INDEX(B2:M2, MATCH(MAX(INDEX((B1:M1)+(B2:M2=0)*-1E+99, , )), B1:M1, 0))


Q: In Python got many issues with Spyne Well, here's my Python code:
#!/usr/bin/env python
from spyne import Application, rpc, ServiceBase, Unicode
from lxml import etree
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
# Wsgi это Web server Getewap Interface - стандар взаимодействия с питон программой и серверо где он работает

class Soap(ServiceBase):
    @rpc(Unicode, _return=Unicode)
    def Insoap(ctx, words):
        print("Connection detected: ", etree.tostring(ctx.in_document))
        ww = str(words).capitalize()
        return ww

app = Application([Soap], tns='Capitalize', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11())
application = WsgiApplication(app) # Важна названия переменной, иначе сервер не поймет

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    server = make_server('localhost', 8002, application)
    server.serve_forever()

But get this error, what's the problem? What should I do for a solution? Please, get help me to solve this problem
Traceback (most recent call last):
  File "C:/Users/David374/PycharmProjects/untitled8/venv/test.py", line 3, in <module>
    from spyne import Application, rpc, ServiceBase, Iterable, UnsignedInteger, \
  File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\__init__.py", line 63, in <module>
    from spyne.server import ServerBase, NullServer
  File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\server\__init__.py", line 23, in <module>
    from spyne.server.null import NullServer
  File "C:\Users\David374\PycharmProjects\untitled8\venv\lib\site-packages\spyne\server\null.py", line 69
    self.service = _FunctionProxy(self, self.app, async=False)
                                                  ^
SyntaxError: invalid syntax

A: async is a reserved keyword in Python 3.7+, and you'll need to use the latest version of Spyne, which doesn't use that reserved keyword as a parameter in its functions, if you want to use it with Python 3.7+.
Either update Spyne to spyne-2.13.2-alpha, or use Python 3.6 or lower.
Sources:

*

*https://docs.python.org/3/whatsnew/3.7.html

*https://pypi.org/project/spyne/2.13.2a0/


Q: How to send array of dictionarys in swift by using alamafire(Post method) I am running with an issue where my server is expecting an array of dictionarys from the app side. Please suggest where I'm going wrong here, code below
    {
 let param : [String : AnyObject]  =
            ["trf_id"  :  Constant.constantVariables.trfID,
             "mode"              : Constant.modeValues.createMode,
             "to_city"           : Constant.constantVariables.to_city,
             "from_city"         : Constant.constantVariables.from_city,
             "description"       : Constant.constantVariables.descrption,
             "request_type"      : Constant.constantVariables.request_type,
             "to_date"           : Constant.constantVariables.to_date!,
             "from_date"         : Constant.constantVariables.from_date!,
             "travel_configs"    :  ["Config_id" : "9","values" : "train",
                                      "Config_id" : "10","values" : "bus"]]
        print(param)
}

*

*Where travel_configs is array of dictionaries

I have to send it like this because of server exceptions
trf_id:37
mode:1
request_type:0
from_city:sdfsd
to_city:qws
from_date:2016-08-17
to_date:2016-08-26
description:sdfsdf
travel_configs:[
{"config_id":"11","values":"1"}
,{"config_id":"2","values":"Flight"}]

A: Finally i got answer after 3 days of struggling
just send your array of dictionary into this
  class  func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String{
    let options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : NSJSONWritingOptions(rawValue: 0)

    if NSJSONSerialization.isValidJSONObject(value) {

        do{
            let data = try NSJSONSerialization.dataWithJSONObject(value, options: options)
            if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
                return string as String
            }
        }catch {

            print("error")
            //Access error here
        }

    }
    return ""

}

Hope this will help some one else Thank you..

A: First, it might come from the capital "C" instead of "c" in "config_id" ?
Secondary, you are actually missing [], your code should look like this :
let param : [String : AnyObject]  =
            ["trf_id"  :  Constant.constantVariables.trfID,
             "mode"              : Constant.modeValues.createMode,
             "to_city"           : Constant.constantVariables.to_city,
             "from_city"         : Constant.constantVariables.from_city,
             "description"       : Constant.constantVariables.descrption,
             "request_type"      : Constant.constantVariables.request_type,
             "to_date"           : Constant.constantVariables.to_date!,
             "from_date"         : Constant.constantVariables.from_date!,
             "travel_configs"    :  [["Config_id" : "9","values" : "train",
                                      "Config_id" : "10","values" : "bus"]]]

Why?
Because your server is expecting an array of dictionary, and you are sending only a dictionary ;)


Q: Ubuntu WSL with docker could not be found The command $ docker could not be found in this WSL 1 distro.
We recommend to convert this distro to WSL 2 and activate
the WSL integration in Docker Desktop settings.
See https://docs.docker.com/docker-for-windows/wsl/ for details.
Not able to change to WSL2 and not able to install docker:

A: My problem seems like it's the same, despite the integration WSL is already enabled since installation.
In the windows shell:
> wsl docker --version

The command 'docker' could not be found in this WSL 2 distro.
We recommend to activate the WSL integration in Docker Desktop settings.

See https://docs.docker.com/docker-for-windows/wsl/ for details.

An option to resolve this problem is reinstalling Docker Desktop (https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-docker/configure-docker-daemon#how-to-uninstall-docker), but don't need to do this.
The steps below work for me (I found at https://github.com/docker/for-win/issues/7039).
Open windows shell (maybe as admin), and run:
> wsl -t docker-desktop
> wsl --shutdown
> wsl --unregister docker-desktop

Then go to windows services, stop the Docker Desktop Service, OR to do this running the command in windows shell as admin:
> Stop-Service -Name "com.docker.service"

And finally, restart the Docker Desktop App.
Test in the windows shell:
> wsl docker --version
Docker version 20.10.2, build 2291f61

A: For those still having issues with this, some of my symlinks magically vanished and no amount of reinstalling helped.
Make sure you have the following symlinks in your WSL2 installation:
$ ls -l /usr/bin/ | grep docker
lrwxrwxrwx 1 root   root          56 Jul 14 13:01 com.docker.cli -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/com.docker.cli
lrwxrwxrwx 1 root   root          48 Jul 14 13:01 docker -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker
lrwxrwxrwx 1 root   root          56 Jul 14 13:01 docker-compose -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose
lrwxrwxrwx 1 root   root          59 Jul 14 13:01 docker-compose-v1 -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose-v1
lrwxrwxrwx 1 root   root          71 Jul 14 13:01 docker-credential-desktop.exe -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-credential-desktop.exe
lrwxrwxrwx 1 root   root          50 Jul 14 13:01 hub-tool -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/hub-tool
lrwxrwxrwx 1 root   root          48 Jun 29 09:27 notary -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/notary

A: WSL Integration under Resources was not showing for me.
I had to uncheck "Use the WSL2 based engine" under General settings, Apply, then Check it again, Apply, then WSL Integration showed up under resources and I could click the Ubuntu slider.

A: For me running the following command in wsl terminal worked
sudo apt-get update
apt-cache policy docker-ce
sudo apt-get install -y docker-ce
sudo apt-get install docker-compose
sudo apt-get upgrade
source- https://www.srcmake.com/home/fabric

A: I had this issue, for me running
$ ls -l /usr/bin/ | grep docker

showed all the correct symlinks as per this answer however I saw the following:
which docker
/mnt/c/Program Files/Docker/Docker/resources/bin/docker

The fix was to simply to set the PATH variable to have /user/bin as the first entry
PATH="/usr/bin:$PATH"

From the multitude of answers, it seems like there are many things that can cause this error, so your mileage may vary.

Another good thing to check is that Docker Desktop is actually running. If it isn't, which docker will result in the /mnt/c/... directory as above.

A: As Taylor wrote in his comment you need to connect from WSL to docker desktop.
In the image you attached there is a check box expose daemon on ...
Check this box.
Now you need docker cli, you can install Linux vm then install docker in that Linux vm you just installed.
Then run which docker and copy this file to your windows computer.
Copy the docker executable into /usr/local/bin on your WSL.
Now run the following in WSL
echo "export DOCKER_HOST=tcp://localhost:2375" >> ~/.bashrc
. ~/.bashrc

This worked for me on WSL 1.
Here is guide I found on the all process

A: Fabrício Pereiras answer was working for me, but I had to do it pretty often, which was still annoying.
Turns out the order of starting the systems is important too.
Start Docker first, then WSL2 after.
I don't start Docker Desktop with Windows and usually had opened a terminal in WSL already. Then Docker could not be found. Fabricios answer was working for me because I shutdown WSL2, then started it again when Docker was already running.

A: In my case, the integration was correctly set in the docker-app, WSL2 was correctly the default wsl, and I wasn't able to solve unregistering the wsl docker instance and restarting the docker service like mentioned in other answers.
After some time, I noticed that the command docker-compose successfully worked. The issue was limited to the docker command.
I looked for all docker commands in the directory usr/bin, that is the path where docker-compose is located (which docker-compose), so runnining ls -l /usr/bin | grep docker, I found
drwxrwxrwx  1 root   root          48 Nov 29 10:59 docker
lrwxrwxrwx  1 root   root          56 Nov 29 10:59 docker-compose -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose*
lrwxrwxrwx  1 root   root          59 Nov 29 10:59 docker-compose-v1 -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose-v1*
lrwxrwxrwx  1 root   root          71 Nov 29 10:59 docker-credential-desktop.exe -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-credential-desktop.exe*
lrwxrwxrwx  1 root   root          50 Nov 29 10:59 hub-tool -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/hub-tool*

For some weird reason, docker wasn't a symbolic link but a directory.
I solved removing the directory and re-creating manually the symbolic link:
rm -rf /usr/bin/docker
sudo ln -s /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker /usr/bin/docker

A: I followed theses steps: https://learn.microsoft.com/en-us/windows/wsl/install-win10
Also, for docker into ubuntu, I enabled it in docker resources as a final step.
Settings > Resources > WSL Integration.
from: https://docs.docker.com/docker-for-windows/wsl/

A: Make sure that you have a distro that is compatible with wsl2:
https://ubuntu.com/wsl

A: I was experiencing the same issue with Ubuntu-20.04 (WSL2) and Docker Desktop (v4.11.1). For me, WSL integration and other flags are all set but still I was getting:

The command 'docker' could not be found in this WSL 2 distro.

I followed @r590 's method. I turned-off and then turned-on WSL Integration under:

Resources > WSL Integration

and then it worked for me.

A: You need to go to the docker desktop settings, and enable integration with your distro in "Resources -> WSL Integration".

A: I stuck with this error after remove Ubuntu 18.04 and install the 20.04.
Even with the WSL 2 enabled, I still face this error.
This is what works for me, go the Settings --> resource and toggle the "Ubuntu" then the error disappear :)

A: For me, nothing worked excepted : right click on running Docker icon (next to clock) and chose "Switch to Linux containers"

And here we go ! Now i can have the menu Settings > Resources > WSL integration.

A: Assuming you already have wsl 2 in your system, run powershell as admin:
run wsl --list --verbose which will give you a list of your wsl running processes:
> wsl --list --verbose
  NAME                   STATE           VERSION
  Ubuntu-20.04           Running         1

Then to switch it with  wsl --set-version <your proc> 2:
> wsl --set-version Ubuntu-20.04 2
Conversion in progress, this may take a few minutes...
For information on key differences with WSL 2 please visit https://aka.ms/wsl2
Conversion complete.

A: Sometimes the simplest solution is the most effective solution, if you are installing docker desktop for the first time make sure you restart windows for the effects to take change. This is not guaranteed to work but it is always worth a shot.

A: I was having the same issue, however, for me, I installed docker using a different Windows account (admin) because my default account (under a domain) is a standard user and has no admin access.
After installing docker, I started docker and got an error that I'm not part of the docker-users group so I started docker using the admin account that I have. Docker started but it's not able to see the WSL integration. Similar to the screenshot below.

What fixed it for me is to add the domain account to the docker-users and restart my machine. After that WSL is visible in the configuration.
# For local account
net localgroup docker-users "your-user-id" /ADD

# For domain account
net localgroup docker-users "DOMAIN\your-user-id" /ADD

A: I reboot my machine and docker stopped work. I reinstall docker-decktop and did all the suggestion and nothing work.
I found that I have a directory here /usr/bin/docker. I deleted it and then reinstall docker which fixed the issue.

A: In my case my distribution was running in WSL 1 mode
To check the WSL mode, run:
wsl.exe -l -v
To upgrade your existing Linux distro to v2, run:
wsl.exe --set-version (distro name) 2
To set v2 as the default version for future installations, run:
wsl.exe --set-default-version 2

A: You need to run the WSL console as Admin.
If not, the docker command may be not recognized.

A: Switch to linux containers in docker desktop then it will work.


Q: Intellij IDEA create new class from undefined import Suppose I have a java file that has an import that currently is not referencing any real class, because I plan on defining it myself. Is there an easy way to have intellij create a stub class for me in my module by making the file in the right folder based on the package name? I know I can just manually do this but I'm looking for something a bit more automatic, like if I could just right click the import and say "Create class stub".

A: If you wait until it shows up as an error, you can ctrl+enter on the error to bring up idea's intentions, one of which should be an option to create the new class. You can also get the intentions by clicking the red lightbulb that appears next to the error when the cursor is on it. You should change your settings so that F2 Goes to Errors First, then you can press F2 and the cursor will jump to the error making invoking the intentions a little faster.

A: First thing import that currently is not referencing any real class it dont work like this in intelliJ. you cannot have an import statement for a non-existing thing. Suppose you have a package named mypackage. Then you can write something like -
import mypackage.*;

you can define a className inside the existing class then it will report you an error like the name appears to be RED just keep the cursor there Press alt+ins a menu pops up then select create class and then specify the package in Destination package field. In that way it will work.


Q: ant runnable jar not working I created a runnable jar using ant but it is not running. when I run the jar I am getting following error
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: com/teamdev/jxbrowser/events/NavigationListener
    at com.MainClass$2.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Caused by: java.lang.ClassNotFoundException: com.teamdev.jxbrowser.events.NavigationListener
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    ... 15 more

but when I created jar using eclipse that jar worked fine. Menifest of jar I created with ant is as below
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.2
Created-By: 1.6.0_37-b06-434-11M3909 (Apple Inc.)
Main-Class: com.MainClass
Class-Path: ./ commons-cli.jar commons-codec-1.2.jar commons-httpclien
 t-3.0.1.jar commons-logging-1.1.1.jar ffmpeg-java.jar fmj.jar jdom.ja
 r logback-classic.jar logback-core.jar lti-civil-no_s_w_t.jar mail.ja
 r mp3spi1.9.4.jar slf4j-api.jar tritonus_share.jar vorbisspi1.0.2.jar
  xuggle-xuggler.jar comfyj-2.9.jar engine-gecko.jar engine-ie.jar eng
 ine-webkit.jar jniwrap-3.8.4 jxbrowser-3.3.jar jxbrowserdemo.jar log4
 j-1.2.15.jar MozillaInterfaces.jar runtime.jar slf4j-api-1.5.8.jar sl
 f4j-log4j12-1.5.8.jar winpack-3.8.3.jar xulrunner-mac.jar

and menifest of jar I created with eclipse is as below
Manifest-Version: 1.0
Rsrc-Class-Path: ./ jniwrap-3.8.4.jar lti-civil-no_s_w_t.jar commons-h
 ttpclient-3.0.1.jar slf4j-log4j12-1.5.8.jar vorbisspi1.0.2.jar slf4j-
 api.jar ffmpeg-java.jar fmj.jar commons-codec-1.2.jar engine-ie.jar x
 ulrunner-mac.jar commons-logging-1.1.1.jar winpack-3.8.3.jar mp3spi1.
 9.4.jar tritonus_share.jar commons-cli.jar jdom.jar MozillaInterfaces
 .jar comfyj-2.9.jar jxbrowser-3.3.jar runtime.jar logback-classic.jar
  engine-gecko.jar mail.jar engine-webkit.jar log4j-1.2.15.jar jxbrows
 erdemo.jar slf4j-api-1.5.8.jar logback-core.jar xuggle-xuggler.jar
Class-Path: .
Rsrc-Main-Class: com.MainClass
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader

both are same and all dependencies are also inside the created jar but still the jar create with ant is not working.
I know you would recommend me to create jar with eclipse but I want to obfuscate my code that's why I am using ant to create runnable jar.

A: I guess that your jar file generated with Ant does not have jar-in-jar-loader, that's why it is not able to find classes inside embedded jars.
When you generate JAR with Eclipse you can Save Ant script, then jar-in-jar-loader.zip file would be added to project. Then use generated Ant file to create your JAR. This approach works for me.
Your Ant script should look like this:
    <jar destfile="C:\Users\\workspace\Your.jar">
        <manifest>
            <attribute name="Main-Class" value="org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader"/>
            <attribute name="Rsrc-Main-Class" value="org.mypackage.MainClass"/>
            <attribute name="Class-Path" value="."/>
            <attribute name="Rsrc-Class-Path" value="./ libA.jar "/>
        </manifest>
        <zipfileset src="jar-in-jar-loader.zip"/>
        <fileset dir="${ProjectPath}/bin"/>
        <zipfileset dir="${ProjectPath}\lib" includes="libA.jar"/>
    </jar>

First zipfileset would include jar-in-jar-loader.zip
fileset would add all your classes
Second zipfileset would add libA.jar as embedded jar and same should be mentioned in Rsrc-Class-Path

A: With your Ant-generated Manifest, it is looking for the library jar files outside of the main jar file, the Eclipse one uses a special Main-Class and class loader to get to the bundled dependencies.
You probably want to use the OneJar ant task (or something similar) to achieve something comparable to what Eclipse does.


Q: Outlook 2016 Credentials in Credentials Manager I'm writing a client application to access my mailbox using the Redemption/MAPI library. I used to be able to start a session by doing the following:
1.) Create a credentials MS.Outlook.15:{user's email} in windows credentials manager
2.) Create a profile
3.) Open a session using this: https://msdn.microsoft.com/en-us/library/office/cc842103.aspx
However, once i enable "EnableADAL" flag in the registry. I'm unable to open a session successfully.
What I notice is that Outlook creates a credential named: MicrosoftOiffce16_Data:ADALWAM:{unique identifier of the user authenticated during ADAL token acquisition}
With that credential, i'm able to open a session successfully.
Anyone know what is stored in this credential? I've tried the ADAL refresh token and access token but they don't seem to be correct.


Q: Webpage in Iframe is showing without css? I have an IFRAME in a page. And i have loaded another web page in that IFRAME.
But this newly added web page is not showing properly, i.e., web page is displaying without css.
If i open same web page in another window it displays normally with css.
I have searched a lot but haven't found any solution to resolve it.
Any Suggestions,
Thanks

A: *

*Is the webpage from another domain?

*Does the webpage of the iframe start with http while the parent page is https? Make sure the protocols are the same.


Q: Unchecked operations in java I am completing a lab assignment and get this error when I compile. The program runs fine, bit would like to fix what is causing the error. The program code and the complete error is below. Thanks as always!
import java.util.HashSet;
import java.util.Scanner;

public class Problema4 {
public static void main(String[] args) {
   Scanner scan = new Scanner(System.in);
   int n,s;
   while(scan.hasNext()){
        n=scan.nextInt();
        s=scan.nextInt();
        int A[] = new int[n];
        for (int i =0; i < n; i++) {
          A[i] =scan.nextInt();
        }
        find(A, s);
    }
}

public static void find(int[] A, int sum) {
    int[] solution = new int[A.length];
    HashSet<String> conjuntos = new HashSet(); // usamos la estructura HashSet para que los subconjuntos no se repitan
    find(A, 0, 0, sum, solution, conjuntos);
    System.out.println(conjuntos.size());
}

public static void find(int[] A, int currSum, int index, int sum, int[] solution, HashSet<String> conjuntos) {
    if (currSum == sum) {
        String subConjunto = "";
        for (int i = 0; i < solution.length; i++) {
            if (solution[i] == 1) {
                subConjunto += "  " + A[i];
            }
        }
        if (!subConjunto.trim().isEmpty()) {
            conjuntos.add(subConjunto);
        }
    }
    if (index == A.length) {
        return;
    } else {
        solution[index] = 1; // selecionamos el elemento
        currSum += A[index];
        find(A, currSum, index + 1, sum, solution, conjuntos);
        currSum -= A[index];
        solution[index] = 0; // no seleccionamos el elemento
        find(A, currSum, index + 1, sum, solution, conjuntos);
    }
    return;
}
}

A: This warning comes up when you are using a Set without type specifier. So new HashSet(); instead of new HashSet<String>(); It shows up because the compiler can't check that you are using the Set in a type-safe way.
If you specify the type of the objects you are storing the warning will go away:
Replace
HashSet<String> conjuntos = new HashSet();
with
HashSet<String> conjuntos = new HashSet<>();
More details can be found here: https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html


Q: Inject aspx forms and functionality with jQuery Can you inject aspx forms along with their functionality into a div using the jQuery ajax load method. I am essentially trying to create a modal popup that allows me to load remote web forms into the popup and have the user use the form and submit.I have the modal built and it transitions in perfectly, however it isn't worth it to use if there is no functionality( i.e. I want the code behind of that page to be injected along with it).
Thanks,
-Seth

A: jQuery aside - making an AJAX request for any page will merely load the HTML generated by the web server. The corresponding page could be generated by any type of script that's supported by the server: PHP, ASP, whatever.


Q: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sp.gymtest.User.getName()' on a null object reference I am a beginner in java and this project is for one of my modules, so I really have no idea what is wrong with this.
I am trying to create a real-time chat system using Firebase in Android Studio, I also have real-time database and cloud storage enabled.
The app crashes everytime I try to click into a chat of another user.
This is the error code.
Error Code : FATAL EXCEPTION: main
Process: com.sp.gymtest, PID: 23627
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sp.gymtest.User.getName()' on a null object reference
        at com.sp.gymtest.MessageActivity$2.onDataChange(MessageActivity.java:80)
        at com.google.firebase.database.Query$1.onDataChange(Query.java:191)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
        at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

These are my other files
MessageActivity.java
public class MessageActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText edtMessageInput;
    private TextView txtChattingWith;
    private ProgressBar progressBar;
    private ImageView imgToolbar, imgSend;
    private MessageAdapter messageAdapter;

    ArrayList<Message> messages;

    String usernameOfFriend, emailOfFriend, chatRoomId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        usernameOfFriend = getIntent().getStringExtra("username_of_friend");
        emailOfFriend = getIntent().getStringExtra("email_of_friend");

        recyclerView = findViewById(R.id.recyclerMessages);
        imgSend = findViewById(R.id.imgSendMessage);
        edtMessageInput = findViewById(R.id.edtText);
        txtChattingWith = findViewById(R.id.txtChattingWith);
        progressBar = findViewById(R.id.progressMessages);
        imgToolbar = findViewById(R.id.imageToolbar);

        txtChattingWith.setText(usernameOfFriend);

        messages = new ArrayList<>();

        imgSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FirebaseDatabase.getInstance().getReference("messages/"+chatRoomId).push().setValue(new Message(FirebaseAuth.getInstance().getCurrentUser().getEmail(),emailOfFriend,edtMessageInput.getText().toString()));
                edtMessageInput.setText("");
            }
        });
        messageAdapter = new MessageAdapter(messages, getIntent().getStringExtra("my_img"),getIntent().getStringExtra("img_of_friend"),MessageActivity.this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(messageAdapter);
        Glide.with(MessageActivity.this).load(getIntent().getStringExtra("img_of_friend")).placeholder(R.drawable.account_img2).error(R.drawable.account_img2).into(imgToolbar);

        setUpChatRoom();

    }

    private void setUpChatRoom(){
        FirebaseDatabase.getInstance().getReference("user/"+ FirebaseAuth.getInstance().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String myUsername = snapshot.getValue(User.class).getName();
                if(usernameOfFriend.compareTo(myUsername)>0){
                    chatRoomId = myUsername + usernameOfFriend;
                }else if(usernameOfFriend.compareTo(myUsername) == 0){
                    chatRoomId = myUsername + usernameOfFriend;
                }else {
                    chatRoomId = usernameOfFriend + myUsername;
                }
                attachMessageListener(chatRoomId);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
    private void attachMessageListener(String chatRoomId){
        FirebaseDatabase.getInstance().getReference("messages/" + chatRoomId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                messages.clear();
                for(DataSnapshot dataSnapshot:snapshot.getChildren()){
                    messages.add(dataSnapshot.getValue(Message.class));
                }
                messageAdapter.notifyDataSetChanged();
                recyclerView.scrollToPosition(messages.size()-1);
                recyclerView.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}

MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageHolder> {

    private ArrayList<Message> messages;
    private String senderImg, receiverImg;
    private Context context;

    public MessageAdapter(ArrayList<Message> messages, String senderImg, String receiverImg, Context context) {
        this.messages = messages;
        this.senderImg = senderImg;
        this.receiverImg = receiverImg;
        this.context = context;
    }

    @NonNull
    @Override
    public MessageHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.message_holder,parent, false);
        return new MessageHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageHolder holder, int position) {
        holder.txtMessage.setText(messages.get(position).getContent());

        ConstraintLayout constraintLayout = holder.ccLayout;

        if(messages.get(position).getSender().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
            Glide.with(context).load(senderImg).error(R.drawable.account_img2).placeholder(R.drawable.account_img2).into(holder.profImage);
            ConstraintSet constraintSet = new ConstraintSet();
            constraintSet.clone(constraintLayout);
            constraintSet.clear(R.id.prof_cardView,constraintSet.LEFT);
            constraintSet.clear(R.id.txt_message,constraintSet.LEFT);
            constraintSet.connect(R.id.prof_cardView,constraintSet.RIGHT,R.id.ccLayout,ConstraintSet.RIGHT, 0);
            constraintSet.connect(R.id.txt_message,constraintSet.RIGHT,R.id.prof_cardView,ConstraintSet.LEFT, 0);
            constraintSet.applyTo(constraintLayout);
        }else {
            Glide.with(context).load(receiverImg).error(R.drawable.account_img2).placeholder(R.drawable.account_img2).into(holder.profImage);
            ConstraintSet constraintSet = new ConstraintSet();
            constraintSet.clone(constraintLayout);
            constraintSet.clear(R.id.prof_cardView, constraintSet.RIGHT);
            constraintSet.clear(R.id.txt_message, constraintSet.RIGHT);
            constraintSet.connect(R.id.prof_cardView, constraintSet.LEFT, R.id.ccLayout, ConstraintSet.LEFT, 0);
            constraintSet.connect(R.id.txt_message, constraintSet.LEFT, R.id.prof_cardView, ConstraintSet.RIGHT, 0);
            constraintSet.applyTo(constraintLayout);
        }
    }

    @Override
    public int getItemCount() {
        return messages.size();
    }

    class MessageHolder extends RecyclerView.ViewHolder{
        ConstraintLayout ccLayout;
        TextView txtMessage;
        ImageView profImage;

        public MessageHolder(@NonNull View itemView) {
            super(itemView);

            ccLayout = itemView.findViewById(R.id.ccLayout);
            txtMessage = itemView.findViewById(R.id.txt_message);
            profImage = itemView.findViewById(R.id.small_profImg);
        }
    }
}

ChatActivity.java
public class ChatActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ArrayList<User> users;
    private ProgressBar progressBar;
    private UserAdapter usersAdapter;
    UserAdapter.OnUserClickListener onUserClickListener;
    private SwipeRefreshLayout swipeRefreshLayout;
    String myImageUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        progressBar = findViewById(R.id.chatProgressBar);
        users = new ArrayList<>();
        recyclerView = findViewById(R.id.recycler);
        swipeRefreshLayout = findViewById(R.id.swipeLayout);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getUsers();
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        onUserClickListener = new UserAdapter.OnUserClickListener() {
            @Override
            public void onUserClicked(int position) {
                startActivity(new Intent(ChatActivity.this, MessageActivity.class)
                        .putExtra("username_of_friend", users.get(position).getName())
                        .putExtra("email_of_friend", users.get(position).getEmail())
                        .putExtra("image_of_friend", users.get(position).getProfilePic())
                        .putExtra("my_img", myImageUrl)
                );
            }
        };
        getUsers();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.profile_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId() == R.id.menu_item_profile){
            startActivity(new Intent(ChatActivity.this, ChatProfile.class));
        }
        return super.onOptionsItemSelected(item);
    }

    private void getUsers(){
        users.clear();
        FirebaseDatabase.getInstance().getReference("Users").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot dataSnapshot : snapshot.getChildren()){
                    users.add(dataSnapshot.getValue(User.class));
                }
                usersAdapter = new UserAdapter(users,ChatActivity.this,onUserClickListener);
                recyclerView.setLayoutManager(new LinearLayoutManager(ChatActivity.this));
                recyclerView.setAdapter(usersAdapter);
                progressBar.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);

                for(User user: users){
                    if(user.getEmail().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
                        myImageUrl = user.getProfilePic();
                        return;
                    }
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}

Message.java
public class Message {

    private String sender;
    private String receiver;
    private String content;

    public Message(){

    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getReceiver() {
        return receiver;
    }

    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Message(String sender, String receiver, String content) {
        this.sender = sender;
        this.receiver = receiver;
        this.content = content;
    }
}

User.java
public class User {

    public String fullName, age, email, profilePic;

    public User(){

    }

    public User(String fullName, String age, String email, String profilePic){
        this.fullName = fullName;
        this.age = age;
        this.email = email;
        this.profilePic = profilePic;
    }

    public String getName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getProfilePic() {
        return profilePic;
    }

    public void setProfilePic(String profilePic) {
        this.profilePic = profilePic;
    }
}

UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserHolder> {

    private ArrayList<User> users;
    private Context context;
    private OnUserClickListener onUserClickListener;

    public UserAdapter(ArrayList<User> users, Context context, OnUserClickListener onUserClickListener) {
        this.users = users;
        this.context = context;
        this.onUserClickListener = onUserClickListener;
    }

    interface OnUserClickListener {
        void onUserClicked(int position);
    }

    @NonNull
    @Override
    public UserHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.user_holder,parent, false);
        return new UserHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull UserHolder holder, int position) {
        holder.username.setText(users.get(position).getName());
        Glide.with(context).load(users.get(position).getProfilePic()).error(R.drawable.account_img2).placeholder(R.drawable.account_img2).into(holder.imageProf);

    }

    @Override
    public int getItemCount() {
        return users.size();
    }

    class UserHolder extends RecyclerView.ViewHolder{
        TextView username;
        ImageView imageProf;
        public UserHolder(@NonNull View itemView) {
            super(itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onUserClickListener.onUserClicked(getAdapterPosition());
                }
            });
            username = itemView.findViewById(R.id.username);
            imageProf =  itemView.findViewById(R.id.imageProf);
        }
    }
}

I have tried going through all the layouts, java classes and trying to find if I missed out anything or typo'd anything but to no avail.


Q: tomcat session not serializable for spring component with @Value injection It's a rather strange problem. In Spring I've configured a bean as session.
@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class UserSession implements Serializable{...}

There is an interceptor which who interact with this session.
public class UserInterceptor extends HandlerInterceptorAdapter{
    ...
    @Autowired private UserSession userSession;
    @Autowired private WebUser webUser;

    public boolean preHandle(...){
        userSession.setUserId(webUser.getUserId());
        userSession.setUserList(webUser.getUsers());
        ...
    }
...
}

The WebUser is an interface, in which depend on environment it will inject different WebUser. In profile LOCAL, in will inject LocalWebUser
@Component
@Primary
@Profile({"LOCAL"})
public class LocalWebUser implements WebUser, Serializable{
   @Autowired private transient UserManager userManager;

   @Value("${env.tester.userId}")
   private transient String userId;

   @Override
   public List<String> getUsers() {
       return this.userManager.getUsers();
   }
   ...
}

Notice that I did give make field as transient to prevent common serialization problem. However, in tomcat it throws that LocalWebUser is not serializable.

Caused by: java.io.NotSerializableException:
         com.company.component.web.LocalWebUser$1
         at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
         at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
         at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
        ....

LocalWebUser is actually not stored in session, it's just that session retrieve value from it. Why it complains about it is not serializable?
I did found out a solution that by removing @Value injection from properties, the exception went away, which confuse me even more....

A: It's not complaining about LocalWebUser. It's complaining about LocalWebUser$1 which is an anonymous inner class within LocalWebUser. Look through the code in LocalWebUser for something like this:
Object something = new Something() { .... };

That's an anonymous inner class. If that isn't serializable and a reference to that is being leaked into an object stored in the session, then there's your problem.

A: One possibility is that the @Value annotation modifies the type of the userId field to some other, non serializable type, through bytecode manipulation.
So when you call userSession.setUserId(webUser.getUserId()) it copies that non serializable type to the UserSession.
However I could not find any reference about the @Value annotation to support that, so this is just a hunch.
You could probably validate this by inspecting the type of the userId field at runtime with a debugger.


Q: $f$ is an even function defined on $(-5,5)$
If $f$ is an even function defined on $(-5,5)$ on the interval, then find four real values of x satisfying $f(x)=f(\frac{x+1}{x+2})$.

My book gives the answer as $\frac{\pm3 \pm\sqrt{5}}{2}$

And the solution is given as:
      Since, f is an even function,
      then, $f(x)=f(-x)$,$\forall x\in (-5,5)$
      $$\implies f(x)=f(\frac{1-x}{2-x}) \implies x=\frac{1-x}{2-x} \implies x=\frac{3\pm\sqrt{5}}{2}$$
      Again, $$f(-x)=f(\frac{x+1}{x+2}) \implies -x=\frac{x+1}{x+2} \implies x=\frac{-3\pm\sqrt{5}}{2}$$

What I can't understand is that how can we say $\implies f(x)=f(\frac{1-x}{2-x}) \implies x=\frac{1-x}{2-x}$? It is nowhere said that $f(x)$ is a one-one function then how can we say so? Also if we do use this logic then $f(x)=f(\frac{x+1}{x+2})$
which gives $x=\frac{-1\pm\sqrt{5}}{2}$ which is not given as a solution.

A: You are correct; we can't conclude that $x=\frac{1-x}{2-x}$ just from $f(x) = f\left(\frac{1-x}{2-x}\right)$.  But we don't need to; we need to make the opposite inference: If $x = \frac{1-x}{2-x}$, then $f(x) = f\left(\frac{1-x}{2-x}\right)$, which is what we are looking for.
There might of course be many other $x$ for which $f(x) = f\left(\frac{1-x}{2-x}\right)$ but $x\ne\frac{1-x}{2-x}$. For example, $f$ might be a constant function so that $f(x) = f\left(\frac{1-x}{2-x}\right)$ for all $x\ne 2$. But the question only asks us to find four such values, and this we can certainly do.


Q: confidence in a sample size Firstly, I am not a math expert so I have limited knowledge and language here. bare with me :)
Currently, I am gathering metrics about servers that exist in a datacenter. the situation is that there maybe 100 servers of the same model that i need to sample. Yet I can only collect metrics on 50 of them for reasons that are not relevant. One metric happens to be power. So I collect power consumption on 50 servers and average the power data to come up with a number like 500 watts for example. So the average power consumption of a particular model of server is 500 watts. There are a few questions:

*

*Is there anyway to know that the sampling I have is significant enough to be considered?

*How confident/probable am I that the next server I install of the same model type will be around 500 watts?

I've been reviewing statistical significance, confidence interval, tolerance interval and the like but I want to be sure this is the right way to go. Maybe I'm completely off target on my research. So I am looking for some information to at least point me in the correct direction.

A: First off, all those confidence intervals usually assume that you take random samples from the population. It sounds to me like your are not selecting your servers randomly to collect measurements, but rather, "for reasons you think are not relevant (but maybe are)".
So before you compute any confidence intervals, you should either be certain that the servers you sample are no different (on average) than those you cannot sample---so look at those irrelevant reasons. Or, if you cannot, you need to control for that difference somehow.
In the first case, where you think sampled and nonsampled servers don't differ, you can indeed compute confidence intervals fairly easily. First, you compute the sample mean as usual, then you compute the standard error of the mean (using finite sample correction, since you want to sample about 50% of your population) and on this basis construct confidence intervals (CIs) using the t-distribution.
CIs can be used to answer your 2nd question. Suppose your standard error is 15W. Then you can construct a 95% confidence interval as
$$CI=\bar{x}\pm 1.96 SE=500W \pm 1.96*15W.$$
The 1.96 factor comes from the fact that, if the measured values are normally distributed (which they are for sufficient sample size), then 95% of the values lie within 1.96 of the standard error above and below the sample mean. As I mentioned, if the sample size is relatively small, you should instead use the t-distribution (then the factor will be $>1.96$, i.e., you estimate the values are more spread out). To sum up, after this calculation, you can choose confidence level $l$ yourself (in the example: $l=95$) to calculate the range in which $l$% of the server measurements will be. If you did everything right, not only do you know your confidence ($l$), but can also quantify "around" with the CIs. All of this, of course, relies on random sampling.
I don't understand your first question. Significant sampling? If you sample 50% of your servers, that would be a lot and you need not worry about small sample size. The more important thing about sampling, as stressed above, is that it is random, to rule out differences between the sampled and nonsampled units. We recently had a thread discussing what can happen with nonrandom sampling.


Q: FTP/FTPS looks like it's gradually being deprecated. What are Windows + browser clients moving to and what should I provide instead? In the past I've used FTP over TLS to let non-technical friends and family remotely access important files on my server.
I've just found that they can't do so using Firefox any more, and the firefox bug/feature states that FTP is heading for being "clearly deprecated" and FTP over TLS is being tagged as WONTFIX (Mozilla link1 link2 but see also link3). I also can't get IE11 in Win8.1 to connect either (most family are on 8.1 not 10).
I do provide SMB on the LAN but not WAN, and I'd like to not start running a full web server locally if avoidable. (Because having far greater unnecessary functionality also means scope for a wider attack surface: best avoided if not needed).
Given that scenario, what is the substitute expectation for users who have been using FTPS (or who have been using FTP and want to add TLS transport) to be doing instead?
I assume a not-especially-technical client user who wants it to "just work"within the default OS or their usual browser, and not download specific FTP/client software just to add that capability. The functionality they need is as simple as "enter URI -> authenticate -> get file system root listing -> browse & search directories and up/download files".
Of course decent FTP clients will support this and will exist for many years, but the point was that an ftp(s):// URI has been usable in browsers for decades but now clearly won't be (or won't reliably be). So what should I do, to give them what they need/expect insead?

A:
So what should I do, to give them what they need/expect insead?

IMHO the expectations need to change.  This is 2018, not 1992.
In the early 90's when Web browsers were a new thing, browsers had to plan to support things other than HTTP because:

*

*The Web was barely out of the hands of the academics.  So everything online was static text and image documents, and that's what HTML was doing back then.  HTTP itself was really a file transfer mechanism.

*Since HTTP was new, it wasn't a given at that time that HTTP would pretty much be the most common protocol on the web.  There were others before HTTP - so you had browsers supporting Gopher, FTP, integrated with email clients, etc.

So back then integrating FTP support in the browser made sense.
Of course, it wasn't long before CGI made HTTP a primitive interactive protocol, then Javascript, XHR/AJAX, Webkit, websockets, Webkit, WebRTC, and all the other things browsers support besides display and formatting of static documents.
So now: HTTP(S) is not a simple file transfer mechanism like FTP any longer but really an application delivery mechanism - and static documents are just one possible application.  The perspective of a browser not being in the same category as an FTP client and not supporting protocols other than HTTP(S) is very reasonable these days.

I do provide SMB on the LAN but not WAN, and I'd like to not start running a full web server locally if avoidable. (Because having far greater unnecessary functionality also means scope for a wider attack surface: best avoided if not needed).
Given that scenario, what is the substitute expectation for users who have been using FTPS (or who have been using FTP and want to add TLS transport) to be doing instead?

What non-technical people are doing these days is using cloud services like Dropbox/Google Drive/OneDrive to move files, at the cost of privacy of course.

The functionality they need is as simple as "enter URI -> authenticate -> get file system root listing -> browse & search directories and up/download files".

Microsoft is moving to the cloud model for this, and is pushing OneDrive for this purpose.
There is WebDAV, but you will have to run a webserver, and WebDAV is often difficult to get working properly due to Windows quirks.
Want to do it yourself and not run a webserver?  The answer is SCP.  Your non-technical users will simply have to learn to use an SCP client.  It isn't hard.
SCP has many benefits over FTP, some of which are:

*

*It's based on SSH, which has a long history, so it's secure and encrypted by default.

*Uses one port instead of two and does not need "passive mode" or firewall workarounds.  Simply forward the single port on your router and you are good.

*You can administrate users in the same manner as FTP.


Q: Make responsive larger image of a div I'm trying to make a responsive email template, with a letter that gets it out from an envelope.
The letter is smaller than the envelope and I can't resize it in the same way as the div.
If I put width: 100% on the envelope, I get the same div resize so not good.
If I put  margin-left: -50px;, it gets to the right on the left, but on the right the envelope remains on default size and div resize.
I am using bootstrap for grid system.
This is the template: http://www.kakaostudio.it/newsletter_v1/index_test.html
And this is the final result:

A: The brute force approach would be as follows, this will give you a good idea on how to proceed.
.envelop img {
margin-top: 50px;
margin-left: -60px;
width: 113%;
}
.envelop {
padding: 0;
margin: 0;
}

By doing this you're giving the envelop a bigger width so it matches the div above it. Then move it to the left with negative margin-left.
I have a 1920px width screen and it shows perfectly in sync for me, but it's not responsive with this approach. You'd need to use many media queries to adjust the size as it goes.
You can try playing around with negative % for the margin-left or even better the "vw" values. Position: relative and a negative value for left will give you the same result as margin-left.
Image of my approach's result.


Q: How to restrict admin user to log in if already any user logged in I know about the feature of Admin Account Sharing of magento2. Using this feature if someone login to admin panel from another device then already logged in user get expired session error and logged out automatically.
But I want if any admin user is already login in admin panel and same user or another user try to login in admin panel then user will get message that any admin user already logged in system.
So Is there any setting in magento2 for this or any extension for this?
If no then How can I develop my own module to to so?

A: Hello you can merge up two thing.
First at admin login event you can check weather admin login or not.
for admin login event you can use this event
magento 2 proper way of using the events to capture the admin login success and login failure
for this you can take reference of this post
Magento 2 How to check if Admin Logged on frontend
by merging up above two post you can get your answer


Q: Quick image search using histograms of colors I want to search images using their histograms of colors. For extracting these histograms I will use OpenCV, I also found examples which describes how to compare two images using histograms of colors. But I have some issues:

*

*Google and another search-engines uses these histograms for searching by image, but I do not think that they iteratively compare described image with images in the database (as it done in the OpenCV examples). So how can I implement quick image search using histograms?

*Can I use for this purpose and another image searching purposes common RDBMS like MySQL?


Q: In Word, failure of numbered list under Heading I am working on a Word document with headings. Under one heading, I would like to create a numbered list. However each numbered item appears as a new Heading, so I end up with a bunch of headings rather than a numbered list. What is going on?
Here are the steps. I'd like to insert a numbered list after the heading named 'Method'. The text after this heading is Normal style.

I choose the numbered list button at the top to create a new numbered item. But it appears as a new heading (#3, no name) instead, even though the style where I inserted the item still appears as Normal on the Style Inspector on the right of the screen.

How can I insert a numbered list after the heading named 'Method'?

A: Try this.
With your new item listed as Number 3 (like screen shot 2).

*

*Highlight (select) it.

*Click Normal Style (from the Top Style boxes).

*Now click on the Numbering button, it should now be normal but with a 3.

*Click increase Indent button (it should become "a" still in normal style).

*Right Click it.

*Hightlight Numbering (don't click it)

*Under Numbering Libray pick 1.2.3.

A: Word comes with some predefined heading styles, Heading 1-9. Usually, the definition of these styles specifies the style of the following paragraph. This means that, if you are typing in a paragraph with the Heading N style and then hit [enter], the new paragraph will have the specified style.
Additional paragraph and character formatting can be applied to paragraphs that have a heading style applied to them. For example, it's possible to apply the Heading 1 style to a paragraph and then to turn on bullets or numbering. And if the Heading 1 style had been changed so that the same style was applied to the following paragraph, you would get the situation you are describing.
You could look at the Style Inspector to see what formatting directives have been applied to your headings, which are part of the style definition, and which have been applied directly.
This article gives an overview of using styles in Word 2007.
Hope that helps.

A: I used Word 2007's built-in styles, and created the document shown below. I first created the four headings, and applied the Heading 1 style to them. I then inserted a new paragraph -- with Normal style -- and was able to enable numbering, which changed the style to List Paragraph. The Style Insepctor confirms this.

I then modified the Heading 1 style to include automatic numbering. When I turned on numbered list for the subordinate paragraph, Word changed the style of that paragraph from Normal to Heading 1.
I believe this happens because the numberd list functionality tries to keep numbering consistent, and by default, a newly numbered paragraph will join an adjacent numbered list. In the image beow, you can see in the Style Inspector that the new paragraph has changed its style to Heading 1.

Some possible work-arounds:

*

*Create a new style for your numbered paragraphs. I have confirmed that this works. (see below)

*Turn off the automatic numbering in your heading style and just enter the numbers in the headings manually

I hope that this isn't too late to be of any help. It took me a while to build a system with Word 2007 to play with. For what it's worth, the same behavior affects Word 2010.
Good luck!

A: Here's an easier fix. This still happens in Word 2013, so this may also work for Word 2007.
Instead of clicking the numbered list button, click the down arrow to bring up the menu and select the format you want. This will cause the Normal style to be numbered, instead of converting it to a heading.


Q: How to put text after the input field in python? In python if I wanted to have someone enter a loan amount in dollars, I could code something like this:
# Loan amount
L = float(input("Enter the loan amount: $"))

But what if I want, let's say the interest rate, which is a percentage. If I coded:
# Interest rate
I = float(input("Enter the interest rate: "))

How could I get the percentage sign, %, to show up after what they input?

A: What you need is controlling the terminal's cursor.
After user giving input and hit enter, cursor moves to next line.
You need to move the cursor up one line then move it to end of that line, print % then move cursor back to the new line.
You can do that using Terminal's escape sequence.
This library can make it easier for you to perform cursor movement
http://code.activestate.com/recipes/475116-using-terminfo-for-portable-color-output-cursor-co/


Q: is an android API essentially just using GET/POST to get information? I'm trying to get the root of an API and I'm just wondering if most APIs are essentially using GET/POST requests to send and receive information?
My thought is that anything that android does with an API has to connect to some server somewhere, but is there a connecting language between the server and android? or can it essentially be explained like Android is sending a GET/POST request to a PHP page that makes calls to a database (if a database is involved)?
Example. If I'm very comfortable with php, can I make an API that references the php page?

A: yes u can use php or there is some backend providers that offer alot of good stuff
backendless or parse.com
but if u already have your php services dame u can use them by the HTTPRequests / HTTPResponses using this in some asynch task will make it eazy