text:
Q: Authentication with AngularJS, session management and security issues with REST Api WS I started developing a web-app with angularJS and I'm not sure that everything is right secured (client and server side).
Security is based on a single login page, if credentials are checked ok, my server sends back an unique token with custom time-validity. All other REST api are accessible through this token.
The application (client) browse to my entry-point ex: https://www.example.com/home.html user insert credentials and receive back a unique token. This unique token is stored in the server database with AES or other secure techniques, it is not stored in clear format.
From now on, my AngluarJS app will use this token to authenticate to all REST Api exposed.
I'm thinking on temporary store the token in a custom http cookie; basically, when the server verifies the credentials, it sends back a new cookie Ex.
app-token : AIXOLQRYIlWTXOLQRYI3XOLQXOLQRYIRYIFD0T

The cookie has the secure and HTTP Only flags set on.
Http protocol directly manage the new cookie and store it. Successive requests will presents the cookie with the new parameter, without the need to manage it and store it with javascript; at every request, server invalidates the token and generates a new one and sends it back to the client --> prevent replay-attacks with a single token.
When the client receives an HTTP status 401 unauthorized response from any REST Api, the angular controller clean all the cookies and redirect the user to the login page.
Should I have to consider other aspects? Is it better to store the token inside a new cookie or in localStorage?
Any tips on how to generate a unique strong token?
Edit (improvements):

*

*I decided to use HMAC-SHA256 as session token generator, with 20 minutes validity. I generate a random 32byte GUID, attach a timestamp and compute the HASH-SHA256 by providing a 40 bytes key. It's quite impossible to obtain collisions since the token validity is quite minimal.

*Cookie will have domain and path attributes to increase security.

*No multi-logins are permitted.

A: If you talk to the server via https, you don't have a problem with replay attacks.
My suggestion would be to leverage your server's security technology. For example, JavaEE has an out-of-the-box login mechanism, declarative role-based protection of resources (your REST endpoints) etc. These are all managed with a set of cookies and you don't have to care about storage and expiration. Check out what your server/framework already gives you.
If you plan to expose your API to a broader audience (not specifically to the browser-based UI that you serve) or other types of clients (e.g. mobile app), consider adopting OAuth.
Off the top of my head, Angular has the following security features (will add more as they pop-out):
CSRF/XSRF attacks
Angular supports an out of the box mechanism for CSRF protection. Check out $http docs. Server-side support is needed.
Content Security Policy
Angular has a mode of expression evaluation that is compatible with more strict JavaScript runtimes that are enforced when CSP is enabled. Check out ng-csp docs.
Strict Contextual Escaping
Use Angular's new $sce feature (1.2+) to harden you UI against XSS attacks etc. It's a bit less convenient but more secure. Check out the docs here.

A: app/js/app.js
-------------

'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
  $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
  $routeProvider.otherwise({redirectTo: '/login'});
}]);

app.run(function($rootScope, $location, loginService){
    var routespermission=['/home'];  //route that require login
    $rootScope.$on('$routeChangeStart', function(){
        if( routespermission.indexOf($location.path()) !=-1)
        {
            var connected=loginService.islogged();
            connected.then(function(msg){
                if(!msg.data) $location.path('/login');
            });
        }
    });
});

 app/js/controller/loginCtrl.js
-------------------------------

'use strict';

app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
    $scope.msgtxt='';
    $scope.login=function(data){
        loginService.login(data,$scope); //call login service
    };
}]);

app/js/directives/loginDrc.js
-----------------------------
'use strict';
app.directive('loginDirective',function(){
    return{
        templateUrl:'partials/tpl/login.tpl.html'
    }

});
app/js/services/sessionService.js
---------------------------------
'use strict';

app.factory('sessionService', ['$http', function($http){
    return{
        set:function(key,value){
            return sessionStorage.setItem(key,value);
        },
        get:function(key){
            return sessionStorage.getItem(key);
        },
        destroy:function(key){
            $http.post('data/destroy_session.php');
            return sessionStorage.removeItem(key);
        }
    };
}])

app/js/services/loginService
----------------------------
'use strict';
app.factory('loginService',function($http, $location, sessionService){
    return{
        login:function(data,scope){
            var $promise=$http.post('data/user.php',data); //send data to user.php
            $promise.then(function(msg){
                var uid=msg.data;
                if(uid){
                    //scope.msgtxt='Correct information';
                    sessionService.set('uid',uid);
                    $location.path('/home');
                }
                else  {
                    scope.msgtxt='incorrect information';
                    $location.path('/login');
                }
            });
        },
        logout:function(){
            sessionService.destroy('uid');
            $location.path('/login');
        },
        islogged:function(){
            var $checkSessionServer=$http.post('data/check_session.php');
            return $checkSessionServer;
            /*
            if(sessionService.get('user')) return true;
            else return false;
            */
        }
    }

});

index.html
----------
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="css/app.css"/>
</head>
<body>
  <div ng-view></div>
  <!-- In production use:
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  -->
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-route.js"></script>

  <script src="js/app.js"></script>

  <script src="js/directives/loginDrc.js"></script>

  <script src="js/controllers/loginCtrl.js"></script>
  <script src="js/controllers/homeCtrl.js"></script>

  <script src="js/services/loginService.js"></script>
  <script src="js/services/sessionService.js"></script>
</body>
</html>

A: First, there is no short or only one answer to what you have asked. In addition to what has already been answered, let me try to add something more. At enterprise level , there are four major components ,

*

*UI

*User Authentication Server - Here you validate user credentials and generate necessary cookies for user to move forward on UI. If this step fails, user gets stopped right there. This server has nothing to do with API token generation & you need this for non -  API based systems too.Google Authentication is one example.

Extension:Siteminder Authentication
SiteMinder Cookies, their Usage, Contents and Security
Building a Java authentication server for Chatkit

*API Token Server - This server generates API tokens based on cookies generated on step # 2 i.e. you send cookies to server and get a token

*APIs - You use token generated in step # 3 to make API calls.

Its better that you deploy & manage these four components independently for better scale . e.g. in this article, they have mixed up authentication & token generation in single end point & thats not good - Microservices with Spring Boot — Authentication with JWT (Part 3)
By your write up, it looks that you have written component two & three on your own - usually folks utilize some ready made tools for this like CA SiteMinder - How CA Siteminder works – Basics

Any tips on how to generate a unique strong token?

I would suggest that you go via standardized way for better maintainability & security i.e. you choose JWT format. JSON Web Token (JWT) Authentication Scheme
Your token will be signed & encrypted so You would also need an encryption key server & a mechanism to rotate these keys at regular intervals.
JSON Web Tokens - How to securely store the key?
What is the difference between JWT and encrypting some json manually with AES?
CA person has attached a detailed pdf guide on this community portal - that will help you to understand the overall flow.
Sample Code / App to use of REST JWT token API
Your API code will need to fetch the encryption key and decrypt & decode the token to authenticate token. If token is tampered or missing, you need to flag it as such. There are libraries available for this.

Is it better to store the token inside a new cookie or in
  localStorage?

local Storage if UI & API are on different domains & Cookies if on same domain.
Should JWT be stored in localStorage or cookie?
Cross-Domain Cookies
Security of an application is also dependent on deployment model and that part you haven't specified in your question. Sometimes , developers might leave as simple flaws in their code as SQL Injection :)
What if JWT is stolen?

A: This is client side security which you can implement in regular Angular versions.
I have tried and tested this.
(Please find my article here:- https://www.intellewings.com/post/authorizationonangularroutes )
In addition to client side route security, you need to secure access at server side also.
Client side security helps in avoiding extra round trip to server. However, if someone tricks the browser , then server server side security should be able to reject unauthorized access.
Hope this helps!
Step 1: Define Global variables in app-module
-define roles for the application
  var roles = {
        superUser: 0,
        admin: 1,
        user: 2
    };

-Define route For Unauthorized Access for the  application
 var routeForUnauthorizedAccess = '/SomeAngularRouteForUnauthorizedAccess';

Step 2: Define the service for authorization
appModule.factory('authorizationService', function ($resource, $q, $rootScope, $location) {
    return {
    // We would cache the permission for the session, to avoid roundtrip to server for subsequent requests
    permissionModel: { permission: {}, isPermissionLoaded: false  },

    permissionCheck: function (roleCollection) {
    // we will return a promise .
            var deferred = $q.defer();

    //this is just to keep a pointer to parent scope from within promise scope.
            var parentPointer = this;

    //Checking if permisison object(list of roles for logged in user) is already filled from service
            if (this.permissionModel.isPermissionLoaded) {

    //Check if the current user has required role to access the route
                    this.getPermission(this.permissionModel, roleCollection, deferred);
} else {
    //if permission is not obtained yet, we will get it from  server.
    // 'api/permissionService' is the path of server web service , used for this example.

                    $resource('/api/permissionService').get().$promise.then(function (response) {
    //when server service responds then we will fill the permission object
                    parentPointer.permissionModel.permission = response;

    //Indicator is set to true that permission object is filled and can be re-used for subsequent route request for the session of the user
                    parentPointer.permissionModel.isPermissionLoaded = true;

    //Check if the current user has required role to access the route
                    parentPointer.getPermission(parentPointer.permissionModel, roleCollection, deferred);
}
                );
}
            return deferred.promise;
},

        //Method to check if the current user has required role to access the route
        //'permissionModel' has permission information obtained from server for current user
        //'roleCollection' is the list of roles which are authorized to access route
        //'deferred' is the object through which we shall resolve promise
    getPermission: function (permissionModel, roleCollection, deferred) {
        var ifPermissionPassed = false;

        angular.forEach(roleCollection, function (role) {
            switch (role) {
                case roles.superUser:
                    if (permissionModel.permission.isSuperUser) {
                        ifPermissionPassed = true;
                    }
                    break;
                case roles.admin:
                    if (permissionModel.permission.isAdministrator) {
                        ifPermissionPassed = true;
                    }
                    break;
                case roles.user:
                    if (permissionModel.permission.isUser) {
                        ifPermissionPassed = true;
                    }
                    break;
                default:
                    ifPermissionPassed = false;
            }
        });
        if (!ifPermissionPassed) {
            //If user does not have required access, we will route the user to unauthorized access page
            $location.path(routeForUnauthorizedAccess);
            //As there could be some delay when location change event happens, we will keep a watch on $locationChangeSuccess event
            // and would resolve promise when this event occurs.
            $rootScope.$on('$locationChangeSuccess', function (next, current) {
                deferred.resolve();
            });
        } else {
            deferred.resolve();
        }
    }

};
});

Step 3: Use security in routing: Lets use use all our hardword done so far, to secure the routes
var appModule = angular.module("appModule", ['ngRoute', 'ngResource'])
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider
            .when('/superUserSpecificRoute', {
                templateUrl: '/templates/superUser.html',//path of the view/template of route
                caseInsensitiveMatch: true,
                controller: 'superUserController',//angular controller which would be used for the route
                resolve: {//Here we would use all the hardwork we have done above and make call to the authorization Service
                    //resolve is a great feature in angular, which ensures that a route controller(in this case superUserController ) is invoked for a route only after the promises mentioned under it are resolved.
                    permission: function(authorizationService, $route) {
                        return authorizationService.permissionCheck([roles.superUser]);
                    },
                }
            })
        .when('/userSpecificRoute', {
            templateUrl: '/templates/user.html',
            caseInsensitiveMatch: true,
            controller: 'userController',
            resolve: {
                permission: function (authorizationService, $route) {
                    return authorizationService.permissionCheck([roles.user]);
                },
            }
           })
             .when('/adminSpecificRoute', {
                 templateUrl: '/templates/admin.html',
                 caseInsensitiveMatch: true,
                 controller: 'adminController',
                 resolve: {
                     permission: function(authorizationService, $route) {
                         return authorizationService.permissionCheck([roles.admin]);
                     },
                 }
             })
             .when('/adminSuperUserSpecificRoute', {
                 templateUrl: '/templates/adminSuperUser.html',
                 caseInsensitiveMatch: true,
                 controller: 'adminSuperUserController',
                 resolve: {
                     permission: function(authorizationService, $route) {
                         return authorizationService.permissionCheck([roles.admin,roles.superUser]);
                     },
                 }
             })
    });


text:
Q: In Android okhttpclient not caching public cache-control
*

*I am using below code to cache in Android device to collect the response and get from cache till the max age expires. When i use "public" I was able to see the response cached in my application installed folder(/data/data/app_folder).

*I tried all below none of them works for "private" but when I change to "public" all my solutions i tried works.

*But I need to make it to work for "private". Am I missing something.

*Header I will receive "Cache-Control", "private,max-age=120"
Solution 1:
File httpCacheDirectory = new File(context.getCacheDir(), "responses");

HttpResponseCache httpResponseCache = null;
try {
        httpResponseCache = new HttpResponseCache(httpCacheDirectory, 10 * 1024 * 1024);
    } catch (IOException e) {
        Log.e("Retrofit", "Could not create http cache", e);
    }

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setResponseCache(httpResponseCache);

Solution 2:

*

*And I am using Retrofit library, an Android client.
Cache cache = new Cache(cacheDirectory, cacheSize);
client = new OkHttpClient();
client.setCache(cache);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting Subscription ID with Resource Group and System ID Is there a way to programmatically get the subscription ID from Azure with only the Resource Group and System Id?
I have tried using the azure rest api
https://management.azure.com/subscriptions?api-version=2020-01-01
Which returns a single subscription ID but the ID returned doesn't house the resource group.

A: To get the subscription id using resource group use :
Get-AzResourceGroup -Name "ResourcegroupName"

Reference.


text:
Q: How to reshape multiple array in a list in Python I have a list of 3D arrays that are all different shapes, but I need them to all be the same shape.  Also, that shape needs to be the smallest shape in the list.
For example my_list with three arrays have the shapes (115,115,3), (111,111,3), and (113,113,3) then they all need to be (111,111,3). They are all square color images so they will be of shape (x,x,3).
So I have two main problems:

*

*How do I find the smallest shape array without looping or keeping a variable while creating the list?

*How do I efficiently set all arrays in a list to the smallest shape?

Currently I am keeping a variable for smallest shape while creating my_list so I can do this:
for idx, img in enumerate(my_list):
    img = img[:smallest_shape,:smallest_shape]
    my_list[idx] = img

I just feel like this is not the most efficient way, and I do realize I'm losing values by slicing, but I expect that.

A: I constructed a sample list with
In [513]: alist=[np.ones((512,512,3)) for _ in range(100)]

and did some timings.
Collecting shapes is fast:
In [515]: timeit [a.shape for a in alist]
10000 loops, best of 3: 31.2 µs per loop

Taking the min takes more time:
In [516]: np.min([a.shape for a in alist],axis=0)
Out[516]: array([512, 512,   3])
In [517]: timeit np.min([a.shape for a in alist],axis=0)
1000 loops, best of 3: 344 µs per loop

slicing is faster
In [518]: timeit [a[:500,:500,:] for a in alist]
10000 loops, best of 3: 133 µs per loop

now try to isolate the min step.
In [519]: shapes=[a.shape for a in alist]
In [520]: timeit np.min(shapes, axis=0)
The slowest run took 5.75 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 136 µs per loop

When you have lists of objects, iteration is the only way to deal with all elements.  Look at the code for np.hstack and np.vstack (and others).  They do one or more list comprehensions to massage all the input arrays into the correct shape.  Then they do np.concatenate which iterates too, but in compiled code.


text:
Q: Google Tag Manager LookUp of LookUps Output Values I have grouped four sets of landing pages into four corresponding LookUp Table variables, using {{page path}} as the input variable. I've applied an output value for each landing page within each of these groupings.
I group the above variables into another LookUp Table variable (basically a LookUp of LookUps), and use this in an all-pages pageview tag to populate a Google Universal Content Grouping.
My question is whether I need to apply an output value to each input in the LookUp of LookUps?
Asked differently -- since output values are applied to each input in the four landing page lookups, will these pass through to the lookup of lookups, or do I need to apply output values there, too?

A: In short, the approach above cannot work. It requires GTM variable values to change (as values go from the set of lookups to the 'lookup of lookups'), but they're not meant to chance. A variable is meant to either represent a value, or not.
I wound up inserting dataLayer variables into the landing page code to apply the needed page-by-page designations.


text:
Q: How to refer textfield name in ajax? I am trying to autofill information from a database into text fields when the user selects the specific name. I initialized the text fields with unique names that are dynamically added.
This is the table for the form:
  <form name="senarai" id="senarai">

                #
                Nama
                No Personal
                Department
                Telefon
                Ext

      </form>

            <input type="button" class="add-row" value="Add Row">
            <button type="button" class="delete-row">Delete Row</button>

The javascript below added the text field dynamically. It contains a selection field and text fields which will be filled with information grabbed from the database.

This is a javascript code to autofill the text fields.

I cannot put id on the text fields, it creates problems and warning in the console. I tried to use text field name property but the dynamic name  "nopersonal'+count+'" cannot be identified.
When i tried this:
  alert($('input[name="nopersonal'"]').val()); //i put test value in the textfield

The text field can be identified and the value appears in the alert.
How I can fix this issue? Thank you.
edited:
I had added a few rows, and the html as follows
   <input type="text" name="nopersonal1" value="test">
   <input type="text" name="jabatan1" value="test">
   <input type="text" name="telefon1" value="test">
   <input type="text" name="ext1" value="test">

   <input type="text" name="nopersonal2" value="test">
   <input type="text" name="jabatan2" value="test">
   <input type="text" name="telefon2" value="test">
   <input type="text" name="ext2" value="test">

   <input type="text" name="nopersonal3" value="test">
   <input type="text" name="jabatan3" value="test">
   <input type="text" name="telefon3" value="test">
   <input type="text" name="ext3" value="test">

The textfield name is in sequence as it should be.
But if you notice, there are 14 'inputs' in console without '+count+'. If I put id with '+count+' there is console with repeatitive 14 elements non unique id.
  selector string: input[name="nopersonal"] selected element: n.fn.init(14) [input, input, input, input, input, input, input, input, input, input, input, input, input, input, prevObject: n.fn.init(1), context: document, selector: "input[name="nopersonal"]"]

I am not sure the cause of it. Do you have any idea?

A: alert($('input[name="nopersonal'+count+'"]').val());//the problem is here

Have you tried building the selector first as a string, console.loging it to confirm that it looks right, and then passing it in to jQuery? I'm wondering if there might be an issue with count for some reason. If it were just a number, JS would be interpolating it into the string before it ever became a jQuery problem.
EDIT:
jQuery.ajax({
  url : 'add_demo/get_nama/'+ID,
  type : "GET",
  dataType : "json",
  success: function(data) {
    console.log(data);
    //   Changes
    const selectorString = 'input[name="nopersonal'+count+'"]';
    console.log("selector string: ", selectorString, "selected element: ", $(selectorString));
    alert($(selectorString).val());
    //   /Changes
    $('input[name="jabatan'+count+'"]').val(data.JabID);
    $('input[name="telefon'+count+'"]').val(data.notelttp);
    $('input[name="ext'+count+'"]').val(data.ext);
  }
});


text:
Q: Only desktop wallpaper is showing on booting? I updated my grub by removing nomodeset.
When I restarted my pc it showed only wallpaper.
I updated my grub again by adding nomodeset. It did not made any difference.
My terminal is not working I had to use ctrl - alt -f4 for cmd line operations.
My system is ubuntu 20.04 .

A: I don't have an actual solution, but a workaround I'm using is patience... I have found that if I wait several minutes after the login screen appears before logging in, it works.
Obviously, if you're not even getting the login prompt, this isn't apropos. Sorry I've got nothing else.


text:
Q: Windows form application clicking an "onclick=return" So im trying to make an script that does the BFH (in a game) auto but when it clicks on the sumbit button the webbrowser opens up an confirm box (code element inspecting showed down). So how do i make it so my application clicks the ok on the confirm box
The webbrowser opens up a box and the application has to click the ok button
Sorry if i explain it strange its because my english isnt that great
this is the button it clicks
<input class="submit" type="submit"
       onclick="return verifyTransport('Are you sure you want to transport €…,000 to the team deposit?\nThe trip will take 25 minutes.');"
       value="Transport € 5,000,000"
       name="dr_transport_money"></input>

Example of what it shows(cant show the real one can only do that once a day):

A: Try This:
private IWebElement element;
element = driver.FindElement(By.XPath("//input[@name='dr_transport_money']"));
element.Submit();

driver.SwitchTo().Alert().Accept();


text:
Q: Call to a member function find() on a non-object with extended model I have an "Admin" model which extends another model "User" which extends the "AppModel".
I have a controller "ApisController" in which I am trying to query the data from the admins table.
So I'm doing something like this:
$admins = $this->Admin->find('all');

But when I do that, I get the following error message:
Error: Call to a member function find() on a non-object
File: /home/farhan/www/core/app/Controller/ApisController.php
Line: 9

If I try to do the same thing in a controller "AdminsController", everything works fine. So I'm not sure what I'm doing wrong. I'm new to cake, so I understand if this is a simple error.

A: If you have ApisController and want to use an "Admin" model (which clearly is not the singular form from "Apis" - it would probably be Api), you need to manually declare your used model:
public $uses = array('Admin');

Then the controller has the "Admin" model available as primary one.
Book
Default is that cake tries to find the right one based on inflection:
PostsController => Post model
(plural => singular)


text:
Q: angular foreach problems when adding new items I have an angular application with Firebase. I want to change the value of an firebase item. Everytime the total KM changes it needs to be set to the right value. so this is my services:
    countKm(){
    this.totalKmRef = this.db.list(this.uid + '/rides');
    this.totalKm$ = this.totalKmRef.valueChanges();
    this.totalKm$.subscribe(res=> this.getAllRides(res));
  }

  getAllRides(res){
    this.rides = res;
    this.rides.forEach(ride =>{
        this.uniqueRides.push(ride.km);
    })
    this.totalKm = this.uniqueRides.reduce(this.sum);
    localStorage.setItem("totalKm", this.totalKm);
  }

  sum(a, b){
    return a += b;

  }

Now for some reason, when i add a ride everything is fine, but the second time everything goes wrong.
for example the first time the foreach runs i get (after firebase has already 5 items):
0{
0: 5,
1: 5,
2: 5,
3: 5,
4: 5,
}

After i run the foreach 1 time my object list is like this:
 0{
    0: 5,
    1: 5,
    2: 5,
    3: 5,
    4: 5,
    5: 5,
    }
After add a new value the second time and further the foreach does this:
0{
    0: 5,
    1: 5,
    2: 5,
    3: 5,
    4: 5,
    5: 5,
    6: 5,
    7: 5,
    8: 5,
    9: 5,
    10: 5,
    11: 5,
    12: 5,

        }

Is there some one who can help me? I think it's a wrong configuration in the foreach but can't find out where.
Thanks for you help!

A: this.uniqueRides.push(ride.km); is just pushing additional items into the array.
Either check to see if the ride is included .includes
this.rides.forEach(ride => {
   if(!this.uniqueRides.includes(ride)) {
      this.uniqueRides.push(ride.km);
   }
})

or clear the array out every time. this.uniqueRides = []


text:
Q: Upload a Folder to S3 bucket in Rails How can I upload an entire folder to the S3 Bucket or all the files of my folder to s3 bucket folder.
Right now I am only able to upload a file using the following code :
I want to upload a folder having  .gif,.jpeg,.html etc kind of files in it .
  def myfunction(location,source_file)
            s3 = Aws::S3::Resource.new(region:'region-name')
            obj = s3.bucket(bucket-name).object(location)
            obj.upload_file(source_file)
        end

A: There is no Amazon S3 API call to upload multiple files. You will need to upload one at a time, but you can do them in parallel if your programming language does multi-threading.
If you just need to copy files rather than including this functionality within your own app, you could use the AWS Command-Line Interface (CLI). It provides a aws s3 cp --recursive command and a aws s3 sync command that can copy whole directories for you. (It recursively copies each file.)


text:
Q: Stack Exchange profile shows zero count before posting any posts on the respective site The Stack Exchange network profile page showing zero questions and zero answers for all accounts.

After posting this question, it shows the questions count for Meta Stack Overflow.

Now the issue is clear, I'd posted a question just now on Sports.SE beta site and then I can see the questions count for Sports.SE in my network profile.
We should fix it.


text:
Q: XPath Count function always return 0.0 I'm using below xml to get the count of tag 'c'.
<?xml version='1.0' encoding='UTF-8'?>
<xyz xmlns=".....">
<a>
  <b>
    <c>X:1 Y:0</c>
    <c>X:1 Y:0</c>
    <c>X:2 Y:0</c>
  </b>
  <b>
    <c>X:1 Y:0</c>
    <c>X:2 Y:0</c>
  </b>
</a>
</xyz>

Below is my java code :
xpath = factory.newXPath();
xpr = xpath.compile("count(//xyz/a/b/c)");
System.out.println(xpr.evaluate(inputSource, XPathConstants.NUMBER));

But the above code always returns 0.0
Am I doing something wrong ?

A: If you want to count elements with the local name of xyz, the expression should be as follows:
XPathExpression xpr = xpath.compile("count(//*[local-name()='xyz']/*[local-name()='a']/*[local-name()='b']/*[local-name()='c'])");

Demo.

A: Don't delete the namespace attribute value. It is important because that is the actual namespace.
A xmlns="urn:somevalue"defines a default namespace for elements. A <xyz xmlns="urn:somevalue"/> or a <ns1:xyz xmlns:ns1="urn:somevalue"/> can be both read as node name {urn:somevalue}:xyz.
XPath 1.0 does not have a default namespace. You always have to use an prefix for nodes in a namespace.
So if you define the prefix ns1 in a namespace resolver for your XPath the expression would be:
count(//ns1:xyz/ns1:a/ns1:b/ns1:c)


text:
Q: Как добавить ограничение размера при копирование файлов? Для копирование файлов использую:
private static IEnumerable<string> nGetFiles(string path, string searchPatternExpression = "", SearchOption searchOption = SearchOption.AllDirectories)
{
  Regex reSearchPattern = new Regex(searchPatternExpression);
  return Directory.EnumerateFiles(path, "*", searchOption).Where(file =>
  reSearchPattern.IsMatch(Path.GetFileName(file)));
}
public static void CopyDesktopFiles()
{
  string LookForExt = @"\.ico|\.txt|\.doc|\.jpg|\.html"; // форматы
  IEnumerable<string> files = nGetFiles(des, LookForExt);
  foreach (var f in files)
  {
      try
      {
        File.Copy(f, Path.Combine(str1, Path.GetFileName(f)),true);
      }
      catch(Exception) { }
  }
}

Ранее для проверки размера папки использовал данный способ:
public static void CopyDesktopFiles(string Mask, SearchOption Option = SearchOption.AllDirectories)
{
   const long LimitSizeFiles = 3 * 1024 * 1024;// не копировать файл больше 3МБ
   long HighLimit = 59000000;
   long LowLimit = 0;
   var ListFormat = new List<string>() { ".txt", ".doc", ".cs", ".Html", ".Dll", ".Xml", ".Php", ".json" };
   foreach (var Files in new DirectoryInfo(otkuda).EnumerateFiles(Mask, Option))
   {
      var ext = Path.GetExtension(Files.Name);
      int Check = ListFormat.IndexOf(ext);
      if (Check < LowLimit) continue;
      if ((HighLimit -= Files.Length) < LowLimit) break; // тут проверка
      try
      {
        if (ListFormat.Contains(ext) && Files.Length <= LimitSizeFiles)
            Files.CopyTo(Path.Combine(kudacopy, Files.Name));
      }
      catch { }
   }
}

Подскажите как в 1-ом методе добавить ограничение?
Пробовал сделать как и во 2-ом но не выходит, он просто копирует всё сразу.
Нужно добавить только ограничение размера папки при копирование файлов, и если размер превышает допустимый размер (HighLimit = 59000000) то завершить копирование.

A: Единственное отличие новой версии от предыдущей в том, что в цикле работа ведется со строкой, вместо экземпляра класса FileInfo.
Так как строка, в данном случае - это путь к файлу, можно изменить метод nGetFiles таким образом, чтобы он возвращал список FileInfo и можно будет использовать предыдущий код.
Например так:
private static IEnumerable<FileInfo> nGetFiles(string path, string searchPatternExpression = "", SearchOption searchOption = SearchOption.AllDirectories)
{
  Regex reSearchPattern = new Regex(searchPatternExpression);
  return Directory.EnumerateFiles(path, "*", searchOption)
                  .Where(file => reSearchPattern.IsMatch(Path.GetFileName(file)))
                  .Select(file => new FileInfo(file));
}

Либо создавать экземпляр FileInfo непосредственно внутри foreach для проверки размера текущего файла.


text:
Q: How can I update the R home directory in Jupyter Lab? I am having a hard time updating my R version in Jupyter Lab.  I downloaded the most recent R version (4.1.3), but Jupyter still appears to be pointing at the wrong R folder / old version of R (4.1.0).  Can someone help me with how to update which version of R jupyter is using?
I don't use Conda, which may complicate things.


text:
Q: Pattern matching in instanceof sometimes cannot resolve theoretically resolvable scope import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

List<Node> list = new ArrayList<>();
Node x = list.get(0);
if (!(x instanceof Comment comment)) {
    if (!(x instanceof Document doc && doc.getFirstChild() instanceof Comment comment)) {
        return null;
    }
}
System.out.println(comment.ToString()); // cannot resolve comment

Variable comment cannot be resolved but it should be - we covered 2 mutually exclusive happy paths and each of them assigns Comment comment - and system out should be able to see comment, otherwise return null would have been triggered.

A: You can't declare the same variable in two different places using pattern matching. Those are still two different variables, with two different scopes.
Perhaps, we can clear the confusion by giving them different names:
if (!(x instanceof Comment comment)) {
    if (!(x instanceof Document doc && doc.getFirstChild() instanceof Comment comment2)) {
        return null;
    }
    //comment2 and doc are in scope here,
    //but their scope ends with an enclosing block
    System.out.println(comment2.toString());
}
//FAIL! You can't access comment2 outside its scope
System.out.println(comment2.toString());
//FAIL! You can't access comment here because
//the compiler can't guarantee that the block above exited.
System.out.prinltn(comment.toString()

You can verify that pattern-matched variables still remain in their enclosing scope using a simple example like this:
{
    Object o = null;
    if(!(o instanceof String s)) {
          return;
    }
    System.out.println(s); //OK
}
System.out.println(s); //Doesn't work

Sorry, I don't really have an elegant alternative for you to use. You can achieve what you want with a somewhat ugly workaround:
Comment comment;
if (!(x instanceof Comment c)) {
    if (!(x instanceof Document doc && doc.getFirstChild() instanceof Comment c)) {
        return null;
    }
    comment = c;
} else {
    comment = c;
}
System.out.println(comment.toString());

This workaround gets better if you can move this snippet into a separate method:
private static Comment extractComment(Node x) {
    if (!(x instanceof Comment comment)) {
        if (!(x instanceof Document doc && doc.getFirstChild() instanceof Comment comment)) {
            return null;
        }
        return comment;
    }
    return comment;
}

Or even:
private static Comment extractComment(Node x) {
    if (x instanceof Comment comment) {
        return comment;
    }
    if (x instanceof Document doc && doc.getFirstChild() instanceof Comment comment) {
        return comment;
    }
    return null;
}


text:
Q: column_spec does not render in beamer presentation
So as picture shows, after using kableExtra in beamer presentation my tables don't render properly.
My header included
 header-includes:
- \usepackage{booktabs}
- \usepackage{longtable}
- \usepackage{array}
- \usepackage{multirow}
- \usepackage{wrapfig}
- \usepackage{float}
- \usepackage{colortbl}
- \usepackage{pdflscape}
- \usepackage{tabu}
- \usepackage{threeparttable}
- \usepackage{threeparttablex}
- \usepackage[normalem]{ulem}
- \usepackage{makecell}
- \usepackage{xcolor}

Code to example:
StrukturaWiekuIPlciWedlugProgramu2 %>%
    mutate(Kobiety = cell_spec(Kobiety,"latex",
           background =  ifelse(Kobiety > 0, "#91d400", "white")),
           `Mężczyźni` = cell_spec(`Mężczyźni`,   "latex",
           background =  ifelse(`Mężczyźni` > 0, "#91d400", "white")))   %>%
           kable(format = "latex", booktabs = T) %>%
           kableExtra::column_spec(4, bold = T) %>%
           kable_styling("striped", full_width = F,
           position = "center",
           font_size = 7)


text:
Q: Getting Missing number, treated as zero error when trying to fit table in the document While trying to dynamically render a table, it gets out of the document generated and looks as follows:

To avoid this, I followed the steps mentioned in:

*

*SO Post - 1, which uses tabularx

*SO Post - 2, which uses adjustbox
But for both the approaches tried, I get an error saying:
Missing number, treated as zero

I tried reading about this error but could not understand, as it does not throw any error when doing without tabularx or adjustbox.
I am rendering my table using lualatex code as shown below:
 tex.print("\string\\begin{tabularx}{"  .. col_schema ..  "}")

 -- row / col rendering here

 tex.print("\string\\end{tabularx}")

The document is generated from the JSON. I have shared JSON with the link for easier viewing : https://codebeautify.org/jsonviewer/cbe2bd65
What could I do to avoid this error?

A: The problem is in
tex.print("\string\\begin{tabularx}{"  .. col_schema ..  "}")

This generates TeX code like
\begin{tabularx}{ | l | l|}

which misses a parameter: The tabularx environment expects the total width as first parameter, like
\begin{tabularx}{5cm}{ | X | X|}

Also this uses X, a column type for automatically sized columns. This type is the main feature of tabularx, so if you do not want to use it for your table, a normal tabular is a better choice.
So there are two possible fixes: Decide for a width and pass it to tabularx, additionally replace at least one column by a X column or replace tabularx with tabular. With tabular, you do not need to pass a width, TeX automatically uses the natural width of your table.


text:
Q: Electron.js app: Bootstrap dropdown menu won't open I'm trying to use Bootstrap in my first Electron.js app. The dropdown button does appear, but the menu itself doesn't appear when I click on the button. I suspect there is something wrong with how I've added Bootstrap and jQuery to the app.
Here is my index.html:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Magic</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="index.css" />

Magic Demo!

Welcome to the most magical demo ever!

      <button class="btn btn-secondary dropdown-toggle"
              type="button"
              id="dropdownMenu2"
              data-toggle="dropdown"
              aria-haspopup="true"
              aria-expanded="false">
        Dropdown
      </button>

        <button class="dropdown-item" type="button">Action</button>
        <button class="dropdown-item" type="button">Another action</button>
        <button class="dropdown-item" type="button">Something else here</button>

I added Bootstrap, jQuery and Popper.js via npm and this is the relevant part of my package.json:
"dependencies": {
    "bootstrap": "^4.6.0",
    "electron-log": "^4.3.2",
    "electron-squirrel-startup": "^1.0.0",
    "jquery": "^3.6.0",
    "popper.js": "^1.16.1"
  },

Also, I discovered that on the Electron DevTools, I get the error:
"Uncaught ReferenceError: require is not defined"

A: You are loading the bootstrap.js before the content. If the elements do not exist in the DOM when the script is loaded it will have no effect.
The Bootstrap Docs tell you where to place the script:

... near the end of your pages, right before the closing  tag, to
enable them.

A: The Bootstrap 4.6.0 drop-down menu doesn't open with jQuery version 3.6.0, but works correctly with jQuery 3.5.1. I just tried it, and it's true.
Try downgrading jQuery to version 3.5.1.


text:
Q: Wordpress REST API - get custom taxonomy category posts I want to use Wordpress REST API to get the posts that are inside a custom taxonomy created by the theme.
The taxonomy is called "my_portfolio" but if I use this I have this response:

{"code":"rest_no_route","message":"Nessun percorso fornisce una
corrispondenza tra l'URL ed il metodo
richiesto.","data":{"status":404}}

Instead if I use "my_portfolio_category" I have 4 categories that are called: "photo", "video", "design", "web".
I want to retrieve the posts inside the category "photos" but the only thing I managed to get is the category info.
The API I used is the one down below where 921 is the ID of the category "photo", using the slug doesn't work.
https://www.mywebsite.com/wp-json/wp/v2/my_portfolio_category/921
Is there a way to get the posts?
If this is not possible it could be helpful getting just the posts inside the taxonomy without dividing them into categories.


text:
Q: Representation Theory on Hilbert spaces Are there any good references on representation theory of Lie groups on infinite-dimensional vector spaces, or more specifically, unitary reps on Hilbert spaces? Some application in physics would be nice if possible.

A: Brian C. Hall: Lie Groups, Lie Algebras, and Representations: An Elementary Introduction (Graduate Texts in Mathematics)


text:
Q: In-House Distribution - Xamarin and VS2019 Version I was wondering whether I need the Enterprise version of VS2019 to create In-House Distribution for Xamarin.iOS Apps or Pro would suffice?
Also, what would be benefit for Mobile when using Enterprise vs. Professional?
Thanks,
Alex

A: When we check Compare Visual Studio 2019 Editions,we will find each version has all the features of the previous version, as well as additional features.
With Visual Studio Professional, it's an excellent choice for most developers. For software architects though, Visual Studio Enterprise might make sense, as long as you have plenty of budget.  But if you don't, a lot of plugins in the Visual Studio ecosystem can help you get VS Enterprise's features in ala carte fashion.
For creating In-House Distribution for Xamarin.iOS Apps, the Visual Studio Community is suffice, let alone the professional version.


text:
Q: Chrome different versions different outputs Im styling a Joomla site (I will never in my life work with Joomla again not for all the tea in China) and I was specifically aware of the outputs in IE, but now I realize that there are huge differences between different chrome versions outputs, even with the shame OS (mac).
Is there anyway I can check how the bloody site looks like with different chrome versions?
The pages that do screenshots wont do the job, as much of this disorders appear in loged areas...
Please help me, I need to finish this and forget Joomla for the rest of my life.

A: Sorry, it was not a problem of the Chrome version but the screen resolution.
I'm a bit obfuscated after this fight with Joomla.


text:
Q: Change value of duplicated rows There is a table with tow columns(ID, Data) and there are 3 rows with same value.
ID          Data
4           192.168.0.22
4           192.168.0.22
4           192.168.0.22

Now I want to change third row DATA column. In update SQL Server Generate an error that I ca not change the value.
I can delete all 3 rows. But I can not delete third row separately.
This table is for a software that I bought and I changed the third Server IP.

A: You can try the following query
create table #tblSimilarValues(id int, ipaddress varchar(20))
insert into #tblSimilarValues values (4, '192.168.0.22'),
(4, '192.168.0.22'),(4, '192.168.0.22')

Use Below query if you want to change all rows
with oldData as (
      select *,
             count(*) over (partition by id, ipaddress) as cnt
      from #tblSimilarValues
     )
update oldData
    set ipaddress = '192.168.0.22_1'
    where cnt > 1;
select * from #tblSimilarValues

Use Below query if you want to skip firs row
;with oldData as (
      select *,
             ROW_NUMBER () over (partition by id, ipaddress order by id, ipaddress) as cnt
      from #tblSimilarValues
     )
update oldData
    set ipaddress = '192.168.0.22_2'
    where cnt > 1;

select * from #tblSimilarValues
drop table #tblSimilarValues

You can find the live demo live demo here

A: Since there is no column that allows us to distinguish these rows from each other, there's no "third row" (nor a first or second one for that matter).
We can use a ROW_NUMBER function to apply arbitrary row numbers to these rows, however, and if we place that in a CTE, we can apply DELETE/UPDATE actions via the CTE and use the arbitrary row numbers:
declare @t table (ID int not null, Data varchar(15))
insert into @t(ID,Data) values
(4,'192.168.0.22'),
(4,'192.168.0.22'),
(4,'192.168.0.22')

;With ArbitraryAssignments as (
    select *,ROW_NUMBER() OVER (PARTITION BY ID, Data ORDER BY Data) as rn
    from @t
)
delete from ArbitraryAssignments where rn > 2

select * from @t

This produces two rows of output - one row was deleted.
Note that I say that the ROW_NUMBER is arbitrary. One of the expressions in both the PARTITION BY and ORDER BY clauses is the same. By definition, then, we know that no real ORDER is defined by this (because all rows within the same partition, by definition, have the same value for that expression).

A: In this case ID columns allows duplicate value which is wrong, ID should be unique.
Now what you can do is create a new column make that unique or Primary Key or change the duplicate values of ID column and make it Unique/Primary key.

Now as per your Unique key/Primary key you can update DATA column value by query as below:
UPDATE <Table Name>
SET DATA = 'new data'
WHERE ID = 3;


text:
Q: Python 2.7 -- Calling an Abstract Base Class' method from an Instance I am searching for the proper way to call an abstract base class' method from an instance of a class that is registered as a subclass of the ABC. This is some very basic test code to first figure out how to make this work. This is where I am currently at:
from abc import ABCMeta

# Dog class
class Dog(object):
    def speak(self):
        pass
    def move(self):
        pass

# Barking behaviors
class Bark(object):
    __metaclass__ = ABCMeta
    def speak(self):
        print "bark bark bark"

class Howl(object):
    __metaclass__ = ABCMeta
    def speak(self):
        print "ahwoooooo"

# Movement behaviors
class Run(object):
    __metaclass__ = ABCMeta
    def move(self):
        print "I'm running"

class Walk(object):
    __metaclass__ = ABCMeta
    def move(self):
        print "I'm walking"

# Dog implementations
class Beagle(Dog):
    pass
Howl.register(Beagle)
Run.register(Beagle)

nora = Beagle()
nora.speak() # THIS IS THE ISSUE: Calls speak() from original Dog class
nora.move()  # Need to call move() from registered ABC

# Test to be sure .register() was used properly
assert isinstance(nora, Howl)

While this approach may seem overly involved to alter the two Dog methods, I am looking to have the flexibility of being able to assign the behaviors to an unknown amount of instances. I'd like to be able to call speak() and move() without the instance knowing the actual behavior. I also like this approach because I am able to easily remove or change the behavior that a class is registered too, without altering any existing code.
The way the code reads currently nora.speak() and nora.move() call the inherited methods from Dog to Beagle, which just contain pass.
I'd appreciate if anyone has any insight on what I need to do from this point to make the registered behavior's methods callable, or if my approach is flawed entirely.

A: Here is my attempt (probably not the most pythonic way, but something close to your post):
class Animals(object):
    def speak(self):
        return self.speak_action

    def swim(self):
        return self.swim_action

    def move(self):
        return self.move_action

class Dog(Animals):
    @property
    def speak_action(self):
        return "bark bark bark"

    @property
    def move_action(self):
        return "I'm Running"

class Beagle(Dog):
    @property
    def speak_action(self):
        return "ahwoooooo"

class Duck(Animals):
    @property
    def swim_action(self):
        return "Im floating"

    @property
    def speak_action(self):
        return "Quack!!"

    @property
    def move_action(self):
        return "I Fly!"

class Mallard(Duck):
    @property
    def speak_action(self):
        return "I'm Flying higher"

(It is good practice to let exceptions to bubble up)
In [825]: d = Dog()

In [826]: d.speak()
Out[826]: 'bark bark bark'

In [827]: d.move()
Out[827]: "I'm Running"

In [828]: d.swim()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-828-c6d2ef2b464d> in <module>()
----> 1 d.swim()

.stuff/python/git_py/help_so.py in swim(self)
      4
      5     def swim(self):
----> 6         return self.swim_action
      7
      8     def move(self):

AttributeError: 'Dog' object has no attribute 'swim_action'

You can chose what you want to delegate:
In [830]: b = Beagle()

In [831]: b.speak()
Out[831]: 'ahwoooooo'

In [832]: b.move()
Out[832]: "I'm Running"

In [833]: b.swim()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-833-9c7b1a0c0dca> in <module>()
----> 1 b.swim()

/stuff/python/git_py/help_so.py in swim(self)
      4
      5     def swim(self):
----> 6         return self.swim_action
      7
      8     def move(self):

AttributeError: 'Beagle' object has no attribute 'swim_action'

And create other animals that with more skills:
In [849]: dd = Duck()

In [850]: dd.speak()
Out[850]: 'Quack!!'

In [851]: dd.move()
Out[851]: 'I Fly!'

In [852]: dd.swim()
Out[852]: 'Im floating'

You can specific things to individual classes, and even defaults, to the main class, and you can extended as you want/need.


text:
Q: Change Background Color When
* is Active using Javascript I want to change background color of
 where the class is active, when I click on those li > a. How can I do it in this case. He is what I have tried:
Script

Style
.sidebar-collapse .nav > li > a {
    background: #EFEFEF;
    text-shadow: none;
    color: #595959;
    border-top: 1px solid #dfdfdf;
}

Menu List HTML

                Dashboard

                UI Elements

                        Notifications

                        Elements

                        Free Link

                Table Examples

                Forms

                Multi-Level Dropdown

                        Second Level Link

                        Second Level Link

                        Second Level Link

                                Third Level Link

                                Third Level Link

                                Third Level Link

                Tabs & Panels

                Mettis Charts

                Last Link

                Blank Page

A: If you are somewhy bounded to js solution you need to use css. Since background is not an attribute but a style and can't be "removed".
$('.sidebar-collapse .nav > li > a').click(function (e) {
    var li = $(this).closest('li');
    if (li.hasClass('active')) {
        li.css('background-color', 'transparent'); //or inherit
    }
});

Or a pure CSS solution. Which is preferred:
.sidebar-collapse .nav > li.active > a {
    background-color: transparent;
}


text:
Q: Does ukelele custom keyboard allow multiple unicodes values for single keypress? I want to create a custom keyboard in Mac. Came across ukelele, which accepts unicode value.
I am designing layout for devnagri indian language, so one character can be a combination of 2-3 unicode values, does ukelele support this?
Or only one unicode can be given at at time for a keypress


text:
Q: Keras LSTM with varying timesteps Suppose the input to the model is a series of vectors, each with equal length. However, the number of vectors in each input can change. I want to make an LSTM model using Keras, but if I were to write
input = keras.layers.input(dims)
img_out = keras.layers.recurrent.LSTM(16)

Then what would I put for "dims"? Thanks so much.

A: You can fix an upper bound for dims. When the input is less than dims, you can pad the rest with zero vector.


text:
Q: Google AuthToken Validity for C2DM Services I am Developing a web server which sends push messages automatically to my android application whenever I add new data on web server. But, for sending the push message through C2DM server we need to get a google Authentication Token(AuthToken). My doubt is that whether the token can be saved and used for later times also, or we should every time get a fresh AuthToken...!!!
Someone please help me regarding this..!
Thanks in Advance

A: As far as I know, Google did not state how long the Authentication Token will be valid. But when sending out a push notification to the C2DM server, the response may include a Update-Client-Auth, where also a new AuthToken is included.
So basically you can store the AuthToken and reuse it, just make sure that you handle the response, and of course, if you receive a 401 Code as response, you have to manually request a new Auth Token.
See also:
C2DM Sending Messages
Google C2DM


text:
Q: Create data frame with column characteristics from separate table's rows I have a descriptive, auxiliary table whose rows specify variable's characteristics, where varCat describes a variable category, rept the number of later-to-implement repetitions of said category, and form their data format:
require(dplyr)
require(tidyr)
require(purrr)

descr <- tibble(
  varCat = c("a", "b"),
  rept = c(1, 3),
  form = c("text", "num")
)
descr
#> # A tibble: 2 × 3
#>   varCat  rept form
#>   <chr>  <dbl> <chr>
#> 1 a          1 text
#> 2 b          3 num

What I'd like to obtain is the following (empty) data frame:
d
#> # A tibble: 0 × 4
#> # … with 4 variables: a <chr>, b_1 <dbl>, b_2 <dbl>, b_3 <dbl>

Created on 2022-09-27 with reprex v2.0.2
Two steps are involved:

*

*The auxiliary table's var and rept together establish column names in the 'goal' data frame such that if rept equals 1, no suffix should be applied; yet if rept is larger than 1, a sequence of columns with suffix should be created;

*Each column's format should be read off descr$form
I have managed to implement these steps, albeit I feel quite clumsily:
# Step 1:
tmp <- descr %>%
  uncount(rept, .id = "rept") %>%
  group_by(varCat) %>%
  mutate(
    n = n(),
    var = case_when(
      n > 1 ~ paste0(varCat, "_", rept),
      TRUE ~ varCat
    )
  ) %>%
  ungroup %>%
  select(var, form)
c <- tmp$var
d <- matrix(ncol = length(c), nrow = 0) %>%
  as_tibble(.name_repair = "unique") %>%
  set_names(c)

# Step 2:
for (i in colnames(d)) {
  for (j in seq_along(tmp$var)) {
    if (tmp$var[j] == i & tmp$form[j] == "text") d[i] <- as.character(d[i]) else
    if (tmp$var[j] == i & tmp$form[j] == "num") d[i] <- as.numeric(d[i])
  }
}
d
#> # A tibble: 0 × 4
#> # … with 4 variables: a <chr>, b_1 <dbl>, b_2 <dbl>, b_3 <dbl>

Created on 2022-09-27 with reprex v2.0.2
I'm sure there must be a much more concise way to achieve this. Any help would be much appreciated.

A: Using mapply with a custom function that returns a list, then use call data.frame to convert the list to a data.frame:
foo <- function(varCat, rept, form){
  f <- setNames(c("character", "numeric"), c("text", "num"))[ form ]
  x <- rep(list(vector(mode = f)), rept)
  x <- setNames(x, rep(varCat, rept))
  if(rept > 1) names(x) <- paste(names(x), seq(names(x)), sep = "_")
  x
}

out <- data.frame(mapply(foo, descr$varCat, descr$rept, descr$form,
                         USE.NAMES = FALSE))

#check the output
out
# [1] a   b_1 b_2 b_3
# <0 rows> (or 0-length row.names)
str(out)
# 'data.frame': 0 obs. of  4 variables:
# $ a  : chr
# $ b_1: num
# $ b_2: num
# $ b_3: num

A: Similar to @zx8754's answer, but making the a/b_1/b_2/b_3 naming as well:
as.data.frame(
    list("text"=character(0), "num"=numeric(0))[rep(descr$form, descr$rept)],
    col.names=paste0(
        rep(descr$varCat, descr$rept),
        unlist(lapply(descr$rept, \(x) if(x > 1) paste0("_", sequence(x)) else "" ))
    )
)
##[1] a   b_1 b_2 b_3
##<0 rows> (or 0-length row.names)

The key element is as.data.frame.list, which allows the subset list() generating the column types, to be named directly via the col.names= argument.

A: A tidyverse approach using purrr::pmap and dplyr::bind_cols may look like so:
library(dplyr)
library(purrr)

descr <- tibble(
  varCat = c("a", "b"),
  rept = c(1, 3),
  form = c("text", "num")
)

purrr::pmap(descr, function(varCat, rept, form) {
  col_type <- switch(form,
                     "text" = character(0),
                     "num" = numeric(0)
  )
  d <- bind_cols(map(seq(rept), ~ col_type))
  names(d) <- if (rept > 1) {
    paste(varCat, seq(rept), sep = "_")
  } else {
    varCat
  }
  d
}) %>%
  bind_cols()
#> New names:
#> • `` -> `...1`
#> New names:
#> • `` -> `...1`
#> • `` -> `...2`
#> • `` -> `...3`
#> # A tibble: 0 × 4
#> # … with 4 variables: a <chr>, b_1 <dbl>, b_2 <dbl>, b_3 <dbl>


text:
Q: Stored procedure could not be found Java App looks like this
In my Database class I have a method connect() and generateCSV(),
First one looks like this:
public void connect() throws Exception {
    System.out.println("Begining of connect method");
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    } catch (ClassNotFoundException e) {
        throw new Exception("Driver not found");
    }

    String ser = "<ser name>";
    String user = "<user name>";
    String pass = "<password>";

    String dbURL = "jdbc:sqlserver://" + ser + ";user=" + user + ";password=" + pass;
    con = (Connection) DriverManager.getConnection(dbURL);

    System.out.println("Connected! " + con);
}

and the second one generateCSV() like this
public void generate_CSV(String db,String tbl,String date, String out) {

    try {
        connect();
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    ResultSet rs = null;
    try {
        CallableStatement st = con
                .prepareCall("{call dbo.generate_CSV(?,?,?,?)}");
        st.setEscapeProcessing(true);

            st.setString(1, db);
            st.setString(2, tbl);
            st.setString(3, date);
            st.setString(4, out);

            rs= st.executeQuery();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

When I fire event and call generateCSV method, method will call connect() and connect to the server and afterwards call my procedure written in mssql.
Unfortunately I receive this...

com.microsoft.sqlserver.jdbc.SQLServerException: Could not find stored
  procedure 'dbo.generate_CSV'.

What am I missing?
I tried it without specifying the schema but nothing changes.


text:
Q: read a file from runner in github actions using java I have couple of files: asdf.json and qwer.json that are sitting in /runner of self-hosted vm after github actions is run
Now I want to read those files into my java code with something like File file = new File("asdf.json");
I always end up getting file not found exception while doing this. I tried with new File("runner/asdf.json") and is still the same

A: If you file is located in your repository you have to use GITHUB_WORKSPACE variable to access it, like this:
${{ env.GITHUB_WORKSPACE }}/asdf.json
and pass it to your Java code.
Of course you have checkout your repository first:
- uses: actions/checkout@v2


text:
Q: WPF panel header title I am not sure they correct terminology for a header/title bar of a component in WPF. What I need is a panel/non-floating window, in which I can set the title? I want a few components in a panel that needs a title like Properties and Toolbox in Visual Studio.
As mentioned earlier, this doesn't need to be a floating/docking panel. I don't want GroupBox. I will be adding close button later just to hide the component from the user.

A: I think, that in WPF visual solutions are limited only by our imagination.
If there isn't the control you want - you can build it.
My simple solution is here:
<Border Visibility="Visible" BorderThickness="2" BorderBrush="Blue" CornerRadius="8" Margin="30,30,30,30">
    <StackPanel Margin="3">
        <Label  Height="25" Content="H e a d e r" Background="LightSkyBlue" />
            <Separator Height="5"/>
            <Grid>
                <!-- content -->
            </Grid>
        </StackPanel>
    </Border>

Changing Visibility="Collapsed" you can hide this "panel".

A: If you don't need it to undock and float then you can use a HeaderedContentControl.
When you want to add the close button you can template the header presenter to include a button.


text:
Q: How to position nested cards in React using Material UI? Im using Material UI for React and working on the Material Cards Component. My requirement is, Im displaying a card which sits right below the main App bar. This card has one more smaller card nested inside it. The problem is Im able to move the smaller card inside the bigger card horizontally using the marginLeft attributes. However Im unable to move this smaller card vertically inside the bigger card. When i use marginTop attribute, the bigger(Parent card) also moves down.
How can I change the position of the card vertically inside the parent card?
My code is as follows:

<div>
  <Card style={{ width: '100vw', height: '60vh', margin: 'auto', marginTop: '0.05vh', backgroundColor: '#263238', }}>
    <Card style={{ width: '30vw', height: '40vh', marginLeft: '10vw', marginTop: '0.05vh', backgroundColor: '#FAFAFA', }}>
      <CardText color="#263238" style={{ fontSize: '3vw', }}>
        Lorem Ipsum Lorem Ipsum
      </CardText>
    </Card>
  </Card>
</div>


text:
Q: Bash Script - initiate remote X redirected application Perhaps I am using the wrong keywords to find an answer to this requirement.
I have a GUI installed on a remote linux system that use remote connecting into it and initiating the application with X redirection, like this:
ssh -Y user.known@aServer.lan
cd /home/user.known/TheAppDir/
sh ./ApplicationCommand

with the above I have the GUI displayed on my local linux from the aServer
My question is - how can I write a bash on my local linux that would initiate the process above in one go?
Ideally, I want to run a bash script like:
aServer.ApplicationCommand

And I have the GUI running locally as a result?

A: If you create the file aServer.ApplicationCommand (don't forget the chmod +x to make it executable) and place in it:
#!/bin/bash
ssh -Y user.known@aServer.lan "cd /home/user.known/TheAppDir/ ; sh ./ApplicationCommand"

This should work. You will still be prompted for a password unless you have ssh keys configured.
Explanation
SSH can be used strictly to run a command rather than return a session by placing the command after the SSH command. Essentially when doing this it opens a session, runs the provided command and then closes it.
Because you want multiple commands to be executed we simply place a semi-colon between to separate them and enclose in quotations so it remains an argument to the SSH command.
BONUS
Rename the script to aServer and change the script to:
#!/bin/bash
ssh -Y user.known@aServer.lan "cd /home/user.known/TheAppDir/ ; sh ./$1"

and call it using aServer ApplicationCommand, the advantage to this is if you have multiple scripts in TheAppDir that you want to call you just change the argument.
I think you can even still capture $? to see if the script executed properly and create an error message if the file was not found, but you'd have to test that.


text:
Q: Cannot sign up for aws The first entrance asks for an ID. Which I do not know because I did not go. I registered the same thing 3 times. I can't write to support because I need to sign in. I registered. And a message came in an email that I was registered
enter image description here

A: You are not on the Signup page and its a login which you are trying now.
Hope below AWS documentation will help you.
https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/


text:
Q: How to add an event to the body tag in Angular? I would like to find out a better way to implement this functionality.
I'm trying to add an even to the body tag. I'm using Angular 4.
Since the body tag (in index.html) is not processed through a component, I can't use the angular way to accomplish this.
I would normally do something like this for the xyz.component.html:
(click)="myMethod()"

And something like this in the xyz.component.ts
public myMethod(): void {
    // do something here
}

Due to my limited knowledge in Angular, I can't think of a better way to do this, other than adding the event directly to the body tag, like this:
<body onscroll="myMethod()">

And place the actual function between script tags in the head of the index.html file itself, like so:
<head>
    <script>
        function myMethod(){
            // do something here
        }
    </script>
</head>

I tried adding an event listener to the body (window/document) inside the class in app.component.ts, like so:
export class AppComponent implements OnInit{
    public myMethod(): void{
        window.addEventListener('myEvent', this.myEventHandler, false);
    }
}

This did not work for me. After I inspected the element, I could see that the event does not get attached.

A: You can have access to document/window scroll event from your components or directives with Hostlistener.
For example, the bellow will track the body scroll. It's used inside a directive, but you can also put it in a component.
import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({ selector: '[trackScroll]' })
export class TrackScrollDirective {
    constructor(private el: ElementRef) {
}

    @HostListener('document:scroll', [])
    onScroll(): void { //will be fired on scroll event on the document
         document.querySelector('body').classList.add('newClass'); // access to the body tag
    }
}

This can be used with window:scroll event.


text:
Q: Auto-opening side-loaded taskpane Is it possible to auto-open plugins that are in developer mode?
According to documentation

The pane that you designate to open automatically will only open if
  the add-in is already installed on the user's device. If the user does
  not have the add-in installed when they open a document, the autoopen
  feature will not work and the setting will be ignored. If you also
  require the add-in to be distributed with the document you need to set
  the visibility property to 1; this can only be done using OpenXML, an
  example is provided later in this article.

In particular, the file i'm attempting to auto-open is what based off office-generator with a single modification:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <we:webextension xmlns:we="http://schemas.microsoft.com/office/webextensions/webextension/2010/11" id="{acbc717b-5139-428a-9089-e9d6d7d8affc}">
  <we:reference id="acbc717b-5139-428a-9089-e9d6d7d8affc" version="1.0.0.0" store="developer" storeType="Registry"/>
  <we:alternateReferences/>

  <we:properties>
    <we:property name="Office.AutoShowTaskpaneWithDocument" value="true"/>
  </we:properties>

  <we:bindings/>
  <we:snapshot xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"/>
</we:webextension>

with the addition of <we:property name="Office.AutoShowTaskpaneWithDocument" value="true"/>
and by modifying manifest.xml as follows:
<Action xsi:type="ShowTaskpane">
  <TaskpaneId>Office.AutoShowTaskpaneWithDocument</TaskpaneId>
  <SourceLocation resid="Taskpane.Url"/>
</Action>

Problem:
It is expected that there would be one taskpane which would be opened automatically.
The task pane that was opened automatically has an error which states that we can't find the task pane to open. On the other hand, clicking on the ribbon allows the task pane to open as per normal, side by side with the broken auto-opened task pane as shown in the image below:

A: There's a hidden-state in Microsoft Word somewhere, that persists even after restarts. To reproduce the error you pretty much need a new computer.
Let me explain how i got it working after... 1 week.
First start with office-js generator.
yo office, for which i selected typescript.

Modify src/taskpane/taskpane.ts as follows:
export async function run() {
  return Word.run(async context => {
    /**
     * Insert your Word code here
     */

    // insert a paragraph at the end of the document.
    const paragraph = context.document.body.insertParagraph("Hello World", Word.InsertLocation.end);

    // change the paragraph color to blue.
    paragraph.font.color = "blue";

    // Add these two lines
    Office.context.document.settings.set("Office.AutoShowTaskpaneWithDocument", true);
    Office.context.document.settings.saveAsync();
    // Technically should wait, but doesn't matter.

    await context.sync();
  });

Modify manifest.xml as follows:
Replace ButtonId1 with Office.AutoShowTaskpaneWithDocument
<Action xsi:type="ShowTaskpane">
  <TaskpaneId>Office.AutoShowTaskpaneWithDocument</TaskpaneId>
  <SourceLocation resid="Taskpane.Url"/>
</Action>

Launch the project as per normal.
npm run start
Click the run button to trigger the creation of the auto-open file.

Save the file somewhere.
Re-open it to verify that it works. Funnily enough, it created an identical taskpanes when i clicked on the show taskpane button. This is a bug but works for me. It's for testing purposes after all.

To prove that the file's problem is indeed a hidden state:
Clone the repo on a new computer, npm run start, copy the file over.
Run the file and you will get the same problem as i got in my original post.


text:
Q: Mongodb: Query on the last N documents(some portion) of a collection only In my collection that has say 100 documents, I want to run the following query:
collection.find({"$text" : {"$search" : "some_string"})

Assume that a suitable "text" index already exists and thus my question is : How can I run this query on the last 'n' documents only?
All the question that I found on the web ask how to get the last n docs. Whereas My question is how to search on the last n docs only?
More generally my question is How can I run a mongo query on some portion say 20% of a collection.
What I tried
Im using pymongo so I tried to use skip() and limit() to get the last n documents but I didn't find a way to perform a query on cursor that the above mentioned function return.
After @hhsarh's anwser here's what I tried to no avail
# here's what I tried after initial answers
recents = information_collection.aggregate([
                {"$match" : {"$text" : {"$search" : "healthline"}}},
                {"$sort" : {"_id" : -1}},
                {"$limit" : 1},
            ])

The result is still coming from the whole collection instead of just the last record/document as the above code attempts.
The last document doesn't contain "healthline" in any field therefore the intended result of the query should be empty []. But I get a documents.
Please can someone tell how this can be possible

A: What you are looking for can be achieved using MongoDB Aggregation
Note: As pointed out by @turivishal, $text won't work if it is not in the first stage of the aggregation pipeline.
collection.aggregate([
  {
    "$sort": {
      "_id": -1
    }
  },
  {
    "$limit": 10  // `n` value, where n is the number of last records you want to consider
  },
  {
    "$match" : {
      // All your find query goes here
    }
  },
], {allowDiskUse=true})  // just in case if the computation exceeds 100MB

Since _id is indexed by default, the above aggregation query should be faster. But, its performance reduces in proportion to the n value.
Note: Replace the last line in the code example with the below line if you are using pymongo
], allowDiskUse=True)

A: It is not possible with $text operator, because there is a restriction,

The $match stage that includes a $text must be the first stage in the pipeline

It means we can't limit documents before $text operator, read more about $text operator restriction.

Second option this might possible if you use $regex regular expression operator instead of $text operator for searching,
And if you need to search same like $text operator you have modify your search input as below:

*

*lets assume searchInput is your input variable

*list of search field in searchFields

*slice that search input string by space and loop that words array and convert it to regular expression

*loop that search fields searchFields and prepare $in condition

searchInput = "This is search"
searchFields = ["field1", "field2"]
searchRegex = []
searchPayload = []

for s in searchInput.split(): searchRegex.append(re.compile(s, re.IGNORECASE));
for f in searchFields: searchPayload.append({ f: { "$in": searchRegex } })
print(searchPayload)

Now your input would look like,
[
  {'field1': {'$in': [/This/i, /is/i, /search/i]}},
  {'field2': {'$in': [/This/i, /is/i, /search/i]}}
]

Use that variable searchPayload with $or operator in search query at last stage using $in operator,
recents = information_collection.aggregate([
  # 1 = ascending, -1 descending you can use anyone as per your requirement
  { "$sort": { "_id": 1 } },
  # use any limit of number as per your requirement
  { "$limit": 10 },
  { "$match": { "$or": searchPayload } }
])

print(list(recents))

Note: The $regex regular expression search will cause performance issues.

To improve search performance you can create a compound index on your search fields like,
information_collection.createIndex({ field1: 1, field2: 1 });


text:
Q: Are the reminders of a set's elements modulo the cardinal all equal when none of the subset's sums is divisible by the cardinal? If I have a set, I know it has a subset whose sum is divisible by the original set's cardinal. (See here)
If I have a set where none of its proper subsets' sums is divisible by the original set's cardinal, does all of the original set's elements have the same reminder modulo the original set's cardinal?

A: It is true that all numbers in the set are congruent modulo the cardinality of the set.
Denote the set by $S$ and suppose $|S| = n \geqslant 2$. If $n = 2$, suppose $S = \{a, b\}$, then $2 \not\mid a$, $2 \not\mid b$ implies $a \equiv b \equiv 1 \pmod{2}$.
For $n \geqslant 3$, if $a, b \in S$ satisfy $a \not\equiv b \pmod{n}$, suppose $S = \{a, b, c_1, \cdots, c_{n - 2}\}$. Now consider the following $n$ proper subsets:$$
\{a\}, \{b\}, \{a, b\}, \{a, b, c_1\}, \cdots, \{a, b, c_1, \cdots, c_{n - 3}\}.
$$
Because for any of these sets, $n$ does not divide the sum of its elements, by the pigeonhole principle, there are two sets $A$ and $B$ such that the sum of $A$'s elements is congruent to that of $B$'s. Note that if $A = \{a\}$, then $B \neq \{b\}$, and if $A = \{b\}$, then $B \neq \{a\}$, therefore either $A$ and $B$ are in this chain:$$
\{a\} \subset \{a, b\} \subset \{a, b, c_1\} \subset \cdots \subset \{a, b, c_1, \cdots, c_{n - 3}\},
$$
or in this chain:$$
\{b\} \subset \{a, b\} \subset \{a, b, c_1\} \subset \cdots \subset \{a, b, c_1, \cdots, c_{n - 3}\}.
$$
Without loss of generality, suppose $A \subset B$, then $B \setminus A$ is a non-empty proper set of $S$ but $n$ divides the sum of the elements of $B \setminus A$, a contradiction.
Therefore, all elements in $S$ are congruent modulo $|S|$.


text:
Q: Is it possible to push to gitlab from a gitlab job I'd like to push tags to the gitlab repository for which a job is running.
I'm using the Gradle plugin reckon which is using the grgit/JGit API. Reckon is managing semantic versioning and is able to create and push a tag to a Git repository.
First I want to run in GitLab SaaS. And I assume I need a kind of token so I don't have to pass my personal credentials for security reasons?
Then I also have to work on running it in GitLab hosted environment. But I would expect that in both environments it should work the same way.
There is some thing like a deploy key but I really can't find any references on how to use them. But maybe deploy key is not really made for that kind of operation.
.release-template:
  stage:
    release
  image: adoptopenjdk:11-jdk-hotspot
  dependencies:
    - deliver
  script:
    - |
      ./gradlew reckonTagPush -Preckon.scope=$scope -Preckon.stage=$stage \
        -Dorg.ajoberstar.grgit.auth.username=${???} \
        -Dorg.ajoberstar.grgit.auth.password=${???}
    artifacts:
      paths:
        - build/
  #only:
  #  - master
  when: manual #ONLY MANUAL RELEASES, ONLY FROM MASTER

release-major:
  extends: .release-template
  variables:
    scope: major
    stage: final

release-minor:
  extends: .release-template
  variables:
    scope: minor
    stage: final

release-patch:
  extends: .release-template
  variables:
    scope: patch
    stage: final

A: If all you're doing is adding a git tag to the repo, and not adding commits, merging branches, etc. you can simply use the Tags API to create a new tag:
curl --request POST --header "PRIVATE-TOKEN: $(CI_JOB_TOKEN)" "https://gitlab.example.com/api/v4/projects/:project_id:/repository/tags?tag_name=test&ref=master"

The $CI_JOB_TOKEN variable is a Predefined Variable automatically provided to running jobs by Gitlab. The $CI_JOB_TOKEN specifically will hold a non-admin API token, which should be fine for the Tags API.
If you were using other API's that requires Admin permissions, you'd have to use a personal access token of an Admin.


text:
Q: How can I screen-scrape the HTML result of a non-trivial user scenario I want to be able to get the HTML for a page which, if I was doing it interactively in a browser, would involve multiple actions and page loads:
1. Go to homepage
2. Enter text into a login form and submit the form (post)
3. The post will go through various redirections and frameset usage.
Cookies are adapted throughout this process.
In the browser, after submitting, I just get the page.
But to do this with curl (in PHP or whatever) or wget or A.N.Other low level technology, the management of cookies, redirections and framesets all becomes quite a chore and very tightly binds my script to the website (making it very susceptible to even small changes in the website that I'm scraping from.)
Can anyone suggest a way to do this?
I've already looked at Crowbar and PhantomJS and Lynx (with cmd_log/cmd_script options) but chaining everything together to mimic exactly what I'd do in Firefox or Chrome is difficult.
(As an aside, it might even be useful/necessary for the target website to think this script is Firefox or Chrome or a "real" browser)

A: One way to do this is using Selenium RC. While it's usually used for testing, at it's core it's just a browser remote control service.
Use this web site as a starting point: http://seleniumhq.org/projects/remote-control/

A: You can use irobot at irobotsoft to record a robot and replay it.
If you prefer low-level control, you can use HTQL python interface, see: http://htql.net/htql-python-manual.pdf.  It allows you to access an IE-based browser from python.

A: Use a tool like Firebug to check what headers are submitted to the website for login, and then replicate that exactly in your code.
Or just login with your browser and then reuse the cookie in your code.


text:
Q: Has anyone been able to use 21CFR Part 11 with Embedded Signing? There is a guide on the Docusign website (https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-in-app-embedded-cfrpart11/) for this, but I keep getting the error "This Account lacks sufficient permissions. In-Session permission required when specifying a captive recipient." which suggests that embedded signing is not possible.
Has anyone been able to use the guide above?

A: CFR Part 11 is possible with embedded signing but as the how to guide shows you will need to use the SMS for access & signatures authentication method.
Running this example requires that you have a CFR Part 11 account with the "SMS for access & signatures" authentication method enabled.
You can contact DocuSign Support to get that enabled.


text:
Q: Securing file system for secure SFTP server This might not seem as a development question, but in essence it is.  Let me explain how.  Our main development focus is dynamic content pages.  Some of our customers have asked us to allow them space in our servers (which they pay) for their old static content.  We use to accomplish this by giving the customer a ftp account to a different domain.  (e.g. Customer domain is customer.com but they were accessing their static content through otherdomain.com/customerstatic).
Now we want to increase the security giving customers sftp accounts in their linux servers.  I am using openssh/sftp-server in their shell environment so they are unable to log in or execute commands.
The problem is that by nature many file system files are by default (drwxr-xr-x) which means that any user will be able to read the content of the directory and possibly some files.  I don't think that changing the whole file system to -rwxr-x--x is a wise move since I don't know how many system files will need that read permission.
Have someone confronted this issue in the past.  If you have, could you enlighten the way?
Thanks

A: SFTP by nature isn't insecure; letting them into your whole filesystem is. Check this out to see how you can enable SFTP access on a chroot basis, which will lock in the directories they can access to, say, their home directories, or wherever you want them to upload.
On Linux, I would pay attention to this part (configuring /etc/ssh/sshd_config):
  Match Group sftponly
         ChrootDirectory %h
         ForceCommand internal-sftp
         AllowTcpForwarding no

This means that anyone in the 'sftponly' user group would be restricted to their home directories.
See the link for more, and also read the sshd_config manpage. Hope that helps.

A: This may be of interest - http://sublimation.org/scponly/wiki/index.php/Main_Page
Allowing you to restrict some users to scp only - and also optionally chroot'ing them.

A: When you say "Many filesystems are by default 755 permissions", that actually means the default umask is set to 022.  You can change this default (for new files) by setting the umask to 027, which would make the default permissions 750, or set the umask to 007, which would make the default permissions 770.

A: You might consider setting up an OpenVZ server, and then creating a separate small VM ftp/sftp 'container' for each company.  This keeps them all separate, and once you get the hang of OpenVZ it really handy for these sort of small things.


text:
Q: Prove by induction for a sequence Consider a sequence $g(n)$ defined by $g(1) = 2, g(2) = 3$ and $g(n+1) = 3g(n) - g(n-1)$ for $n > 1$.
Prove by induction that $$g(2n) \equiv 3 \pmod{5}\quad \text{and} \quad g(2n+1) \equiv 2 \pmod{5}$$ for $n > 0$.
I'm kind of getting stuck at the induction steps. Please help!

A: Suppose the thesis holds until $2n$. Then
$$ g(2n+1) = 3g(2n) - g(2n-1) = 3(5k +3) - (5h +2) = 5d +2, $$
and
$$ g(2n+2) = 3g(2n+1) - g(2n) = 3(5k+2) - (5h+3) = 5d +3. $$


text:
Q: Elasticsearch 2.4.3 having issue with .docx file during creating document index Thanks in advance
I am new in elasticsearch and using elasticsearch 2.4.3. When I am indexing documents then .doc, pdf,txt,xls is working fine but when I tried with .docx file then it is creating issue.
Below are response which I am getting, It is showing successful but in Response section, we are getting created : false
Successful low level call on PUT: /ilemsdocuments/indexeddocument/F%3A%5CIndexTestSamples%5CIndexTestSamples%5CBaconNarrative.docx?pretty=true
# Audit trail of this API call:
 - [1] HealthyResponse: Node: http://localhost:9200/ Took: 00:00:00.1688474

         # Request:
        {
        "activityNumber": "2016-001390",
        "activityOccurrenceDate": "2016-03-09T00:00:00",
        "activityPrepDate": "2016-01-26T00:00:00",
        "activityReportDate": "2016-01-08T00:00:00",
        "author": "Bard Laabs",
        "category": "Interviews",
        "dataOwnerDatabase": "main",
        "dataOwnerDisk": "main",
        "databaseLastUpdate": "2016-03-28T00:00:00",
        "documentEntityId":   "F:\\IndexTestSamples\\IndexTestSamples\\BaconNarrative.docx",
      "file": {
        "_content": "-- Remove the actual content as its size is big",
        "_indexed_chars": -1
      },
      "fileExtension": "docx",
      "fileFullName": "F:\\IndexTestSamples\\IndexTestSamples\\BaconNarrative.docx",
      "indexedFileInfo": {
        "creationTime": "2016-09-09T12:50:32+05:30",
        "fullName": "F:\\IndexTestSamples\\IndexTestSamples\\BaconNarrative.docx",
        "lastIndexTime": "2017-01-03T11:55:20.6993801+05:30",
        "lastWriteTime": "2017-01-03T11:52:18.1251173+05:30",
        "length": 14479
      },
      "fileLastUpdate": "2017-01-03T11:52:18.1251173+05:30",
      "fileName": "BaconNarrative.docx",
      "indexDate": "2017-01-03T11:55:20.6993801+05:30",
      "indexSource": "IndexingAgent.FileWatcher",
      "indexedPath": "F:\\IndexTestSamples\\IndexTestSamples",
      "isLocked": false,
      "isNarrative": false,
      "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "title": "My Document: 2017-01-03T11:55:22.3480831+05:30",
      "uploadedBy": "testuser"
    }

     # Response:
        {
        "_index" : "ilemsdocuments",
        "_type" : "indexeddocument",
        "_id" : "F:\\IndexTestSamples\\IndexTestSamples\\BaconNarrative.docx",
        "_version" : 3,
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
         },
        "created" : false
        }

Please help me, if someone face this issue.


text:
Q: Realm objects returns nil after adding I created an Person object when the User logs in:
let creds = SyncCredentials.jwt(accessToken)
SyncUser.logIn(with: creds, server: Constants.syncAuthURL, onCompletion: { [weak self](user, err) in
    if let user = user {
        self?.setDefaultRealmConfiguration(with: user)
        let realm = try! Realm()
        let identity = (user.identity)!

        let person = Person()
        person.id = identity
        try! realm.write {
          realm.add(person, update: true)
        }

        self?.performSegue(withIdentifier: "showProfile", sender: self)
     }
})

The Person successfully created on the cloud server.
In the next viewcontroller i like to fetch the object based on the id:
let realm = try! Realm()
guard let uuid = SyncUser.current?.identity! else { return }
let person = realm.objects(Person.self).filter("id = %@", uuid).first

try! realm.write {
  person?.name = "test"
}

The person is always nil I also tried the query the object with the primary key, but with no success.
The Person class looks like:
class Person : Object {

    @objc dynamic var id = ""
    @objc dynamic var created: Date = Date()
    @objc dynamic var name = ""
    @objc dynamic var email = ""
    @objc dynamic var avatar : Data?

    override static func primaryKey() -> String? {
        return "id"
    }
}

UPDATE
I created a new app with just one Viewcontroller and the Person class:
class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let creds = SyncCredentials.usernamePassword(username: "admin", password: "test")
    SyncUser.logIn(with: creds, server: Constants.AUTH_URL, onCompletion: { (user, err) in
        if let user = user {

            var config = user.configuration(realmURL: Constants.REALM_URL)
            config.objectTypes = [Person.self]
            Realm.asyncOpen(configuration: config, callback: { (realm, error) in

                guard let realm = realm else {return}

                let objects = realm.objects(Person.self)

                print(objects) // always empty why???

                try! realm.write {
                    let p = Person()
                    p.id = "test"
                    realm.add(p)
                }
                print(objects) // one object
            })
        }
    })
  }
}

as with my other problem the person is successfully added to the cloud. but when I restart the app the objects are empty on the first query. Maybe I miss understanding something with the synched realms?

A: let results = realm.objects(Person.self)
let subscription = results.subscribe()
print(results)

resolve my problem


text:
Q: python text to hex and searching hex data or convert everything to binary Decided to do a complete remake of the question. Hexedit in its default settings displays hex in the center window and ansi text in the right window. The below is the current code:
patlst = [line.strip() for line in open(patch,'rb',1)] #Read Patch start
if alphex == 'h' :
    old = patlst[patlst.index('OLD:')+1] #get old data str
    new = patlst[patlst.index('NEW:')+1] #get new data str
    old = old.lower();old = ''.join(old.split())
    new = new.lower();new = ''.join(new.split())
pircwd = os.chdir('..'); pircwd = os.getcwd() ##DIR change
with open(tar, 'rb') as f:
    data = binascii.hexlify(f.read(160))
with open(tar+'BAK', 'wb') as f:
    f.write(data.replace(b'old',b'new'))

Original hexedit view unaltered:

Desired result:

Actual result:

I believe this requires the pack and unpack function to work properly? Or is there a better way all in all to do this?

A: To convert from (ASCII-encoded) hex to binary, you can use binascii.unhexlify().

A: Ok lost ALL my login info. And the registered email account is dead. Parks Banyon is the secret identity of Gary Washington. I'm going to repost the question in a different context, titled "python print data to stout in the format python sees. IE raw.

A: Basically this particular question was looking at 3 problems and hopefully a single solution.  Apparently this is not the case. As such I will refer to the following stackoverflow question as a partial answer (Why does Python print unicode characters when the default encoding is ASCII?) and vote Dan Getz' reply as the workable solution. I will repost the problems as 3 individual questions and hope the answers do not conflict.


text:
Q: Cloudfront suddenly slow We are a B2B company and one of our clients customers is facing very slow download speeds from our cloudfront distribution for the 6-7 days. Earlier it was working fine. Our client provides learning videos which his customer is not able to stream at all (speeds < 4-5 kbps). The internet connection is good as all other video sites are working smooth and even cloudfront was smooth earlier. 2-3 other customers have also been complaining about sudden slowness.

A: I will advice you to try following steps to debug to understand where the real problem is:

*

*accessing the video directly viz. using S3 bucket and not via CloudFront. Response with CloudFront should be faster as compared to accessing directly.

*Note that Cloudfront is faster when u acccess same video second time. First time it will be slower.

*Try accessing via CF from different IP Address and if possible from different Data provider. Might be you can try using your Mobile connection.. sometimes, it is the problem of connectivity between that particular data provider and CF.


text:
Q: Caching the resultset of a very slow query I have a table with about 13 million rows. Each row represents a measurement of a certain type for a particular project for a particular hour of a particular day.
I have a query that finds sums or averages of these values depending on the measurement type. It's very slow, like a few minutes.
We have certain reporting pages that utilize the results of this query, but it's not acceptable for the pages to take multiple minutes to load. My solution so far has been to cache the results of the query in what I'm calling a summary table.
The problem is that the nightly-run script that refreshes the summary table takes too long to run. I'm not even trying to refresh the whole summary table at once but it still takes too long. (By "too long" I mean errors are raised and the refresh job is not completed.)
I have a hunch that the challenges I'm facing are a result of going about things in the wrong way, and that the solution is maybe not to tweak a few things to shave off the query run time by 1% here and there but to approach the problem in a completely different way.
Any suggestions would be appreciated. I apologize if I'm not asking this question in a very good way; I'm not sure how to formulate it better. Happy to provide clarification or more details.
Here's a simplified version of the query that takes forever to run. (Even this simplified version takes quite a long time.)
  select date(calc_dt),
         project_id,
         calculation_type_cd,
         sum(result)
    from calc_calculation_results
group by date(calc_dt),
         project_id,
         calculation_type_cd

The nightly job is basically a SELECT INTO that takes the results of this query and puts them into my summary table. The result column is the value we're interested in for the purpose of the reports.

A: Summary table(s) -- good.  Rebuilding them -- bad.  Instead, augment them incrementally every night.
With a Summary table, the main table needs very few indexes, thereby making it more efficient to load.
The Summary tables have whatever indexes are appropriate for the queries.
More discussion of Summary Tables
Your simplified version might become
INSERT INTO Summary ( date, project_id, type_cd, sum_result )
    select CURDATE() - INTERVAL 1 DAY,
           project_id,
           calculation_type_cd,
           sum(result)
    from calc_calculation_results
    WHERE calc_dt >= CURDATE() - INTERVAL 1 DAY
      AND calc_dt  < CURDATE()
    group by project_id,
             calculation_type_cd

It might have
PRIMARY KEY(date, project_id, type_cd),
INDEX(project_id, date),
INDEX(type_cd, date)