Q: Windows 7 in Oracle VirtualBox I took a .vhd of my current Windows 7 Lenovo laptop and would like to install it on my Macbook Air Oracle Virtual Box as a new virtual machine. When I import the .vhd file into VirtualBox I am prompted to activate Windows.
If I activate this, will my current Lenovo laptop stop working, and if yes, what should I do?

A: Kevin, I would not activate the Windows 7 OS for virtual box. I am not sure what you're using it for, but Windows 7 will work just fine without being activated. I have four machines and three Windows 7 OSs have not been activated for over a year. I have legal keys, but the issue is that each key can only be activated several times before Microsoft red flags it. Once this happens, you will have to call Microsoft and manually activate your OS over the phone. Because I am constantly reformating my drive, or loading OSs into virtual Box like you, I do not activate them until I am sure I will never uninstal and reactivate them. I hope this makes sense.


Q: Elastic Search missing some documents while creating index from another index I have created one index in elastic search name as documents_local and load data from Oracle Database via logstash. This index containing following values.
"FilePath" : "Path of the file",
"FileName" : "filename.pdf",
"Language" : "Language_name"

Then, i want to index those file contents also, so i have created one more index in elastic search named as document_attachment and using the following Java code, i fetched FilePath & FileName from the index documents_local with the help of the filepath i retrived file will is available in my local drive and i have index those file contents using ingest-attachment plugin processor.
Please find my java code below, where am indexing the files.
private final static String INDEX = "documents_local";  //Documents Table with file Path - Source Index
private final static String ATTACHMENT = "document_attachment"; // Documents with Attachment...  -- Destination Index
private final static String TYPE = "doc";

public static void main(String args[]) throws IOException {

    RestHighLevelClient restHighLevelClient = null;
    Document doc=new Document();

    try {
        restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    //Fetching Id, FilePath & FileName from Document Index.
    SearchRequest searchRequest = new SearchRequest(INDEX);
    searchRequest.types(TYPE);
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    QueryBuilder qb = QueryBuilders.matchAllQuery();
    searchSourceBuilder.query(qb);
    searchSourceBuilder.size(3000);
    searchRequest.source(searchSourceBuilder);
    SearchResponse searchResponse = null;
    try {
         searchResponse = restHighLevelClient.search(searchRequest);
    } catch (IOException e) {
        e.getLocalizedMessage();
    }

    SearchHit[] searchHits = searchResponse.getHits().getHits();
    long totalHits=searchResponse.getHits().totalHits;

    int line=1;
    String docpath = null;

    Map<String, Object> jsonMap ;
    for (SearchHit hit : searchHits) {

        String encodedfile = null;
        File file=null;

        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        doc.setId((int) sourceAsMap.get("id"));
        doc.setLanguage(sourceAsMap.get("language"));
        doc.setFilename(sourceAsMap.get("filename").toString());
        doc.setPath(sourceAsMap.get("path").toString());

        String filepath=doc.getPath().concat(doc.getFilename());

        System.out.println("Line Number--> "+line+++"ID---> "+doc.getId()+"File Path --->"+filepath);

        file = new File(filepath);
        if(file.exists() && !file.isDirectory()) {
            try {
                FileInputStream fileInputStreamReader = new FileInputStream(file);
                byte[] bytes = new byte[(int) file.length()];
                fileInputStreamReader.read(bytes);
                encodedfile = new String(Base64.getEncoder().encodeToString(bytes));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        jsonMap = new HashMap<>();
        jsonMap.put("id", doc.getId());
        jsonMap.put("language", doc.getLanguage());
        jsonMap.put("filename", doc.getFilename());
        jsonMap.put("path", doc.getPath());
        jsonMap.put("fileContent", encodedfile);

        String id=Long.toString(doc.getId());

        IndexRequest request = new IndexRequest(ATTACHMENT, "doc", id )
                .source(jsonMap)
                .setPipeline(ATTACHMENT);

        try {
            IndexResponse response = restHighLevelClient.index(request);
        } catch(ElasticsearchException e) {
            if (e.status() == RestStatus.CONFLICT) {
            }
            e.printStackTrace();
        }

    }

    System.out.println("Indexing done...");
}

Please find my mappings details for ingest attachment plugin( i did mappping first and then executing this java code ).
    PUT _ingest/pipeline/document_attachment
    {
      "description" : "Extract attachment information",
      "processors" : [
        {
          "attachment" : {
            "field" : "fileContent"
          }
        }
      ]
    }

But while doing this process, Am missing some of the doucments,
My source index is documents_local which is having 2910 documents.
Am fetching all the 118 documents and attaching my PDF  ( after converting to base64) and writting in another index document_attachment
But document_attachment index having only 118 it should be 2910. some of the doucments are missing. Also, for indexing its taking very long time.
Am not sure, how the documents are missing in second index ( document_attachment ) and is there any other way to improvise this process ?
Can we include Thread mechanism here. Because, i future i have to index more than 100k pdf, in this same way.


Q: Purge hidden storage on Github Desktop OSX? I have several folders of jpg files on my OSX laptop, cloned from a GitHub repository. The files I can see total less than 20GB, but my system tells me that they occupy 65+GB.

Where are these hidden files? How can I purge them?
I should mention that there is only one branch in the repository.
(Also, I know that GitHub is not meant to be a place to store lots of image files. This repo is a component of a larger project.)

A: As mentioned in "Show system files / Show git ignore in osx", use in your Finder ⌘⇧.
That should show you the hidden folder .git/, which include all the history of the repo.
And for a repo of binaries (like jpeg images), and new version of an image might take quite a lot of place (poor diff, poor compression between each version)

I wonder if there's any way I can purge this history from local storage? (I'd like to keep it in the cloud)

You would need to download only the archive of the repo (meaning the content, without the history).
If you don't need to change and push back those modification, the archive would be enough.
If you need the history, a shallow clone (git clone --depth 1) that I detailed here (or here) is best to keep the downloaded data at a minimum.

A: I would try re-indexing your hdd and see if that accurately displays file sizes once its done.
Run the following in osx terminal:
    sudo mdutil -E /

Original article:
https://www.maketecheasier.com/fix-wrong-hard-drive-data-usage-calculation-osx/


Q: Auto Generate Patient ID Using Two Columns In the table Screening i have StudyID. The StudyID is a combination of two numbers StudyType( For Cases = KNH-01, For Controls = KNH-02) and Serealized 5 digit number (00001,00002). So the screening table looks like this;
ID  StudyID        Age
 1   KNH-01/00001   22
 2   KNH-01/00002   15
 3   KNH-02/00001   4
 4   KNH-02/00002   28
Currently the StudyID numbers are manually saved in a log book and I would wish to automate the process of generating the StudyID numbers. I have created a table to manage StudyID
CREATE TABLE [dbo].[PatientID](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [PatientType] [varchar](5) NULL,
    [PatientNumber] [int] NULL,
 CONSTRAINT [PK__PatientI__3214EC2739E294A9] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

I am unable to get last PatientNumber  based on the PatientType my intention is to have a button at the vb.net front end when a user clicks to generate StudyID it checks the last given number within a studytype adds 1 to it and loads to form. e.g. KNH-01/00003 or KNH-02/00003. If you have a better Idea i will really appreciate.

A: Well, my personal favorite way of solving such requirements involves using a computed column and a UDF to compute the values in that column.
So first, you create the UDF:
CREATE FUNCTION dbo.GenerateStudyID (
    @PatientType varchar(5),
    @id int
)
RETURNS char(11)
AS
BEGIN
    RETURN (
        SELECT @PatientType +'/'+ RIGHT('00000', CAST(COUNT(*) as char(5)), 5)
        FROM [dbo].[PatientID]
        WHERE PatientType = @PatientType
        AND Id <= @id
    )
END
GO

Then, you add the computed column to your table:
ALTER TABLE [dbo].[PatientID]
ADD StudyID as dbo.GenerateStudyID (PatientType, id)
GO

Please note that you can't use this method if you need this column to be persisted, since once you will delete a record the values will change.


Q: uploaded files - database vs filesystem, when using Grails and MySQL I know this is something of a "classic question", but does the mysql/grails (deployed on Tomcat) put a new spin on considering how to approach storage of user's uploaded files.
I like using the database for everything (simpler architecture, scaling is just scaling the database).  But using the filesystem means we don't lard up mysql with binary files.  Some might also argue that apache (httpd) is faster than Tomcat for serving up binary files, although I've seen numbers that actually show just putting Tomcat on the front of your site can be faster than using an apache (httpd) proxy.
How should I choose where to place user's uploaded files?
Thanks for your consideration, time and thought.

A: I don't know if one can make general observations about this kind of decision, since it's really down to what you are trying to do and how high up the priority list NFRs like  performance and response time are to your application.
If you have lots of users, uploading lots of binary files, with a system serving large numbers of those uploaded binary files then you have a situation where the costs of storing files in the database include:

*

*Large size binary files

*Costly queries

Benefits are

*

*Atomic commits

*Scaling comes with database (though w MySQL there are some issues w multinode etc)

*Less fiddly and complicated code to manage file systems etc

Given the same user situation where you store to the filesystem you will need to address

*

*Scaling

*File name management (user uploads same name file twice etc)

*Creating corresponding records in DB to map to the files on disk (and the code surrounding all that)

*Looking after your apache configs so they serve from the filesystem

We had a similar problem to solve as this for our Grails site where the content editors are uploading hundreds of pictures a day. We knew that driving all that demand through the application when it could be better used doing other processing was wasteful (given that the expected demand for pages was going to be in the millions per week we definitely didn't want images to cripple us).
We ended up creating upload -> file system solution. For each uploaded file a DB meta-data record was created and managed in tandem with the upload process (and conversely read that record when generating the GSP content link to the image). We served requests off disk through Apache directly based on the link requested by the browser. But, and there is always a but, remember that with things like filesystems you only have content per machine.
We had the headache of making sure images got re-synchronised onto every server, since unlike a DB which sits behind the cluster and enables the cluster behave uniformly, files are bound to physical locations on a server.
Another problem you might run up against with filesystems is folder content size. When you start having folders where there are literally tens of thousands of files in them, the folder scan at the OS level starts to really drag. To avert this problem we had to write code which managed image uploads into yyyy/MM/dd/image.name.jpg folder structures, so that no one folder accumulated hundreds of thousands of images.
What I'm implying is that while we got the performance we wanted by not using the DB for BLOB storage, that comes at the cost of development overhead and systems management.

A: Just as an additional suggestion: JCR (eg. Jackrabbit) - a Java Content Repository. It has several benefits when you deal with a lot of binary content. The Grails plugin isn't stable yet, but you can use Jackrabbit with the plain API.

A: Another thing to keep in mind is that if your site ever grows beyond one application server, you need to access the same files from all app servers.  Now all app servers have access to the database, either because that's a single server or because you have a cluster.  Now if you store things in the file system, you have to share that, too - maybe NFS.

A: Even if you upload file in filesystem, all the files get same permission, so any logged in user can access any other's file just entering the url (Since all of them get same permission). If you however plan to give each user a directory then a user permission of apache (that is what server has permission) is given to them. You should su to root, create a user and upload files to those directories. Again accessing those files could end up adding user's group to server group. If I choose to use filesystem to store binary files, is there an easier solution than this, how do you manage access to those files, corresponding to each user, and maintaining the permission? Does Spring's ACL help? Or do we have to create permission group for each user? I am totally cool with the filesystem url. My only concern is with starting a seperate process (chmod and stuff), using something like ProcessBuilder to run Operating Systems commands (or is there better solution ?). And what about permissions?


Q: Serverless Web App Architecture I am currently designing a simple Serverless Web App using Serverless.
My current expected stack is;

*

*API Gateway

*Lambda

*DynamoDB

*Static Single Page App

I have followed a few tutorials for building the Serverless API, Lambda and DynamoDB using the Serverless Framework and I have built my single page app however right now they are 2 separate entities.
What I am looking to do now is bring the static site (nodejs) into the same project as my API, Lambda and DynamoDB and use the Serverless Framework to control the deployment however I'm struggling to find guidance on;

*

*How do you represent the static web site part in the Serverless
Framework

*How best to host that static web site (e.g. s3 static site hosting
or other option?)

*How best to reference a API Gateway URL that is being generated at
the same time the deployment is happening (e.g. via Serverless
Framework)

Could anyone provide any insight into how this is supposed to work, or maybe point me int he direction of some good blogs/resources?
Kind Regards,
John

A: I had a SPA (single page application) written in React communicating to a REST JSON API written in nodejs and hosted on Heroku as a monolith.
I migrated to AWS Lambda and split the monolith into 3+ AWS Lambdas micro services inside of a monorepo
The following project structure is good if your SPA requires users to login to be able to do anything.
I used a single git repository where I have a folder for each service:

*

*api

*app

*www

Inside of each of the services' folders I have a serverless.yml defining the deployment to a separate AWS Lambda.
Each service maps to only 1 function index which accepts all HTTP endpoints. I do use 2 environments staging and production.
My AWS Lambdas are named like this:

*

*example-api-staging-index

*example-api-production-index

*example-app-staging-index

*example-app-production-index

*example-www-staging-index

*example-www-production-index

I use AWS Api Gateway's Custom Domain Names to map each lambda to a public domain:

*

*api.example.com (REST JSON API)

*app.example.com (single page application that requires login)

*www.example.com (server side rendered landing pages)

*api-staging.example.com

*app-staging.example.com

*www-staging.example.com

You can define the domain mapping using serverless.yml Resources or a plugin but you have to do this only once so I did manually from the AWS website console.
My .com domain was hosted on GoDaddy but I migrated it to AWS Route 53 since HTTPS certificates are free.
app service

*

*/bundles-production

*/bundles-staging

*src (React/Angular single page application here)

*handler.js

*package.json

*serverless.yml

The app service contains a folder /src with the single page application code. The SPA is built locally on my computer in either ./bundles-production or ./bundles-staging based on the environment. The built generates the .js and .css bundles and also the index.html. The content of the folder is deployed to a S3 bucket using the serverless-s3-deploy plugin when I run serverless deploy -v -s production.
I defined only 1 function getting called for all endpoints in the serverless.yml (I use JSON instead of YAML):
...
    "functions": {

        "index": {
            "handler": "handler.index",
            "events": [
                { "http": "GET /" },
                { "http": "GET /{proxy+}"}
            ]
        },

    },

The handler.js file returns the index.html defined in /bundles-staging or /bundles-production
I use webpack to build the SPA since it integrates very well with serverless with the serverless-webpack plugin.
api service
I used aws-serverless-express to define all the REST JSON API endpoints. aws-serverless-express is like normal express but you can't do some things like express.static() and fs.sendFile().
I tried initially to use a separate AWS Lambda function instead of aws-serverless-express for each endpoint but I quickly hit the CloudFormation mappings limit.
www service
If most of the functionality of your single page application require a login it's better to place the SPA on a separate domain and use the www domain for server-side rendered landing pages optimized for SEO.
BONUS:
graphql service
Using a micro service architecture makes it easy to experiment. I'm currently rewriting the REST JSON API in graphql using apollo-server-lambda

A: I have done pretty much the same architecture and hosted the single page app on s3. What you can do is set up cloudfront for api gateway and than point api.yourDomain.com to that cloudfront. Than you will also need to enable cors on your api.
This plugin handles setting up domain and cloudfront for you:
https://github.com/amplify-education/serverless-domain-manager
I am not sure about your project requirements but if you want to serve static files faster setting up domain->cloudfront->s3 might be a wise choice.

A: Here is something meaningful and worthy to read about the Serverless Architecture and Azure Serverless services
https://sps-cloud-architect.blogspot.com/2019/12/what-is-serverless-architecture.html


Q: At he and or at his and? The headline reads:

A family affair for Boris as sister Rachel arrives at he and Carrie's wedding celebration party.

Is the subjective 'he' after the proposition 'at' incorrect?


Q: cannot import name 'PackageFinder' from 'pip._internal.index' pip3 On my mac, pip3 exists in /usr/bin. When I try to install any package using pip3, it is failing. Even simple 'pip3' also failing with below error.
Traceback (most recent call last):
  File "/Library/Developer/CommandLineTools/usr/bin/pip3", line 6, in <module>
    from pip._internal import main
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/__init__.py", line 40, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/autocompletion.py", line 8, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/main_parser.py", line 11, in <module>
    from pip._internal.commands import (
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/__init__.py", line 6, in <module>
    from pip._internal.commands.completion import CompletionCommand
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/completion.py", line 6, in <module>
    from pip._internal.cli.base_command import Command
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 26, in <module>
    from pip._internal.index import PackageFinder
ImportError: cannot import name 'PackageFinder' from 'pip._internal.index' (/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/index/__init__.py)

I tried to remove /usr/bin/pip3. But it is saying operation is not permitted. I am unable to remove pip3. Can any one please let me know how to fix this issue.
Note: I went through some stack overflow questions related to this. Most of the answers suggested to uninstall and install pip3. But I am unable to remove pip3.


Q: jquery: Callback not received on clicking of button I need to send a request on click of button but callback is not received on firing of click event of the button.
Following is code snippet:
$(document).ready(function () {
    var counter = 0;
    $("#trail").click(function () {
        $("#dialog").dialog();
        if (counter < 1) {
            $("#searchboxdiv").after('<input type="text" id="searchbox">');
            $("#searchbox").after('<input type="button" id="searchbutton" value="search">');
            counter++;
        }
    });
    $("#searchbutton").click(function () {
        var dataToSend = null;
        $.ajax({
            data: dataToSend,
            url: "FormHandler",
            success: function (result) {},
            beforeSend: function () {
                dataToSend = $("#searchbox").val();
            }
        });
    });
    $("#searchboxdiv").on('click', "#searchbutton", function(){
        var data = null;

    });
});

I added the textbox in the dialog box dynamically and on click of button in dialog box, callback is not received

A: Use event delegation (for dynamically added #searchbutton)
 $('#searchboxdiv').on('click',"#searchbutton",function(){

*

*http://learn.jquery.com/events/event-delegation/

A: Your options:

*

*Use event delegation. Bind the click to immediate static parent like this :
 $("#searchboxdiv").on('click', "#searchbutton", function(){ });

*Or, bind it to the document.
 $(document).on('click', "#searchbutton", function(){ });

*Or, move the existing click after counter++;, ie., inside  $("#trail")'s click handler.
For more info, see on()


Q: Is there a method to setup flink memory dynamically? When using Apache Flink we can configure values in flink-conf.yaml. But here using CLI commands we can assign some values Dynamically when starting or submitting a job or a task in flink.
eg:- bin/taskmanager.sh start-foreground -Dtaskmanager.numberOfSlots=12

But some values like jobmanager.memory.process.size and taskmanager.memory.process.size are unable to set Dynamically using "-D".
Is there a way to set up those values dynamically when starting jobmanager and taskmanager using CLI?

A: May be this might help you :
ParameterTool parameters = ParameterTool.fromPropertiesFile("src/main/resources/application.properties"); // one can specify the properties defined in conf/flink-conf.yaml in this properties file
Configuration config = Configuration.fromMap(parameters.toMap());
TaskExecutorResourceUtils.adjustForLocalExecution(config);

StreamExecutionEnvironment env =
        StreamExecutionEnvironment.getExecutionEnvironment(config);
env.setParallelism(3);

System.out.println("Config Params : " + config.toMap());

Make a note to set the parallelism equal to the number of task slots for task manager as per this link. By default, the number of task slots for a task manager is one.


Q: Fetching npm module from GitHub brings ".git" folder I recently forked an npm package and updated it for my needs. Then, I changed the dependency on packages.json to point to my GitHub repo, and it worked fine. But, when npm installed the module, it brought also the git folder (.git). Because of that, when I try to install anything else, npm gives me this error:
npm ERR! path /node_modules/react-native-static-server
npm ERR! code EISGIT
npm ERR! git /node_modules/react-native-static-server: Appears to be a git repo or submodule.
npm ERR! git /node_modules/react-native-static-server
npm ERR! git Refusing to remove it. Update manually,
npm ERR! git or move it out of the way first.

What am I doing wrong? How do I avoid the .git folder from being downloaded?
You can check the repo here: https://github.com/dccarmo/react-native-static-server
EDIT
The dependency in my packages.json:
"react-native-static-server": "dccarmo/react-native-static-server"

A: This seems to be an old question, but I was running into the same thing today.
I am rather new to git and npm, but I did find something that may be of help to someone.
If the git repo does not have a .gitignore, the .git folder is not downloaded / created.
If the git repo does have a .gitignore, the .git folder is downloaded / created.
I had two repos, one without a .gitignore (because when I made it I was not aware of what .gitignore was or did), and one with a .gitignore. I included both as npm packages in a project, and noticed that the one without the .gitignore was not giving me the EISGIT error (because of the .git folder).
So, after I found this question, I removed the .gitignore from that repo and now it too does not create a .git folder.
Later on, I discovered that adding both a .gitignore and a .npmignore to the project now stops the .git folder from appearing. I did not add .git in my .npmignore.


Q: Linux: access i2c device within board_init function (iMX6 SOC running Linux 3.0)
I need to run a few I2C transactions in my board_init function. I tried calling i2c_get_adapter, then i2c_transfer, those being available in kernel mode, but i2c_get_adapter returns NULL. It's already called imx6q_add_imx_i2c, which is a wrapper around platform_device_register_full, but that isn't enough.
I can manipulate GPIO in board_init by calling gpio_request to obtain access, and gpio_free at the end. Is there something analogous to those functions for i2c?
--- added details ---
I've got a LAN9500A USB 100Base-T Ethernet MAC connected to a LAN9303 3-port switch with a virtual PHY. The MAC has a GPIO reset line that has to be turned off before it will spring to life and enumerate on the USB. That's done in board_init because it's completely nonstandard, so we don't want to patch the stock driver to manipulate some GPIO that's not part of the device.
The problem I'm having is that even though the MAC is permanently attached to the VPHY, it's not noticing it's connected, and an "ip link show eth1" command shows NO-CARRIER. I found I can kickstart it by unmasking the VPHY's Device Ready interrupt via I2C, but I also have to mask it immediately, or I get infinite interrupts. That's not the right solution, but Microchip has been no help in showing me a better way. But we don't want to patch the MAC driver with code to fiddle with the PHY.
There is no PHY driver for this part, and the MII interface to the VPHY doesn't include any interrupt-related registers, so it must be done through I2C. Writing a PHY driver just to flip a bit on and off once seems a lot of trouble, especially for a newbie like me who's never written a driver before.
I can do it in Python in a startup script, but that, too, seems like a heavyweight solution to a lightweight problem.

A: That's a wrong approach. Board file supposed to register device drivers and pass important information to them, rather than act as a device driver itself. I'm not sure if what you're trying to do is even possible.
If you really need to extract something from your I2C device on a very early stage - do that in the bootloader and pass the data to kernel via cmdline (U-boot, by the way, has I2C support for a quite some time). Then later, kernel might do appropriate actions depending on what you have passed to it.


Q: Re-Enable NVidia-Prime Icon in Lower Right Task Bar I am running Linux Mint 18.1 with the Cinnamon desktop on a Dell Inspiron 7559 with NVidia GPU.
I recently messed around with my NVidia packages (installed bumblebee only to quickly uninstall bumblebee due to prime conflicts). After this fiasco, the little NVidia icon on the bottom right of the task bar that indicated which GPU I was using has since disappeared.
I sniffed through the NVidia X Server Settings GUI to see if there was any obvious solution, but I fear I have come up dry. I tried the "Display Status Bar" option but that did nothing.
Is there a way to re-enable this small, but useful icon?

A: When I attempted the bumblebee installation I purged some of my nvidia settings, this included a small piece of software called nvidia-prime-applet.
Reinstalling this software was done by the following:
sudo apt-get install nvidia-prime-applet

And then rebooting.


Q: Calling methods from objects which implement an interface I am trying to wrap my head around interfaces, and I was hoping they were the answer to my question.
I have made plugins and mods for different games, and sometimes classes have onUpdate or onTick or other methods that are overridable.
If I make an interface with a method, and I make other classes which implement the method, and I make instances of the classes, then how can I call that method from all the objects at once?

A: You'll be looking at the Observer pattern or something similar. The gist of it is this: somewhere you have to keep a list (ArrayList suffices) of type "your interface". Each time a new object is created, add it to this list. Afterwards you can perform a loop on the list and call the method on every object in it.
I'll edit in a moment with a code example.
public interface IMyInterface {
    void DoSomething();
}

public class MyClass : IMyInterface {
    public void DoSomething() {
         Console.WriteLine("I'm inside MyClass");
    }
}

public class AnotherClass : IMyInterface {
    public void DoSomething() {
         Console.WriteLine("I'm inside AnotherClass");
    }
}

public class StartUp {
    private ICollection<IMyInterface> _interfaces = new Collection<IMyInterface>();

    private static void Main(string[] args) {
        new StartUp();
    }

    public StartUp() {
        AddToWatchlist(new AnotherClass());
        AddToWatchlist(new MyClass());
        AddToWatchlist(new MyClass());
        AddToWatchlist(new AnotherClass());
        Notify();
        Console.ReadKey();
    }

    private void AddToWatchlist(IMyInterface obj) {
        _interfaces.Add(obj);
    }

    private void Notify() {
        foreach (var myInterface in _interfaces) {
            myInterface.DoSomething();
        }
    }
}

Output:
I'm inside AnotherClass
I'm inside MyClass
I'm inside MyClass
I'm inside AnotherClass

Edit: I just realized you tagged it as Java. This is written in C#, but there is no real difference other than the use of ArrayList instead of Collection.

A: An interface defines a service contract. In simple terms, it defines what can you do with a class.
For example, let's use a simple interface called ICount. It defines a count method, so every class implementing it will have to provide an implementation.
public interface ICount {
    public int count();
}

Any class implementing ICount, should override the method and give it a behaviour:
public class Counter1 implements ICount {
    //Fields, Getters, Setters
    @Overide
    public int count() {
        //I don't wanna count, so I return 4.
        return 4;
    }
}

On the other hand, Counter2 has a different oppinion of what should count do:
public class Counter2 implements ICount {
    int counter; //Default initialization to 0
    //Fields, Getters, Setters
    @Overide
    public int count() {
        return ++count;
    }
}

Now, you have two classes implementing the same interface, so, how do you treat them equally? Simple, by using the first common class/interface they share: ICount.
ICount count1 = new Counter1();
ICount count2 = new Counter2();
List<ICount> counterList = new ArrayList<ICount>();
counterList.add(count1);
counterList.add(count2);

Or, if you want to save some lines of code:
List<ICount> counterList = new ArrayList<ICount>();
counterList.add(new Counter1());
counterList.add(new Counter2());

Now, counterList contains two objects of different type but with the same interface in common(ICounter) in a list containing objects that implement that interface. You can iterave over them and invoke the method count. Counter1 will return 0 while Counter2 will return a result based on how many times did you invoke count:
for(ICount current : counterList)
    System.out.println(current.count());

A: You can't call a method from all the objects that happen to implement a certain interface at once. You wouldn't want that anyways. You can, however, use polymorphism to refer to all these objects by the interface name. For example, with
interface A { }
class B implements A { }
class C implements A { }

You can write
A b = new B();
A c = new C();

A: Interfaces don't work that way. They act like some kind of mask that several classes can use. For instance:
public interface Data {
    public void doSomething();
}

public class SomeDataStructure implements Data {
    public void doSomething()
    {
        // do something
    }
}

public static void main(String[] args) {
    Data mydataobject = new SomeDataStructure();
}

This uses the Data 'mask' that several classes can use and have certain functionality, but you can use different classes to actually implement that very functionality.

A: The crux would be to have a list that stores every time a class that implements the interface is instantiated. This list would have to be available at a level different that the interface and the class that implements it. In other words, the class that orchestrates or controls would have the list.
An interface is a contract that leaves the implementation to the classes that implements the interface. Classes implement the interface abide by that contract and implement the methods and not override them.
Taking the interface to be
 public interface Model {
        public void onUpdate();
        public void onClick();
       }

    public class plugin implements Model {

        @Override
        public void onUpdate() {
            System.out.println("Pluging updating");

        }

        @Override
        public void onClick() {
            System.out.println("Pluging doing click action");

        }
    }

Your controller class would be the one to instantiate and control the action
 public class Controller {

    public static void orchestrate(){
        List<Model> modelList = new ArrayList<Model>();
        Model pluginOne  = new plugin();
        Model plugTwo  = new plugin();
        modelList.add(pluginOne);
        modelList.add(plugTwo);

        for(Model model:modelList){
            model.onUpdate();
            model.onClick();
        }
    }
}

You can have another implementation called pluginTwo, instantiate it, add it to the list and call the methods specified by the interface on it.


Q: Why does multiprocessing use only a single core after I import numpy? I am not sure whether this counts more as an OS issue, but I thought I would ask here in case anyone has some insight from the Python end of things.
I've been trying to parallelise a CPU-heavy for loop using joblib, but I find that instead of each worker process being assigned to a different core, I end up with all of them being assigned to the same core and no performance gain.
Here's a very trivial example...
from joblib import Parallel,delayed
import numpy as np

def testfunc(data):
    # some very boneheaded CPU work
    for nn in xrange(1000):
        for ii in data[0,:]:
            for jj in data[1,:]:
                ii*jj

def run(niter=10):
    data = (np.random.randn(2,100) for ii in xrange(niter))
    pool = Parallel(n_jobs=-1,verbose=1,pre_dispatch='all')
    results = pool(delayed(testfunc)(dd) for dd in data)

if __name__ == '__main__':
    run()

...and here's what I see in htop while this script is running:

I'm running Ubuntu 12.10 (3.5.0-26) on a laptop with 4 cores. Clearly joblib.Parallel is spawning separate processes for the different workers, but is there any way that I can make these processes execute on different cores?

A: Python 3 now exposes the methods to directly set the affinity
>>> import os
>>> os.sched_getaffinity(0)
{0, 1, 2, 3}
>>> os.sched_setaffinity(0, {1, 3})
>>> os.sched_getaffinity(0)
{1, 3}
>>> x = {i for i in range(10)}
>>> x
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> os.sched_setaffinity(0, x)
>>> os.sched_getaffinity(0)
{0, 1, 2, 3}

A: After some more googling I found the answer here.
It turns out that certain Python modules (numpy, scipy, tables, pandas, skimage...) mess with core affinity on import. As far as I can tell, this problem seems to be specifically caused by them linking against multithreaded OpenBLAS libraries.
A workaround is to reset the task affinity using
os.system("taskset -p 0xff %d" % os.getpid())

With this line pasted in after the module imports, my example now runs on all cores:

My experience so far has been that this doesn't seem to have any negative effect on numpy's performance, although this is probably machine- and task-specific .
Update:
There are also two ways to disable the CPU affinity-resetting behaviour of OpenBLAS itself. At run-time you can use the environment variable OPENBLAS_MAIN_FREE (or GOTOBLAS_MAIN_FREE), for example
OPENBLAS_MAIN_FREE=1 python myscript.py

Or alternatively, if you're compiling OpenBLAS from source you can permanently disable it at build-time by editing the Makefile.rule to contain the line
NO_AFFINITY=1

A: This appears to be a common problem with Python on Ubuntu, and is not specific to joblib:

*

*Both multiprocessing.map and joblib use only 1 cpu after upgrade from Ubuntu 10.10 to 12.04

*Python multiprocessing utilizes only one core

*multiprocessing.Pool processes locked to a single core
I would suggest experimenting with CPU affinity (taskset).


Q: Can't uninstall npm module on OSX I have installed cordova on my mac and want to uninstall it.
I've tried the following:
npm uninstall cordova -g

but I get the following error:
npm WARN uninstall not installed in /usr/local/Cellar/node/0.10.32/lib/node_modules: "cordova"

Any ideas?

A: There are know issues with the way homebrew and npm play together. From this article by Dan Herbert

There's an NPM bug for this exact problem. The bug has been "fixed" by
  Homebrew installing npm in a way that allows it to manage itself once
  the install is complete. However, this is error-prone and still seems
  to cause problems for some people. The root of the the issue is really
  that npm is its own package manager and it is therefore better to have
  npm manage itself and its packages completely on its own instead of
  letting Homebrew do it.

Aside from that your node version is out of date. If you can upgrade you should do so to Node v4.1.2. Follow the instructions on the node.js site.


Q: Sum of arrays between specific positions in the array I have two arrays of doubles. For example: {1,2,3} {4,5,6} We are using (x,y) coordinates as (1,4),(2,5) and (3,6) for example. So there are 3 data points in this example. We need to calculate the slope between all of the points and store the slope with the maximum absolute value. To do this I have a function with a 'for' loop inside a 'for' loop. My code is successfully calculating the maximum absolute value slope when I use it in the Main.
We need to find the positions that this max slope occurs at and print out the corresponding positions in array2. I have done this.
Finally there is a third array. We need to calculate the average value of the numbers up to the first point used in the max slope, the average value of the numbers between the first and second points used in the max slope and also the average value of the numbers from the second point used in the max slope to the end of the array.
Does this needs to be done in the main, or does it need its own method?
public static void Main()
{
    List<double> Array1 = new List<double>();
    List<double> Array2 = new List<double>();
    List<double> Array3 = new List<double>();

    Array1.Add(Convert.ToDouble(columns[0]));
    Array2.Add(Convert.ToDouble(columns[1]));
    Array3.Add(Convert.ToDouble(columns[1]));

    int[] positions = GreatestSlopeLocation(Array1, Array2);

    Console.WriteLine("The Location of the max slope is {0} {1}",
        Array2[positions[0]], Array2[positions[1]]);
}

static int[] GreatestSlopeLocation(List<double> x, List<double> y)
{
    int size = x.Count;
    double maxSlope = Double.MinValue; // don't set this to 0
    // consider case when all slopes are  negative
    //
    int index1 = 0;
    int index2 = 0;

    for (int i = 0; i < size; i++)
    {
        for (int j = i + 1; j < size; j++)
        {
            double slope = Math.Abs((y[j] - y[i]) / (x[j] - x[i]));
            if (slope > maxSlope) // I think you want > instead of < here
            {
                maxSlope = slope;
                index1 = i;
                index2 = j;
            }
        }
    }
    return new int[]{index1, index2};
}


Q: Firebase hosting using Old webpack bundle when deployed via GitHub Actions I'm trying to create a GitHub-Action that first uses Webpack to create a bundle.js file and then deploy my index.html and newly created bundle.js to Firebase hosting.
First I just pushed my bundle.js in my GitHub repository, but I since removed it via "git rm --cache public/bundle.js" (not sure if this is the exact command) and added bundle.js to my .gitignore.
The action does work (no error or crash) but it seems that Firebase does not use the newly packaged bundle.js, but instead uses an old version that might be cached somewhere?
firebase-hosting-pull-request.yml:
name: Deploy to Firebase Hosting on PR
'on': pull_request
jobs:
  build_and_preview:
    if: '${{ github.event.pull_request.head.repo.full_name == github.repository }}'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: npm ci && npm run build
      - uses: FirebaseExtended/action-hosting-deploy@v0
        with:
          repoToken: '${{ secrets.GITHUB_TOKEN }}'
          firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT_PROJECTLIBRARIAN }}'
          projectId: projectlibrarian

npm run build in this case executes webpack --mode=production
My index.js (which is webpack'd into bundle.js) only contains a single log statement which I changed to test the GitHub-Action.
Link to the Repo if it helps someone
I'm wondering if I need to clear some kind of GitHub actions cache? or maybe the Firebase deploy action script I'm using isn't doing what I think it should be doing? What confusing me the most is where does Firebase get the old version of bundle.js!

A: Ok I have found two changes that fixed the problem.
Add channelId: live in my workflow yaml
Reload the site with the "Empty chache and Hard reload" developer option.


Q: Javascript: List Files in Directory on Server Is there a way to list all files in a particular directory on the server using Javascript? If so, how? I  am not allowed to use platforms which require server side installation. I mean platforms like node.js and such.

A: Well how would you list the server side files if you have no access to server side ?
"I am not allowed to use platforms which require server side installation."
There are some workarounds for this problem, but these usually needs some extra enabled flags from the user side. http://www.chrome-allow-file-access-from-file.com/

A:
I am not allowed to use platforms which require server side installation.

You need some server side handler for this request. But may be you already have something. For example mod_autoindex for apache..


Q: Integral Involving Cos and Cosh I would like to evaluate the following integral $\int\limits_{0}^{\infty} \dfrac{\cos \left(\omega t\right)}{\cosh ^{\sigma}\left(t\right)} dt$ where $\sigma$ and $\omega$ are positive real constants. If you have noticed this integral in any table or handbook, lease let me know. Thanks for your help...

A: As  @Jack D'Aurizio commented, this involves the Gaussian hypergeometric function.
$$I=\int \cosh ^{-\sigma }(t) \cos ( \omega t )\;dt=\Re \int \cosh ^{-\sigma }(t) e^ {i \omega t})\;dt$$
$$J=\int \cosh ^{-\sigma }(t) \,e^ {i \omega t}\;dt$$ $$J=\frac{\left(e^{2 t}+1\right) e^{i t \omega } \cosh ^{-\sigma }(t)
  }{\sigma +i \omega } \, _2F_1\left(1,\frac{2-\sigma +i \omega }{2} ;\frac{2+\sigma +i \omega }{2};-e^{2 t}\right)$$
$$K=\int_0^\infty \cosh ^{-\sigma }(t)\, e^ {i \omega t}\;dt$$
$$K=\frac{2^{\sigma } }{\sigma
   -i \omega }\,\,\, _2F_1\left(\sigma ,\frac{\sigma -i
   \omega}{2} ;\frac{2+\sigma -i \omega }{2};-1\right)$$


Q: How do I remove duplicate values in a v-for array? I coded like this to remove duplicate values.

vue

       {{member.mem_name}}

vue (script)

  computed: {
    uniqueMemName() {
      return _.uniqBy(this.members, function(m) {
        return m.mem_name;
    });
  }
},

I also installed lodash. But I get an error. Which part is wrong?
Please let me know if there is another method other than the one I wrote.
++) error console
console window
++) array information:
I have tables A and B. Table A imports only the mem_name column. Table B imports all columns.
Example ->

a.mem_name
b.col1
b.col2

mem1
10
20

mem1
30
40

mem2
50
60

I'm working on making duplicate mem_names into one at this time. Using lodash's unique features.

A: If you want to use lodash just for this, which sounds like the case, I suggest that there may be a better way without it, only using newer vanilla JS:
...
  computed: {
    uniqueMemName() {
      return [...new Set(this.members.map(m => m.mem_name))]
    }
  }

Sets are always unique, so mapping and converting to a set and then back to array gives us a unique array.


Q: How do you reference a C# class library from a Win8 Javascript metro application? When I try the standard way it complains of an unsupported reference and I can't seem to use any of my classes.

A: You need to create a Windows Runtime component by creating a class library from the "Visual C#" -> "Windows Metro Style" -> "Class Library" template. Then in the properties for that class library project you need to mark the output type as "WinMD File"
Better instructions can be found here:
http://msdn.microsoft.com/en-us/library/windows/apps/hh779077(v=vs.110).aspx
This isn't stated in the documentation and is probably just a bug with the Windows 8 Consumer Preview and the Visual Studio 11 Beta but be sure not to include a period in the name of the project you're referencing. For instance, I was working on a Car application so I made an assembly named "Car.Business". The application would always crash with a blank startup screen whenever I tried to reference this. If on the other hand I just used "Business" as the name of the assembly then the application would work fine.


Q: How do I reference the Toggle Button Circle and override vertical alignment of the Aero theme Expander? Currently, I am referencing the Aero theme in my App.xml file.
In the main.xml file, I am using expanders to display the content in a resizable width app.
(For this example, I limited the width to 500)
The expander header content generally will be short, but it allows for up to 500 chars.
Depending on the window size (600 pixels by default), the content can wrap (thereby stretching the expander header downwards).
This is fine, but the toggle button (a circle /w arrow) is set for VerticalAlignment=center from what I can tell.
I need a way to override that VerticalAlignment in a style without re-creating the Aero template for the Expander.
I just cant seem to reference the circle and arrow objects.
I have tried overriding Toggle Button as well, with no luck.
As you can see below, I can override some aspects of the Aero Expander.
I just need that little nudge to get the Toggle Button Circle and Arrow objects to change the VerticalAlignment.
Thanks
Code example follows:
<Window.Resources>
    <Style TargetType="{x:Type Expander}" BasedOn="{StaticResource {x:Type Expander}}">
        <Setter Property="Foreground" Value="White" />
        <Setter Property="Background" Value="#464646" />
        <Setter Property="Width" Value="Auto" />
        <Setter Property="Margin" Value="1,0,1,0" />
        <Setter Property="IsExpanded" Value="False" />
    </Style>
</Window.Resources>

<Expander ContextMenu="{StaticResource cMnu}" Width="auto">
    <Expander.Header>
        <StackPanel Orientation="Horizontal" Width="auto" Margin="0">
            <TextBlock Width="65">Normal</TextBlock>
            <TextBlock Width="80">Open</TextBlock>
            <TextBlock Width="80">10/31/2009</TextBlock>
            <TextBlock TextWrapping="Wrap" Width="500">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            Aliquam ultrices auctor magna, sit amet commodo ipsum accumsan eu.
            Sed a mollis felis. Nam ullamcorper augue vel mauris consequat imperdiet.
            Nunc in augue mauris.
            Quisque metus tortor, porttitor nec auctor id, mollis nec ipsum.
            Suspendisse eget ipsum vitae lectus fermentum porta.
            Aliquam erat volutpat.
            Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
            Phasellus congue dui ac arcu eleifend a amet.
            </TextBlock>
        </StackPanel>
    </Expander.Header>
</Expander>

A: If you look at the default template for the Expander, you can see why none of your property setters are working:
<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="20" />
    <ColumnDefinition Width="*" />
  </Grid.ColumnDefinitions>
  <ToggleButton IsChecked="{Binding Path=IsExpanded,Mode=TwoWay,
                RelativeSource={RelativeSource TemplatedParent}}"
                OverridesDefaultStyle="True"
                Template="{StaticResource ExpanderToggleButton}"
                Background="{StaticResource NormalBrush}" />
  <ContentPresenter Grid.Column="1"
                    Margin="4"
                    ContentSource="Header"
                    RecognizesAccessKey="True" />
</Grid>

The ToggleButton's VerticalAlignment is what you are after, and there are no setters for it.
It seems to me that there is no way to change this alignment property through the Style. You must provide a new template.


Q: How to ensure the exception "The calling thread cannot access this object because a different thread owns it"? In C# WPF application, if in the following button click event habdler:
private void start_Click(object sender, RoutedEventArgs e)
{
  for (int i = 2; i < 20; i++)
  {
    var t = Task.Factory.StartNew
    (() =>
         {
            var result=Thread.CurrentThread.ManagedThreadId.ToString();
       //this.Dispatcher.BeginInvoke(new Action(() =>
            textBlock1.Text += "root " + i.ToString() + " " +
            result + Environment.NewLine
       ;//to comment this line if to uncomment th others
       //), null);
          }
     );
  }
}

to uncomment the commented lines, i.e. to output to textblock through Dispatcher.BeginInvoke() then it is filled with varying thread IDs.
Though with commented lines, as shown above, the textblock stays blank and there is no exception thrown.
In similar situation using Parallel.For
private void start_Click(object sender, RoutedEventArgs e)
{
  Parallel.For(2, 6, (i)
     => {
           var result = Thread.CurrentThread.ManagedThreadId.ToString();
           textBlock1.Text += "root " + i.ToString() + " " +
                               result + Environment.NewLine;

         }   );
}

the application breaks with exception:

"The calling thread cannot access this object because a different
  thread owns it"

Why isn't it thrown in first case, while using Task.Factory.StartNew() ?
Any way to ensure this exception?

A: Exceptions thrown in tasks are always handled by the Task object itself. The exception is later rethrown when you, e.g., access the Task.Result property. This way the handling of the exception is left to the thread creating the Task. If you run the first code snippet and look at the Output pane, you'll see that there are multiple first-chance InvalidOperationException logged there. The exceptions are thrown - the tasks just stash them away for later rethrowing.
Parallel.For actually does the same - it stashes away all exceptions occurring within the delegate and then, when the loop is finished, it rethrows all exceptions that occurred in a single AggregateException. You'll notice that the debugger breaks in the thread calling Parallel.For, not within the delegate passed to it.
To cause the exception in the task to propagate to the calling thread, like Parallel.For does, call Wait/WaitAll on the tasks.


Q: Morphia aggregation query to get size of list I am trying to count the number of elements in a list of each document in a collection, similar to below example. (https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size)
db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            numberOfColors: { $size: "$colors" }
         }
      }
   ]
)

This query would return size of list "colors" in each document.
An equivalent morphia query would be something like this :
pipeline =  ds.createAggregation(Abc.class)
                .match(query)
                .project(Projection.projection("count",
                 Projection.expression("$size","colors")));

Error on executing above : java.lang.String cannot be cast to com.mongodb.DBObject
I am unable to arrive at an equivalent morphia query to achieve the same.
Any help in this regard would be greatly appreciated.

A: Change the following lines of code
project(Projection.projection("count",
                 Projection.expression("$size","colors"))

to
Projection.expression("count",new BasicDBObject("$size","$colors")))

A: Did you try
Projection.expression("$size","$colors")));

With dollar before colors?


Q: distinct value of one column based on another column mysql Table structure
Column1 | Column2 | Column 3 | Column 4 . . .. .  Column N

Col1Val1    | Col2Val2    |  . . . . .
Col1Val1    | Col2Val2    | . . . ..
Col1Val1    | Col2Val3    | . . . .
Col1Val2    | Col2Val4    | .  . .
Col1Val3    | Col2Val5    | . .
Col1Val3    | Col2Val6    | . ..

I want to query for all the distinct values of column2 for a every distinct value of column1 and its count & values
Example output should be:
Col1Val1 | Col2Val2,Col2Val3 | 2
Col1Val2 | Col2Val4          | 1
Col1Val3 | Col2Val5,Col2Val6 | 2
.
.

This is pretty much doable from the querying + application handling.
Can this/similar output be achieved via only the sql query.

A: You can use GROUP_CONCAT() to aggregate and count he distinct Column2 values:
SELECT
    Column1,
    GROUP_CONCAT(DISTINCT Column2),
    COUNT(DISTINCT Column2)
FROM yourTable
GROUP BY Column1

Output:

Demo here:
Rextester

A: Try this.
select Column1 , group_concat(distinct column2) ,count(distinct column2)
from your_table
group by column1


Q: Prolog: How to find and remove minimum list element? I am new to Prolog.
I need help writing a predicate which finds and deletes the minimum element in a list.
Thank you very much!

A: If all list items are integers, we can use clpfd!
:- use_module(library(clpfd)).

We define zmin_deleted/2 using maplist/2, (#=<)/2,
same_length/2, and select/3:
zmin_deleted(Zs1,Zs0) :-
   same_length(Zs1,[_|Zs0]),
   maplist(#=<(Min),Zs1),
   select(Min,Zs1,Zs0).

Sample queries:
?- zmin_deleted([3,2,7,8],Zs).
  Zs = [3,7,8]
; false.

?- zmin_deleted([3,2,7,8,2],Zs).
  Zs = [3,  7,8,2]
; Zs = [3,2,7,8  ]
; false.

Note that zmin_deleted/2 also works in the "other direction":
?- zmin_deleted(Zs,[3,2,7,8]).
  _A in inf..2, Zs = [_A, 3, 2, 7, 8]
; _A in inf..2, Zs = [ 3,_A, 2, 7, 8]
; _A in inf..2, Zs = [ 3, 2,_A, 7, 8]
; _A in inf..2, Zs = [ 3, 2, 7,_A, 8]
; _A in inf..2, Zs = [ 3, 2, 7, 8,_A]
; false.

A: Let me google it for you.
How could you find a minimum of a list..
Anyway, there is a nice min_list predicate.
?- min_list([1,2,2,3],X).
X = 1.

Here is a little example how could you remove some element from a list (notice, that all 2s is gone):
?- delete([1,2,2,3],2,X).
X = [1, 3].

If you wanna remove only first occasion of a element, use select:
?- select(2, [2,1,2,2,3], X), !.
X = [1, 2, 2, 3].

So your final answer could be something like that:
delete_min(A, C) :-
  min_list(A, B),
  select(B, A, C), !.

And
?- delete_min([1,1,2,3],X).
X = [1, 2, 3].

A: Again, just use the structural recursion on lists. Lists are built of nodes, [H|T], i.e. compound data structures with two fields - head, H, and tail, T. Head is the data (list element) held in the node, and T is the rest of the list.
We find minimum element by rolling along the list, while keeping an additional data - the minimum element from all seen so far:
minimum_elt([H|T],X):- minimum_elt(T,H,X).

There is no definition for the empty list case - empty lists do not have minimum elements.
minimum_elt([],X,X).

If there are no more elements in the list, the one we have so far is the answer.
minimum_elt([A|B],M,X):-

two cases here: A < M, or otherwise:
    A < M, minimum_elt(B,A,X).

minimum_elt([A|B],M,X):-

    A >= M, minimum_elt(B,M,X).

Nothing more to say about it, so this completes the program.

edit: except, you wanted to also delete that element. This changes things. Hmm. One obvious approach is first find the minimum elt, then delete it. We'll have to compare all elements once again, this time against the minimal element found previously. Can we do this in one scan?
In Lisp we could have. To remove any element from a list, surgically, we just reset the tail pointer of a previous node to point to the next node after the one being removed. Then using this approach, we'd scan the input list once, keeping the reference to the previous node to the minimum element found so far, swapping it as we find the smaller and smaller elements. Then when we've reached the end of the list, we'd just surgically remove the minimal node.
But in Prolog, we can't reset things. Prolog is a set once language. So looks like we're stuck with the need to pass over the list twice ... or we can try to be very smart about it, and construct all possible lists as we go, sorting them out each time we find the new candidate for the smallest element.
rem_min([A|B],L):-
    % two possibilities: A is or isn't the minimum elt
    rem_min(B,A,([A|Z],Z,Z),L).

rem_min([],A,(With,Without,Tail),L):- Tail = [],
    % A is indeed the minimal element
    L = Without.

rem_min([H|T],A,(With,Without,Tail),L):- H >= A, Tail=[H|Z],
    rem_min(T,A,(With,Without,Z),L).

rem_min([H|T],A,(With,Without,Tail),L):- H < A,  % use this H
    copy_the_list(With,Tail,W2,T2),              % no good - quadratic behaviour
    Tail=[H|Z], T2=Z,
    rem_min(T,A,(With,W2,Z),L).

copy_the_list([A|B],T,[A|C],C):- var(B), !, T=B.            % fresh tail
copy_the_list([A|B],T,[A|C],T2):- copy_the_list(B,T,C,T2).

So looks like we can't avoid the second pass, but at least we can save all the superfluous comparisons:
rem_min([A|B],L):- N=[A|_], rem_min(B,A,N,[N|Z],Z,L).

rem_min([],_A,N,L2,Z,L):- Z=[], N=[_,1], % finalize the minimal entry
    scan(L2,L).
rem_min([H|T],A,N,L2,Z,L):- H >= A, Z=[H|Z2], rem_min(T,A,N,L2,Z2,L).
rem_min([H|T],A,N,L2,Z,L):- H < A,       % use this H
    N2=[H|_], N=[_],                     % finalize the non-minimal entry
    Z=[N2|Z2], rem_min(T,H,N2,L2,Z2,L).

scan( [], []).
scan( [[_,1]|B],C):- !, scan(B,C).       % step over the minimal element
scan( [[A]|B],[A|C]):- !, scan(B,C).     % previous candidate
scan( [A|B], [A|C]):- !, scan(B,C).


Q: Compare two NSDate by .Day in swift is giving wrong results Im trying to compare two NSDate by .Day doing this (both on gmt timezone):
 var order = NSCalendar.currentCalendar().compareDate(event.startDate!, toDate: cell.date!,
                    toUnitGranularity: .Day)
                    if (order == .OrderedSame) {
                            print(String(event.startDate!) + " == " + String(cell.date!))
                        cell.events.append(event)
                        break
                    }

When using 2016-03-08 21:43:53 +0000 and 2016-03-09 00:00:00 +0000 it says they are orderedSame, but they arent, the days are different. This function outputs:
 2016-03-08 21:43:53 +0000 == 2016-03-09 00:00:00 +0000

Can someone help me please?

A: Those two logged dates are being logged in the UTC timezone. But if your current timezone is west of that, then both dates are on March 8, 2016 in your timezone and the comparison is done in your timezone. Or, if you live east of that by at least 2.5 hours, then both dates are March 9, 2016.
Example. If you live in the eastern USA (GMT-4 currently but GMT-5 on March 8), then those two dates are actually 2016-03-08 16:43:53 -0500 and 2016-03-08 19:00:00 -0500.
Example. If you live in eastern Europe or Asia (say GMT+5), then those two dates would be 2016-03-09 02:43:53 +0500 and 2016-03-09 05:00:00 +0500.
As you can see, those are on the same day so the comparison is correct.


Q: iFrame disappears on Internet Explorer A friend of mine created a simple web site using iWeb and added an iFrame to one of the pages. iWeb seems to be loading iFrames through a series of Javascript libraries and CSS files (quite strange). But whenever I look at this page on IE, the iFrame disappears after a few seconds: http://bit.ly/fD7QGD
Does anyone know what could be causing this buggy behavior on IE?
Thanks,
Ralph

A: Well, I tried it on Firefox, Chrome and IE and waited more than 1 minutes. It didn't disappear.
Maybe there's a problem with your browser or it was a temporary bug.


Q: LibGDX 3d mesh transformation my intention is to make the "liquid" 3d structure, which is dynamically changing. The idea is to make it as the array of meshes and then change the elevation of the points of meshes.
So, my question is how to transform the mesh by setting the vertices Y variable? And is it even possible in LibGDX?


Q: Catch throw error from node module I am using a module which throws an error in case something is wrong. The error is not being returned as part of the callback and the run is being stopped when is thrown.
I am calling it like this:
co(function*(){
  try{
    for (let item of items){
       item.newValue = yield myFunction(param)
    }
  }catch(err){
  }
}

myFunction: function(param){
return new Promise(function(resolve, reject){
   module.callMethod(param), function(result){
     if (result)
         resolve(result)
  }else{
      reject('err')}
}
}

During callMethod I get a throw error but it is not caught on the co try and I'd like in case of a error to catch it but allow the for loop to continue.
How can I properly catch the thrown error?

A:
I'd like in case of a error to catch it but allow the for loop to
  continue

Promise constructor should treat errors thrown inside executor as promise rejection.

MDN If an error is thrown in the executor function, the promise is
  rejected.

So moving try-catch inside for loop should work.
.

'use strict'
co(function*() {
  for (let item of [1, 2, 3, 4]) {
    try {
      const newValue = yield myFunction(item)
      console.log(newValue)
    } catch (e) {
      console.error(e.message)
    }
  }
})

function callMethod(param, cb) {
  if (param % 2) cb('Success')

  throw new Error(`Invalid param ${param}`)
}

function myFunction(param) {
  return new Promise(function(resolve, reject) {
    callMethod(param, function(result) {
      if (result) {
        resolve(result)
      } else {
        reject('err')
      }
    })
  })
}
<script>
  const module = {}
</script>
<script src="https://unpkg.com/co@4.6.0/index.js"></script>


Q: Can't run jar file of JavaFx application on Linux I created JavaFx application on Windows.Then created jar file which works normal on windows.But when i try run this jar on Linux Mint i get this log:
нояб. 07, 2022 3:15:00 PM com.sun.javafx.application.PlatformImpl startup
WARNING: Unsupported JavaFX configuration: classes were loaded from 'unnamed module @6a7840b4'
java.lang.ClassNotFoundException: com.sun.glass.ui.gtk.GtkPlatformFactory
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
 at java.base/java.lang.Class.forName0(Native Method)
 at java.base/java.lang.Class.forName(Class.java:375)
 at com.sun.glass.ui.PlatformFactory.getPlatformFactory(PlatformFactory.java:42)
 at com.sun.glass.ui.Application.run(Application.java:146)
 at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:291)
 at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:293)
 at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:163)
 at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:659)
 at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:679)
 at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
 at java.base/java.lang.Thread.run(Thread.java:833)
Failed to load Glass factory class
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.sun.glass.ui.PlatformFactory.createApplication()" because the return value of "com.sun.glass.ui.PlatformFactory.getPlatformFactory()" is null
 at com.sun.glass.ui.Application.run(Application.java:146)
 at com.sun.javafx.tk.quantum.QuantumToolkit.startup(QuantumToolkit.java:291)
 at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:293)
 at com.sun.javafx.application.PlatformImpl.startup(PlatformImpl.java:163)
 at com.sun.javafx.application.LauncherImpl.startToolkit(LauncherImpl.java:659)
 at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:679)
 at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
 at java.base/java.lang.Thread.run(Thread.java:833)

I installed on Linux openjfx and i have openjdk 17.0.4.
Please, i'm waiting any help.


Q: Flask SQLAlchemy pagination error I have this code and the all() method and every other method works on this and I have looked all over and I could that the method paginate() works on BaseQuery which is also Query
@app.route('/')
@app.route('/index')
@app.route('/blog')
@app.route('/index/<int:page>')
def index(page = 1):
    posts = db.session.query(models.Post).paginate(page, RESULTS_PER_PAGE, False)
return render_template('index.html', title="Home", posts=posts)

but this gives me the error AttributeError: 'Query' object has no attribute 'paginate'
I've looked everywhere and I can't find any solution to this.

A: From your question...
that the method paginate() works on BaseQuery which is also Query

I think this is where you're being confused. "Query" refers to the SQLAlchemy Query object. "BaseQuery" refers to the Flask-SQLALchemy BaseQuery object, which is a  subclass of Query. This subclass includes helpers such as first_or_404() and paginate(). However, this means that a Query object does NOT have the paginate() function. How you actually build the object you are calling your "Query" object depends on whether you are dealing with a Query or BaseQuery object.
In this code, you are getting the SQLAlchemy Query object, which results in an error:
db.session.query(models.Post).paginate(...)

If you use the following code, you get the pagination you're looking for, because you are dealing with a BaseQuery object (from Flask-SQLAlchemy) rather than a Query object (from SQLAlchemy).
models.Post.query.paginate(...)


Q: Field Dao in DaoImpl required a bean named 'entityManagerFactory' that could not be found I have error message as follows:
***************************
APPLICATION FAILED TO START
***************************

Description:

Field visitorDao in com.ahmed.service.VisitorDaoImpl required a bean named 'entityManagerFactory' that could not be found.

Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.

Please have the classes as below. I am unable to understand what compiler wants to say.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>landon-hotel-event-mgmt-app</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.0.5.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
            <!--<scope>test</scope>-->
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!--         jsr303 validation
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.3.Final</version>
        </dependency>-->
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
        <hibernate.version>5.2.17.Final</hibernate.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <name>Ahmed Visitor application</name>
</project>

Here are the classess.
package com.ahmed.service;

import com.ahmed.dao.VisitorDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VisitorDaoImpl {

    @Autowired
    VisitorDao visitorDao;

}

Here is another....
package com.ahmed.dao;

import com.ahmed.domain.Visitor;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 *
 * @author abhiramagopaladasa
 */
@Repository
public interface VisitorDao extends CrudRepository<Visitor, Integer>{
    List<Visitor> findByOutTime(LocalDateTime outTime);
    List<Visitor> findByInTime(LocalDateTime outTime);

}

I also have the HibernateConfiguration class as such:
[![/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ahmed.configuration;

import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 *
 * @author abhiramagopaladasa
 */

@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ahmed.domain" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {
    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String\[\] { "com.ahmed.domain" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManager = new HibernateTransactionManager();
       txManager.setSessionFactory(s);
       return txManager;
    }

}][1]][1]

Any help will be greatly appreciated. According to me I have already done everything required. I dont know what I am missing. Do I need to have another class configuring the entityManager or something?


Q: Is there a keyboard shortcut to minimize the Prosperworks CRM sidebar in Gmail? In Gmail, the Prosperworks Chrome Extension takes up a lot of space on the side. It auto-expands upon a new pageload which is really annoying when I don't want to use it.

A: You can create a "custom search engine" to easily minimize the sidebar with a keyboard shortcut.

*

*go here: chrome://settings/searchEngines

*scroll to "Other Search Engines", and click "ADD"

*
*

*Name it whatever you want. Search engines are listed alphabetically so I named mine "zzz Minimize Prosperworks" to make it easy to find.

*Keyword: i. This is the keyboard shortcut you'll use to shut the Prosperworks sidebar. I use "i" because it's close to resting hand position.

*URL with %s in place of query: javascript:document.getElementsByClassName('PWExtensionFrame_toggleIcon')[0].click();

*Now, when you want to minimize the Prosperworks sidebar, you:

*

*⌘ + L to select the URL bar,

*i to invoke the custom search bar,

*enter to execute it.


Q: What does this hand gesture mean? I was watching this video in which someone made a gesture with his hand, he pointed his fingers except the thumb at himself and started moving his hand to the left and to the right.

I have seen the same gesture made here by one of the The X Factor judges when he wanted the music to stop while a contestant was singing.

Could you tell me what this gesture is called and what it means?

A: That action is used to convey a relatively negative message when trying to be silent, sort of a "stop it right now, or else" or "nope, nope, nope".
The motion looks like cutting one's throat with their hand, which can be like "I will do this to you if you don't stop right now", or "you're dead".  While not to be taken literally (they will not actually do that to you, of course), the message the person is usually trying to convey with this motion is to stop what you are doing immediately.


Q: Let $f : X → X$ be an injective map such that $f ( X ) \neq X$ . Show that: a. The set $X$ is infinite.
b. For $x\in X-f(X)$, the elements $x, f(x), f(f(x)), \ldots$ are pairwise distinct.
I came across this problem while looking online for some abstract math problems to do and I have no clue how to solve it.
For a, I said:
Suppose that $X$ is finite, meaning that there is a finite number of elements and is injective, then $f(x):X \rightarrow X$ is also contains $n$ distinct elements and is contained in $X$ based on the definition of a finite set. However, the prompt says that $f ( X ) \neq X$, therefore $X$ cannot be finite.
For b, I have no clue.

A: For b, use a proof by induction.  Define $f^0(x)=x$ and define $f^i(x)$ to mean $f$ composed with itself $i$ times.  Our base case is easy because, by assumption, we know that $x$ and $f^1(x)$ are pairwise distinct.
Now assume as our inductive hypothesis that $\{ x, f^1(x), f^2(x), \ldots f^n(x) \}$ are pairwise distinct.  Assume $f^{i+1}(x)=f(f^i(x))=f^{n+1}(x)=f(f^n(x))$.  Then because $f$ is injective, we also know that $f^i(x) = f^n(x)$, which can't happen because our inductive hypothesis is that those elements are part of a pairwise distinct set.  Alternatively, if $x=f^{n+1}(x)=f(f^n(x))$, then $x \in \operatorname{range}(f)$, contradicting our assumption that $x \in X \setminus f(X)$.

A: Suppose that, say $f(f(x))=f(f(f(f(x))))$. Since $f$ is injective, it follows that $f(x)=f(f(f(x)))$. Now, again because $f$ is injective, $x=f(f(x))$. But this is impossible, since $x\in X\setminus f(X)$.

A: Suppose $f^{i}(x)=f^{j}(x)$ with $i <j$. [ $f^{i}$'s are the function obtained by composing $f$ with itself repeatedly]. Use injectivity of $f$ to conclude that $x=f^{j-i}(x)$. But then  $x \in f(X)$ which is  a contradiction.


Q: Why did jupyter server fail in VS code? I had this problem for a while now. I am trying to work on Jupyter Notebooks on VS code, but the jupyter server doesn't connect when I open VS code directly, but it works when I open VS code from Anaconda. Here is the error message:
Activating Python 3.7.4 64-bit ('base': conda) to run Jupyter failed with Error: StdErr from ShellExec, tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
tput: No value for $TERM and no -T specified
 for . /Users/jingzhaogao/opt/anaconda3/bin/activate && conda activate base && echo 'e8b39361-0157-4923-80e1-22d70d46dee6' && python /Users/jingzhaogao/.vscode/extensions/ms-python.python-2020.6.88468/pythonFiles/pyvsc-run-isolated.py /Users/jingzhaogao/.vscode/extensions/ms-python.python-2020.6.88468/pythonFiles/printEnvVariables.py.

Please assist.

A: Unfortunately there's nothing to specifically do here other than continue to open VS Code from the activated conda environment. Conda simply wants to own the environment you work from and those settings need to propagate into the one VS Code works from to make conda work.


Q: Identifying Windows Active Directory Connection - Windows 8 Is there a way from within a Windows 8 store app (C#) to either identify that the OS is Windows 8 Pro or Enterprise edition?  Can you also check to see if the OS has the capability to connect to an AD domain?
I have found other posts saying that it isn't possible to find the version of Windows, and the posts suggest checking for capabilities.  I have not been able to find any information on how to check if the user is connected to a domain or not.

A: You can call UserInformation.GetDomainNameAsync to determine if the user is part of a domain.  The app must declare the Enterprise Authentication app capability.
To determine if you are on Pro, you might be able to call GetNativeSystemInfo and figure it out from the processor architecture.


Q: Python assert -- Best way to report non-existing files in a list with one line Background
I use assert statement to check if certain files in a list exist in my computer, then I would like to do further work if these files are all there.
I've referenced to this thread, so I do something like this:
from pathlib import Path

# The list containing several filepaths
files = ['folder/file1', 'folder/file2', 'folder/file3']

# check if all of these files are exist
assert all(Path(n).exists() for n in files)

# Do something else ...
# ...

This piece of code is runnable. If one file does not exist, the program will raise AssertionError.
Question
Now I would like to all the file(s) that not exist, instead of a simple AssertionError.
Is there any one-liner solution for this?
What I have tried
I've tried the following:
assert all(Path(n).exists() for n in files), f"file {n} not exist!"

Runing this code will report NameError: name 'n' is not defined.

A: You'll need to use a loop:
for file in files:
    assert Path(file).exists(), f"{file} does not exist!"

In Python 3.8+, you can do it in one line by using the walrus operator:
assert not (missing_files := [n for n in files if not Path(n).exists()]), f"files missing: {missing_files}"

A: n from comprehension isn't in scope where you do f'{n}'
You can show all not exists files
not_exists = [f for f in files if not Path(f).exists()]
assert not not_exists, f'Files {not_exists} not exist'

Or, only the first one
for f in files:
  assert Path(f).exists(), f'{f} not exists'

A: As already pointed out in comments, assert is strictly a development tool. You should use an exception which cannot be turned off for any proper run-time checks; maybe create your own exception for this. (Assertions will be turned off in production code under some circumstances.)
Secondly, the requirement to do this in a single line of code is dubious. Code legibility should trump the number of lines everywhere, except possibly in time-critical code, where execution time trumps both.
class MissingFilesException(Exception):
   pass

missing = {x for x in files if not Path(x).exists()}
if missing:
    raise MissingFilesException(
        'Missing files: {}'.format(", ".join(missing))


Q: Determining what action an NPC will take, when it is partially random but influenced by preferences? I want to make characters in a game perform actions that are partially random but also influenced by preferences.  For instance, if a character feels angry they have a higher chance of yelling than telling a joke.  So I'm thinking about how to determine which action the character will take.  Here are the ideas that have come to me.
Solution #1: Iterate over every possible action.  For each action do a random roll, then add the preference value to that random number.  The action with the highest value is the one the character takes.
Solution #2: Assign a range of numbers to an action, with more likely actions having a wider range.  So, if the random roll returns anywhere from 1-5, the character will tell a joke.  If it returns 6-75, they will yell.  And so on.
Solution #3: Group all the actions and make a branching tree.  Will they take a friendly action or a hostile action?  The random roll (with preference values added) says hostile.  Will they make a physical attack or verbal? The random roll says verbal.  Keep going down the line until you reach the action.
Solution #1 is the simplest, but hardly efficient.  I think Solution #3 is a little more complicated, but isn't it more efficient?
Does anyone have any more insight into this particular problem?  Is #3 the best solution? Is there a better solution?

A: #1 and #2 are simple but probably won't scale well to more complicated behaviors. Behavior trees (#3) seem to be the preferred system in many games nowadays. You can find some presentations and notes on AiGameDev.com, e.g. http://aigamedev.com/open/coverage/paris09-report/#session3 and http://aigamedev.com/open/coverage/gdc10-slides-highlights/#session2 (the first one from Crytek is quite good)
You probably don't need to worry about "efficiency" here in the sense of CPU usage, since this is very unlikely be a major bottleneck in your game. Reducing the amount of programmer/designer time needed to tweak the behavior is much more important.

A: If you're going to go with options 1 or 2, look into buckets of random results - see Randomness without Replacement.  If you go with a tree action, you can still use some of the same concepts to determine which branch of the tree to go down; however, you'd have a bit more determinism built in, as your options will restrict as you traverse down the tree.
If I recall correctly, Neverwinter Nights, which had a fairly nice scripting engine for its NPCs, would use a random probability to determine some of the actions their NPCs would take in certain states, but the states themselves were more driven by the script for that NPC (more of a state machine than a tree, but the concepts are similar).  For example, if the NPC was walking, there was a chance they would stop, maybe laugh, etc. - but if they were attacked, they would switch to combat and stay there.
In other words, it all depends on what your actions are, and how you want the character to behave.

A: Markov chain, influenced by real user actions.
From wikipedia:

A Markov chain is a discrete random
  process with the property that the
  next state depends only on the current
  state.


Q: javascript function internal scope property What is the Difference in internal scope property assigned on function declaration and on entering the function execution context?
Definition:
[[Scope]] property is already written and stored in function object. [[Scope]] in contrast with Scope (Scope chain) is the property of a function instead of a context.
Link:(http://dmitrysoshnikov.com/ecmascript/chapter-4-scope-chain/#function-creation)
What i mean is :as soon as function gets declared will it be assigned scope property or during execution time will scope property gets assigned.

A: This is the closure concept.  It is worded differently here than normal.  Basically there are two things going on -- first you have the closure, that is the variables that are declared locally to the context of the function definition are made available to the function.  This is the "scope chain" he refers to.  In addition, locally defined variables (var statements within the function) don't exist until the function starts at "execution context".  (Typically these are stored on the stack or a heap).


Q: Does Fermat's Last Theorem hold for cyclotomic integers in $\mathbb{Q(\zeta_{37})}$? The first irregular prime is 37. Does FLT(37)
$$x^{37} + y^{37} = z^{37}$$
have any solutions in the ring of integers of $\mathbb Q(\zeta_{37})$, where $\zeta_{37}$ is a primitive 37th root of unity?
Maybe it's not true, but how could I go about finding a counter-example? (for any cyclotomic ring, not necessarily 37)

A: This question was answered in mathoverflow. I am writing this to close up this question and making this answer as a community wiki according to MSE's guidelines. The answer is due to Tauno Metsänkylä.


Q: Bluebird promises and async.forEach iteration This is my first time asking a question, so please bear with me. I'm trying to write a content scraper in node.js. My program will go to the landing page of the site, get the link to the next page and get the link for the next batch of pages. My problem is when I have to cycle through an array of links, go to that page, and get scrape information there. I'm trying a async.forEach iteration, but it finishes after the last then() in my chained promises.  Many of the concepts here are new to me, so I'm sure this code is screwy. Any help would be appreciated.

var sX = require('scraper-x');
var request = require('request');
var async = require('async');
var Promise = require('bluebird');
var request = (require('request'));
var colors = require('colors');

var baseURL = 'http://shirts4mike.com';
var arrShirts = [
    {
        link: 'shirt.php?id=101',
        img: 'some img'
    },
    {
        link: 'shirt.php?id=102',
        img: 'some img'
    },
    {
        link: 'shirt.php?id=103',
        img: 'some img'
    }
];

var page = '';

var configMain = {
    repeatItemGroup: '.nav > li',
    dataFormat: {
        link: {
            selector: 'li > a',
            type: 'attr:href'
        }
    }
};

var configShirts = {
    repeatItemGroup: '.products > li',
    dataFormat: {
        link: {
            selector: 'li > a',
            type: 'attr:href'
        },
        img: {
            selector: 'li > a > img',
            type: 'attr:src'
        }
    }
};

var configDetails = {
    repeatItemGroup: '.shirt-details',
    dataFormat: {
        price: {
            selector: '.price',
            type: 'text'
        },
        title: {
            selector: '.shirt-details > h1',
            type: 'text'
        }
    }
};

function getPage(url, config) {
    return new Promise(function(resolve, reject) {
        request(url, function(error, response, body, shirt) {
                if (error) {
                    console.log('error');
                    reject();
                }
                if (!error && response.statusCode == 200) {
                    detail = sX.scrape(body, config);
                    resolve(detail);
                }
            });

    });
}

function getDetailPage(arr, config) {
    return new Promise(function(resolve, reject) {
        async.forEach( arr, function( item, callback) {
            request('http://www.shirts4mike.com' + '/' + item.link, function(error, response, body, item) {
                if (!error && response.statusCode == 200) {
                    detail = sX.scrape(body, configDetails);
                    console.log('Item: ', detail);
                }
            });
           callback();
        });
        resolve(detail);
    });
}

    getPage(baseURL, configMain).then( function(data) {
        for (var i = 0; i < data.length; i++) {
            //console.log('getMainPage: ', scrapedResult[i].link);
            if (data[i].link.search('shirt') !== -1) {
                page = '/' + data[i].link;
                console.log(page.yellow);
                baseURL += page;
                return baseURL;
            }
        }
    }).then( function(baseURL) {
        return getPage(baseURL, configShirts);
    }).then( function(data) {
        for (var i = 0; i < data.length; i++) {
            //console.log(data[i].link);
            if (data[i].link.search('shirt') !== -1) {
                arrShirts.push(data[i]);
                console.log("arrShirts[" + i + "]: " + arrShirts[i].link);
            }
        }
        return arrShirts;
    }).then( function(arr) {
        return getDetailPage(arrShirts, configDetails);
    }).then(function (data) {
        console.log("end: ", data);
    }).catch( function(err) {
        console.log(err);
    });

A: I would suggest a bunch of changes.

*

*Stop using globals or higher scoped variables or undeclared variables.  Declare local variables where they are used/needed and don't share variables with other functions.

*Don't mix the async library with promises.  Since you're already promisifying your async functions, then use promise functions to manage multiple async operations.  You can just remove the async library from this project entirely.

*Promisify at the lowest level that is practical so all higher level uses can just use promises directly.  So, rather than promisifying getPage(), you should promisify request() and then use that in getPage().

*Since you have the Bluebird promise library, you can use it's higher level iteration functions such as Promise.map() to iterate your collection, collect all the results and return a single promise that tells you when everything is done.
Using these concepts, you can then use code like this:
// promisified request()
function getRequest(url) {
    return new Promise(function(resolve, reject) {
        request(url, function(err, response, body) {
            if (err) {
                reject(err);
            } else {
                resolve(body);
            }
        });

    });
}

// resolves to scraped contents for one page
function getPage(url, config) {
    return getRequest(url).then(function(body) {
        return sX.scrape(body, config);
    });
}

// resolves to an array of scraped contents for an array of objects
// that each have a link in them
function getDetailPage(arr, config) {
    return Promise.map(arr, function(item) {
        return getPage('http://www.shirts4mike.com' + '/' + item.link);
    });
}


Q: Using "this" in a jquery multiple selector Im trying to figure this one out, but no joy yet. For reasons that I cant go into here, I need to use both "this" and another selector to bind a click event.. Example
    $('mySelector').each(function(){
    $(this, this.siblings('img')).bind('click', function(e){
        e.preventDefault();
        doStuffTo($(this));
    });
});

But I cant figure out how to do it. Anyone have any idea how I would achieve it?

A: Most of the jQuery methods (that don't return a value) are automatically applied to each element in the collection, so each() is not necessary.
Combining siblings() and andSelf(), the code can be simplified to:
$('.mySelector').siblings('img').andSelf().click(function (e) {
    e.preventDefault();
    doStuffTo($(this));
});

A: Instead, you could do this:
$('mySelector').each(function(){
    $(this).siblings('img').andSelf()).bind('click', function(e){
        e.preventDefault();
        doStuffTo($(this));
    });
});

A: It's not entirely clear what you're trying to do, but perhaps it's this:
var f = function(e){
    e.preventDefault();
    doStuffTo($(this));
};

$('mySelector').each(function() {
   $(this).bind('click', f);
   $(this).siblings('img').bind('click', f);
});


Q: When eliminating the lambda expressions from this grammar, are we missing a production? I'm working on converting this grammar to CNF (Chomsky Normal Form).
S-> abAB
A-> bAB | lambda
B-> BAa | A | lambda

So I started off by eliminating the lambda productions, and in doing so I got this:
S-> abAB | abB | abA | ab
A-> bAB  | bA  | bB  | b
B-> BAa  | A   | Ba  | Aa  | a

I went a little bit further into the conversion process and ran into an issue of adding more unit productions than necessary, so I went and checked the answer key to see what I missed and it turns out that when we remove the lambdas, the following productions are not correct:
S-> ab
A-> b
B-> a

I would like to know why because it is not obvious to me yet. If we are looking at the production:
A-> bAB

and A and B can produce lambda, then we are just simply left with b correct? So why is it not a part of our production after eliminating lambda?
After the $\lambda$ eliminination the key has the following grammar:
S-> abAB | abA | abB
A-> bAB  | bA  | bB
B-> BAa  | A   | Ba  | Aa


Q: Simulating multivariate time series with seasonality Let's say I have a seasonal multivariate time series xyz with seasonal order 12:
x <- rnorm(100, 1)
y <- rnorm(100, 30)
z <- rnorm(100, 500)

xyz <- data.frame(x, y, z)
ts <- ts(xyz, frequency = 12)

I estimated VAR model using VAR function from the vars package:
model <- vars::VAR(xyz, p = 1, type = 'const', season = 12)

How do I simulate new seasonal multivariate time series using this estimated model?