text:
Q: Tree Shaking with webpack 3 doesn't work I just upgraded webpack in my react project from version 1 to the latest (3.5.5).
I followed the migration guide and there were no problems, however apparently tree shaking isn't applied to my bundle (all of aws-sdk is included in the bundle,even though I imported only the s3 module).
This is my webpack configuration:
webpack.config.base.js
const paths = require('./paths')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  resolve: {
        modules: [
         paths.appSrc,
         paths.appNodeModules
        ]
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'eslint-loader',
        include: paths.appSrc,
      },
          {
        exclude: [
          /\.html$/,
          /\.(js|jsx)$/,
          /\.(scss|sass)$/,
          /\.css$/,
          /\.json$/,
          /\.svg$/
        ],
        use: {
          loader: 'url-loader',
          query: {
            limit: 10000,
            name: 'static/media/[name].[hash:8].[ext]'
          }
        },

  },
  {
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    use: {
      loader: 'babel-loader',
      query: {
        cacheDirectory: true,
        presets: [
          'react',
          ['es2015', { modules: false }],
          'stage-1',
        ],

      }
    }
  },
  {
    test: /\.svg$/,
    use: {
      loader: 'file-loader',
      query: {
        name: 'static/media/[name].[hash:8].[ext]'
      }
    }
  }
],
},
plugins: [
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml
    })
  ]
}

webpack.config.prod.js
const webpack = require('webpack')
const merge = require('webpack-merge')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const InterpolateHtmlPlugin = require('react-dev-
utils/InterpolateHtmlPlugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const ShakePlugin = require('webpack-common-shake').Plugin;
const url = require('url')
const paths = require('./paths')
const baseConfig = require('./webpack.base')

function ensureSlash(path, needsSlash) {
  const hasSlash = path.endsWith('/')
  if (hasSlash && !needsSlash) {
    return path.substr(path, path.length - 1)
  } else if (!hasSlash && needsSlash) {
    return path + '/'
  } else {
    return path
  }
}

const homepagePath = require(paths.appPackageJson).homepage
const homepagePathname = homepagePath ? url.parse(homepagePath).pathname : '/'
const publicPath = '.' + ensureSlash(homepagePathname, true)
const publicUrl = '.' / +ensureSlash(homepagePathname, false)

const clientConfig = {
  name: 'client',
  bail: true,
  devtool: 'cheap-module-source-map',
  entry: [
    require.resolve('./polyfills'),
    paths.appIndexJs
  ],
  output: {
    path: paths.appBuild,
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    publicPath: publicPath
  },
  module: {
    rules: [
      {
        test: /\.(sass|scss)$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: "css-loader"
            },
            {
              loader: "resolve-url-loader"
            },
            {
              loader: "sass-loader?sourceMap"
            }],
          publicPath: publicPath
        })
      },
    ]
  },
  plugins: [
    new InterpolateHtmlPlugin({ PUBLIC_URL: publicUrl }),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    }),
    new UglifyJsPlugin({
      sourceMap: true,
      minimize: true,
      compress: {
        screw_ie8: true,
        warnings: false
      },
      mangle: {
        screw_ie8: true
      },
      output: {
        comments: false,
        screw_ie8: true
      }
    }),
    new ExtractTextPlugin('static/css/[name].[contenthash:8].css'),
    new ShakePlugin()
  ]
}

module.exports = merge(baseConfig, clientConfig)

I 've tried many different configs but nothing seems to work, does anyone have an idea of what I'm doing wrong?


text:
Q: Google Drive Api service accounts without Google Apps I am trying to build connector for my google drive account via google api oauth service account. I am using official gooogle client libraries for java.

public static Drive getDriveService() throws GeneralSecurityException,
            IOException, URISyntaxException {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        GoogleCredential credentials = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(JacksonFactory.getDefaultInstance())
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(Arrays.asList(new String[]{DriveScopes.DRIVE}))
                .setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
                .setServiceAccountUser(ACCOUNT_USER)
                .build();
        Drive service = new Drive.Builder(httpTransport, JacksonFactory.getDefaultInstance(), credentials)
                .setHttpRequestInitializer(credentials).build();
        return service;
    }

It's pretty much basic sample from docs. Problem is it does not work. After execution I got NullPointerException on json deserialization.
So I debug this code with source code to google libraries and I found that httpRequest for access token returns status code 401 and content is null. I used same approach for Google Calendar API and it works without any problems.
Could someone tell me what I am doing wrong? Or is there another way to access my files without user interaction? thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Volley onResponse does not execute :( I would like to check the user existence and return the result, however the onResponse() does not implement before returning the isUserExist, could anyone can advise how to fix? :)
// Check existence of email address
private boolean verifyEmail(String email) {
    isUserExist = false;

    loginURL = Uri.parse(loginURL).buildUpon()
            .appendQueryParameter("email",email)
            .build().toString();

    GsonRequest<StaffUser> gsonRequest = new GsonRequest<StaffUser>(loginURL, StaffUser.class, null,
            new Response.Listener<StaffUser>() {
                @Override
                public void onResponse(StaffUser response) {
                    if (response != null) {
                        Log.i(TAG, "staffUserId: " + response.getStaffUserId());
                        isUserExist = true;
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO: Handle error
            Log.e(TAG, "VolleyError: " + error);
        }
    }
    );

    // Access the RequestQueue through your singleton class.
    MySingleton.getInstance(this).addToRequestQueue(gsonRequest);

    return isUserExist;
}

A: you have to create interface and pass listner to verifyEmail method that provide verify response in callback method.
Add interface for callback
public interface VerifyEmailListner {
    void onResponse(boolean success);
}

change your method like this,set void return type instead of boolean
private void verifyEmail(String email,final VerifyEmailListner listner) {
    isUserExist = false;

    loginURL = Uri.parse(loginURL).buildUpon()
            .appendQueryParameter("email",email)
            .build().toString();

    GsonRequest<StaffUser> gsonRequest = new GsonRequest<StaffUser>(loginURL, StaffUser.class, null,
            new Response.Listener<StaffUser>() {
                @Override
                public void onResponse(StaffUser response) {
                    if (response != null) {
                        Log.i(TAG, "staffUserId: " + response.getStaffUserId());
                        listner.onResponse(true);
                        isUserExist = true;
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO: Handle error
            Log.e(TAG, "VolleyError: " + error);
            listner.onResponse(false);
            isUserExist = false;
        }
    }
    );
    // Access the RequestQueue through your singleton class.
    MySingleton.getInstance(this).addToRequestQueue(gsonRequest);
}

call method like this
  verifyEmail("abc@gmail.com",new VerifyEmailListner () {
        public void onResponse(boolean success){
            if(success){
                // verified
            } else{
              // not verified
            }
        }
    });

A: You have to use listener for Response detection
Because Volly is Asyncronous
https://developer.android.com/training/volley

*

*Strong ordering that makes it easy to correctly populate your UI with
data fetched asynchronously from the network.

So you have to use listener handle responce
see how to do it
  public class MyCustomListnerObject {
      // Step 1 - This interface defines the type of messages I want to communicate to my owner
      public interface MyCustomObjectListener {
          // These methods are the different events and
          // need to pass relevant arguments related to the event triggered
          public void onObjectReady(String title);
          // or when data has been loaded
          public void onDataLoaded(SomeData data);
      }

    private MyCustomObjectListener listener;

  // Constructor where listener events are ignored
    public MyCustomObject() {
        // set null or default listener or accept as argument to constructor
        this.listener = null;
    }

    // Assign the listener implementing events interface that will receive the events
    public void setCustomObjectListener(MyCustomObjectListener listener) {
        this.listener = listener;
    }
    }

then your Volly
  // Check existence of email address
    private void verifyEmail(String email) {
        isUserExist = false;

        loginURL = Uri.parse(loginURL).buildUpon()
                .appendQueryParameter("email",email)
                .build().toString();

        GsonRequest<StaffUser> gsonRequest = new GsonRequest<StaffUser>(loginURL, StaffUser.class, null,
                new Response.Listener<StaffUser>() {
                    @Override
                    public void onResponse(StaffUser response) {
                        if (response != null) {
                            Log.i(TAG, "staffUserId: " + response.getStaffUserId());
                         if (listener != null)
                      listener.onDataLoaded(data); // <---- fire listener here
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO: Handle error
listener.onDataLoaded(data); // <---- fire listener here
                Log.e(TAG, "VolleyError: " + error);
            }
        }
        );

        // Access the RequestQueue through your singleton class.
        MySingleton.getInstance(this).addToRequestQueue(gsonRequest);

    }

How to create a proper Volley Listener for cross class Volley method calling


text:
Q: php pdo statement not updaing the table? I am trying to update the table with the following code but always get rowcount to 0 and the table is not updated. The same query updates the table when I use phpmyadmin.
$query="UPDATE userprofile SET password=:newpassword WHERE userid=:userid AND password=:oldpassword";
$queryprepare=parent::getPreparedQuery($query);
$queryprepare->bindParam(':newpassword',$newpassword);
$queryprepare->bindParam(':userid',$userid);
$queryprepare->bindParam(':oldpassword',$oldpassword);
$queryprepare->execute();

A: I'm not expert of PDO, but usual an UPDATE with no table modify depend on missing commit.
Which DB (and ISAM engine) do you use?
EDIT
looking at PDO manual I found this post of nils andre with my googelian maily accou: about the correct encoding of the connecction.
I usual set all the chain (html-page, db-connection, db-column-type) with the same enconding (usually UTF-8) to avoid any problem.
In your case if your password contains some "binary" character the where will not match, so no update.
Simply remove the old-password condition to verify my hypothesis.


text:
Q: Facebook login in swift I am trying to implement facebook login in swift. I am currently getting error
The operation couldn't be completed. (com.facebook.sdk.core error 3.)

My current implementation are as follows:
My pod file:
target 'AlamofireTest' do
# Comment the next line if you're not using Swift and don't want to use
dynamic frameworks
use_frameworks!

# Pods for AlamofireTest
pod 'Alamofire'
pod 'AlamofireImage'
pod 'FBSDKLoginKit'

target 'AlamofireTestTests' do
inherit! :search_paths
# Pods for testing
end

target 'AlamofireTestUITests' do
inherit! :search_paths
# Pods for testing
end

end

My Appdelegate file:
import UIKit
import FBSDKCoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FBSDKApplicationDelegate.sharedInstance()?.application(application, didFinishLaunchingWithOptions: launchOptions)
    return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    let handled = FBSDKApplicationDelegate.sharedInstance()?.application(app, open: url, options: options)
    return handled!
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

and my ViewController implementation:
@IBAction func loginWithFacebook(_ sender: Any) {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
    fbLoginManager.logIn(withReadPermissions: ["public_profile","email"], from: self) { (result, error) -> Void in
        if error != nil {
            print(error!.localizedDescription)
            self.dismiss(animated: true, completion: nil)
        } else if result!.isCancelled {
            print("Cancelled")
            self.dismiss(animated: true, completion: nil)
        } else {
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, relationship_status"]).start(completionHandler: { (connection, result, error) -> Void in
                if (error == nil){
                    let fbDetails = result as! NSDictionary
                    print(fbDetails)
                }
            })
        }
    }
}

I have followed the steps mentioned in the guide facebook login ios, and also used the suggestions in this. I am unable to find the steps, I did wrong. Any help is much appreciated.

A: Imprt SDKs:

*

*FBSDKCoreKit.framework

*Bolts.framework

*FBSDKLoginKit.framework

In Appdelegate.swift
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool
{
    return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

 return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

}

In ViewController.swift
@IBAction func ButtonClickFB(_ sender: Any){

    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logOut()

    fbLoginManager.logIn(withReadPermissions:["email","user_friends","user_birthday"], from: self, handler: { (result, error) -> Void in
        if ((error) != nil)
        {
            // Process error
            //  print(error)
        }
        else if (result?.isCancelled)!
        {
            // Handle cancellations
            // print(error)
        }
        else
        {
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                self.getFBUserData()
                // fbLoginManager.logOut()
            }
        }
    })

}

    func getFBUserData () {
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(normal), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){

                print((result! as AnyObject))
                //  print(((result! as AnyObject).value(forKey: "id") as? String)!)

                self.strEmail = ((result! as AnyObject).value(forKey: "email") as? String) ?? ""
                self.strID = ((result! as AnyObject).value(forKey: "id") as? String) ?? ""
                self.strName = ((result! as AnyObject).value(forKey: "name") as? String) ?? ""

                self.TextFBEmail.text = self.strEmail

            }
        })
    }
}

Add this in info

Add FB id in info.plist


text:
Q: How to parse json response from Bigquery results? I tried sample javascript code to call Google bigQuery API ( https://developers.google.com/bigquery/docs/authorization#client-side-javascript )
Js:
function runQuery() {
   var request = gapi.client.bigquery.jobs.query({
      'projectId': project_id,
      'timeoutMs': '30000',
      'query': 'SELECT TOP(repository_language, 5) as language, COUNT(*) as count FROM [publicdata:samples.github_timeline] WHERE repository_language != "";'
    });
    request.execute(function(response) {
        console.log(response);
        var results = response.result.rows ;
        $('#result_box').html(JSON.stringify(results, null));
    });
}

Above big query returns :
[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]

Please help me how to parse the values from above results in JSON Format ?
{"JavaScript": "949899", "Ruby": "640659", "Java": "568202", "Python": "484852", "PHP": "453830" }

A: Eval is a security risk.
var text = '[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]';
myData = JSON.parse(text);
alert(myData[4].f[0].v);

A: http://jsfiddle.net/jv7vm/
var a='[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]';

var evala=eval('('+a+')');

for(i=0;i<evala.length;i++)
{
document.write(evala[i].f[0].v+' '+evala[i].f[1].v+'<br>');
}

A: Got answer from below javascript
var total = response.result.totalRows;
var data = [];
for(i=0; i < total; i++){
            data[i]= [ response.rows[i].f[0]["v"], response.rows[i].f[1]["v"] ];
        }

 console.log(data);


text:
Q: Spring @Transactional not rolling back after failure I have a Spring @Service bean in which some data saving in a MySQL occurs. It's saving LocalDateTime objects, for booking rooms in future dates.
The problem is: when booking multiple rooms at once and one of them is not available (i.e. already booked), Spring should rollback all the rooms that were booked already, but isn't doing it. Everything but the error one is commited to the database.
Code inside my @Service, the one that should rollback after an exception is thrown.
@Transactional(rollbackFor = { RecurrentMeetingBookingException.class})
public void bookRecurringMeeting(RecurrentMeeting meeting) throws RecurrentMeetingBookingException {
    LocalDateTime start = meeting.getMeetingEntity().getStartDate();
    LocalDateTime end = meeting.getMeetingEntity().getEndDate();

    while (start.isBefore(meeting.getRecurrenceEndTime())) {
        MeetingEntity recurrent = copyOfRecurrent(meeting, start, end);

        try {
            bookRoomForDate(recurrent);
        } catch (MeetingException e) {
            throw new RecurrentMeetingBookingException(e.getMessage());
        }

        start = start.plus(1, meeting.getRecurrenceType().getUnitOfTime());
        end = end.plus(1, meeting.getRecurrenceType().getUnitOfTime());
    }
}

I tried throwing a RuntimeException too, but it also didn't work.
When returning a ResponseEntity from my Controller, the exception is indeed thrown, as I return Room is not available as an exception, returning it's message.

What is the problem with my @Transactional? Shouldn't Spring/Hibernate rollback everything when an exception is thrown? What can I do to solve this issue, and correctly rollback the @Transactional?

A: When facing this problem, a member from the spring forums came with a solution, back in 2011.

Make sure you're using transactional tables, for example INNODB
You might be using a non-transactional table, for instance MyISAM, and @Transactional won't work as expected.
This isn't exactly a Spring/Hibernate problem, but your database's.


text:
Q: Python to read services Description I want my python script to read the windows service description, In order to decide whether to stop it \ make it run only manually..
The point is that I don't find the method that reads the Description.
(may be something like 'GetServiceDescription').
help anyone?

A: You can use wmi library also follow other answers like List running processes on 64-bit Windows.
i haven't tested this but this should be the short snippet to list them reference,
import wmi
c = wmi.WMI()
for service in c.Win32_Service(): #if its win32
    print service.Name

Follow this tutorial

If you find it tough to follow may be looking at the tutorial may help or come again with another question.


text:
Q: What else can i use instead of 'setInterval' in React-Native? I have a function where I am using setIntevals but I would like to use something else instead  as I am implementing background processes and intervals do not work in background.
Here is the simplified code I am using(can't post all of it because is waay too long):
this.carInterval = setInterval(() => {
   try{
   ///
   }
  catch{
   ////
   },5000);
}


text:
Q: Rails 3.2.13 Javascript Asset Pipeline I am working on a Rails 3.2.13 app, and encountering the following problem:
The Javascript files I wrote in the app/assets/javascripts/  directory don't seem to be run.
I have JS code in a file called menu_list.js  in the app/assets/javascripts/ directory, but it does not do anything.  Whereas when I put the same code on the view page in a  tag, it works.
<script>$("#sortable").sortable();</script>

Here's my application.js file:
//= require jquery
//= require jquery_ujs
//= require jquery.purr
//= require jquery-ui
//= require best_in_place
//= require bootstrap
//= require bootstrap-switch
//= require_tree .

my menu_list.js  file:
$(function() {
  $("#sortable").sortable();
});

It does not make sense to me, as I thought //= require_tree . would include all the javascript files in the directory.  I tried other javascript files too, but they don't seem to have any effects.

A: Most common cause for this is that the call to javascript_include_tag that is on the default layout, then you create another layout, forget to add the include there and then nothing works in controllers where you use this new layout.

A: $("#sortable").sortable();

If this truly is all you have in app/assets/javascripts/menu_list.js it will run as soon as the script is loaded, which is not what you want. You want to run the above code at least after the DOM has fully loaded into the page and not before.
$(function() {
  $("#sortable").sortable();
});

If the environment you're running in is :development, and you properly have the following in your layout
<%= javascript_include_tag "application" %>

you will see a separate <script> tag for every Javascript file Sprockets is loading. The //= require_tree . will pick up your app/assets/javascripts/menu_list.js file.
I suggest also making sure you don't have any precompiled version of your assets in place by running the following in shell
rake assets:clean

You can also force debug mode (individual <script> tags for each file) by adding a :debug option to the above include tag
<%= javascript_include_tag "application", debug: true %>


text:
Q: Docker 's Error: libselinux conflicts with fakesystemd I'm building docker image with a Dockerfile:
FROM       centos:centos7.1.1503
MAINTAINER foo <foo@bar.com>

ENV TZ "Asia/Shanghai"
ENV TERM xterm

RUN \
    yum update -y && \
    yum install -y epel-release &&\
    yum update -y && \
    yum install -y curl wget tar bzip2 unzip vim-enhanced passwd sudo yum-utils hostname net-tools rsync man && \
    yum install -y gcc gcc-c++ git make automake cmake patch logrotate python-devel libpng-devel libjpeg-devel && \
    yum install -y pwgen python-pip && \
    yum clean all

and it show the error as below:
Error: libselinux conflicts with fakesystemd-1-17.el7.centos.noarch

If I change FROM centos:centos7.1.1503 to FROM centos:centos7,all will  work fine. So ,what should I do to using centos7.1.1503
My Linux Distribution is Ubuntu 16.04.1 LTS and my docker version is 1.12.6.

A: Try running this inside the container you create, before any installation is made:
yum swap -y fakesystemd systemd && yum clean all
yum update -y  && yum clean all

Or inside a Dockerfile at the begining before the first RUN you have tipped:
RUN yum swap -y fakesystemd systemd && yum clean all \
    && yum update -y  && yum clean all

Hope was useful!


text:
Q: My Linux box cannot access other devices on the LAN I have new mini PC (ASUS) with UBUNTU 21.10
it has an Intel network controller (WiFi 6 Ax200)
I can access the internet and I can see other devices such as my laptop and NAS on the LAN but I cannot access them, i.e., open a directory.
In "Files" " | "Other Locations" are listed: - MyMacBook with remote login and file sharing; - RASPBERRYPI (Samba - updated); and - Windows Network
When I click on them I get the following error messages
MyMacBook (Remote Login) -
Unable to access location
"No route to host"

MyMacBook (File Sharing) & RASPBERRYPI
Unable to access location
 "Failed to retrieve share list from server: No route to host"

Windows Network
Unable to access location
 "Failed to retrieve share list from server: No such file or directory"

my laptop does not have problems, e.g., it can readily access the NAS.
I only "problem" that I can find is that the Intel driver is not the one recommended by Intel - they recommend:

*

*iwlwifi-cc-a0-46.ucode but

*iwlwifi-cc-a0-63.ucode is being loaded
(the iwlwifi.ko file requests the iwlwifi...63.ucode file)
(both files are in /lib/firmware)

dmesg | grep iwl output verifies that the file: iwlwifi-cc-a0-63.ucode (the incorrect one) is loaded and gives an error:

"api flags index 2 larger than supported by driver".

could it be the driver that is the problem? if so, can I edit the iwlwifi.ko file and change the 63 to 46?
But some have suggested that the error messages cannot result from a driver problem.
Could it be a hardware problem?
Any suggestions of how to tackle this would be greatly appreciated (please articulate - it has been 40-45 years since I last used UNIX and I am stumbling a bit getting back into it :-)


text:
Q: How do you find the number of contestants in a tv show based on their eye colors? The problem is as follows:

To participate in an edition of The Price is Right $60$ people
showed up. The producer of the show collected the following
information:
$10$ women have black eyes $16$ women don't have black eyes $14$ women
do not have brown eyes $10$ men do not have brown or black eyes
Based on information from the show's producer. How many men have brown
or black eyes?

The alternatives in my book are as follows:
$\begin{array}{ll}
1.&\textrm{24 men}\\
2.&\textrm{22 men}\\
3.&\textrm{18 men}\\
4.&\textrm{28 men}\\
5.&\textrm{20 men}\\
\end{array}$
What I attempted to do is summarized in the table from below which showcases my findings. I must indicate that I arranged the characters of the story in two groups. One for women and the other for men. One column indicates $F$ for false of those who do not have a certain characteristic, i.e. A man who does not have black eyes would be in the F column below black eyes, a woman who has black eyes will lie below T in the black eyes column.
Hence this is represented as:

Where $x+y=10$
Adding all of these yields:
$14+10+16 +x+y+a+b=60$
Since it mentions $x+y=10$ and they want to know what is a+b then this would mean:
$a+b=60-50=10$
However this is not within the alternatives.
In my effort to better represent this situation and avoid counting twice I made the diagram from below:

This different representation using an Euler diagram shows what I thought, the set of those who do not have brown eyes must account for those who have black eyes.
There is no interesection in any of these sets as there cannot be someone who has brown and black eyes at the same time. Thus I concluded what they want is the number of men who have brown eyes and those who have black eyes.
This part I require clarification, what is the meaning of OR translated in set theory language?. Does it mean is it a Union?. Is it $\cup$?. Can someone help me with this part?.
Returning to my attempt I then thought that the number $14$ of those who do not have brown eyes will include those who have black eyes therefore.
Adding those who have black eyes with those who have brown eyes with those who dont have brown neither black in the women side. With those on the men side who dont have neither black or brown with those who have brown and those who have black will equate to $60$. This translated into an equation would be as this:
14+16+10+u=60
Assuming $u=\textrm{unknown males with brown with those with black eyes}$
This would become into:
$u=20\,men$
But this is not the right answer. Why?.
Did I made a mistake or something?. Because of this reason I need a very detailed help with this.
Please an answer must include a Venn or Euler diagram strategy or using a table. To better aid the understanding of this problem. I have tried all sorts, but I don't seem to get the right answer.
Can someone include also the representation of set notation using algebraic notation accompanied with an Euler or Table diagram?.

A: You are given:

10 women have black eyes
16 women don't have black eyes
14 women do not have brown eyes
10 men do not have brown or black eyes

Assuming no one have heterochromia, each person only has one single eye color.
Hence either they have black eyes, or they do not.
From the first two conditions we see that there are $26$ women. Thus there are $34$ men.
Now $10$ men do not have brown or black eyes, and we are to find the number of men with brown or black eyes, which is the complement of those $10$ men, so there are $24$ of them.
The major mistake in your answer is the equation
$$14+10+16+x+y+a+b=60$$
Since the $14$ women without brown eyes and those $16$ women without black eyes are not mutually exclusive, you can't just add them up; you will overcount.
To answer your side question, OR translates to the union $\cup$ and AND translates to the intersection $\cap$. However these do not come into play in this specific question.

A:

*

*There are 60 contestants

*10 women have black eyes 16 women don't have black eyes

*10 men do not have brown or black eyes

I will try to give as best an explanation as I can possibly give:
Notice, statement 2 will represent all women, since they have black eyes or don't. Just like if I were to say there are 2 guys with a shirt and 3 without: there are 5 guys. So back to statement 2, $10+16=26$ so there are $\boxed{26 women}$
Since there are 26 women, this means $60-26=34$ so there are $\boxed{34 men}$ since the contestants are women or they aren't just like above, the women either have black eyes or they don't
Statement 3 suggests there are 10 men without brown or black eyes, the opposite of that would be men with brown or black eyes. And as I've done through the whole answer, we have $34-10=24$ $\boxed{24}$ men with brown or black eyes
The logic of this whole answer is basically: There are $n$ number of things with the attribute(s) $X$ and $s$ number of things without attribute(s) $X$, so there are $n+s$ number of things total.


text:
Q: NSPredicate for checking the same date I want to check to 2 NSDates that they are on the same date (time can be different).
What I have currently is this:
- (NSPredicate*) predicateWithDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit ) fromDate:date];
    //create a date with these components
    NSDate *startDate = [calendar dateFromComponents:components];
    [components setMonth:0];
    [components setDay:1];
    [components setYear:0];
    NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];
    return [NSPredicate predicateWithFormat:@"((ANY notes.date >= %@) AND (ANY notes.date < %@))",startDate,endDate];
}

A: Your startDate, endDate calculation looks almost correct, you only forgot the NSDayCalendarUnit:
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];

There are various ways to compute the start and end date for the current day,
I prefer the following slightly shorter code:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startDate;
NSTimeInterval interval;
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&startDate interval:&interval forDate:date];
NSDate *endDate = [startDate dateByAddingTimeInterval:interval];

Your predicate will find all objects that have any note with date >= startDate,
and any (possibly different) note with date < endDate.
If you want to find objects that have at least one note on the given day, you need a SUBQUERY:
[NSPredicate predicateWithFormat:@"SUBQUERY(notes, $n, $n.date >= %@ AND $n.date < %@).@count > 0",
           startDate,endDate];


text:
Q: How can I cast a collection with generic type? Given the following code:
interface IParam {}

class Parameter implements IParam {}

void foo(Collection<? extends IParam> params) {
    SortedSet<? extends IParam> sortedParams;
    if (params instanceof SortedSet)
        sortedParams = (SortedSet<? extends IParam>) params;
    else
        sortedParams = new TreeSet<IParam>(params);
}

What I get is some collection of parameters.
What I need is a SortedSet of the parameters.
If the given collection already is a SortedSet, I want to use that.
Otherwise, I'll create a new TreeSet with just the content of the given collection.
However, this code doesn't compile with warnings about unchecked casts.
Is there any way to achieve what I want, without suppressing warnings?

A: Compiles just fine for me. I would restructure the code slightly though to make it easier to conceptualize and maintain:
protected <T extends IParam> void foo(Collection<T> params) {
    SortedSet<T> sortedParams;
    if (params instanceof SortedSet)
        sortedParams = (SortedSet<T>) params;
    else
        sortedParams = new TreeSet<T>(params);

    System.out.println(sortedParams);
}

As an aside, checking for instanceof within a method, though not illegal, is sometimes a sign of code smell. Your method can be refactored with some overloading:
protected <T extends IParam> void foo(SortedSet<T> params) {
    System.out.println("Doing something with sorted set);
}

protected <T extends IParam> void foo(Collection<T> params) {
    SortedSet<T> sortedParams = new TreeSet<T>(params);
    System.out.println("Doing something with other collection types");
    foo(sortedParams);
}

A: You can make this code compilable by adding two things:

*

*Your method foo needs to be in a class. Java does not allow the existence of methods outside of classes.

*Missing ; on lines 8 and 10. Semicolons are mandatory in Java.


text:
Q: how to split string by position c# I have a text string that when it exceeds a specific length, I separate the string into 2 strings, passing the rest of the remaining content to another variable, but I have an exception

Index and length must refer to a location within the string. (Parameter 'length')

My C# code:
        string text = "Hello word jeje";
        if (text.Length > 10)
        {
            string stringOne = text.Substring(0, 10);
            string stringTwo = text.Substring(11, text.Length); //throw exception
        }

expected result:
string text = "Hello word jeje";
string stringOne = "Hello";
string stringTwo = " jeje";

A: You have an off-by-one error; you'd need text.Length - 1.
The two-argument version of String.Substring() accepts start and length arguments; you'd need text.Substring(11, text.Length - 11).
However, you can just leave the second argument off for the second half, since the single-argument version of String.Substring() returns a substring to the end of the string.
string stringOne = text.Substring(0, 10);
string stringTwo = text.Substring(11);

A: How about using the Linq Chunk() extension method?
var test = "Hello World Yeah";
var chunks = test.Chunk(10);

foreach (var chunk in chunks)
{
    var subtext = new string(chunk.ToArray());
    Console.WriteLine(subtext);
}

Output:
Hello Worl
d Yeah


text:
Q: How to avoid an incompatible types error with a non parameterless constructor in a generic container? I get E2010 Incompatible types: 'TDerivedFrame' and 'TBaseFrame' on the following code:
type
  TBaseFrame = class(TFrame)
  end;

  TDerivedFrame = class(TBaseFrame)
  end;

  TContainer<T: TBaseFrame> = class
  private
    FFrame: T;
  public
    property Frame: T read FFrame;
    constructor Create;
  end;

constructor TContainer<T>.Create;
begin
  inherited;
  FFrame := TBaseFrame(T).Create(nil);
end;

var
  FTab: TContainer<TDerivedFrame>;

Using only T.Create(nil) causes E2568 Can't create new instance without CONSTRUCTOR constraint in type parameter declaration.
As far as I know you can only create a constructor constraint with a parameterless constructor.
What is the correct way to do this?
PS: The code compiles when I remove the variable which makes me think this is a compiler error?!
Edit: I understand the E2010 error, but even with T(TBaseFrame(T).Create(nil)) it doesn't work. This compiles, but causes an access violation at runtime:
type
  TBaseFrame = class(TFrame)
  public
    constructor Create(AOwner: TComponent); override;
  end;

  TDerivedFrame = class(TBaseFrame)
  public
    constructor Create(AOwner: TComponent); override;
  end;

  TContainer<T: TBaseFrame> = class
  private
    FFrame: T;
  public
    property Frame: T read FFrame;
    constructor Create;
  end;

constructor TBaseFrame.Create(AOwner: TComponent);
begin
  inherited;

end;

constructor TDerivedFrame.Create(AOwner: TComponent);
begin
  inherited;

end;

constructor TContainer<T>.Create;
begin
  inherited;
  FFrame := T(TBaseFrame(T).Create(nil));
end;

var
  FTab: TContainer<TDerivedFrame>;
begin
  FTab := TContainer<TDerivedFrame>.Create;
end.

A: FFrame := T(TBaseFrameClass(T).Create(nil));

is the correct way to do this.
You'll need
type
  TBaseFrameClass = class of TBaseFrame;

Your compiler error is because you are instantiating a type, TContainer<TDerivedFrame>. When you instantiate that type you ask the compiler to deal with
FFrame := TBaseFrame(...);

where FFrame is TDerivedFrame. If you wrote that code out without generics you'd understand the compiler error.
So, the compiler is behaving correctly here, but the issue of instantiation is catching you out. It's only at the point of instantiation that the compiler error becomes apparent. Without instantiation, of if you had instantiated TContainer<TBaseFrame> there would be no compiler error.
The AV is because you were casting T to be an instance rather than a class.

A: Try to use this one:
   TContainer<T:constructor, TBaseFrame> = class


text:
Q: How to calculate velocity of a column in a csv file? I have a csv file  which has two columns, the first is a Id of a person and the second the velocity. I want to find the average speed for every ID.
My csv file looks like this:
0001;12
0001;0.14
0001;96
0002;19
0002;20
0002;6.3
0003;25
0003;1.9
0003;16

I am a beginner in Python and don't really know many Python tricks. What I do know is that I probably complicated my code too much.

A: Here's how to read the data from the file:
import csv
from pprint import pprint

filename = 'velocities.csv'

# read user velocities from file into a dictionary of lists
user_velocities = {}
with open(filename, newline='') as csvfile:
    for user_id, velocity in csv.reader(csvfile, delimiter=';'):
        user_velocities.setdefault(user_id, []).append(float(velocity))

print('User velocities read from file:', filename)
pprint(user_velocities)

Output:
User velocities read from file: velocities.csv
{'0001': [12.0, 0.14, 96.0],
 '0002': [19.0, 20.0, 6.3],
 '0003': [25.0, 1.9, 16.0]}

It should now be easy for you to figure out how compute the average velocity for each user id in the user_velocities dictionary from the list of values associated with each one.
(Hint: use the built-in sum() and len() functions.)


text:
Q: Parallel gnu-make skips commands Given an empty file a.c and the following Makefile -
CC=gcc
l.a : l.a(a.o)
    ranlib l.a
    echo done

l.a(a.o) : a.c

clean::
    rm -f l.a a.o

Running the command "make clean ; make" gives the following output -
rm -f l.a a.o
gcc    -c -o a.o a.c
ar rv l.a a.o
a - a.o
ranlib l.a
echo done
done

Running the command "make clean ; make -j2" gives the following output -
rm -f l.a a.o
gcc    -c -o a.o a.c
ar rv l.a a.o
a - a.o

Why does "make -j2" skip the commands listed under the first rule?
This occurs consistently on a 32-bit single processor system with gnu make 3.79.1
Does not occur on a 64-bit multi-core system with gnu make 3.81.
This is a very shortened example of a larger Makefile where I ran into the problem.
So, I made the example Makefile a bit more "complex" as follows -
AR := flock make.lock ar
RANLIB := flock make.lock ranlib

CC=gcc
l.a : l.a(a.o) l.a(b.o)
        echo doing ranlib
        $(RANLIB) l.a
        echo done

l.a(a.o) : a.c

l.a(b.o) : b.c

clean::
        rm -f l.a a.o b.o

The flock() trick is my invention (perhaps a re-invention) to serialize "ar".
Output -
> make clean ; make -j1
rm -f l.a a.o b.o
gcc    -c -o a.o a.c
flock make.lock ar rv l.a a.o
ar: creating l.a
a - a.o
gcc    -c -o b.o b.c
flock make.lock ar rv l.a b.o
a - b.o
echo doing ranlib
doing ranlib
flock make.lock ranlib l.a
echo done
done
rm a.o b.o

> make clean ; make -j2
rm -f l.a a.o b.o
gcc    -c -o a.o a.c
gcc    -c -o b.o b.c
flock make.lock ar rv l.a a.o
flock make.lock ar rv l.a b.o
ar: creating l.a
a - a.o
a - b.o
rm a.o b.o


text:
Q: Refreshing an HTML page
Possible Duplicate:
How can I refresh a page with JQuery?

How can I possibly trigger a reload of a page using either something in Django views.py or with Jquery? Basically, I want the page to automatically reload the same way when you click on the URL bar of a web browser and press enter does.
Thanks,
Alex

A: Don't go overboard with automatic full page refreshes; they're expensive. Consider performing AJAX calls at a reasonable interval to refresh just the information you need.

A: In javascript you can refresh the page as:
window.location.reload()


text:
Q: How to use the IF ALL statement in Python I have a function named checker(nums) that has an argument that will later receive a list. What i want to do with that list is to check if each other element is greater or equal to the previous one.
Example:
I have a list [1, 1, 2, 2, 3] and i have to check if it fulfills the condition.
Since it does, the function should return True
My code:
def checker(nums):
    for x in range(len(nums)):
        if x+1<len(nums):
            if nums[x] <= nums[x+1] and nums[-1] >= nums[-2]:
                return True

This will only run once and return True if the first condition is true.
I've seen a statement if all and am unsure of how to use it.

A: Your function can be reduced to this:
def checker(nums):
    return all(i <= j for i, j in zip(nums, nums[1:]))

Note the following:

*

*zip loops through its arguments in parallel, i.e. nums[0] & nums[1] are retrieved, then nums[1] & nums[2] etc.

*i <= j performs the actual comparison.

*The generator expression denoted by parentheses () ensures that each value of the condition, i.e. True or False is extracted one at a time. This is called lazy evaluation.

*all simply checks all the values are True. Again, this is lazy. If one of the values extracted lazily from the generator expression is False, it short-circuits and returns False.

Alternatives
To avoid the expense of building a list for the second argument of zip, you can use itertools.islice. This option is particularly useful when your input is an iterator, i.e. it cannot be sliced like a list.
from itertools import islice

def checker(nums):
    return all(i <= j for i, j in zip(nums, islice(nums, 1, None)))

Another iterator-friendly option is to use the itertools pairwise recipe, also available via 3rd party more_itertools.pairwise:
# from more_itertools import pairwise  # 3rd party library alternative
from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def checker(nums):
    return all(i <= j for i, j in pairwise(nums))

Another alternative is to use a functional approach instead of a comprehension:
from operator import le

def checker_functional(nums):
    return all(map(le, nums, nums[1:]))

A: Similar solution to @jp_data_analysis using more_itertools.windowed
>>> from more_itertools import windowed
>>> nums = [1, 1, 2, 2, 3]
>>> all(i <= j for i, j in windowed(nums, 2))
True

And for scientific purposes (not recommended code), here is a more functional approach
>>> from operator import le
>>> from itertools import starmap
>>> all(starmap(le, windowed(nums, 2)))
True

A: Your code can in fact be reduced to checking if nums is sorted, e.g.
def checker(nums):
    return sorted(nums) == nums

This does exactly what you expect, e.g.
>>> checker([1, 1, 2, 2, 3])
True
>>> checker([1, 1, 2, 2, 1])
False


text:
Q: How to show Microsoft list item to person, who has edit rights? Hello I am working on a Microsoft Lists project and I want to know, whether it is possible to show an item in the list default view to a person, who has rights to edit this item but is not the author of the item. I have list permissions set to the following picture:

A: So I have figure it out. The only way how you can view desired list items is creating a new view in SharePoint lists and setting up some advanced access permissions.


text:
Q: Can adding a columnstore index to a table affect read performance of a query that uses a rowstore index on the same table? I'm doing some testing of columnstore indexing on a single table that has about 500 million rows.
The performance gains on aggregate queries have been awesome (a query that previously took about 2 minutes to run now runs in 0 seconds to aggregate the entire table).
But I also noticed another test query that leverages seeking on an existing rowstore index on the same table is now running 4x as slow as it previously did before creating the columnstore index. I can repeatedly demonstrate when dropping the columnstore index the rowstore query runs in 5 seconds, and by adding back in the columnstore index the rowstore query runs in 20 seconds.
I'm keeping an eye on the actual execution plan for the rowstore index query, and it's almost exactly the same in both cases, regardless if the columnstore index exists. (It uses the rowstore index in both cases.)
The rowstore test query is:
SELECT *
INTO #TEMP
FROM Table1 WITH (FORCESEEK)
WHERE IntField1 = 571
    AND DateField1 >= '6/01/2020'

The rowstore index used in this query is: CREATE NONCLUSTERED INDEX IX_Table1_1 ON Table1 (IntField1, DateField1) INCLUDE (IntField2)
The columnstore test query is:
SELECT COUNT(DISTINCT IntField2) AS IntField2_UniqueCount, COUNT(1) AS RowCount
FROM Table1
WHERE IntField1 = 571 -- Some other test columnstore queries also don't use any WHERE predicates on this table
    AND DateField1 >= '1/1/2019'

The columnstore index is: CREATE NONCLUSTERED COLUMNSTORE INDEX IX_Table1_2 ON Table1 (IntField2, IntField1, DateField1)
Here is the execution plan for the rowstore index query before I create the columnstore index:

Here is the execution plan for the rowstore index query after I create the columnstore index:

The only differences I notice between the two plans is the Sort operation's warning goes away after creating the columnstore index, and the Key Lookup and Table Insert (#TEMP) operators take significantly longer.
Here is the Sort operation's info with the warning (before creating the columnstore index):

Here's the Sort operation's info without the warning (after creating the columnstore index):

I would've thought a read query that is specifically leveraging the same rowstore index and execution plan in both cases should have roughly the same performance on every run, regardless of what other indexes exist on that table. What gives here?
Edit: Here's the TIME and IO stats before creating the index:

Here's the stats after creating the columnstore index:

A: Adding the nonclustered columnstore index allows for a batch mode sort in the second execution plan.  This causes all of the processing to be done on one thread - so even though the query has a parallel plan, it's essentially running serially.  You can see that by looking at the details of the different operators.
I reproduced your problem locally, here's the sort operator with per-thread counts - as you can see, everything is on thread 1:

Notice the "Actual Execution Mode" is "Batch."
Everything after the sort (the nested loops join, key lookup, etc) is essentially serial, which is what slows the query down.
See this KB article for details and possible solutions:
Adds trace flag 9358 to disable batch mode sort operations in a complex parallel query in SQL Server 2016

Batch mode sorts were introduced in SQL Server 2016 under compatibility level 130.  If a query execution plan contains parallel batch mode sorts in conjunction with directly-upstream parallel operators, you may encounter degraded performance compared to row mode sort plan equivalents.
This occurs due to a parallel batch sort outputting fully sorted data via a single thread to the upstream parallel operator (for example, a parallel merge join operator).  The performance degradation occurs when the upstream parallel operator uses single-threaded processing due to the incoming single-threaded batch mode sort operator.

For completeness, the options outlined there are either:

*

*enable TF 9358

*enable query optimizer hotfixes (through TF 4199, the QUERY_OPTIMIZER_HOTFIXES database option, or the ENABLE_QUERY_OPTIMIZER_HOTFIXES query hint)

Getting rid of the sort is another solution for this problem.  The sort is only present to try and prevent too much random I/O from the nested loops join, which is using unordered prefetch, as mentioned in this article by Craig Freedman:
Optimizing I/O Performance by Sorting – Part 1

The plan uses the non-clustered index to avoid unnecessarily touching many rows.  Yet, performing 64,000 random I/Os is still rather expensive so SQL Server adds a sort.  By sorting the rows on the clustered index key, SQL Server transforms the random I/Os into sequential I/Os.

You can get rid of the sort by:

*

*eliminating the need for the key lookup (by selecting less columns, or creating a covering nonclustered index)

*disabling nested loops prefetching by adding (undocumented, unsupported trace flag) OPTION (QUERYTRACEON 9115) to the query


text:
Q: What does negative index mean in a data frame? Recently I read a R statement somewhere, which said:
mtcars[-1]

What does -1 imply here? I do understand the following statement:
mtcars[1]

which means select the first column from the data frame, but I just could not infer the negative sign in the index?

A: Minus means remove the element with that index, just like "no minus" extract that element with the index


text:
Q: Função que retorne um array de strings que estiverem em todos os arrays Fala gente, tudo bom?
Minha dúvida é simples, mas a solução talvez não seja TÃOOO simples assim.
A verdade é que estou realizando um trabalho em JS e em breve vou precisar resolver um problema que vai me fazer perder algumas horas quebrando a cabeça.
Então resolvi perguntar aqui no StackOverflow para adiantar um pouco da solução.
Vamos a problemática.
Suponha que eu tenha declarado 5 arrays, seguem:

var objetos = ["abridor de garrafa", "abridor de latas", "adaga", "ábaco", "abajur", "abotoadura", "acetona", "açucareiro", "zabumba", "xícara", "zarabatana", "xilofone"];
var redondos = ["ábaco", "abajur", "abotoadura", "acetona", "açucareiro", "zabumba", "xícara"];
var cozinha = ["abridor de garrafa", "abridor de latas", "açucareiro", "xícara"];
var arma = ["adaga", "zarabatana"];
var musical = ["xilofone", "zabumba"]

Agora, eu preciso de uma função que quando eu passar 2 (ou mais) arrays, ela me retorne um novo array, contendo apenas as strings que estiverem presentes em TODOS os arrays que eu tiver passado.
Exemplificando:
Caso eu passe para a função os arrays: "objetos", "redondos" e "musical", o novo array que eu receber, deve conter apenas "zabumba".

A: Bom gente, segue a solução do problema:

var objetos = ["abridor de garrafa", "abridor de latas", "adaga", "ábaco", "abajur", "abotoadura", "acetona", "açucareiro", "zabumba", "xícara", "zarabatana", "xilofone"];
var redondos = ["ábaco", "abajur", "abotoadura", "acetona", "açucareiro", "zabumba", "xícara"];
var cozinha = ["abridor de garrafa", "abridor de latas", "açucareiro", "xícara"];
var arma = ["adaga", "zarabatana"];
var musical = ["xilofone", "zabumba"]

var arrays = [objetos, redondos, musical];

var result = arrays.shift().filter(function(v) {
    return arrays.every(function(a) {
        return a.indexOf(v) !== -1;
    });
});

document.write('<pre>' + JSON.stringify(result,null,4) + '</pre>');

Se alguém tiver uma solução melhor e quiser/puder compartilhar, agradeço!

A: Uma versão mais "manual" porque terá que iterar todos os itens do primeiro array.
Exemplo

var objetos = ["abridor de garrafa", "abridor de latas", "adaga", "ábaco", "abajur", "abotoadura", "acetona", "açucareiro", "zabumba", "xícara", "zarabatana", "xilofone"];
var redondos = ["ábaco", "abajur", "abotoadura", "acetona", "açucareiro", "zabumba", "xícara"];
var cozinha = ["abridor de garrafa", "abridor de latas", "açucareiro", "xícara"];
var arma = ["adaga", "zarabatana"];
var musical = ["xilofone", "zabumba"];

function comuns(...arrays){

    let aux = 1,
        possui = false,
        npossui = false,
        novo = [];

    arrays[0].forEach(function(item){

       aux = 1;
       npossui = false;

       while (arrays[aux]){
          if (arrays[aux].indexOf(item) > -1) possui = true;
          else npossui = true;
          aux++;
       }

       if (possui && !npossui) novo.push(item);
    });

    return novo;
}

console.log(comuns(objetos,redondos,musical));


text:
Q: Direction of electrons (current) in car circuit I read this somewhere.

Electrons flow from negative to positive. This is called electron flow. Originally it was believed they flowed from positive to negative. This was later found to be incorrect and we call this conventional current.

Can someone explain how current flows from car battery to e.g car radio (and other things) and return back to battery ?
Why is the negative terminal of battery connected to the chassis/car body?
Why it is advised to always remove negative terminal first when removing the battery?

A: What you are referring to is the "conventional current flow". It says the current flows from a high potential to a low potential (i.e. from plus to minus). Now remember that current was discovered long before the electron. So the convention stuck. For any practical purpose in e.e. you just use the conventional current flow.
Why is negative terminal of battery is connected to chassis/car body?
It is an industry standard (after WWII) deriving from the practicalities of electronics (whether you need positive or negative voltages).
Why it is advised to always remove negative terminal first when removing battery ?
If leave the negative to the chassis there are many non-isolated points to short-circuit the positive. Removing the negative is much safer.

A: Too many questions that are not really related, but I'll try.

The "direction" of the electric current is a matter of convention.
It was standardized as the direction of a virtual positive charge carrires, long before the discovery of the electron.
That's why electrons travel in the direction opposite to the "current".
The "current" outside the battery flows from the positive to the negative terminal, electrons travel from the negative to the positive terminal.
(The "outside of the battery" part is important - inside the battery everything is the other way round)

!!! Edit:
No, the directions of electron drift and the current are not the same. The current (as used in calculations of electric circuits) is the direction of travel of IMAGINARY positive charge carriers. If the REAL charge carriers are negative, they happily travel in the opposite direction.
For analyzing an electric circuit, it doesn't matter if the real carrires are positive or negative. It is up to them to move in a proper way.
What matters is the direction of the current. You may find quite a few cases when the conductor has both positive and negative carriers (as in electrolytes, then they travel in the opposite directions) or only positive carriers (as in P-type semiconductors).
As for your metaphor about the "excess" of electrons - they are in excess at the negative battery terminal. They repell each other (as they carry the same charge) and they use every possibility to jump to the positive terminal.
(The excess of electrons is exactly that - a metaphor. So is the moving of the electrons - I wrote "drift" for a reason. It looks way too early for a young person like you to imagine what a real electron party with beer and cigarettes looks like...)

In cars, the chasis is used as a negative conductor. Historically, it was positive (randomly choosen and standardized). It was later found that the positive potential promotes corrosion and from 1960s on cars (as well as boats, machinees and pretty much everything else that is DC-powered) are negative-chasis.

Why disconnect the negative terminal in the car?

*

*See the corrosion point above. You don't want to mess with the problem-prone connection at the positive terminal. It is usually harder to undo as well.

*The car may have sources of electricity other than the battery. It may be the capacitors of various electronic devices in the car.
Shorting them by touching the positive wire to an exposed metal parts will make the current flow backwards and may blow something. This is a common failure mode of the voltage regulators that are part of almost any electronics.
On the other hand, it is not possible to short anything by touching the negative wire to a part that is connected to the negative wire in the first place.

A:
"Electrons flow from Negative to Positive. This is called Electron flow.

Correct but don't worry about it. The convention is that current flows from positive to negative.

Originally it was believed they flowed from Positive to Negative.

Not quite. Since there was no knowledge of electrons there was no belief that they flowed one way or another.

Can someone explain how current flows from car battery to e.g car radio (and other things) and return back to battery ?

It's the same as any other circuit. In the case of a car half the wiring can be eliminated by using the chassis as the return 'wire'.

Why is negative terminal of battery is connected to chassis/car body?

@fraxinus has explained well that this is due to convention and minimising corrosion.

Why it is advised to always remove negative terminal first when removing battery ?

Figure 1. Here an uninsulated spanner is being used to work on the battery + terminal. If any other part of the spanner touches any grounded part of the vehicle while the battery - lead is still attached a major short will occur. Disconnecting the negative first eliminates this risk. Image source: Mechanicbase.


text:
Q: Remove value from nested array item react native I have below array format:
[
  {
    "category": "c8kr0cv012vtr8vm3iqg",
    "subcategories": [
      "c8kr3d7012vtr8vm3jm0",
      "c8kr3d7012vtr8vm3jlg",
      "c8kr3d7012vtr8vm3jk0",
      "c8kr8h7012vtr8vm3m5g",
      "c8tjghovq0ahq4ccf980",
      "c8kr3nn012vtr8vm3jog",
      "c8kr3nn012vtr8vm3jo0",
      "c8kr3nn012vtr8vm3jp0",
    ]
  },
  {
    "category": "c8kr0cv012vtr8vm3ivg",
    "subcategories": [
      "c8kr3d7012vtr8vm3jm0",
      "c8kr3d7012vtr8vm3jlg",
      "c8kr3d7012vtr8vm3jk0",
      "c8kr8h7012vtr8vm3m5g",
      "c8tjghovq0ahq4ccf980",
      "c8kr3nn012vtr8vm3jog",
      "c8kr3nn012vtr8vm3jo0",
      "c8kr3nn012vtr8vm3jp0",
    ]
  },
  {
    "category": "c8kr0cv012vtr8vm3is0",
    "subcategories": [
      "c8kr3d7012vtr8vm3jm0",
      "c8kr3d7012vtr8vm3jlg",
      "c8kr3d7012vtr8vm3jk0",
      "c8kr8h7012vtr8vm3m5g",
      "c8kr3nn012vtr8vm3jog",
      "c8kr3nn012vtr8vm3jo0",
      "c8kr3nn012vtr8vm3jp0",
    ]
  },
  {
    "category": "c8kr0cv012vtr8vm3ir0",
    "subcategories": [
      "c8kr3d7012vtr8vm3jm0",
      "c8kr3d7012vtr8vm3jlg",
      "c8kr3d7012vtr8vm3jk0",
      "c8kr8h7012vtr8vm3m5g",
      "c8tjghovq0ahq4ccf980",
      "c8kr3nn012vtr8vm3jog",
      "c8kr3nn012vtr8vm3jo0",
      "c8kr3nn012vtr8vm3jp0",
    ]
  }
]

I want to remove value from subcategory array for example c8tjghovq0ahq4ccf980
I tried below code:
tempPayload.some(function (a) {
  return a.subcategories.some(function (b, i, bb) {
    if (b === "c8tjghovq0ahq4ccf980") {
      bb.splice(i, 1);
      return true;
    }
  });
});

But it is not working any idea how can I resolve this?

A: Try with following code:
tempPayload.map((item) => {
  const index = item.subcategories.indexOf("c8tjghovq0ahq4ccf980");
  if (index > -1) {
    item.subcategories.splice(index, 1);
  }
});

A: for(let i=0; i<tempPayload.length; i++){
  tempPayload[i].subcategories = tempPayload[i].subcategories.filter(i => i!==  "c8tjghovq0ahq4ccf980")
}
console.log(tempPayload)


text:
Q: Is there a way to autoplay audio in html? I want to autoplay audio in my website as soon as I open my site. But it doesn't work.
  <audio id="myAudio" autoplay>
  <source src="./Welcome to Kitchen Nightmares..mp3" type="audio/ogg">
  <source src="./Welcome to Kitchen Nightmares..mp3" type="audio/mpeg">
  </audio>
  <script>
    function myFunction() {
      var x = document.getElementById("myAudio").autoplay;
      document.getElementById("demo").innerHTML = x;
    }
    myFunction();

A: Should start playing the audio file when the page loads, thanks to the autoplay attribute on the <audio> element. The buttons in the HTML code allow you to control the audio playback by calling the play() and pause() methods on the <audio> element.
Note that some browsers may not allow audio to automatically play on a website due to user experience and security concerns. In these cases, the user may need to explicitly start the audio playback by clicking on a button or some other element on the page.
<audio id="myAudio" autoplay>
  <source src="./Welcome to Kitchen Nightmares..mp3" type="audio/ogg">
  <source src="./Welcome to Kitchen Nightmares..mp3" type="audio/mpeg">
</audio>

<p>
  <button onclick="playAudio()">Play Audio</button>
  <button onclick="pauseAudio()">Pause Audio</button>
</p>

<script>
  function playAudio() {
    var audio = document.getElementById("myAudio");
    audio.play();
  }

  function pauseAudio() {
    var audio = document.getElementById("myAudio");
    audio.pause();
  }
</script>

A:

<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
function PlayMusic() {

  var play=document.getElementById("music");
  play.play();
}

$(document).ready(function(){
  setTimeout(PlayMusic,3000);
})

</script>
</head>
<body>

<audio controls id="music" >

  <source src="https://www.computerhope.com/jargon/m/example.mp3" type="audio/mpeg">
</audio>

</body>
</html>

After page load audio will play (1 sec delay).

URL   The URL of the audio file. Possible values:
An absolute URL - points to another web site (like
src="http://www.example.com/horse.ogg")
A relative URL - points to a
file within a web site (like src="horse.ogg")


text:
Q: How to design a simple current based class A amplifier Very much along the lines of Class A single transistor amplifier with 2N3904, but with a current signal input.  My circuit is a Zener noise source using the simplest of  components.  Traditional class A design starts with locating the Q point based on a voltage signal.  I'm not sure how to proceed due to the R1/R3 relationship affecting the Zener current which should target 60uA DC. Is this architecture even possible?
My parameters are as follows.  The Zener current is empirically determined for maximum noise using the ones I have.
Target gain = 10x.
Vcc = 30V.
Noisiest Zener current and Ib = 60uA DC with 10uA avalanche signal.
Bandwidth 100kHz.
I can foresee a design situation where R1 = 0 and becomes redundant. I have considered  a FET based design, but was curious about a BJT design and due the fact that Horowitz & Hill do not recommend them (§ 3.08, 2nd Ed.)

A: Since Hfe varies greatly with temperature and operating current your class A design is going to have quite variable gain.
The 2N3904 has high variance of Hfe with operating current, and requires substantial current to get good gain.
Since you seem to have established the Zener current to produce the best noise output, it may be a circuit like this would be better.

simulate this circuit – Schematic created using CircuitLab
R1/R2 provide about 1mA current and set the base close to 2V.
R4 has about 1.2V across it and set the operating point of the 2N3904 at about 18V.
R3/R4 set the gain to 10 for the noise signal.


text:
Q: Non-completeness of the Borel-Lebesgue measure and countable choice Is it possible to prove the non-completeness of the Borel-Lebesgue measure on $\mathbb{R}$ (restricted to the Borel $\sigma$-algebra) without the full axiom of choice, but still with Countable Choice ?
It seems to be the case when I read Non-Borel sets without axiom of choice, but I was unable to really prove it.

A: Countable choice is sufficient to prove that there is a non-Borel set, since under countable choice, the collection of sets of reals with a Borel code (which is a well-founded countable tree labeled with the instructions for building a Borel set, so that leaves are labeled with basic open sets and other nodes are labeled with instructions for taking a countable union or a complement) is a $\sigma$-algebra containing the open sets. One uses countable choice to prove that this collection is closed under countable unions, because if each $A_n$ has a Borel code, you can use countable-choice to pick a code $b_n$ for $A_n$ and then glue these codes to together to make a code for $\bigcup_n A_n$. Thus, under countable choice, every Borel set has a Borel code.
Once you know that every Borel set has a Borel code, this gives you a surjection from the reals onto the Borel sets, and so by Cantor's theorem there must be a non-Borel set of reals, since every Borel code is coded by a real, but the reals do not surject onto the power set of the reals.


text:
Q: How to show graphically that $\sum_i(1/3)^i$ goes to $1/2$ As everybody knows, it is very easy to show:
$$\sum_{i=1}^\infty \frac{1}{2^i} = 1$$
As follows:

The coloured parts always show $\frac{1}{2^i}$ and it's easy to see they all come together to fill the entire square.
Does anybody know a similar drawing to show that:
$$\sum_{i=1}^\infty \frac{1}{3^i} = \frac{1}{2}$$
Thanks in advance

A:
Start with any isosceles triangle of area $1$. Connect all its corners to a point such that we have three triangles of the same area. Repeat for successive isosceles triangles, all sharing the same base.
The yellow area is $\frac 13$, green area is $\frac 13 \times \frac 13 =\frac 19$, red area is $\frac 19 \times \frac 13 =\frac{1}{27}$ and so on.
The total area approaches exactly $\frac 12$.

A: This is a visual proof for
$$\sum_{i=1}^\infty \frac{1}{3^i} = \frac{1}{2}.$$
For any positive integer $i$:

*

*the term  $\frac{1}{3^{2i-1}}$ is given by the area of a rectangle $\frac{1}{3^{i}}\times \frac{1}{3^{i-1}}$.

*the term $\frac{1}{3^{2i}}$ is given by the area of a square $\frac{1}{3^{i}}\times \frac{1}{3^{i}}$.
Such squares and rectangles cover half of the square $1\times 1$.

I found the picture HERE

A: I like to use rectangles that I divide up based on the common ratio in the geometric series and compare filled to unfilled areas. This works well if the common ratio is less than $\displaystyle \frac{1}{2}$. I haven't yet figured out how to make it work for bigger than $\displaystyle \frac{1}{2}$.
The idea is to compare the number of filled rectangles and the unfilled rectangles of the same size (neglecting any rectangles that need to be split up for the next piece in the geometric series).
Here is a common ratio of $\displaystyle \frac{1}{3}$:

For $\displaystyle \frac{1}{3}$, there is one filled rectangle for every unfilled of the same size, meaning the areas are in a $1:1$ ratio. If the original rectangle's area is $1$, that must mean the filled areas are $\displaystyle \frac{1}{3} + \frac{1}{9} + \frac{1}{27} + \cdots = \frac{1}{2}$ (in agreement with the geometric series formula).
Here is a common ratio of $\displaystyle \frac{1}{4}$:

For $\displaystyle \frac{1}{4}$, there is one filled rectangle for every  two unfilled rectangles of the same size, meaning the areas are in a $1:2$ ratio. If the original rectangle's area is $1$, that must mean the filled areas are $\displaystyle \frac{1}{4} + \frac{1}{16} + \frac{1}{64} + \cdots = \frac{1}{3}$ (in agreement with the geometric series formula).
Here is a common ratio of $\displaystyle \frac{2}{9}$:

For $\displaystyle \frac{2}{9}$, there are two filled rectangles for every  five unfilled rectangles of the same size, meaning the areas are in a $2:5$ ratio. If the original rectangle's area is $1$, that must mean the filled areas are $\displaystyle \frac{2}{9} + \frac{4}{81} + \frac{8}{729} + \cdots = \frac{2}{7}$ (in agreement with the geometric series formula).
Edit: After thinking for a few minutes, I realized how to do the case of the common ratio being bigger than $\displaystyle \frac{1}{2}$: multiply the common ratio by itself until you end up with a ratio less than $\displaystyle \frac{1}{2}$, then do the above process and add the portion that was chopped off at the end. I came up with this idea Summer of 2022 and after a lot of thought could not come up with this. Funny the difference some time makes.


text:
Q: How to convert date format to UTC specific format - yyyy-MM-dd'T'HH:mm:ss.FFF+000? I am trying to convert a date time to yyyy-MM-dd'T'HH:mm:ss.FFF+000. But not sure of the exact format to be used in the query to get the expected value.
The closest I could get is:
SELECT TO_CHAR(cast(SYSDATE as timestamp) at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.FF') FROM DUAL

I need to validate this against a JSON object which returns the value with +000 at the end.


text:
Q: Linking error using 'idf.py build' on esp32s2 I am trying out a very simple case on my esp32s2. The build seems ok, but the linking not so much.
The aim of the code is to send a keystroke (esp32s2 as a USB device). It is as following:
#include "tinyusb.h"
#include "class/hid/hid_device.h"
#include "tusb.h"

enum {
ITF_KEYBOARD = 1,
ITF_MOUSE = 0
};

void app_main(void)
{
tusb_init();
tud_task(); // tinyusb device task

uint8_t keycode[6] = { 0 };
keycode[0] = 0x04 ; //HID_KEY_A;
tud_hid_n_keyboard_report(ITF_KEYBOARD, 0, 0, keycode);
}

The CMakeLists.txt inside the main folder is like:
idf_component_register(SRCS main.c
INCLUDE_DIRS ".")

The CMakeLists.txt ouside the main folder is like:
cmake_minimum_required(VERSION 3.5)

include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(test)

And the makefile is like:
PROJECT_NAME := project_name

include $(IDF_PATH)/make/project.mk

I also tryed to copy the lib hid_device.c/h inside my project, it works well, but the linking still not work.
When I build the project, I got the following error:
[ 99%] Linking C static library libmain.a
[ 99%] Built target __idf_main
[ 99%] Generating ld/sections.ld
[ 99%] Built target __ldgen_output_sections.ld
[ 99%] Linking CXX executable test.elf
/home/me/.espressif/tools/xtensa-esp32s2-elf/esp-2021r2-8.4.0/xtensa-esp32s2-elf/bin/../lib/gcc/xtensa-esp32s2-elf/8.4.0/../../../../xtensa-esp32s2-elf/bin/ld: esp-idf/main/libmain.a(main.c.obj):(.literal.app_main+0x0): undefined reference to `tud_hid_n_keyboard_report'
/home/me/.espressif/tools/xtensa-esp32s2-elf/esp-2021r2-8.4.0/xtensa-esp32s2-elf/bin/../lib/gcc/xtensa-esp32s2-elf/8.4.0/../../../../xtensa-esp32s2-elf/bin/ld: esp-idf/main/libmain.a(main.c.obj): in function `app_main':
/home/me/My_project/project_test_HID/main/main.c:37: undefined reference to `tud_hid_n_keyboard_report'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/test.elf.dir/build.make:538 : test.elf] Erreur 1
make[1]: *** [CMakeFiles/Makefile2:2458 : CMakeFiles/test.elf.dir/all] Erreur 2
make: *** [Makefile:149 : all] Erreur 2
make failed with exit code 2

If you have any idea, please let me know :)
Thanks
Regards

A: You're including headers from an ESP-IDF component called "tinyusb" (that's the name of the directory in its source code: esp-idf/components/tinyusb). But if you're using a component, you must tell the build system about this - otherwise it will not pull in the implementation of this component and you get linker errors.
You can pull it in via your main CMakeLists.txt like so:
idf_component_register(SRCS main.c
INCLUDE_DIRS "."
REQUIRES "tinyusb")

It's all explained more or less clearly in the ESP IDF build system documentation

A: Using menuconfig under Component config > TinyUSB Stack > Human Interface Device Class (HID), setting TINYUSB_HID_COUNT to a value greater than 0 will enable TinyUSB HID.


text:
Q: Generating function of some Apéry's series According to Mathematica, we have
$$\sum _{n=1}^{\infty } \frac{H_n }{n^2 \binom{2 n}{n}}z^n=-\text{Li}_3\left(\frac{2}{-z+\sqrt{z-4} \sqrt{z}+2}\right)-\text{Li}_3\left(-\frac{2}{z+\sqrt{z-4} \sqrt{z}-2}\right)+2 i \pi  \csc ^{-1}\left(\frac{2}{\sqrt{z}}\right)^2,$$
but how to prove this formula. Moreover, what is the generating function of the apery series
$$\sum_{n=1}^\infty \frac{H_n}{n^3\binom{2n}{n}}z^n?$$
More general,
$$\sum_{n=1}^\infty \frac{H_n}{n^p\binom{2n}{n}}z^n?\quad (p=0,1,2,3,4,5,...)$$


text:
Q: Match cells in different files and return Value of another I have two files I need to look up cells in and make sure they match and return the actual value of another. When I use the formula posted below it just returns a True or False and I need the actual value of the cell...

=IF(V:V='[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,AND(K:K='[HW inbound shipment info 21 Oct
  (2).xls]Inbound'!$X:$X,VLOOKUP('[HW inbound shipment info 21 Oct
  (2).xls]Inbound'!$U:$U,1,0)))

A: As I understand your formula, nearly each function and bracket in it is wrongly used. Excuse me :-) The AND is on the false position, the IF has no useful parameters and the VLOOKUP makes no sense at all. Try using this formula:
=IF(AND(V:V='[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,K:K='[HW inbound shipment info 21 Oct (2).xls]Inbound'!$X:$X),"success","failed"))

I'm not sure if it is correct as I don't have the means to test it here but I tried to resolve your brackets.
As I don't understand at all which value you intend to return from your formula, I return "success" if the row matches succeed and "failed" if not. If that works, replace these string by your desired values.

A: Your OP "I have two files I need to look up cells in and make sure they match"
So looking at the first test in your formula, presumably entered in column H of the sheet where your data being tested sits:
V:V='[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W

this will return TRUE if V1 = '[HW inbound shipment info 21 Oct (2).xls]Inbound'!W1 but FALSE if V1 is in any other row of '[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W
Comparison of columns implicitly tests for equality in the row in which the formula is entered. I prefer to be explicit wherever possible.
It's possible to determine if your PN/Item in column V exists anywhere in '[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W using one of the lookup functions VLOOKUP or MATCH. For example:
= MATCH(V1, '[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,0)
will return the row number of the first match for V1 in '[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W even if the searched array is unsorted. It will return a #N/A error if no match is found. You need to test firstly if V1 is in the searched array:
IF(ISNA(MATCH(V1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,0), FALSE, TRUE)
The reason I return FALSE if the match is not found is to allow testing of two conditions within an AND function:
=AND(IF(ISNA(MATCH(V1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,0), FALSE, TRUE), IF(ISNA(MATCH(K1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$X:$X,0), FALSE, TRUE)
which will evaluate to AND(TRUE, TRUE) only if your PN/Item and QTY are found.
At this point all you know is that both values are found but you don't know if they are on the same row so you need another test for that, bearing in mind that MATCH returns the position of the matched value within the array being tested:
=(MATCH(V1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,0) =
MATCH(K1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$X:$X,0)
will return TRUE if PN/Item and QTY
 are on the same row. Disclaimer: Testing revealed this will only work if PN/Item and QTY are both unique. If not, you will have to resort to a macro solution.
The value you want to return is to the left of the columns you are looking up so you can't use VLOOKUP to return the value you want. The only option is to use INDEX(array, row_num, [column_num]) using row_num returned by one of your MATCH formula:
=INDEX('[HW inbound shipment info 21 Oct (2).xls]Inbound'!$U:$U, MATCH(V1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,0))
Now we can put it all together in H1:
=IF(AND(
    IF(ISNA(MATCH(V1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,0)),FALSE,TRUE),
    IF(ISNA(MATCH(K1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$X:$X,0)), FALSE, TRUE)),
 IF(MATCH(V1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,0)
=MATCH(K1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$X:$X,0),
    INDEX('[HW inbound shipment info 21 Oct (2).xls]Inbound'!$U:$U,
    MATCH(V1,'[HW inbound shipment info 21 Oct (2).xls]Inbound'!$W:$W,0)),""),"")
Indentation added to make it a bit easier to read.
Tried and tested by creating a HW inbound shipment info 21 Oct (2).xls workbook with an Inbound sheet having test data in columns U, W and X.


text:
Q: "Unexpected character '" when importing theme I'm trying import the element ui chalk theme with
import 'element-ui/lib/theme-chalk/index.css'

But I get this in the console:

Error: Module parse failed: Unexpected character '

Am I missing something?

A: After following this guide I managed to fix this
Basically had to install sass-loader with
npm install sass-loader node-sass style-loader --save-dev

and then add the loader to my webpack.config.js, but I had to do it like this, due to my version:
module: {
    rules: [
        { test: /\.s[a|c]ss$/, loader: 'style!css!sass' },
    ]
}


text:
Q: HTTP Status 500 with java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet Checked the other posts didn't help.
This is  in Spring Tool Suite Version: 3.6.0. When I start the server, the web page opens up. After I enter a word and click on submit I get A status 500 error.
Screen shot JARS
Directory Screen shot
Hellocontroller.java
  package controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.*;

//import com.sun.javafx.collections.MappingChange.Map;

public class Hellocontroller implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest req,
            HttpServletResponse res) throws Exception {

           String name = req.getParameter("name");

           Map m = new HashMap();
           m.put("msg", "Hello ...."+name);

           ModelAndView mav =new ModelAndView("success",m);

        return mav;
    }

}

HelloWorld-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean
        class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />

    <bean name="/hello.ds" class="controller.Hellocontroller">
    </bean>

    <bean class="org.springframework.web.servlet.InternalViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>*.ds</url-pattern>
    </servlet-mapping>
</web-app>

index.jsp

HelloWorld

<form action ="./hello.ds">

NAME:<input type = "text" name="name">

SUBMIT<input type = "submit" value="sayHello">

</form

success.jsp
${msg}

HTTP Status 500 - Error instantiating servlet class org.springframework.web.servlet.DispatcherServlet

type Exception report

message Error instantiating servlet class org.springframework.web.servlet.DispatcherServlet

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Error instantiating servlet class org.springframework.web.servlet.DispatcherServlet
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    java.lang.Thread.run(Unknown Source)

root cause

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve

A: Try by changing web.xml to like below...add load on start up
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>*.ds</url-pattern>
    </servlet-mapping>


text:
Q: В чем причина возврата указателя или мусора из памяти? VS 2013, консольный, x64-разрядный проект.
Версия OpenSSL: 1.0.2h x64
Метод получения хеша SHA1:
#include <openssl/sha.h>

void SHA1::ComputeHash(std::vector<unsigned char> &buffer, std::vector<unsigned char> &result)
    {
        int i = 0;
        SHA_CTX sha1handler;
        unsigned char sha1digest[SHA_DIGEST_LENGTH] = { 0 };
        auto str = std::string(buffer.begin(), buffer.end());

        SHA1_Init(&sha1handler);
        SHA1_Update(&sha1handler, &str, str.size());
        SHA1_Final(sha1digest, &sha1handler);

        Framework::Array::Copy(sha1digest, 0, result, 0, SHA_DIGEST_LENGTH);
    }

Метод Framework::Array::Copy:
void Array::Copy(unsigned char *sourceArray, int sourceIndex, std::vector<unsigned char> &destinationArray, int destinationIndex, int length)
    {
        if (destinationArray.size() == 0 || destinationArray.size() < (destinationIndex + length))
            destinationArray.resize(destinationIndex + length);

        for (int i = sourceIndex; i < (sourceIndex + length); i++)
        {
            destinationArray[destinationIndex] = sourceArray[i];
            destinationIndex++;
        }
    }

Метод Framework::Array::AddRange:
void Array::AddRange(std::vector<unsigned char> &sourceArray, std::vector<unsigned char> &destinationArray, int offset, int length)
    {
        for (int i = offset; i < (offset + length); i++)
            destinationArray.push_back(sourceArray[i]);
    }

Метод, в котором возвращается указатель или мусор из памяти вместо значения:
void Hash(std::vector<unsigned char> &inData, std::vector<unsigned char> &salt1, std::vector<unsigned char> &salt2, int salt)
{
    std::vector<unsigned char> buffer(20);
    std::vector<unsigned char> buffer2(4);
    std::vector<unsigned char> destinationArray(0x30);
    int num = 0;
    for (num = 0; num < 3; num++)
    {
        for (int i = 0; i <= num; i++)
            buffer2[i] = (salt + num);
        std::vector<unsigned char> localBuffer;
        Framework::Array::AddRange(buffer2, localBuffer, 0, (num + 1));
        Framework::Array::AddRange(inData, localBuffer, 0, 0x30);
        Framework::Array::AddRange(salt1, localBuffer, 0, 0x20);
        Framework::Array::AddRange(salt2, localBuffer, 0, 0x20);

        SHA1::ComputeHash(localBuffer, buffer); // Вот тут в buffer возвращается указатель или мусор из памяти!
    }
}

Вопрос - почему возвращается указатель\мусор? Если нужны еще какие либо данные - напишите в комментариях.
Не первый раз уже сталкиваюсь с подобным, в прошлый раз не удалось воспроизвести проблему, надеюсь хоть в этот раз причина станет ясна.

Update:
Удалось выяснить что указатель\мусор возвращается из OpenSSL,
пример смены значения:
1) http://i7.5cm.ru/i/kkXu.png
2) http://i7.5cm.ru/i/caXS.png
Метод:
void SHA1::ComputeHash(std::vector<unsigned char> &buffer, std::vector<unsigned char> &result)
{
int i = 0;
SHA_CTX sha1handler;
unsigned char sha1digest[SHA_DIGEST_LENGTH] = { 0 };

// Выводим HEX значение буфера
printf("Buffer HEX: ");
for (int i = 0; i < (int)buffer.size(); i++)
    printf("%X-", buffer[i]);
printf("\r\n\r\n");

std::string str = std::string(buffer.begin(), buffer.end());

// Выводим длину строки
printf("Str Length: %u\r\n\r\n", str.size());

// Выводим HEX значение строки
printf("Str HEX: ");
for (int i = 0; i < str.size(); i++)
    printf("%X-", str[i]);
printf("\r\n\r\n");

if (!SHA1_Init(&sha1handler))
{
    printf("SHA1_Init == false\r\n"); // Все ок, сообщение не выводится
}
if (!SHA1_Update(&sha1handler, &str, str.size()))
{
    printf("SHA1_Update == false\r\n"); // Все ок, сообщение не выводится
}
if (!SHA1_Final(sha1digest, &sha1handler))
{
    printf("SHA1_Final == false\r\n"); // Все ок, сообщение не выводится
}

// Выводим HEX значение результата обработки SHA1
printf("SHA1 result HEX: ");
for (int i = 0; i < SHA_DIGEST_LENGTH; i++)
    printf("%X-", sha1digest[i]);
printf("\r\n\r\n");

Framework::Array::Copy(sha1digest, 0, result, 0, SHA_DIGEST_LENGTH);
}

p.s. попробовал более старую версию OpenSSL (v1.0.1t x64) - проблема так же сохранилась.

Тестовый проект: https://www.sendspace.com/file/japr5z
OpenSSL под Windows: https://slproweb.com/products/Win32OpenSSL.html

A: Не хватает репутации для комментария.
@Владимир Мартьянов, все правильно он передает:
BYTE == unsigned char == [0...255]

Другое дело, в какой форме он передает..
Проблема в том, что в SHA1_Update передается std::wstring, хотя в параметрах она принимает стандартную си-строку. Рекомендации:
1) Заменить std::wstring на std::string.
2) Заменить SHA1_Update(&sha1handler, &str, str.size()) на SHA1_Update(&sha1handler, str.c_str(), str.size())
p.s. Вам придется еще как то разобраться с FFFFF, wstring - отсекает их, а string - нет.


text:
Q: MongoDB Aggregate $unwind on sub-Documents I'm struggling when I $unwind more than one field from a Sub-Document.
Here's what the data looks like:-
{
   resp: {
      field1: 'yes',
      field2: ''
},
{
   resp: {
      field1: 'yes',
      field2: ''
}

etc,etc...

If I process an Aggregation Pipeline for ONE field, it works OK, so this works...
{ $unwind: "$resp" },
{ $unwind: "$resp.field1" },
{ $project: { field1: "$resp.field1" } }
{ $group: {
     _id: 1,
     field1: { $sum: { $cond: [{ $eq: ["$field1","yes"] },1,0] } }
   }
}

But if I now want to return field 2 in the same aggregation, using the following, it will return a count of Zero for both fields, whereas previously field1 had a count > Zero.
{ $unwind: "$resp" },
{ $unwind: "$resp.field1" },
{ $unwind: "$resp.field2" },
{
 $project: {
     field1: "$resp.field1",
     field2: "$resp.field2"
},
{ $group: {
     _id: 1,
     field1: { $sum: { $cond: [{ $eq: ["$field1","yes"] },1,0] } },
     field2: { $sum: { $cond: [{ $eq: ["$field2","yes"] },1,0] } }
   }
}

Any suggestions would be much appreciated.

A: it seems the above is the correct way to do this, but I'd happily take alternative suggestions.  The error was in may mapping of the fields in the $project stage.  When typing the issue into SO I realised where the problem was !


text:
Q: converting a row of data.frame to column names using data.table I have a large data frame of 5 million rows, with three columns.  I would like to transform it to a matrix which has as its rows USER_ID, ID as columns, and value as CNT. This could be done with melt and cast or
xtabs(CNT ~ USER_ID + ID, data = foo)

however the object created is to large and I get a following error 'dim' specifies too large an array
USER_ID ID CNT
1      1.813e+14 21   1
2      1.559e+14 28   1
6      1.592e+14 71   2

I'm trying to use data.table as is seams to handle large data much better then data.frame, but I can't figure out how to use data.table to create a contingency table I want.
Does any one have any idea how to get this working? I'm also thinking of creating and empty matrix with appropriate dimensions and fill it with appropriate indexes.

A: Try this using the built in data.frame CO2 :
> xtabs(uptake ~ Treatment + Type, CO2)
            Type
Treatment    Quebec Mississippi
  nonchilled  742.0       545.0
  chilled     666.8       332.1

or similarly using tapply:
> with(CO2, tapply(uptake, list(Treatment, Type), sum))
           Quebec Mississippi
nonchilled  742.0       545.0
chilled     666.8       332.1

and now compare to data.table:
> library(data.table)
>
> DT <- data.table(CO2)
> DT[, as.list(tapply(uptake, Type, sum)), by = Treatment]
    Treatment Quebec Mississippi
1: nonchilled  742.0       545.0
2:    chilled  666.8       332.1

Cautionary Note:   If the same levels of Type do not appear in every Treatment group then this would not be sufficient.  In that case it would be necessary to convert Type to be a factor in the data table (as it already is in CO2).
ADDED:
Its actually possible to get rid of tapply and have a pure data table approach like this:
> DT[, setNames(as.list(.SD[,list(uptake = sum(uptake)), by = Type][, uptake]),
+   levels(Type)), by = Treatment]
    Treatment Quebec Mississippi
1: nonchilled  742.0       545.0
2:    chilled  666.8       332.1

The cautionary note above applies here too.

A: Here's another approach (also using CO2 dataset):
dt = data.table(CO2)
dt[, sum(uptake), by = list(Treatment, Type)][,
     setNames(as.list(V1), paste(Type)), by = Treatment]
#    Treatment Quebec Mississippi
#1: nonchilled  742.0       545.0
#2:    chilled  666.8       332.1


text:
Q: Unknown Custom element laravel vue I am getting this error when I try to do post request with the vue
My app.js
Vue.component('comment', require('./components/Comment').default);
const app = new Vue({
   el: '#app',
   store
});

My Comment.vue
    <template>

                   @comments(['model'=>$book])

     </template>

and I have used this component in this page called review.blade.php

    <comment></comment>

But is is giving me the error in the console Do I have to give the name to the component or what .I cant understand this problem
vue.common.dev.js:630 [Vue warn]: Unknown custom element:
<comment> - did you register the component correctly?
For recursive components, make sure to provide the "name" option.

(found in <Root>)

A: You have some Blade syntax inside your template:

    @comments(['model'=>$book])

If this does not fix your problem than you might want to check when you load your app.js file or load the component locally for the Vue instance:
import comment from './components/Comment';

const app = new Vue({
    el: '#app',
    store,
    components: {
        comment
    }
});


text:
Q: Question mark folder I have read all of the other questions and websites about it. I cannot solve my problem.
I have had a problem with my Windows 7 bootcamp freezing. I force restarted a few times, and the last time it started a disk check (in windows 7 boot) and I didn't let it finish since I have like 1 billion files on it. It was at 5 percent for 2 hours and I just force restarted it.
Now I can't enter on the normal Macbook or Windows. I tried using the First Aid option a few times but it never worked.
Any help on this?


text:
Q: Why doesn't the sys.exit() terminate the script when typing NO or N the file just keeps running, why?
while True:
        game_choice = input('Do you want to play? ').lower()

    if game_choice == 'yes' or 'y':
        break
    elif game_choice == 'no' or 'n':
        sys.exit()
    else:
        print('Please answer only Yes/y or No/n')
        continue

A: your or statement is not correct or y will always be true, try this:
import sys

while True:
    game_choice = str(input('Do you want to play? ')).lower()
    if game_choice == 'yes' or game_choice == 'y':
        print("yes")
        break
    elif game_choice == 'no' or game_choice == 'n':
        sys.exit()
    else:
        print('Please answer only Yes/y or No/n')
        continue

or a better version:
import sys

while True:
    game_choice = str(input('Do you want to play? ')).lower()
    if game_choice in ['yes', 'y']:
        print("yes")
        break
    elif game_choice in ['no', 'n']:
        sys.exit()
    else:
        print('Please answer only Yes/y or No/n')
        continue