text:
Q: problem with Count number of online users with angular ,nodeJS and Socket.io I have trouble to display the correct amount of online users. So When the user connect the count increase and decrease if disconnect but the problem is when i refresh the page the count still increasing i use angular as frontend and nodejs as backend please i need help to resolve this problem my code ServerSide is

var numberOfOnlineUsers = 0;
      io.on('connection', function(socket) {

         socket.on('join', function(data){
            //joining
            numberOfOnlineUsers++;
            socket.emit('numberOfOnlineUsers',numberOfOnlineUsers); console.log('Hey, welcome! '+data.username);
            socket.broadcast.emit('new user joined',numberOfOnlineUsers );console.log(numberOfOnlineUsers+ ' Users connected!');

          });

          socket.on('leave', function(data){
            numberOfOnlineUsers--;
            socket.broadcast.emit('user left',numberOfOnlineUsers);console.log(numberOfOnlineUsers+ ' Users connected!');

          });

         socket.on('demande',function(data){
            socket.broadcast.emit('new demande', {demandeur:data.demandeur, demande:data.demande,datedem:data.datedem});
          })

      });

and Client Side is:

  public ngOnInit(): void {

        this.socket.on('new user joined', (numberOfOnlineUsers) => {
            this.numberOfOnlineUsers = numberOfOnlineUsers;
            console.log(this.numberOfOnlineUsers);
          });

          this.socket.on('user left', (numberOfOnlineUsers) => {
            this.numberOfOnlineUsers = numberOfOnlineUsers;
            console.log(this.numberOfOnlineUsers);
          });

  }

A: You should subscribe to socket.on('disconnect')
The logic on disconnect event at server side is fired when the socket disconnects due to any reason.
Check This Article Also
So the code should look like :-
io.on('connection', function(socket) {

        .
        .
        .
  socket.on('disconnect', (reason) => {
     console.log('Socket disconnected');
  });

});

A: My problem is when i reload the page the count of online users increment so i didn't have the real count of the users you understand the issue?


text:
Q: Should a HTML table with checkboxes to select each row be contained in a fieldset with a legend element? Fieldset and legend elements are used to group related form controls. This is easy to understand and apply for "regular" forms, e.g. a "Your Details" fieldset with text input fields for first name, surname etc.
However, should fieldset and legend elements be used on a list page in an application, where users select table rows with associated checkboxes, prior to performing a bulk action on the selected rows?
For example:
<form>
  <fieldset>
    <legend>Users</legend>

          Name

          <input type="checkbox" name="SelectedItem" value="Anna" />
          Anna

          <input type="checkbox" name="SelectedItem" value="Chris" />
          Chris

    Bulk action
    <select id="ListAction" name="ListAction">
      <option value="Nothing" selected="selected">Select action</option>
      <option value="Delete">Delete</option>
      <option value="Suspend">Suspend</option>
    </select>
    <input type="submit" value="Go" name="BulkActionGo" />
  </fieldset>
</form>

https://www.w3.org/TR/WCAG20-TECHS/H71.html states that "Grouping controls is most important for related radio buttons and checkboxes. A set of radio buttons or checkboxes is related when they all submit values for a single named field."
This is the case in the example above, but fieldset/legend still doesn't seem like a natural fit for this use case, which may contain a lot of tabular data - and unrelated pagination controls - rather than a simple set of form controls.

A: The easiest solution is to name each checkbox with a different name, for instance using an array (which is easily parsable in PHP for instance)

   <input type="checkbox" name="SelItem[0]" value="Anna" title="Select Anna" />
   Anna

   <input type="checkbox" name="SelItem[1]" value="Chris" title="Select Chris" />
   Chris

This way it will be apparent for assistive technologies (and any inner algorithm inside your software or external softwares) that your intent is not to create group related checkboxes, but a set of checkboxes related to individual records.
The fieldset is useful for situations where the legend give the instructions:
<fieldset>
  <legend>Select your favorite Beatles</legent>
  <input type="checkbox" nama="fab4" value="John" />John
  <input type="checkbox" nama="fab4" value="Paul" />Paul
  <input type="checkbox" nama="fab4" value="George" />George
  <input type="checkbox" nama="fab4" value="Ringo" />Ringo
</fieldset>

If you want to specify characteristics about individual records, the intent is different and the checkbox names may be linked to the row, not to the column.

John

    <input type="checkbox" name="john[is_singer]" value="1" />Sing
    <input type="checkbox" name="john[play_guitar]" value="1" />Play guitar

Paul

    <input type="checkbox" name="paul[is_singer]" value="1" />Sing
    <input type="checkbox" name="paul[play_guitar]" value="1" />Play guitar

This will let assistive technologies handle the form easily without the use of any redundant fieldset

A: No, there's no reason to include it in a fieldset. If you want to apply styling elements or refer to it in JavaScript, you can put it in a div, but a fieldset doesn't have any practical application in this case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing the Page Object Model I am building a test automation project using Perl and Selenium. I am using the Page Object Model. I am somewhat unsure about where the Selenium driver would fit into the implementation of the page object model.
Should each page object 'have' a driver ? The way I am thinking is that each page object represents a set of services that the page offers to a user. With this concept in mind , a page object does not have a 'has-a' relationship with a driver. A page object interacts with a driver. However, I am still looking for suggestions. Should I have the driver as part of each page object in the web-application?
Thanks!

A: This answer won't be any much different from @zodvik, and your thought process, but is another optional approach. Instead of passing the driver around, you can create an abstract class that each page object can then inherit from. From the abstract class, can also contain some common functional methods that you will find yourself often using.
This is at least how I do it in Java language.

A: I always include driver as part of every Page Object. The way I thought about driver was that it represents the state of the current page. It gives access to the URL, Page Source, etc.
Now, each page has a a current URL, a page source code, a page title which are all accessible through the driver.

A: In the way, I implemented the framework. I used the driver in the commonFactory.class that contains commonly used elements. Each page was implemented as a child class of the commonFactory.class. so you don't have to implement the driver in each and every class. Since the driver is independent of the test scenarios it's better to have it in a separate way.

A: As I understand, there are No set rules/standards for implementing POM.
However, the general thumb rule is to create a BaseTest and BasePage class in your Framework where each respective webpage (like Login) will represent by its PageClass(LoginPage).
Similarly, all your Page classes will extend your BasePage and all tests will extend your BaseTest class.
Below is a rough idea of its implementation ->

public class BaseTest{

@BeforeSuite()
setupMethod(){
initialize your WebDriver here
}

}

------------------------------------------
public class BasePage {

  //create constructor
  public BasePage(WebDriver driver) {
    this.driver = driver;
    this.wait = new WebDriverWait(this.driver, Duration.ofSeconds(TIMEOUT));
    PageFactory.initElements(new AjaxElementLocatorFactory(this.driver, TIMEOUT), this);
  }

  //other common methods which can be utilized in your respective child Page classes

}

----------------------------------------------------
public class LoginPage extends BasePage {

    //Your Locators and Weblelements
    private static final LOGIN_ID = "login";

    //Constructor to supply webdriver
    public LoginPage(WebDriver driver) {
        super(driver);
    }

    //your action methods
    public void loginToApp(){
    driver.findbyelement(By.ID(LOGIN_ID)).click
    }

}
----------------------------------------------------
public class LoginTest extends BaseTest{

public LoginPage login;
BeforeAll()
{
login = new LoginPage(driver);
}

@Test
public void verifyLogin(){
login.loginToApp();
}

}


text:
Q: Postgres error: non-integer constant in ORDER BY Running this query produces an error only on windows (psql v14 & v15) and runs fine on linux. Are there some settings that are causing this?
SELECT 1 ORDER BY TRUE;

To make it work on windows it needs casting:
SELECT 1 ORDER BY TRUE::BOOLEAN;


text:
Q: Access the HTML page inside service in AngularJS I want to access particular HTML page inside a service. Currently, I have made the function inside a controller that can be called from its linked HTML page but I want to access that function from multiple pages. So, I'll want service or factory for it to make it available from anywhere.
In that function, I want the content of particular HTML page but that content is available only when I call the function from that page only.
Here is my function.
$scope.downloadReport = function(type) {

      var pdf = new jsPDF('p', 'pt', 'a4');
      var source;

      var options = {
         pagesplit: true,
         background: '#ffffff',
         letterRendering: true
      };
      pdf.internal.scaleFactor = 2;

      source = document.getElementsByClassName('complete-report')[0];

      pdf.addHTML(source, options, function () {
        pdf.save('report.pdf');
      });
  };

document.getElementsByClassName('complete-report')[0]; It will get data from the HTML page linked with controller.

So, I need service which access the particular HTML page such that I use that function there to get the content of particular HTML page.

A: As pointed to wprzechodzen, you shouldn't access directly your HTML inside a service but, instead, you should pass only source variable.
However, if you want to access HTML in service you have to do something like this:
yourApp.controller('something', function($scope, $window, $document, yourServiceName){
  yourServiceName.yourFunction($document)
})

yourApp.factory('yourServiceName', function(){
  return {
    yourFunction: function(doc){
       //here you get  $document
    }
  }
})

Here's the $document's docs

A: You have to make sure that the DOM element which you are trying to access must be loaded in the DOM. Till then you cant do anything.
You can try giving id tag (e.g. elementID)for that perticular dom element and try accessing like below.
var source = angular.element("#elementID");


text:
Q: pactl not working in DWM config file After seting up shortcuts in config.h, pactl is not working at all. However when I run pactl in terminal, it works as intended
config.h:
#include <X11/XF86keysym.h>

static const char *upvol[]   = { "/usr/bin/pactl", "set-sink-volume", "@DEFAULT_SINK@", "+5%",     NULL };
static const char *downvol[] = { "/usr/bin/pactl", "set-sink-volume", "@DEFAULT_SINK@", "-5%",     NULL };
static const char *mutevol[] = { "/usr/bin/pactl", "set-sink-mute",   "@DEFAULT_SINK@", "toggle",  NULL };

static Key keys[] = {
    { 0,                       XF86XK_AudioLowerVolume, spawn, {.v = downvol } },
    { 0,                       XF86XK_AudioMute, spawn, {.v = mutevol } },
    { 0,                       XF86XK_AudioRaiseVolume, spawn, {.v = upvol   } }

};

Even if i replace @DEFAULT_SINK@ with 1 (which is my current sink), it still dosen't work
function keys work because xev detects that they have assigned events:
KeymapNotify event, serial 37, synthetic NO, window 0x0,
    keys:  2   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
           0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

I run DWM through LightDM session with dwm.desktop file in /usr/share/xsessions:
[Desktop Entry]
Encoding=UTF-8
Name=dwm
Comment=Dynamic window manager
Exec=dwm
Icon=dwm
Type=XSession

A: Turns out DWM in some cases must be fully reinstalled to overwrite some settings
sudo make uninstall && sudo make install


text:
Q: What can I use as the generic term for "a function that is composed with another"? Suppose I am talking about the composition $g \circ f$ (or more generally $f_n \circ \cdots \circ f_1$). Is there a generic term for the functions $f$ and $g$ (the functions $f_i$)?
"Compositand"?


text:
Q: 1 duplicate symbol for architecture arm64 - Xcode - running out of ideas I've had this issue for a few days now, I've tried all the stuff on Stackoverflow so far and have no where to turn to and I don't know what to do.
Error:

ld: 1 duplicate symbol for architecture arm64

clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any suggestions?
Paste bin to entire log:
https://pastebin.pl/view/dfc1fdca
Relevant entries from the log:
Showing Recent Messages
Ld /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Products/Debug-iphoneos/Countdown\ Widget.app/Countdown\ Widget normal (in target 'Countdown Widget' from project 'Countdown Widget')
    cd /Users/bradleycable/Desktop/Stuff/Countdown\ Widget
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -target arm64-apple-ios14.0 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.2.sdk -L/Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Products/Debug-iphoneos -F/Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Products/Debug-iphoneos -F/Users/bradleycable/Desktop/Stuff/Countdown\ Widget -filelist /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Intermediates.noindex/Countdown\ Widget.build/Debug-iphoneos/Countdown\ Widget.build/Objects-normal/arm64/Countdown\ Widget.LinkFileList -Xlinker -rpath -Xlinker @executable_path/Frameworks -dead_strip -Xlinker -object_path_lto -Xlinker /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Intermediates.noindex/Countdown\ Widget.build/Debug-iphoneos/Countdown\ Widget.build/Objects-normal/arm64/Countdown\ Widget_lto.o -Xlinker -no_deduplicate -fobjc-link-runtime -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphoneos -L/usr/lib/swift -Xlinker -add_ast_path -Xlinker /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Intermediates.noindex/Countdown\ Widget.build/Debug-iphoneos/Countdown\ Widget.build/Objects-normal/arm64/Countdown_Widget.swiftmodule -framework Foundation -framework UIKit -Xlinker -no_adhoc_codesign -Xlinker -dependency_info -Xlinker /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Intermediates.noindex/Countdown\ Widget.build/Debug-iphoneos/Countdown\ Widget.build/Objects-normal/arm64/Countdown\ Widget_dependency_info.dat -o /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Products/Debug-iphoneos/Countdown\ Widget.app/Countdown\ Widget -Xlinker -add_ast_path -Xlinker /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Intermediates.noindex/SQLite.swift.build/Debug-iphoneos/SQLite.build/Objects-normal/arm64/SQLite.swiftmodule

duplicate symbol '_main' in:
    /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Intermediates.noindex/Countdown Widget.build/Debug-iphoneos/Countdown Widget.build/Objects-normal/arm64/Wtarget-fb79391fc42d00bcc0af801429653506c80531174bbc6c7603c27c78464dee8a.o
    /Users/bradleycable/Library/Developer/Xcode/DerivedData/Countdown_Widget-hhxapyypudwfqifpmwtzlpoaerys/Build/Intermediates.noindex/Countdown Widget.build/Debug-iphoneos/Countdown Widget.build/Objects-normal/arm64/Countdown_WidgetApp.o
ld: 1 duplicate symbol for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: This is a typical error that appears during link time due to multiple files exporting the same symbols.
For this particular problem, you seem to have two files in your project that declare the main function:

*

*Countdown_WidgetApp,

*and the oddly named Wtarget-fb79391fc42d00bcc0af801429653506c80531174bbc6c7603c27c78464dee8a
Take a look at the contents of those files and either remove one from the project or remove the main declaration from one of them.


text:
Q: Using requests to download a file results in the webpages html My code currently is:
url = "https://drive.google.com/u/0/uc?id=1-PopFOwxcm39uW4I-tVM5tSrOjvyOCly&export=download"

# Get all the files from mediafire link

def fetchFilesMedia():
  response = requests.get(url, stream=True)
  with open("test", "wb") as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)

I want it to download all the folders in the zip but currently it just downloads the webpage.
<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta content="width=300, initial-scale=1" name="viewport">
  <meta name="description" content="Google Drive is a free way to keep your files backed up and easy to reach from any phone, tablet, or computer. Start with 15GB of Google storage – free.">
  <meta name="google-site-verification" content="LrdTUW9psUAMbh4Ia074-BPEVmcpBxF6Gwf0MSgQXZs">
  <title>Meet Google Drive – One place for all your files</title>
  <style>
  @font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 300;
  src: url(//fonts.gstatic.com/s/opensans/v15/mem5YaGs126MiZpBA-UN_r8OUuhs.ttf) format('truetype');
}

etc.


text:
Q: How to get the "Function Url" which is with in a Function-App deployed using Terraform? As part of IaC, A Function App, lets name it FuncAppX is deployed using Terraform, which has a function with-in.
I need to access the Url of the same function with-in a function app using Terraform. I am sharing the screenshot for same here for reference, in which its easy to get the "GetFunction Url" but using terraform, I am not getting a way to return the same, which needed to be passed as an input to another function app.
Function App
Function within FunctionApp

A: Concider exposing you http triggered functions via the API management resource in azure. However you can call functions directly also.
To get the url of the function app you can use the default_hostname attribute on azurerm_function_app and forexample put in a keyvault using azurerm_key_vault_secret.
The attribute is listed in the terraform documentation here.
Of course this will not link to the specific function and will not include the key needed.
To extract a key needed to access the function you can use the function_app_host_keys. Where you get the default function key with
Then you can retrieve the default_function_key.
Then you need to combine these things to call the function (note you can only call functions with a http trigger).
The url of the function would then be {default_hostname}/api/{functionname}?code={default_function_key}.

A: You need to build the URL of a specific function endpoint yourself. Since the concrete function names are defined via the function.json, you need to copy it to your Terraform scripts.
locals {
  function_foo = "foo"
}

The URL contains a secret as query parameter, which you can grab via the data source azurerm_function_app_host_keys.
data "azurerm_function_app_host_keys" "example" {
  name                = azurerm_function_app.example.name
  resource_group_name = azurerm_function_app.example.resource_group_name

  depends_on = [azurerm_function_app.example]
}

Now you can build the URL yourself.
output "url" {
  value = "https://${azurerm_function_app.example.default_hostname}/api/${local.function_foo}?code=${data.azurerm_function_app_host_keys.example.default_function_key}"
}

Be aware, that the azurerm_function_app_host_keys values may not immediately available, since the deployment of the concrete Function App is decoupled from the azurerm_function_app service creation. Depending on your scenario, you may need to add some manual synchronization (e.g. with null_resource).


text:
Q: Recursion depth limit for a fibonacci program in Python I have a Python program that performs pretty fast for fibonacci sequences up to 999. For numbers above 999, the program fails with RecursionError: maximum recursion depth exceeded in comparison. I am utilizing memoization to cache fibonacci of previous values.
Here is my code.
            def fibonacci(position, cache=None):
                if cache is None:
                    cache = [None] * (position + 1)

                if cache[position] is not None:
                    return cache[position]

                else:
                    if position < 3:
                        return 1
                    else:
                        cache[position] = fibonacci(position - 1, cache) + fibonacci(position - 2, cache)

                return cache[position]

Does anyone have a hint how I can improve my solution?

A: There is a much easier solution which avoids recursion:
def fibonacci(position):
    if position < 3:
        return 1
    i = 3
    last1 = 1
    last2 = 1
    while i <= position:
        result = last1 + last2
        last2 = last1
        last1 = result
        i+=1
    return result

This stores the previous two values and adds them to produce a result, then replaces the last two with the result and the last value.


text:
Q: In Microservices is it acceptable to have an API returning an Aggregate Root that was replicated? Imagine we have a microservice M1 with an aggregate root called Player and a microservice M2 with an aggregate root called Classification, now in the M1 we need to do some logic based on some property from Classification, now some steps to do that are:

*

*Replicate the list of possible Classifications to M1 via asynchronous messaging;

*Do what is asked by the business in M1;

Ok, now imagine we have a view to add Players, and in that view is possible to choose the Classification of the new Player from a dropdown list. Now the question:
Should the dropdown list be populated with the Classifications that were replicated into M1 or from M2?
As you can see, by using the data from M1 we would have to expose the Classification from M1 via an API, thus the title of the question.
EDIT
The replications happens through async messaging using events, so I'm not exposing the entire aggregate to M1 just some properties like an Id and the Description of the classification.

A: I believe both can be done and one is not better than the other. Either ways, you're making API call to M2 to get the classification. But this scenario is now telling you that the service boundary might be wrong - the vertical slice on the view to create a new player perhaps should be a single micro-service. Of course, you will add some fallback mechanism for the call to M2 so that in case of failure to M2, M1 doesn't fail completely (in this case, to create a new player).

A: The main idea when you design your microservices is that one microservice should not make any synchronous calls to any other microservice. This implies that every microservice should gather any required external state in an asynchronous mode, before it will answer to queries or execute commands. One way to do that is (1) by subscribing to events; the other way (2) is by periodically querying some exposed Read-model (see CQRS), i.e. in a cron job.
In any case, you should not expose the entire Aggregate, otherwise you risk to break its encapsulation by depending on its internals. Instead, you should publish its domain events (1) or create a specially designed canonical Readmodel that present the most probable model to the other microservices; something like a canonical Read-model; I would avoid this unless the domain is too simple, too CRUD.

A: You should treat each microservice as a service boundary. Means no aggregates ever leave the bounded context. The reason for this is, if you do that your leak your domain knowledge into other bounded contexts and have a hard dependency on it. Any change on the aggregate will break any depending service.
If you need to retrieve data from other bounded context you should do that through an anti-corruption layer. In terms of Microservices that can be translated into DTOs. This way when you add or remove a property you don't necessary break the contracts with the outside contexts.
From the provided information its hard to tell if Player and Classification belong to the same context or not. Basically there's nothing wrong to compose your UI data from multiple microservices (i.e. displaying orders and delivery notes on the same UI form, whereas they come from different bounding contexts, namely order and logistics).
However if your Player model/aggregates directly depend on each other and neither of them can be used independently of the other one, then its very likely its part of the same bounded context.


text:
Q: Cannot resolve symbol commandBehaviours wpf I am new to commandBehaviours. Whenever I say something like the following it just complains:

cannot resolve symbol commandBehaviours

Do I need to add any reference?
<Style TargetType="{x:Type DataGrid}">
  <Setter Property="commandBehaviors:MouseDoubleClick.Command"></Setter>
</Style>


text:
Q: Twitter API in PHP using codebird I need to incorporate twitter feature in a project of mine. Among all the libraries and wrappers, codebird seemed convenient. I tried to do the basic authentication using codes from their example, but upon uploading the files on the server, i cant get to access them at all. It shows error 500 in server and i cant test them on localhost.
the index.php file
<?php
 require_once ('codebird.php');
 \Codebird\Codebird::setConsumerKey('123456',    '1234567'); // static, see 'Using   multiple Codebird instances'

 $cb = \Codebird\Codebird::getInstance();

 session_start();

 if (! isset($_SESSION['oauth_token'])) {
     // get the request token
     $reply = $cb->oauth_requestToken([
    'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);

// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;

// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();

 } elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);

// get the access token
$reply = $cb->oauth_accessToken([
    'oauth_verifier' => $_GET['oauth_verifier']
]);

// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;

// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}

// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

the callback.php
<?php
 require_once ('codebird.php');
 \Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'

 $cb = \Codebird\Codebird::getInstance();

 if(isset($_SESSION['oauth_token'] &&    isset($_SESSION['oauth_token_secret']))){
     $cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); // see above

     $reply = (array) $cb->statuses_homeTimeline();
     print_r($reply);
 }

 else {
     echo 'necessary session variables couldnt be found!';
 }
 ?>

This might be a really noob question as i have only basic knowledge in PHP, but any help would be much appriciated, please.


text:
Q: How to retrieve "state" param from the oauth response in spring boot I am using spring boot, specifically spring-boot-starter-oauth2-client dependency for google login. Everything is working fine except that I need to send some details in the request and then retrieve them back from the response so that I can use those details. I did some research and found that I can do that by using state parameter while sending the Oauth Request. I can successfully set the "state" value in my custom OAuth2AuthorizationRequestResolver as below:
private OAuth2AuthorizationRequest customizeAuthorizationRequest(OAuth2AuthorizationRequest req,
            HttpServletRequest request) {
        String state = Base64.getEncoder().encodeToString("test".getBytes());
        return OAuth2AuthorizationRequest.from(req).state(state).build();

    }

This is all working fine! However, I'm not sure how to retrieve this value from the response. I can see there is OidcAuthorizationCodeAuthenticationProvider.java which is doing all the magic of creating the user after the authentication. I thought I could somehow override it and get the state value but I can't seem to figure out how to do it. I'm also thinking there maybe an easier way. What do you think?


text:
Q: VS Code Intellisense and Node JS strange behavior EDIT: This has been reported on the VS Code repo. To see the issue and watch a video of the bug, go here https://github.com/Microsoft/vscode/issues/68733

I'm not sure if this is a bug or something related to JavaScript that I'm unaware of. Basically, VS Code Intellisense fails to list any methods of Node modules I require depending on the order I require the module. This affects just about all modules and files I require.
This will show Intellisense prompts for the http module.
const path = require('path');
const fs = require('fs');
const http = require('http');

http.

This won't:
const http = require('http');
const path = require('path');
const fs = require('fs');

http.

All that changed was the order I required the modules. Is this a VS Code bug or a property of JavaScript/Node I'm not getting?

I haven't messed with many settings in VS Code if at all. I will continue to looks through my settings to see if I can find anything relevant.


text:
Q: Switch between mobile and desktop view in power bi embedded I have a power bi report with both desktop and mobile views. I'd like the browser to switch between these views as it resizes. The only way I can currently achieve this is to embed two instances of the report into the browser, one mobile the other desktop, and hide and show them depending on the browser size.
The problem with this is that if I set some filter values when in the desktop view then, narrow the browser so that the mobile view is shown, then the filter values are not same, this obviously being because there are in reality two separate reports.
The other downside of this approach is that I am presumably also incurring the performance cost on my database of generating two reports.
What can I do to only embed a single report that can dynamically switch between mobile and desktop views?
UPDATE Following response below, test code to toggle layout between mobile and custom layout
angular.element($window).on('resize', function () {
    if (vm.report === null)
        return;

    var models = window['powerbi-client'].models;

    var newLayout = models.LayoutType.Custom;
    if (window.innerWidth < 768) {
        newLayout = models.LayoutType.MobilePortrait;
    }

    if (vm.report.config.settings.layoutType !== newLayout) {
        const newSettings = { layoutType: newLayout };
        vm.report.updateSettings(newSettings);
    }}

UPDATE 2, Added code to show how the report is generated
        // report config
    var models = window['powerbi-client'].models;
    var config = {
        type: 'report',
        tokenType: models.TokenType.Embed,
        accessToken: result.accessToken,
        embedUrl: result.embedUrl,
        id: result.reportId,
        permissions: models.Permissions.View,
        viewMode: models.ViewMode.Read,
        settings: {
            filterPaneEnabled: false,
            navContentPaneEnabled: false,
            background: models.BackgroundType.Transparent,
            layoutType: models.LayoutType.Custom,
            customLayout: {
                displayOption: models.DisplayOption.FitToPage
            }
        }
    };

    // get elements and embed them
    var desktopReportContainer = $('.reportContainer')[0];
    vm.report = powerbi.embed(desktopReportContainer, config);

A: Instead of embedding two instances of a report you can do:

*

*Change the layout type by updating settings like here: change-layout-example.
The downside of this approach is that your user's cross filters will not be saved when changing layout.

*Before changing the layout type, save a bookmark and then after changing the layout type apply the saved bookmark:
function changeLayout(layoutType) {
    report.bookmarksManager.capture()
    .then(function (capturedBookmark) {
        var bookmarkState = capturedBookmark.state;

        var config = {
            layoutType: layoutType
        };
        report.updateSettings(config).then(function () {
            report.bookmarksManager.applyState(bookmarkState);
        })
    })
}

Please note that you will have to add error handling code to the sample above.

*Use Custom layout instead of mobile layout like here: Dynamic report layout.
The downside of this approach is that you will have to write code that sets the layout dynamically.

A: Power BI embed Javascript library has direct support for your case.
First you will need to create a report with mobile layout using Power BI desktop. After you created the report you can embed it using JavaScript SDK. In order to decide in which layout to embed, use the layoutType property of settings in embed configuration.
There are two layout types dedicated to mobile devices:

*

*MobilePortrait - Optimized for portrait view (This is the mobile
layout you created on Power BI desktop)

*MobileLandscape - Optimized
for landscape view. This layout looks like the regular report layout.

Load a report in mobile layout Example:
// Get models. models contains enums that can be used.
var models = window['powerbi-client'].models;

var embedConfiguration = {
    type: 'report',
    id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
    embedUrl: 'https://app.powerbi.com/reportEmbed',
    tokenType: models.TokenType.Embed,
    accessToken: 'h4...rf',
    settings: {
            layoutType: models.LayoutType.MobilePortrait
        }
};

Here is the detail guide: https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-For-Mobile


text:
Q: Aliased coefficient problem in R mma package I am trying to replicate Yu's example code for mediation analysis
but keep getting this error:
library("mma")
data("weight_behavior")
x=weight_behavior[,2:14]
pred=weight_behavior[,3]
y=weight_behavior[,15]
data.bin<-data.org(x,y,pred=pred,contmed=c(7:9,11:12),binmed=c(6,10),binref=c(1,1), catmed=5,catref=1,predref="M",alpha=0.4,alpha2=0.4)

Error in Anova.III.LR.glm(mod, singular.ok = singular.ok) : there are
aliased coefficients in the model

I understand this is because of collinearity but don't know how to fix it.
Any help is much appreciated,
Thanks


text:
Q: Can the commutator $[A,\,B]$ be derived if $\left[A,\,B^2\right]$ is known? I have two operators, $A$ and $B$. I want to figure out their commutator, $[A,\,B]$. The commutator $\left[A,\,B^2\right]=C$ is known. Equivalently, I want to compute $\left[A,\,\sqrt{D}\right]$ given a known $[A,\,D]=C$.
The best I have been able to do is to take the identity
$$\left[A,\,B^\beta\right] = \left[A,\,B\right]B^{\beta-1} + B \left[A,\, B^{\beta-1}\right]$$
to get that
$$C = [A,\,B]B + B[A,\,B].$$
This can be solved for the desired commutator in two ways:
\begin{align}
    [A,\,B] & = CB^+ - B[A,\,B]B^+,\ \mathrm{and} \\
    & = B^+ C - B^+ [A,\, B] B,
\end{align}
where $B^+$ is the a pseudo-inverse of $B$ (e.g. the Moor-Penrose inverse). Either of those equations can be applied recursively to get the formulae
\begin{align}
    [A,\,B] & = \sum_{j=0}^\infty (-1)^j B^j C B^+ \left(B^j\right)^+,\ \mathrm{and} \\
    & = \sum_{j=0}^\infty (-1)^j \left(B^j\right)^+ B^+ C B^j.
\end{align}
Is this the best that can be done? If so, how can I tell if those infinite series are convergent? Can more be said if $B$ is a positive semi-definite Hermitian operator (i.e. all eigenvalues are $\ge 0$, but $0$ is definitely one of the eigenvalues)?
In the exact use-case, $A=a(\mathbf{k})$, $B = \sqrt{a^\dagger(\mathbf{k})\, a(\mathbf{k})}$, and $[a(\mathbf{k}),\, a^\dagger(\mathbf{k}')\,a(\mathbf{k}')] = a(\mathbf{k})\,\delta(\mathbf{k}-\mathbf{k}')$. There are a few more identities (like $[a(\mathbf{k}),\, a^\dagger(\mathbf{k}')] = \delta(\mathbf{k}-\mathbf{k}')$) and that the eigenvalues of $a^\dagger(\mathbf{k})\,a(\mathbf{k})$ are discrete, starting at $0$ and going up to infinity. That is, they're Bosonic creation and annihilation operators in quantum field theory.

A: I don't know if this translates to your setting, but if you look at the (Hamilton) quaternions and let $A, B$ be pure quaternions, then $B^2 \in \mathbb{R}$ and hence $[A, B^2] = 0$. But $[A, B]$ could be any pure quaternion (or at least all those $[A,B]$ span the full space of pure quaternions, I have not checked the stronger statement.) So there is not much to infer about it.


text:
Q: How to design my mapper? I have to write a mapreduce job but I dont know how to go about it,
I have jar MARD.jar through which I can instantiate MARD objects.
Using which I call the mard.normalize file meathod on it i.e. mard.normaliseFile(bunch of arguments).
This inturn creates certain output file.
For the normalise meathod to run it needs a folder called myMard in the working directory.
So I thought that I would give the myMard folder as the in input path to hadoop job, but m  not sure if that would help beacuse mard.normaliseFile(bunch of arguments) will search for the myMard folder in the working directory but it will not find it as (**this is what I think) the Mapper will only be able to access the content of files through the "values" obtained from the fileSplit, it cannot give direct access to the files in the myMard folder.
In short I have to execute the follwing code through the MapReduce
File setupFolder = new File(setupFolderName);

setupFolder.mkdirs();

MARD mard = new MARD(setupFolder);

Text valuz = new Text();

IntWritable intval = new IntWritable();

File original = new File("Vca1652.txt");

File mardedxml = new File("Vca1652-mardedxml.txt");

File marded = new File("Vca1652-marded.txt");

mardedxml.createNewFile();

marded.createNewFile();

NormalisationStats stats;

try {

stats = mard.normaliseFile(original,mardedxml,marded,50.0);

//This meathod requires access to the myMardfolder

System.out.println(stats);

} catch (MARDException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Please help


text:
Q: virtual keyword internals I heard lots of times virtual function is usually implemented using a vtable. But I actually don't know actually how its implemented and how it works.
edit
I didn't actually get this code: How can it be rewritten. Can someone explain this in detail please.
Finally, let's see how the compiler implements a call to a virtual function. Your code might look like this:
 // Your original C++ code

 void mycode(Base* p)
 {
   p->virt3();
 }

The compiler has no idea whether this is going to call Base::virt3() or Der::virt3() or perhaps the virt3() method of another derived class that doesn't even exist yet. It only knows for sure that you are calling virt3() which happens to be the function in slot #3 of the v-table. It rewrites that call into something like this:
 // Pseudo-code that the compiler generates from your C++

 void mycode(Base* p)
 {
   p->__vptr[3](p);
 }

A: The explanation of the internals of virtual functions on the C++ FAQ is pretty good. You should give it a read. I think it would be better if you tried to understand it yourself and then asked your doubts.

A: The common implementation is to have one pointer at the beginning of every instance of an object that points to a vtable. There is one vtable per class, so if you have a class A and class B, there will be one table for each.
The vtable essentially has a bunch of function pointers, so if class A has two virtual functions, foo() and bar(), the table will have pointers to both. If class B overrides those two functions, it will have its versions of foo() and bar() at the same offsets.

A: An easy way to understand how vtables work is to implement the same type of functionality in C using function pointers because all that a vtable is,is a table of function pointers to the concrete implementations.


text:
Q: Duplicate url in spring mvc I have a hyper link:
Brake

When I click hyper link first time, the controller will redirect to "MySite/Category/Brake.html" but the second time the controller will redirect to "MySite/Category/Category/Brake.html" and I will get error 404 not found. How do I fix this problem.

A: Add this to your JSP file <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

and  Brake


text:
Q: Split image horizontally with python based on dark center line Goal is to horizontally split an image (double newspaper page) in python based on a vertical centerline that is darker than other areas around.
Example image:

Had some luck using opencv (cv2) for the initial crop and rotation of the double page from a black background using cv2.Canny, and then sorting the contours based on cv2.contourArea.
But, now I'm just interested in finding a center line and then splitting the image into two separate images.  Using cv2.Canny again I see that it's able to identify that centerline, but not sure how to identify that long, vertical line and use that to split the image:

End goal would be two images like the following:

Any suggestions would be most welcome.

A: First, run a horizontal gradient so you only accentuate vertical edges. You can calculate a horizontal gradient with these coefficients:
-1   0   1
-2   0   2
-1   0   1

Then compute the sum of the vertical columns, you can use np.sum(array,axis=0) and you will get this:

I have re-shaped it for ease of viewing - it is actually only 1 pixel tall. Hopefully you can see the bright white line in the middle which you can find with Numpy argmax(). It will also be better when you just do a horizontal gradient because at the moment I am using the purple and yellow image with vertical and horizontal edges enhanced.
Note that the inspiration for this approach is that you said you "want to identify that long, vertical centerline" and the rationale is that a long line of white pixels will add up to a large sum. Note that I have assumed your image is de-skewed (since you said the line is vertical) and this method may not work so well on skew images where "vertical" line will be spread across several columns.


text:
Q: Hexadecimal to float converter I have a hexadecimal to float converter in the form of a code by I am unable to understand as to how did they carry out the conversion.
For Ex: If I have a hexadecimal number as : 11433333;
    the answer I get from that function is: 145.200.
I tried several methods of conversion like these:
http://www.cs.uaf.edu/~cs301/notes/Chapter4/node13.html
http://babbage.cs.qc.edu/IEEE-754/32bit.html
There is something to do with little endian and big endian, but I am not familiar with that. None of these are giving me the output as 145.200. Could anyone explain me a way out of this please?
Cheers in advance.

A: The mystery is resolved when you do the conversion the other way around: the IEEE representation of 145.2 is 43 11 33 3316. So some part of your code is getting the byte order mixed up.


text:
Q: I'm having making an animated line chart, problems with the X axis I'm trying to animate a plot I have where the X axis is non-numeric. The plot itself looks great, but I get a few error messages trying to animate it using the transition_reveal function.
I've got a data set called df100m that tracks the times/speeds of 10 meter splits of the 100 meter dash for various Olympic runners. It looks like this.

splits
runners
times(s)
speed(mph)

10-20
Bolt_08
1.070
21.93

20-30
Bolt_08
0.910
24.58

84 more rows of different splits and runners omitted for space.
Plotting the average speed for this data set using stat_smooth looks great. I removed the reaction time (RT), the final time (TOTAL), and the starting 10m (Start-10), so that it only shows the numeric splits. Here is the code for the plot I have so far:
df100m %>%
  filter(!grepl("RT", splits)) %>%
  filter(!grepl("TOTAL", splits)) %>%
  filter(!grepl("Start-10", splits)) %>%
  ggplot(mapping = aes(x = splits, y = speed, col = runner, group = runner)) +
  stat_smooth(method = loess, se = F, fullrange = F) +
  theme(axis.text.x = element_text(angle = 90)) +
  theme(aspect.ratio = 3/7) +
  theme_solarized_2(light=F)

However when I add +transition_reveal(~splits) I get the following error message:
Error in seq.default(range[1], range[2], length.out = nframes) :
  'from' must be a finite number
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

Playing around with it, I sometimes also get the "invalid 'times' argument" error.
I know there are a few problems with the X axis (splits), it's a character rather than numeric, but also has a dash (-). I've seen a few posts attempting to fix this error, but I am unable to fix it as I am a beginner. Could someone point me to the right direction?

A: Using some minimal made-up data, this is one possible approach creating the smoothed lines before the plotting, then basing the transition_reveal on the splits mutated to integers (as splits_int).
library(tidyverse)
library(gganimate)
library(broom)

tribble(~splits, ~speed, ~runner,
        "10-20", 20.0, "A",
        "20-30", 21.0, "A",
        "30-40", 22.0, "A",
        "10-20", 19.0, "B",
        "20-30", 20.0, "B",
        "30-40", 21.0, "B"
        ) %>%
  mutate(splits_int = factor(splits) %>% as.integer()) %>%
  nest(data = -runner) %>%
  mutate(
    lm_model = map(data, ~loess(speed ~ splits_int, data = .x)),
    augmented = map(lm_model, augment) %>% map(select, .fitted)
    ) %>%
  unnest(c(augmented, data)) %>%
  ggplot(aes(splits, .fitted, col = runner, group = runner)) +
  geom_line() +
  transition_reveal(splits_int)

Created on 2022-12-10 with reprex v2.0.2


text:
Q: Issue Initializing Parameters of SimpleBlobDetector Here is my code:
SimpleBlobDetector::Params params;
//Filter by Area
params.filterByArea = true;
params.minArea = 5000;              //Filters out areas less than 5000 pixels.
//Filter by Circularity.
params.filterByCircularity = true;  //Circle has circularity = 1.000
params.minCircularity = 0.79F;      //Square has circularity = 0.785
//Filter by Convexity
params.filterByConvexity = true;
params.minConvexity = 0.10F;
//Filter by Inertia
params.filterByInertia = true;
params.minInertiaRatio = 0.01F;

Ptr<SimpleBlobDetector> d = SimpleBlobDetector::create(params);
vector<KeyPoint> keypoints;
d->detect(processed_src, keypoints);
drawKeypoints(src, keypoints, im_with_keypoints, Scalar(0, 255, 0), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);

I am drawing my information directly from SimpleBlobDetector tutorials for OpenCV versions >=3. I am receiving the following error being called from Ptr<SimpleBlobDetector> d = SimpleBlobDetector::create(params); Apparently, params is not being set properly. See the following error message:

E0312 - no suitable user-defined conversion from "cv::SimpleBlobDetector::Params" to "const std::string" exists

Can anyone explain why this is? I have used SimpleBlobDetector is past projects and have had no issues.


text:
Q: Replace object1 values with values of object2

var object1 = {
  lol_gif: [22390036, 15154597, 13491369],
  silly_gif: [19048808, 19048861]
}

var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');

function httpGetAsync(theUrl) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      var response = JSON.parse(xmlHttp.responseText);
      var gifs = response.results;
      var object2 = {};
      for (var g in gifs) {
        var id = gifs[g].id;
        object2[id] = gifs[g].media[0].tinygif.url;
      }
      console.log(object2);
      //will return an object with the ID as the keys and gif url as the values
    }
  }
  xmlHttp.open("GET", theUrl, true);
  xmlHttp.send();
  return;
}

I am trying to categorize each gif by replacing object1 values with data from tenor json but failed many times. thanks for your help!
desired output:
var object1 = {
  lol_gif: ["https://media.tenor.com/images/4ad4bc701f2744ddc5220f6d3688e899/tenor.gif",
            "https://media.tenor.com/images/c9b8564d6acbbba994b5413479d0fc2b/tenor.gif",
            "https://media.tenor.com/images/7c27bea2fb5ea0f7600af7e9ad8d0c4a/tenor.gif"],
  silly_gif: ["https://media.tenor.com/images/59669ec95913ef1df85fee2cda08aece/tenor.gif",
              "https://media.tenor.com/images/59669ec95913ef1df85fee2cda08aece/tenor.gif"]
}

A: Something like this would give you an object in the same shape as your original:

var object1 = {
  lol_gif: [22390036, 15154597, 13491369],
  silly_gif: [19048808, 19048861]
}

var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');

function httpGetAsync(theUrl) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      var response = JSON.parse(xmlHttp.responseText);
      var gifs = response.results;

      var object2 = {};

      Object.entries(object1).forEach(([key, gifIds]) => {
        const newGifList = gifIds.map((gifId) => {
          const gif = gifs.find((gifResult) => gifResult.id === gifId.toString());
          return gif.media[0].tinygif.url;
        });

        object2[key] = newGifList;
      });

      console.log(object2);
      //will return an object with the ID as the keys and gif url as the values
    }
  }
  xmlHttp.open("GET", theUrl, true);
  xmlHttp.send();
  return;
}

Side note, its generally not a great idea to include API keys in StackOverflow questions.

A: I haven't really taken a deep dive into the type of responses this API provides back, but my surface-level conclusion is that if you want to maintain the exact structure and order of the data, you'll have to go with this solution:

const object = {
    lolGifs: [22390036, 15154597, 13491369],
    sillyGifs: [19048808, 19048861],
};

const getGifs = async (obj) => {
    const map = {};

    for (const [key, arr] of Object.entries(obj)) {
        map[key] = [];

        for (const id of arr) {
            const res = await fetch(`https://g.tenor.com/v1/gifs?ids=${id}&key=LIVDSRZULELA&media_filter=tinygif`);
            const { results } = await res.json();

            const gifUrl = results[0]?.media[0]?.tinygif?.url;
            map[key].push(gifUrl);
        }
    }

    return map;
};

(async () => {
    const data = await getGifs(object);
    console.log(data);
})();

A: You just need to make some simple change where you search for the ids to put it to the keyname as following:

var object1 = {
  lol_gif: [22390036, 15154597, 13491369],
  silly_gif: [19048808, 19048861]
}

var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');

function httpGetAsync(theUrl) {
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
      var response = JSON.parse(xmlHttp.responseText);
      var gifs = response.results;
      var object2 = {"lol_gif":[],"silly_gif":[]};
      for (var g in gifs) {
        var id = gifs[g].id;
        if(object1["lol_gif"].indexOf(parseInt(id))!=-1) {
          object2["lol_gif"].push(gifs[g].media[0].tinygif.url);
        }
        else if(object1["silly_gif"].indexOf(parseInt(id))!=-1){
        object2["silly_gif"].push(gifs[g].media[0].tinygif.url);
        }
      }
      console.log(object2);
      //will return an object with the ID as the keys and gif url as the values
    }
  }
  xmlHttp.open("GET", theUrl, true);
  xmlHttp.send();
  return;
}


text:
Q: JUnit Mockito returning LinkedList instead of ArrayList I have been tasked to figure out why this JUnit Test is failing.  What I have found is that instead of returning an ArrayList (like the getDeligationsForLoggedInUser is SUPPOSED to return, it returns a LinkedList for "userList".
@SuppressWarnings("unchecked")
@Test
public  void test_getDelegationsForLoggedInUser()
{
    String userId="Abcd";
    List<String>  expectedUserList= new ArrayList<String>();
    expectedUserList.add("efghi");
    expectedUserList.add("jklmn");
    expectedUserList.add("opqrs");

    when(namedParameterJdbcTemplate.queryForObject(anyString(),anyMap(), any(RowMapper.class))).thenReturn(expectedUserList);
    List<String>  userList= workflowProcessDAOImpl.getDelegationsForLoggedInUser(userId);
    verify(namedParameterJdbcTemplate, times(1)).query(sqlCaptor.capture(), namedParameterMap.capture(), rowMapperCaptor.capture());
    assertThat(userList, is(expectedUserList));
    assertThat(sqlCaptor.getValue(), is(SQLConstantsSysConfigV1.getInstance().GET_USERIDS_FOR_DELEGATES));

}

Does anyone have any idea why this is the case?

A: You mock in this test the method queryForObject, but test on the method query.
I suppose that your code defines a mock of the function somwhere else, isn't it? It could then simply be the result of a copy/paste operation...

A: I also had the same problem. To solve that I replaced Mockito.anyList() (if param required is list) and Mockito.anyLong() (if param required is long). Example:-
 Mockito.when(testService.getData(Mockito.anyLong(),
    Mockito.anyList(), Mockito.anyList())).thenReturn(SOME_RESPONSE_DATA);


text:
Q: Перегрузка оператора[] с++ Есть структура данных, полями которой являются std::vector. Как мне перегрузить оператор[], что бы можно было работать по индексам с элементами данной структуры?
Код структуры:
struct matchBlobs {
        std::vector<cv::Point> leftBlob;
        std::vector<cv::Point> rightBlob;
        std::vector<int> colorPoints;

        matchBlobs() {};

        matchBlobs(cv::Point ptLeft, cv::Point ptRight) {
            leftBlob.push_back(ptLeft);
            rightBlob.push_back(ptRight);
        }

        matchBlobs(cv::Point ptLeft, cv::Point ptRight, int color) {
            leftBlob.push_back(ptLeft);
            rightBlob.push_back(ptRight);
            colorPoints.push_back(color);
        }

        void push_back(cv::Point ptLeft, cv::Point ptRight) {
            leftBlob.push_back(ptLeft);
            rightBlob.push_back(ptRight);
        }
        void push_back_color(int color) {
            colorPoints.push_back(color);
        }
        int size() const {
            return leftBlob.size();
        }
    };

И то как я планирую использовать []
matchBlobs outputMatchBlobs, tempMatchBlobs;
....
            for (int i = 0; i < n; ++i) {
                outputMatchBlobs[(i + n - k) % n] = tempMatchBlobs[i];
            }

A: Если доступ к отдельным элементам "записи" то можно воспользоваться кортежем из ссылок:
auto operator[]( size_t i ) { return std::tie( leftBlob[i], rightBlob[i], colorPoints[i] ); }
auto operator[]( size_t i ) const { return std::make_tuple( leftBlob[i], rightBlob[i], colorPoints[i] ); }

Если доступ к элементам данных - нужен, то попробуйте поменять способ хранения:
struct value_type { cv::Point leftBlob, rightBlob; int colorPoint; };
std::vector< value_type > data;

A: Если подразумевается, что вектора могут хранить разное количество cv::Point, то стоит хранить структуру указателей. Кроме того, нужно стараться не повторять и сокращать код. Первоначально это может выглядеть следующим образом:
struct matchBlobs {
using P = cv::Point;
struct Points {
    P* leftBlob = nullptr;
    P* rightBlob = nullptr;
    int colorPoints{};
    ~Points() {
        delete leftBlob;
        delete rightBlob;
    }
    //copy, = ...
};
std::vector<Points> Blob;
//при создании лучше резервировать какое то количество памяти
explicit matchBlobs(size_t size = 10) { Blob.reserve(size); };

matchBlobs(P ptLeft, P ptRight, int color = 0) {
    push_back(ptLeft, ptRight, color );
}
void push_back(P ptLeft, P ptRight, int color = 0) {
    Blob.push_back({ new P(ptLeft), new P(ptRight), color });
}
void push_back_color(int color) {
    Blob.push_back({ nullptr, nullptr, color });
}
int size() const {
    //количество не нулевых указателей на левый шарик
    return std::count_if(Blob.begin(), Blob.end(),
        [](P p) { return p; });
}
Points& operator[](const size_t index)
{
    return Blob[index % Blob.size()];
}};

каждый элемент может иметь или не иметь левый или правый blob


text:
Q: How to set Autodesk Setting to front? I am having an app, which uses the Forge API. The UI displayed when pushing the Forge button "Settings" in "settingsTools group", overlaps one of my buttons.
However since my app zIndex is set (I am in react code) the click upon close of the setting UI, triggers my buttons instead of the close button.
Hence, I am intrested in setting the "Settings UI" to front so the click upon the close button triggers close. My front end code is in the react framework hence a simple zIndex parameter to set could do the trick.
How can I do so?

A: Instead of playing with hacky ways, consider using the docking panels provided by Forge Viewer. From my understanding, it can also work with React.
To elaborate the usefulness of panels, consider the following example:

Here I have a floating div, showing me some information related to the model. Obviously I've set a high z-index, to bring it upfront and here I have the same problem as you have - when opening things like settings, properties, model tree, etc, they all appear behind my div. Moreover, when changing the size of the window, I have to deal with my div position.
On the other hand, Forge Viewer uses everywhere panels, like this very Settings dialog.
Thus, if you would place your button into this kind of panel, this would save you from headache with z-index, docking, rescaling etc, as all the panels are working nice one with each other, as the below Robot Control Panel:

For more information on how to create a panel, I suggest checking http://learnforge.autodesk.io/#/viewer/extensions/panel


text:
Q: How to render components on the same page in react In my design on the top of the page, you can see pictures as links.
When you click on different pictures, the different component is called.
For example, onClick method show component which is set to true:
    state = {
        showPage1: true,
        showPage2: false,
        showPage3: false,
        showPage4: false
      };
      onClick1 = e =>
      this.setState({ showPage1 : true, showPage2: false, showPage3: false, showPage4: false
      });
      //continue with another onClick methods

And in the final render method is:
render (){
    const src = '/images/image.jpg'
    return(
      <div>
      <Image.Group size='tiny'>
      <Image src={src} onClick={this.onClick1}/>
      </Image.Group>
      { this.renderPage() }
      </div>
    )
  }

And based on that, the different components are shown on the same page.
 renderPage() {
    const showPage1 = this.state.showPage1;
    if (showPage1) {
      return (
          <Page1 submit={this.submit}/>
      );}

Now, each component is a form for me, where a user submits details.
When details are submitted, I do not know how to redirect to another component.
For example, if it was Page1, then I want automatically redirect to Page2 and so on.
This is what I have now, but this, of course, does not work.
I am not sure how to call one component after another component if this component does not have link, because it is displayed on the same page.
submit = data =>
     this.props.saveComponent(data).then(() => this.props.history.push('/text'));

Thank you in advance!

A: While it's true that routing is a more sustainable solution for this problem, without installing React Router it seems to me you just need to update your state, don't you? You could include a currentPage and nextPage property in data to indicate which page to transition to. For example:
submit = data =>
  this.props.saveComponent(data).then(
    () => this.setState({
      [data.currentPage]: false,
      [data.nextPage]: true
    })

This is the kind of task routers are pretty good for though, so rather than doing conditional renders I'd definitely suggest learning more about routes.


text:
Q: Object property ordering in javascript I am trying to understand what's the thing with javascript Objects while using them as an associative array.
From ECMA:

4.3.3 An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive
  value, object, or function. A function stored in a property of an
  object is called a method.

Using them in browser (chrome):
x = { 2: 'a', 3: 'b', 1: 'c' }
> Object {1: "c", 2: "a", 3: "b"}

y = { 'b': 2, 'c': 3, 'a': 1 }
> Object {b: 2, c: 3, a: 1}

While in the first example with the numbers as keys, they became ordered, in the second example with strings, they won't ( ordered = a,b,c ).
I am using these objects with string keys and I really don't want them to change order in some stage of app(if that's even possible) because it may crash the pipeline I am using.
Question is, is this approach safe and normal for every javascript machine, or should I use other method to guarantee that order won't ever change?
Thank you!
Edit:
I am using this with node.js which runs on V8 (chrome engine), which 'orders non-numerical properties in insertion order'(Felix Kling). May this behaviour of V8 change?

A: Although Chrome may guarantee property order when using numbers as indexes in objects, the ECMA specification does not say it should do that, so by guarantee I'd not rely on this behavior. I suggest you to restructure your data to use arrays when you want to keep data order.

A: At the end of the day, it's because V8 uses if/else everywhere in the code to determine if it's an array index or an object property and not two separate classes to handle Array and Object separately like other JS engines:
https://lastzero.net/2009/09/object-property-ordering-in-google-chrome/
Yes, Google sticks to the specs, but it also makes it difficult to pass existing data structures from other programming languages to JS, because the ordering changes unexpectedly (even John Resig was surprised!). So you have to use different (possibly slower) data structures or use a converter, which makes code more complex.

A: It depends on the environment the code is running in, and the methods being used to iterate over the keys.
In ES5 and earlier, there is no defined order, regardless of the method used.
In ES6+, some methods which iterate over keys (but not all) are guaranteed to iterate in order over:
(1) increasing numeric keys (eg, 0, 1, 2), followed by
(2) non-numeric keys in insertion order, followed by
(3) symbols in insertion order.
The methods which are guaranteed to behave this way are, among others:

*

*Reflect.ownKeys

*Object.getOwnPropertyNames

*Object.getOwnPropertySymbols

*Object.defineProperties

*Object rest/spread

These all invoke the internal method [[OwnPropertyKeys]], which guarantees the order.
Methods which are not guaranteed to iterate in any order, even in ES6+ environments, include:

*

*for..in

*Object.keys, Object.values, Object.entries

*JSON.stringify
These methods all call EnumerateObjectProperties, which explicitly states:

The mechanics and order of enumerating the properties is not specified

All that said, even though order isn't guaranteed, in newer environments, the above methods will almost always iterate in the same deterministic order as Reflect.ownKeys anyway. Maybe you shouldn't depend on it, but it'll probably work, at least for now.
If you want a

method to guarantee that order won't ever change?

then to dependably iterate over an object, you should iterate using Reflect.ownKeys or Object.getOwnPropertyNames.

May this behaviour of V8 change?

If you use one of the methods guaranteed to iterate in a particular order, the behavior will not change, because Javascript pretty much always retains backwards compatibility, and now that an required order has been described in the specification, no future changes will change that order.

A: I read from the spec.: Arrays are ordered, Objects not. Chrome seems to make no difference between number and string of numbers. (for performance reason?) I sometimes sidestep to an additional array of keys where needed.


text:
Q: Constant pointer to a constant structure is zero I am working on a piece of code developed by others and I am trying to make a structure static. But when debugging it seems the pointer is zero (not pointing a variable that is zero):
typedef struct WiFiIP{
    // Keep the following in order!  (pri,sec)
    uint16_t WiFiPrimaryPort;
    uint16_t WiFiSecondaryPort;
    // Keep the following in order!  (pri,sec,sntp)
    char WiFiPrimaryAddress[32];
    char WiFiSecondaryIpAddress[32];
    char WiFiSntpIpAddress[32];
};
static const struct WiFiIP WiFiIPs = {7781,7781,"10.0.0.1","",""};
static const __typeof__ (WiFiIPs.WiFiPrimaryPort)
        * const PortPtr = &WiFiIPs.WiFiPrimaryPort;

static const __typeof__(WiFiIPs.WiFiPrimaryAddress)
    *AddressPtr = &WiFiIPs.WiFiPrimaryAddress;

So both AddressPtr and PortPtr are 0x0.
I know there are a number of other methods to 'hard code' parameters in code, but in this case the existing code is expecting a pointer to structure and I would like to avoid refactoring.
Please be gentle, I have never been good with pointers, and I know there are a lot of literature on pointers. I have searched and followed a number of examples but am unable to get it to work.
This code is being developed for a cortex-m3 processor

A: This shouldn't happen and if I copy your exact code it seems to work as expected for me. Unfortunately you didn't include how you are displaying the pointer values.
To properly print the value of a pointer, you can use something like:
printf("PortPtr points to memory location at: %#lX\n", (uintptr_t)PortPtr);
printf("AddressPtr points to memory location at: %#lX\n", (uintptr_t)AddressPtr);

It this case you should be able to verify the pointers are not initialized to NULL.


text:
Q: How to stop Service, after get location? Android I want, get location every now and then via AlarmManager which turn on service with GPS.
AlarmManager works correctly, but I have a problem with the stop service.
First case:
I get location, but Service works every time.
ConnectivityReceiver.java - this is my AlarmManager
    public final class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, " onReceive work", Toast.LENGTH_SHORT).show();
        Log.i("ADRIAN", "onRECEIVE ");
        Intent serviceIntent = new Intent(context,LocationUpdaterService.class);
        context.startService(serviceIntent);
}

LocationUpdaterService.java - Service
public class LocationUpdaterService extends Service implements LocationListener,
                                                               GoogleApiClient.ConnectionCallbacks,
                                                               GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    public LocationUpdaterService() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("ADRIAN", "Wlazlem do onCreate");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API).
                        addConnectionCallbacks(this).
                        addOnConnectionFailedListener(this)
                .build();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("ADRIAN", "onStartCommand");
        mGoogleApiClient.connect();
        Toast.makeText(this, "Location services started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onLocationChanged(Location location) {
        System.out.println("MyLocationService.onLocationChanged");

        String latitude = Double.toString(location.getLatitude());
        String longitude = Double.toString(location.getLongitude());

        Log.i("ADRIAN", "Lat:" + latitude + "Long: " + longitude);

        // do your work here with location
    }

    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10); // Update location every second

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            Log.i("ADRIAN", "onConnected");
        }
        Log.i("ADRIAN", "onConnected 2 ");
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onDestroy() {
//        String latitude = "null";
//        String longitude = "null";

        Toast.makeText(this, "Location services stopped", Toast.LENGTH_LONG).show();

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if(loc != null) {
//                latitude = Double.toString(loc.getLatitude());
//                longitude = Double.toString(loc.getLongitude());
//                Log.i("ADRIAN", "Lat:" + latitude + "Long: " + longitude);
            }
        }

        Log.i("ADRIAN", "Location services stopped");
        mGoogleApiClient.disconnect();
        super.onDestroy();
    }
}

Screen LOGCAT
Second case
When I added context.stopService(serviceIntent) then my application doesn't get location. I tried use SystemClock.sleep(10000); but it still works the same.
ConnectivityReceiver.java
public final class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, " onReceive work", Toast.LENGTH_SHORT).show();
        Log.i("ADRIAN", "onRECEIVE ");
        Intent serviceIntent = new Intent(context,LocationUpdaterService.class);
        context.startService(serviceIntent);

        SystemClock.sleep(10000);
        Log.i("ADRIAN", "STOP SERVICE");
        context.stopService(serviceIntent);

}

LocationUpdaterService.java - the same as above.
SCREEN 2 LOGCAT
What am I doing wrong and How I can fix it?

A: onStartCommand ---> Service.START_STICKY

 @Override
           public void onDestroy() {
            locationManager.removeUpdates(listener);
        locationManager=null;
        super.onDestroy();

        Log.v("STOP_SERVICE", "DONE");

        locationManager.removeUpdates(listener);
        locationManager=null;

}


text:
Q: Asp.NET api with Odata [NotMapped] not working I have restful api using ASP.NEt with Odata.
I tried to add a new property (that is not in database) to the model , when I run the server the result I get are correct but the property I added is not shown in JSON.
I tried to add everything like : [DataMember] [JsonProperty] and I have also [NotMapped].
I don't know why I get this problem. it used to work before.
 [Table("Etudiant")]
    public partial class Etudiant
    {

        public int StudentID { get; set; }

        [StringLength(128)]
        [IgnoreDataMember]
        public string UserID { get; set; }

        public int? Age { get; set; }

        [StringLength(15)]
        public string CodeName { get; set; }

//Problem is here.
        [NotMapped]
        public int? ForeignStudentCount { get; set; }

    }

and this is the controller :
 [EnableQuery]
        [Authorize(Roles = "Admin")]
        public Etudiant GetStudent([FromODataUri] int key)
        {
//put data in student ForeignCount property then return the result.
            return db.Student;
        }


text:
Q: How can I store a binary space partitioning tree in a relational database? I'm trying to store the data in a binary space partitioning tree in a relational database.  The tricky part about this data structure is it has two different types of nodes.  The first type, which we call a data node, simply holds a certain number of items.  We define the maximum number of items able to be held as t.  The second type, which we refer to as a container node, holds two other child nodes.  When an item is added to the tree, the nodes are recursed until a data node is found.  If the number of items in the data node are less than t, then the item is inserted into the data node.  Otherwise the data node is split into two other data nodes, and is replaced by one of the container nodes.  When an element is deleted, a reverse process must happen.
I'm a little bit lost.  How am I supposed to make this work using a relational model?

A: Why not have two tables, one for nodes and one for items?  (Note that I used the term "leaf" instead of "data" nodes below when I wrote my answer; a "leaf" node has data items, a non-"leaf" node contains other nodes.)
The node table would have columns like this: id primary key, parentid references node, leaf boolean and in addition some columns to describe the spatial bounaries of the node and how it will/has been split.  (I don't know if you're working in 2D or 3D so I haven't given details on the geometry.)
The data table would have id primary key, leafid references node and whatever data.
You can traverse the tree downward by issuing SELECT * FROM node WHERE parentid = ?queries at each level and checking which child to descend into.  Adding a data item to a leaf is a simple INSERT.  Splitting a node requires unsetting the leaf flag, inserting two new leaf nodes, and updating all the data items in the node to point to the appropriate child node by changing their leafid values.
Note that SQL round trips can be expensive, so if you're looking to use this for a real application, consider using a relatively large t in the DB constructing a finer-grained tree in memory of the leaves you are interested in after you have the data items.


text:
Q: Alcatraz - Xcode Command Line Tools are not currently installed I'm managing Xcode plug-ins via Alcatraz.
Everything was alright until I installed and then uninstalled Git following instruction in the uninstalled.sh file in official git.zip file:
sudo rm -rf /usr/local/git/   (in my case it's /usr/local/git/bin/git)
sudo rm /etc/paths.d/git
sudo rm /etc/manpaths.d/git

I have no idea what I've done with git would affect Alcatraz.
Once I click Package Manager in Xcode I get this error:

I found nothing to download in the Preference Download section,
and I did  try to install the Command Line Tool following Xcode Command Line Tool tutorial
Here's how I verified it:
myMacBook-Air:~ me$ xcode-select -p
/Applications/Xcode.app/Contents/Developer

And even:
myMacBook-Air:~ me$ gcc --version
Configured with:--prefix=/Applications/Xcode.app/Contents/Developer/usr
--with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.0 (clang-700.0.72) Target: x86_64-apple-darwin14.5.0
Thread model: posix

The warning still pops up.
Did I fail to install the command line tool?
(or maybe it's not about the git but has something related to the Xcode 7 upgrade?)
How could I fix this?

A: This answer actually works,
looks like Alcatraz has something to do with git.


text:
Q: How to build an ipa file from a xCode 5 project without developer membership? I have appSync for iOS 7 in my Jailbroken device, so I'm only looking for export a project to a ipa.
Is this possible without having a developer membership from Apple as that costs 99 dollars per year.

A: No it is not possible to install the application on your device for development testing without apple
membership account.
Because to install the application you have to make a provisioning file and without membership account you can not make provisioning file
Thanks.


text:
Q: GTK 3 Eclipse error while loading shared libraries: libgtk-3.so.0 I'm currently using Eclipse IDE for C/C++ Developers Version: 2018-09 (4.9.0) to build a simple GTK 3 app. But after I build and then run the app, in Eclipse, I get the following error:
Debug/Test: error while loading shared libraries: libgtk-3.so.0: cannot open shared object file: No such file or directory

However, When I start the executable from a terminal, it starts just fine.
How can I resolve the shared library not found so I can run the app directly from within Eclipse?


text: Q: UIPageViewcontrollers, childcontroller button tapped events not working I have a uipageviewcontroller in which i have added a childview controller.The uipageviewcontroller scrolls in horizontal direction,the child view controller has six buttons but none of the tap events are working.is it because of some property from UIPageViewcontroller?


text:
Q: Breaking out unit tests into another project I used to have a Tests folders in my main project where a unit test had this line of code:
Foo foo = new Foo(Environment.CurrentDirectory + @"\XML\FooData.xml" );

I have an XML directory in the Foo project that has a FooData.xml
In the post build event of my projects i have the following line
copy "$(ProjectDir)Foo\Currencies.xml"  "$(TargetDir)\XML"
I now have broke all unit tests into another projects to separate them out and i now get the following error when running these unit tests.
Could not find a part of the path 'C:\svncheckout\Foo.Tests\bin\Debug\XML\FooData.xml'

A: Rather than having a post-build step, can you not just make it a "content" item in Visual Studio, telling it to copy it to the target directory? I usually either do that, or make it an embedded resource and use streams and Assembly.GetManifestResourceStream.

A: I believe you need to update the post build event for the Foo.Tests project to be:
"$(ProjectDir)Foo.Test\Currencies.xml" "$(TargetDir)\XML"

A: You can also put the full path of the xml in your test modules app.config


text:
Q: Onclick not working on Knockout array binded fields Im working on a CRUD Table populated using Knockout. jQuery Click event is not working on new pushed elements to the observable array
click event function
$('td').on('click', function () {
    var spanElement = $(this).find('span');
    $(this).find('span').hide();
    $(this).find('input').show().select().on('blur', function () {
        $(this).hide();
        spanElement.show();
    });
});

This code is working for all rows populated on-load, but not for those I add using add button.
Why is it so? How to fix it?
JSFiddle

A: It does not work because you are adding the event handler directly to the table cells. When you add new rows, you never add the click element.
To solve this problem, apply the click event to the table and let event delegation take over
$('table').on('click', 'td', function () {
    var spanElement = $(this).find('span').hide();
    $(this).find('input').show().select().on('blur', function () {
        $(this).hide();
        spanElement.show();
    });
});

A: Try this
$(document).on('click', 'table td', function () {

//Your Functions

});


text:
Q: How to "Auto Generate" String in Sequence from "0-9 A-Z" I am trying to auto generate string from 0-9 and A-z.
00001-99999
A0001-A9999
B0001-B9999
Z9999-AA999
AB001-ZZ999
AAA01-.....
And in sequence

A: just make a recursive call to a function.
list=[]
for i in range(10):
    list.append(str(i))
for i in range(26):
    list.append(chr(ord('a')+i))
def all(pre,n):
    li=[]
    if n==1:
        for x in list:
            for p in pre:
                li.append(x+p)
        return li
    else:
        for x in list:
            for p in pre:
                li.append(x+p)
        return all(li,n-1)
print(all([''],2))

Recursor may take a lot of time for large numbers, so you can also make your own number system to increment.
class NumSys:
    def __init__(self):
        self.val=[0,0,0,0,0]
    def next(self):
        self.val[4]+=1
        for i in range(5):
            if self.val[4-i]>35:
                if i==4:
                    return None
                else:
                    self.val[4-i-1]+=1
                    self.val[4-i]-=35
    def __str__(self):
        stri=''
        for i in range(5):
            x=self.val[i]
            if x<10:
                stri+=str(x)
            else:
                stri+=chr(ord('a')+x-10)
        return stri

n=NumSys()
for i in range(100):
    print (str(n))
    n.next()


text:
Q: Extract new data frame from existing, based on particular values in a column in R language I have a dataset with 3 observations, which are name, age, school
Name | Age | School
John   25     STM |
Anne   20     CODC |
clark  25     GCC |
Tim    25     BBC |
Mary   15     CBIC

How to extract the names who's age in equal to 25 and 20

A: I recommend you install the tidyverse packages and start learning how to use them from now. In dplyr notation what you need looks like this:

library(dplyr)

df <- data_frame(
  Name = c("John", "Anne", "Clark", "Tim", "Mary"),
  Age = c(25, 20, 25, 25, 15),
  School = c("STM", "CODC", "GCC", "BBC", "CBIC")
)

desired_names <- df %>%
  filter(Age %in% c(25,15) %>%
  select(Name) # use pull(Name) instead if you want the names as a vector


text:
Q: foreach, unexpected result for element, which key is 0 I have this code
$arr = array(
    "0"=>"http://site.com/somepage/param1/param2/0",
    "1"=>"http://site.com/somepage/param1/param2/1",
    "thispage" => "http://site.com/somepage/param1/param2/2",
    "3"=> "http://site.com/somepage/param1/param2/3"
);

foreach ($arr as $k=>$v) {
    if ($k == "thispage") {
        echo $k." ";
    }
    else {
        echo ''.$k.' ';
    }
}

Its surprise, for first element "0"=>"http://site.com/somepage/param1/param2/0", not created link, (for other elements works fine)
If replace first element key 0 on something other, for example 4, now links created. What is wrong ?

A: This is happening because 0 == "thispage" and the first key is 0. To find out more about this, take a look at the PHP manual page about Type Juggling.
Use === ("is identical to") instead of == ("is equal to"), because 0 is equal to "thispage", but not identical.
This is what happens with ==:

*

*$key takes the integer value of 0

*PHP tries to compare 0 == "thispage"

*in order to make the comparison, it needs to cast "thispage" to integer

*the resulting comparison is 0 == 0, which is true
If you use ===:

*

*$key takes the integer value of 0

*PHP tries to compare 0 === "thispage"

*since 0 is of a different type (integer) than "thispage" (string), the result is false

A: Do the:
if ($k === "thispage")

You have to use identical comparison operator === as equal comparison operator won't help here, because

If you compare a number with a string or the comparison involves
  numerical strings, then each string is converted to a number and the
  comparison performed numerically.

thispage converted to number will return 0, so your if statement will match if you use equal comparison operator ==. When you do identical comparison === if type does not match it returns false.
You can read about comparison operators here.

A: This is What you are doing wrong.
if ($k === "thispage") {
    echo .$k." ";
}

A: Try this:
if ($k === "thispage") {
        echo $k." ";
    }

A: http://us.php.net/manual/en/language.types.array.php:

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").

So in your case Stings "1", "2" and "3" are treated as integers.
To fix this use the === operator that check for type along with value.

A: The reason for the result you see is the comparison operator you use. == is too imprecise sometimes and can result in wierd things like this. Using the === will compare the values for exactness and will prevent the issue you have.
so:
foreach ($arr as $k=>$v) {
    // this is the important thing
    if ($k === "thispage") {
        echo $k." ";
    }
    else {
        echo ''.$k.' ';
    }
}


text:
Q: How to reference multiple outputs from a project using ProjectReference Assume Project A produces a primary assembly but also some assemblies through the use of an MSBuild task (of our own making).
Is there a way for Project B, that has a ProjectReference to Project A, to also reference the assemblies that are produced by the task without hacking too much (I know, quite relative concept ;-))?

A: By convention a project has one primary target that it is responsible for producing, although that can be multiple related files. e.g. A MyLib.csproj may produce a MyLib.dll with supporting MyLib.pdb and MyLib.dll.config files. In general, files of certain known file extensions that match the name of the project target are associated together.
A ProjectReference will bring in the primary target assembly of the referenced project, files directly associated with the target assembly (e.g. the .pdb and .config), and one depth of assemblies (and their associated files) that are linked to by the primary target assembly.
If you have created a project with 'multiple outputs' then you will also have to create the support to reference the 'multiple outputs'.


text:
Q: Question about factor of a function can you explain this question for me? I don't quite understand it.
Thank you in advance.

$x^2+1$ is a factor of $f(x)$. Which of the following is TRUE?
$\text{a)}\qquad f(-1)=0 \qquad\qquad\qquad\qquad\quad\,\,\, \text{d)}\qquad f(x)\text{ has an $x$-intercept of $1$}$
$\text{b)}\qquad f(x)\text{ has a $y$-intercept of $-1$.} \qquad \text{e)}\qquad f(0)=1$
$\text{c)}\qquad f(i)=0\text{ where $i=\sqrt{-1}$}$

A: We say that $x^2+1$ is a factor of the polynomial $P(x)$ is there is a polynomial $Q(x)$ such that $(x^2+1)Q(x)=P(x)$.


text:
Q: Finding angle in circle to produce equal areas I have a circle that is divided into 4 quadrants with a vertical and a horizontal axis.
The center of the circle (where the axes cross) is point b.
The top of the vertical axis is point d.
On the horizontal axis, to the left of b is point a.
A line is drawn from a diagonally up and to the right, across the vertical axis (at point c) and meets the top right of the circle at e.
Line be and point f (the right end of the horizontal axis) have been added to help with the solution.

The radius of the circle is 30 and the x position of point a is -.5 from b, taking b to be (0, 0) (that is, a is to the left of b by .5)
How would we go about calculating $ \angle eab$ so that $\triangle cab$ = slanty sector dce?
With trial and error in a graphing program, I found the answer to be 88.09075925431...
But how would one go about solving this in a general method?

A: Here is an outline of the solution:
Let $\theta = \angle dbe$, in radians. Then we get the area of the sector to be $900\pi\cdot\frac{\theta}{2\pi} = 450\theta$. And the area of $\triangle abe$ is $\frac12 (ab)(be)\sin(\frac\pi 2+\theta) = \frac{15}2\cos\theta$. Setting these equal, we get the equation
$$60\theta = \cos\theta.$$
We can solve this numerically (e.g., Newton's method) or by using the second-order Taylor polynomial of $\cos$ and the quadratic formula. Either way, we get $\theta\approx 0.0166644$.
Now you can use standard trigonometry (e.g., law of cosines and law of sines) to find your angle $eab$ to be approximately $1.53747$ radians, or $88.0905^\circ$.


text:
Q: For loop to check all possible combination I have a simple shiny consisting of 1 filter, 1 date and submit button. So if the user selects any value in filter, date and click on submit button, the results as displayed in table. At time, the table is not displayed and throws some error. But as a user we cannot check all possible combinations of Filter, date to check if the table is displayed or not. So i have a below code to check that. i am trying to run a for loop here but not able to execute. Can anyone please help me
app <- ShinyDriver$new(getwd())
new_value <- app$setInputs(ID = "AAA", Date = "2019-12-27", Submit = "click")
expect_error(new_value)
app$stop()

So there are actually 8 ID's in my dataset shown below and there are 2 dates. I need to check for all possible combination ID and dates if i am getting any error or not. So I am planning to write a for loop (written down)
df
ID          dates
AAA     2019-12-27
BBB     2019-12-28
CCC     2019-12-27
DDD    2019-12-28
EEE    2019-12-27
FFF     2019-12-28
GGG     2019-12-27
HHH     2019-12-28

For loop
app <- ShinyDriver$new(getwd())
new_value <- list()
for (i in length(df$ID)) {
  for (j in length(df$dates)) {
    new_value <- app$setInputs(Tic = df$ID[i], Date = df$dates[j], Submit = "click")
  }
}
expect_error(new_value)
app$stop()


text:
Q: Cannot send firebase push notification from lambda I am hoping someone can help me point my mistake here.
I am trying to send a firebase push notification through a lambda using the HTTP legacy endpoint
https://fcm.googleapis.com/fcm/send
I am following the guide from:
https://craigrussell.io/2019/03/send-firebase-fcm-push-notification-from-aws-lambda/
Here is my code:
const authHeader ='key=A****IV';
const deviceToken ='eut4****pm';

  console.log('sending Push notification');
  return new Promise((resolve, reject) => {
    const options = {
      host: 'fcm.googleapis.com',
      path: '/fcm/send',
      method: 'POST',
      headers: {
        'Authorization': authHeader,
        'Content-Type': 'application/json',
      },
    };

    const req = http.request(options, (res) => {
      console.log('success');
      resolve('success');
    });

    req.on('error', (e) => {
      console.log('failuree' + e.message);
      reject(e.message);
    });

    // const reqBody = '{"to":"' + deviceToken + '", "priority" : "high"}';
    const reqBody = '{"to":"' + deviceToken + '", "priority": "high", "notification": {"title": "Test", "body": "Test"}}';
    console.log(reqBody);

    req.write(reqBody);
    req.end();
  });
};

I do not receive any push notification after this . Am i doing something wrong here?

A: I think the key point is that you use the http module. Actually, it works well when using https module on my side.
var https = require('https');

The complete code is as follows:
var https = require('https');
exports.handler = async(event) => {
const authHeader = 'key=AA***y';
const deviceToken = 'fG***-';
return new Promise((resolve, reject) => {
    const options = {
        host: 'fcm.googleapis.com',
        path: '/fcm/send',
        method: 'POST',
        headers: {
            'Authorization': authHeader,
            'Content-Type': 'application/json',
        },
    };

    console.log(options);
    const req = https.request(options, (res) => {
        console.log('success');
        console.log(res.statusCode);
        resolve('success');
    });

    req.on('error', (e) => {
        console.log('failuree' + e.message);
        reject(e.message);
    });

    // const reqBody = '{"to":"' + deviceToken + '", "priority" : "high"}';
    const reqBody = '{"to":"' + deviceToken + '", "priority": "high", "notification": {"title": "Test", "body": "Test"}}';
    console.log(reqBody);

    req.write(reqBody);
    req.end();
});
};

For more details, you can see the res field after http request, it will show statusCode 403 when you use http.


text:
Q: VS Code Tuning: Merging Explorer, Search and Source Control in the Panel Now in VS Code there are a lot of tuning possibilities.
Right now I have this Side Bar and the Panel on the left side, and when I want to see the explorer I click on it and if I want to see the SourceControll I must click again to see the Source Control.
Is it posible to make those 3 Elements share the Panel? or at least two of them?


text:
Q: How to make a program that infinitely sends a message after reaching a certain point So I want to make a program that increases  in 'count'. Every interval of 1 000 000, I want the program to say: "(1),000,000" marked has been reached. Of course I want that (1) to be replaced with 2, 3, 4, 5, 6 etc, whenever the interval has been reached. So when the two million mark has been reached I want it to say "2,000,000" mark has been reached."
Here is a simplified version of what my program is doing. However it is fixed to the intervals that I have set.
count = 0

while True:
    count += 1
    if count == 1000000:
        print("The 1000000 mark has been reached.")
    if count == 2000000:
        print("The 2000000 mark has been reached.")
    if count == 3000000:
        print("The 3000000 mark has been reached.")

A: Try the following with a modulus operator:
count = 0

while True:
    count += 1
    if count % 1000000 == 0:
        print(f"The {count} mark has been reached.")

For an explanation about the modulus (%) operator, see this article

A: You can use the modulo operator:
count = 0

while True:
    count += 1
    if count % 1000000 == 0:
        print(f"The {count} mark has been reached.")

A: See if this one can help you:
Var, Count = 0, 1000000

while True:
    Var += 1
    #print(Var)
    if Var == Count:
        Count += 1000000
        Var1 = str(Var).find("0")
        Value = str(Var)[:Var1]+","+str(Var)[Var1::]
        print(f"The {Value} mark has been reached")


text:
Q: Is it possible to set widget options dynamically in R Shiny? As a minimal working example,
# An app with a datatable whose pagination option we can toggle with a button
library(shiny)
runApp(list(
    ui = basicPage(
        actionButton("button", label = "Toggle paginate"),
        dataTableOutput("table")
    ),
    server = function(input, output) {
        output$table <- renderDataTable(
            data.frame(x = 1:100, y = input$button),   # Some dummy data
            options = list(
                bPaginate = as.logical(input$button %% 2)
            )
        )
    }
))

The corresponding browser output:

I should be able to dynamically switch the option bPaginate on and off just by clicking the "Toggle paginate" button.
However, this does not work - the table is never paginated. What's going wrong?

A: I also struggled with the data table widget. Neither renderDataTable nor DT::renderDataTable appear to recognize and re-render output when options are given as a simple list.
Yihui's answer works for the base Shiny renderDataTable, but I would never guess this as a solution and I can't see why a function would work and a plain list wouldn't. I assume it is some internal implementation issue with the underlying Javascript, but this seems like an implementation detail that should not leak out into the R api.
I can't, however, make Yihui's answer work for the DT version of the DataTable package. Perhaps this is just my error, but I eventually figured another way to get user input to affect table options without using a function for options. Doing so requires one extra (reactive) variable layer and uses the datatable() function. (Note that the latest DataTable version this is all based on uses different option names, and I'm using a slightly different ui than the question above. None of that should change the basic problem or its solution.)
# An app with a datatable whose pagination option we can toggle with a button
library(shiny)
runApp(list(
   ui = fluidPage(
      sidebarLayout(
         sidebarPanel(
            checkboxInput("paging", "Paginate table")
         ),
         mainPanel(
            DT::dataTableOutput("table")
         )
      )
   ),
   server = function(input, output) {
      # Create a new table when input$paging changes
      makeTable <- reactive({
         DT::datatable(
            { data.frame(x= 1:100, y = input$paging)},   # Some dummy data
            options= list(
               paging = input$paging
            )
         )
      })
      # Render the datatable returned by the reactive function
      output$table <- DT::renderDataTable( makeTable() )
   }
))

A: You can use a function to return the DataTable options, e.g.
options = function() {
  list(
    bPaginate = as.logical(input$button %% 2)
  )
}

Note this requires shiny >= 0.9.0.

A: Thanks Stuart. Your example works right off the bat.
Here is your code for a flexdashboard:
---
title: "Datatable Pagination"
output: flexdashboard::flex_dashboard
runtime: shiny
---

Inputs {.sidebar}
-------------------------------------

```{r}
# shiny inputs defined here
checkboxInput("paging", "Paginate table")
```

## Column

### Data Table

```{r}

makeTable <- reactive({
    DT::datatable(
        { data.frame(x= 1:100, y = input$paging)},   # Some dummy data
        options= list(
            paging = input$paging
        )
    )
})
# Render the datatable returned by the reactive function
output$table <- DT::renderDataTable( makeTable() )

DT::dataTableOutput("table")

```