text:
Q: angular 2 passing a function var to a different component i am new to angular 2 and i have a question.
I created a modal as a component called ModalContent and one of its functions is:
@Component({
selector: 'modal-content',
templateUrl: './app/d-modal/d.modal.content.component.html',
styleUrls: [ './app/d-modal/d.modal.content.component.css' ],
providers: [InMemoryDataService],
})
export class ModalContent {
    totalSelected:number;

    addM() {
        let selected = this.m.filter((x) => x["selected"]);
        let totalSelected = selected.length;
        console.log(totalSelected);
        this.activeModal.close('Close click');
    }}

How can I pass the variable totalSelected in the modal component to a function in a totally  different component called form to use it same as the below:
@Component({

 moduleId: module.id,
  selector: 'form',
  templateUrl: 'form.component.html',
  styleUrls: [ 'form.component.css' ],
  directives : [ModalContent],`

})`

export class FormComponent {
@ViewChild(ModalContent) childComp: ModalContent;
    addMForm() {
        const modalRef = this.modalService.open(ModalContent);
         modalRef.componentInstance.name = 'World';`
         this.childComp.addM();

    for (var m = 0; m < totalSelected; m++)
    {
        let newGroup = new FormGroup({
          A :new FormControl(),
          B: new FormControl(),
          C: new FormControl(),
          D :new FormControl()
        });

        this.Form.controls.users.push(newGroup);
    }}

}

the thing that i want to achieve is to create a number of fields in my form based on the number of selection in the modal component so whatever the user choose in the modal component i want to capture the number in totalselected variable and push it to the form component and use it in the (for) as a counter but it is not working

A: If the other component is a child component you can use the @input decorator to pass data between a parent and a child component. I would look at this it should be helpful. Also, given that totalselected only exists in the scope of the function you provided you may want to return it from the function or create it before the function definition. Also since you have mentioned that your function resides in a modal it might make more sense for you to make the modal a child of the other component and use @output decorator.
Edit --
You could do something like this
totalSelected: number;
addM() {
let selected = this.m.filter((x) => x["selected"]);
this.totalSelected = selected.length;
console.log(totalSelected);
this.activeModal.close('Close click');
}

Now the variable total selected is available outside of the scope of the function call.


text:
Q: NetSuite: Filter join in SuiteScript I am trying to add a search filter to a search in SuiteScript. What I want to filter is the date a custom record is created. The search is off a job (or Project) record, but the custom record is connected to the job (this needs to be off the job for other reasons).
In the UI this would like like: CustomRecordName : Date Created  (and as a filter you would select the filter you want, such as within this fiscal quarter).
I know the syntax:
new nlobjSearchFilter(fieldId, join, operator, value1, value2);

I went to the custom record and the "Date Created" fieldId is 'created'. My Custom record's id is: customrecord301.
Here is what I have for my specific case:
filters.push(new nlobjSearchFilter('created', 'customrecord301', 'within', 'thisfiscalquarter'));

I get the following error:
An nlobjSearchFilter contains an invalid join ID, or is not in proper syntax: created.
What am I missing/doing wrong?

A: The join parameter should be the ID of the field you are joining through instead of the record type you are joining to. Instead of "customrecord301", you need the ID of the list/record field on the Project (job) record.

A: You don't need to put any value in 'join' until and unless you are executing a joined search.
Please try this
filters.push(new nlobjSearchFilter('created', null, 'within', 'thisfiscalquarter'));

redpajama_set_name: RedPajamaStackExchange


text:
Q: bash script with grep command not I have this part of shell script :
#!/bin/bash
shopt -s extglob
currentDate=$(date +%F)

echo $currentDate
command="grep $currentDate"
gcs3='s3://gc-reporting-pud-production/splunk_printer_log_files'
gcs3ls='aws s3 ls 's3://gc-reporting-pud-production/splunk_printer_log_files/SOUTH_ASIA/' --recursive '
ssyss3=s3://ssyssplunk

gcs3Current=$($gcs3ls|$command|sed 's/^.*\(splunk_printer.*\)/\1/g')

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
s3ls='aws s3 ls --human-readable --summarize 's3://ssyssplunk/' --recursive'
echo "ls: " $s3ls
egrepCommand="'$currentDate|Total'"
echo "grep: " $egrepCommand
totalSize=$($s3ls|egrep $currentDate\|Total|awk -F 'Total Size:' '{print $2}'|sed '/^$/d')
echo "total size: "  $totalSize
IFS=$SAVEIFS

and im getting this error :

2019-05-27 ls:  aws s3 ls --human-readable --summarize
  s3://ssyssplunk/ --recursive grep:  '2019-05-27|Total'
  ./copyFilesFromS13.sh: line 54: aws s3 ls --human-readable --summarize
  s3://ssyssplunk/ --recursive: No such file or directory total size:

what am i doing wrong ?

A: You have set IFS to just the newline and backspace. So, $s3ls, after expansion and word splitting, will be aws s3 ls --human-readable --summarize s3://ssyssplunk/ --recursive taken as a single word. Bash tries to execute this single word as a command, instead of executing aws with a bunch of arguments.
You really shouldn't be storing commands in variables. Use arrays, instead:
s3ls=(aws s3 ls --human-readable --summarize 's3://ssyssplunk/' --recursive)
#...
totalSize=$("${s3ls[@]}" | ...)


text:
Q: Dynamic column and values in react table response : {initial_data: [{
 "Did I see this plant in 2016?"=>"No",
 "Did I see this plant in 2017?"=>"Yes",
 "How Many?"=>1,
 "User Data 4"=>"x",
 "User Data 5"=>nil,
 "Did I see this plant in 2022?"=>"No",
 "Name"=>"Abronia alpina"},
 {"Did I see this plant in 2016?"=>"No",
 "Did I see this plant in 2017?"=>"No",
 "How Many?"=>11,
 "User Data 4"=>"x",
 "User Data 5"=>nil,
 "Did I see this plant in 2022?"=>"Yes",
 "Name"=>"Abronia alpina1"}]
}

Based on above response I am executing below code to print the header and there values dynamically.

const CUSTOM_COLUMNS = (Object.keys(props.initial_data[0].map((item, index) =>
                            [{
                              id: 'user_data',
                              Header: item,
                              headerClassName: 'family-header',
                              accessor: item,
                              className: 'centered capitalize',
                              show: true
                            }][0]
                          ));

const columns = [
  ...CUSTOM_COLUMNS,
  {
    Header: 'Actions',
    accessor: 'id',
    show: true,
    className: 'centered',
    Cell: (props) => (

         Delete

    )
  }
];

I able to correctly print the header dynamically, but my values are not coming dynamically and it's displaying my last hash key values in each column.
My header should be :
["Did I see this plant in 2016?", "Did I see this plant in 2017?", "How Many?", "User Data 4", "User Data 5", "Did I see this plant in 2022?", "Name"]

and row values should be:
Row1 : ["No", "Yes", 1, "x", "", "No", "Abronia alpina"]
Row1 : ["No", "No", 11, "x", "", "Yes", "Abronia alpina1"]

Can you please help me to get it dynamically, or let me know what I am doing wrong here. I am new in react so maybe i am missing here so please correct me.

A: If you are using react-table, to render the table, I think your logic of creating columns is wrong. It should be something like this.
const columns = Object.keys(response.initial_data[0]).map((key, id)=>{
  return {
    Header: key,
    accessor: key
  }
})

I have tried to create a snippet with your data. Let me know if this helps.

const ReactTable = window.ReactTable.default

const response = {
  initial_data: [
   {
     "Did I see this plant in 2016?":"No",
     "Did I see this plant in 2017?":"Yes",
     "How Many?":1,
     "User Data 4":"x",
     "User Data 5":"",
     "Did I see this plant in 2022?":"No",
     "Name":"Abronia alpina"
   },
   {
     "Did I see this plant in 2016?":"No",
     "Did I see this plant in 2017?":"No",
     "How Many?":11,
     "User Data 4":"x",
     "User Data 5":"",
     "Did I see this plant in 2022?":"Yes",
     "Name":"Abronia alpina1"
   }]
}

class App extends React.Component {

  render() {
    const data = response.initial_data

    const columns = Object.keys(response.initial_data[0]).map((key, id)=>{
      return {
        Header: key,
        accessor: key
      }
    })

    return <ReactTable
      data = { data }
      columns = { columns }
    />
  }
}

ReactDOM.render( < App / > , document.getElementById("app"))

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/react-table/6.7.6/react-table.css"></link>

A: With React-Table you header must have a accessor and your data must be mapped with accessor as the key
You would create your columns like
  getColumns() {
    return Object.keys(data.initial_data[0]).map(key => {
      return {
        Header: key,
        accessor: key
      };
    });
  }

and you Table can then look like
class App extends React.Component {
  getColumns() {
    return Object.keys(data.initial_data[0]).map(key => {
      return {
        Header: key,
        accessor: key
      };
    });
  }
  render() {
    const columns = this.getColumns();
    console.log(data.initial_data);
    return (

        <ReactTable
          data={data.initial_data}
          columns={columns}
          defaultPageSize={10}
          className="-striped -highlight"
        />

        <Tips />
        <Logo />

    );
  }
}

According to documentation:
accessor: 'propertyName', // or Accessor eg. (row) => row.propertyName

Accessors are functions that return the value to populate the row's
  value for the column. This lets the render function not have to worry
  about accessing the correct data, the value is automatically populated
  in it's props.
If a string or array is passed the default accessor is used. The
  default accessor will parse the input into an array and recursively
  flatten it. Any values that contain a dot (.) will be split. Any
  values that contain bracket ([]) will be split. This array is then
  used as the path to the value to return.

Working Codesandbox


text:
Q: Azure Virtual Network Point-to-Site (ex. Azure Connect) name resolution While Azure Connect is being retired and Azure Virtual Network provides similar feature with better speed, i've noticed few drawbacks though.
With Azure Connect netbios remote share/computer connect worked perfectly, as well as name resolution. With Windows Azure Virtual Network, name resolution would require DNS and will not work otherwise. I could have survived with this if there at least was some kind of list of connected clients with their IPs, which is not available and different IPs are assigned on each reconnect. So it makes impossible 2 clients connect to each other without prior knowing their current IPs.
The biggest issue though, is that no matter what (i can ping and access any port of remote computer) netbios doesn't seem to work.
When i do a tracert on an IP i can see the computer name. But it doesn't accept a ping with the computername.
Thank you!

A: I solved this problem by using nbtstat. nbtstat will return the NetBios computer name that correspondent with the ip adres given.
As a example: nbtstat -A 10.0.0.5
In Java i created a loop that will check if the given ip is reachable. My Azure VPN range is 10.0.0.x. So my loop will check ip 10.0.0.1 untill 10.0.0.20. If the ip is reachable it will look up the computer name. if the computer name is the computername i was looking for then i have the ip adres to connect to. I use a reachable (ping) to speed up the process.
Sample code: Use a loop the check if the ip is reachable. Similar as ping:
for (byte i = 1; i <= 20; i++)
            {
                inet = InetAddress.getByAddress(new byte[] { 10, 0, 0, i });
                System.out.println("Sending Ping Request to " + inet);
                reachable = inet.isReachable(pingTimeOut);
                System.out.println(reachable ? "Host is reachable" : "Host is NOT reachable");

                if (reachable)
                {
                    System.out.println("Name resolve " + inet.getHostAddress());
                    trace = GetNameByIp(inet.getHostAddress());
                    if (trace.contains(computerName)) return "10.0.0." + Byte.toString(i);
                }
            }

Retreive the Netbios name:
        Process traceRt;
        System.out.println("nbtstat -A " + address);
        traceRt = Runtime.getRuntime().exec("nbtstat -A " + address);

        // read the output from the command
        route = convertStreamToString(traceRt.getInputStream());

A: I solved this problem by editing my hosts file. I was testing against a WCF service and I added the ip address and server name of the azure webserver vm and azure domain controller to the host file.  Be sure to edit the hosts file as an adminstrator.


text:
Q: HtmlFromHtml overrides text color selector on View I have a textview with a custom color selector setup in xml style.
Selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/light" android:state_enabled="false"/>
    <item android:color="@color/dark" />
</selector>

I set the text like this:
mView.setText(Html.fromHtml("Some incoming html text"));

This overrides the current text selector on the view.
I've also tried to reset the selector like this:
mView.setTextColor(ContextCompat.getColor(getContext(),R.color.sel);

I need to keep the style the same, any ideas?


text:
Q: Bitlocker: Create a USB startup key from a recover key file I've encrypted the C: drive of one of my machines and lost the USB startup key.  I DID backup the Recovery Key .txt file.  How can I create a new USB startup key from this .txt file?

A:
How can I create a new USB startup key from this .txt file?

You cannot create the startup from that file.  You will have to run through the following process in order to create a new startup key.

*

*Navigate to All Control Panel Items -> BitLocker Drive Encryption

*Click Copy startup key and go through the process of copying the startup key to a new flash drive.  DO NOT use the same key that
  contains the recovery key, since that currently is your only method,
  you can use to unlock your drive and access your data.

Source: How to Copy Startup Key of OS Drive Encrypted by BitLocker in Windows


text:
Q: How can I get the function name in the shared library with an address from backtrace_symbols? I try to print the call stack in some functions by using "backtrace" and "backtrace_symbols".
But the app builded without -rdynamic. So the output of backtrace_symbols show just like this:
     libnet.so [0x1a08f36]
Then who can tell me how can I get the function name by 0x1a08f36?


text:
Q: AngularJS: How to share scope functions and variables with other controllers I've multiple controllers in my application, where I have some duplicate code like:
$scope.alert = null;

$scope.addAlert = function (message) {
    $scope.alert = { type: 'danger', msg: message };
};

$scope.clearAlerts = function () {
    $scope.alert = null;
};

What is the recommended way sharing these scope functions and variables in AngularJS? Using controller inheritance?

A: Create a one controller and then place common methods inside that controller scope. So that you can use that scope anywhere else and get access to method inside controller.
Controller
app.controller('commonCtrl', function($scope) {
    $scope.alert = null;

    $scope.addAlert = function(message) {
        $scope.alert = {
            type: 'danger',
            msg: message
        };
    };

    $scope.clearAlerts = function() {
        $scope.alert = null;
    };
});

Thereafter use scope of this controller by inject it using $controller, and then inside curly brace you could assign common controller scope to the current scope of controller.
Utilization of Common Controller
app.controller('testCtrl', function($scope, $controller) {
    //inject comomon controller scope to current scope ,
    //below line will add 'commonCtrl' scope to current scope
    $controller('commonCtrl', { $scope: $scope });
    //common controller scope will be available from here

});

Or more precise way would be using common sharable service, that exposed two method and alert data, you can use this service method by injecting service name inside your controller.
Service
app.service('commonService', function($scope) {
    this.alert = null;

    this.addAlert = function(message) {
        this.alert = {
            type: 'danger',
            msg: message
        };
    };

    this.clearAlerts = function() {
        this.alert = null;
    };
});

Utilization of service inside Controller
app.controller('testCtrl', function($scope, commonService) {

  console.log(commonService.alert);
  commonService.addAlert("Something");
  console.log("Updated Alert" + commonService.alert);

});

Hope this has cleared your concept, Thanks.

A: My own solution for this use case was to define a type of Observer Pattern.
The code was structured in the following way:
var app = angular.module('testModule', []);
app.factory('alertService', ['$timeout', function($timeout){
    var alertListeners = [];

    this.register = function (listener) {
        alertListeners.push(listener);
    };

    this.notifyAll = function (data) {
    for (// each listener in array) {
        var listenerObject = alertListeners[i];
        try { // do not allow exceptions in individual listeners to corrupt other listener processing
            listenerObject.notify(data);
        } catch(e) {
            console.log(e);
        }
    }
    };
 }]).
 directive('myAlerts', ['alertService', function(alertService){

     var alertDirectiveObserver = function($scope, alertService) {

        this.notify = function(data) {
        /*
         * TO DO - use data to show alert
         */
         };

         /*
          * Register this object as an event Listener. Possibly supply an event key, and listener id to enable more resuse
          */
         alertService.register(this);

         $scope.on('$destroy', function() {
             alertService.unregister(// some listener id);
         });
     };

   return {
     restrict: 'A',
     template: '
{{alertMessage}}
',
     controller: ['$scope', 'alertService', alertDirectiveObserver],
     link: function(scope){
     }
    }
}]).
controller('alertShowingController', ['$scope', 'alertService',   function($scope, alertService){
    alertService.notifyAll({'warning', 'Warning alert!!!'})
 ]);

The alertShowingController is a simple example of how all controllers can simply inject the alertService and generate an event.
My own implementation is more elaborate in that it uses separate event keys to allow the controllers to generate other event notifications.
I could then define a single div that was in a fixed position at the top of the page that would dispay bootstrap alerts.

{{alert.msg}}


text:
Q: meaning of 'sip'
Two were an old ill-favored pair;
But the third was young, and passing fair,
With laughing eyes and with coal-black hair;
A dainty quean was she!
Rob would have given his ears to sip
But a single salute from her cherry lip.

As far as I know 'to sip' is used when describing the act of drinking. But in this poem, it seems like 'to sip' means 'to listen'. Am I rightly understood?


text:
Q: check datetime value is in DateTimeRangeInput in conda panel I'm trying to build a conda panel that can see values based on DatetimeRangeInput slider
so I created dataframe like this
data = {'name':['A', 'B', 'C', 'D'],
        'open_time': [dt.datetime(2021, 7, 1, 21, 0), dt.datetime(2021, 7, 2, 11, 0), dt.datetime(2021, 7, 3, 3, 0),dt.datetime(2021, 7, 3, 2, 0) ],
        'count':[27, 24, 22, 32],
        'size':[34, 56,67,78]
       }

df_sample = pd.DataFrame(data)
df_sample

so the output like this
   name open_time          count size
0   A   2021-07-01 21:00:00 27   34
1   B   2021-07-02 11:00:00 24   56
2   C   2021-07-03 03:00:00 22   67
3   D   2021-07-03 02:00:00 32   78

then added y axis options in this way
yaxis_sample = pn.widgets.RadioButtonGroup(
    name='Y axis',
    options=['count', 'size'],
    button_type='success'
)

widget created like this
date_range = pn.widgets.DateRangeSlider(
    name='Date Range',
    start=dt.datetime(2021, 7, 1, 00, 00, 00), end=dt.datetime(2021, 8, 1, 00, 00, 00),
    value=(dt.datetime(2021, 7, 2, 00, 00, 00), dt.datetime(2021, 7, 4, 00, 00, 00)),
)

date_range

then I'm struggling to combine pipeline and widget, in this section
names = ['A', 'B','C', 'D']

sample_pipeline = (
    df[
        (date_range.align(df_sample.open_time)) &
        (df_sample.name.isin(names))
    ]
    .groupby(['name', 'open_time'])[yaxis_sample].mean()
    .to_frame()
    .reset_index()
    .sort_values(by='open_time')
    .reset_index(drop=True)
)

how to check df_sample.open_time is in the range of date_range.value ?
I've tried following
Attempt 1
names = ['A', 'B','C', 'D']

sample_pipeline = (
    df[
        (df_sample.open_time >= date_range.param.value_start) & (df_sample.open_time <= date_range.param.value_end) &
        (df_sample.name.isin(names))
    ]
    .groupby(['name', 'open_time'])[yaxis_sample].mean()
    .to_frame()
    .reset_index()
    .sort_values(by='open_time')
    .reset_index(drop=True)
)

TypeError: Invalid comparison between dtype=datetime64[ns] and Date

Attempt 2
names = ['A', 'B','C', 'D']

sample_pipeline = (
    df[
        (df_sample.open_time >= date_range.start) & (df_sample.open_time <= date_range.end) &
        (df_sample.name.isin(names))
    ]
    .groupby(['name', 'open_time'])[yaxis_sample].mean()
    .to_frame()
    .reset_index()
    .sort_values(by='open_time')
    .reset_index(drop=True)
)

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

A: It wasn't clear in your post, but something you have to do is instantiate an interactive dataframe with df.interactive(), .interactive being a dataframe accessor that is registered by hvPlot to on Pandas dataframes when importign hvplot.pandas.
Then indeed you were right in your first attempt, the trick with the date ranges is to rely on the Parameter value_start and value_end.
import datetime as dt
import hvplot.pandas
import pandas as pd
import panel as pn

# Data init
data = {'name':['A', 'B', 'C', 'D'],
        'open_time': [dt.datetime(2021, 7, 1, 21, 0), dt.datetime(2021, 7, 2, 11, 0), dt.datetime(2021, 7, 3, 3, 0),dt.datetime(2021, 7, 3, 2, 0) ],
        'count':[27, 24, 22, 32],
        'size':[34, 56,67,78]
       }
df = pd.DataFrame(data)

names = ['A', 'B','C', 'D']

# Create an interactive dataframe
dfi = df.interactive()

# Create the widgets that will drive the pipeline

date_range = pn.widgets.DateRangeSlider(
    name='Date Range',
    start=dt.datetime(2021, 7, 1, 00, 00, 00), end=dt.datetime(2021, 8, 1, 00, 00, 00),
    value=(dt.datetime(2021, 7, 2, 00, 00, 00), dt.datetime(2021, 7, 4, 00, 00, 00)),
)
yaxis_sample = pn.widgets.RadioButtonGroup(
    name='Y axis',
    options=['count', 'size'],
    button_type='success'
)

# Create the pipeline
sample_pipeline = (
    dfi[
        (dfi.open_time >= date_range.param.value_start) & (dfi.open_time <= date_range.param.value_end) &
        (dfi.name.isin(names))
    ]
    .groupby(['name', 'open_time'])[yaxis_sample].mean()
    .to_frame()
    .reset_index()
    .sort_values(by='open_time')
    .reset_index(drop=True)
)
sample_pipeline


text:
Q: Why am I not able to access the HTTP call in this node.js app? I am trying to build a simple Node Js bot with Twilio, AWS & Claudia Bot.
I'm trying to access this public API, and specifically the "text" part whenever a user's text contains the word "Fact". Currently, I am able to access the first API when a users text contains "Quote", but I am unable to retrieve the fact.
Any thoughts?
var botBuilder = require('claudia-bot-builder');
var greeting = require('greeting');
var fetch = require('node-fetch');

var bot = botBuilder(function(message) {
  if (message.text.match(/quote/i)) {
    return fetch('http://api.forismatic.com/api/1.0/?method=getQuote&format=text&lang=en').then(function(res) {
      return res.text();
    });
  } else if (message.text.match(/fact/i)){
    return fetch('https://uselessfacts.jsph.pl/random.json?language=en').then(function(res) {
      return res.json(text);
    });
  } else {
    return greeting.random();
  }
}, { platforms: ['twilio'] });

module.exports = bot;

A: return fetch('https://uselessfacts.jsph.pl/random.json?language=en').then(function(res) {
      return res.json(text);
});

Here text is undefined so it will return an error. Instead try this:
fetch('https://uselessfacts.jsph.pl/random.json?language=en').then(function(res) {
      return res.json();
});


text: Q: Android application restarts without any expection and logcat message on onresume mostly I am working on shopping application. I am facing a strange problem. Application keeps restarting itself after sometime on resuming some activity. It's happens mostly on 4.2.2 and some devices of 4.3 . Application working very well on s3 , s4 and s5. But having problem with devices of htc mostly. I also checked the heap size and free memory using MAT. In my application I am also doing system.gc() in almost every method.When application restarts I haven't see any error or exception in logcat also. Can anyone had this problem before?


text:
Q: How to setup ViewPager and TabLayout with binding?(IllegalArgumentException: No view found) I try to setup a TabLayout and ViewPager with a Fragment by using binding. I get the next exception:

java.lang.IllegalArgumentException: No view found for  0x7f0e007c (com.movies:id/popular_movies_viewpager) for fragment PopularMoviesTabFragment`

My xml files look like these:
activity_main:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.MainActivity"
    >

<data class="MainActivityBinding"></data>

<RelativeLayout

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/main">

    <android.support.v4.view.ViewPager
        android:id="@+id/popular_movies_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.TabLayout
            android:id="@+id/popular_movies_tablayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top" />

    </android.support.v4.view.ViewPager>

</RelativeLayout>

</layout>

popular_movies_gridview_layout:
<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.PopularMoviesTabFragment">

<data></data>
<FrameLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/popular_movies_gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="600dp"
        android:numColumns="4"
        android:stretchMode="columnWidth"
        android:gravity="left">

    </android.support.v7.widget.RecyclerView>

</FrameLayout>
</layout>

My MainActivity:
public class MainActivity extends AppCompatActivity {

    private MainActivityBinding binding;

    private ViewPager viewPager;
    private TabLayout tabLayout;
    private ViewPagerAdapter viewPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragment(PopularMoviesTabFragment.newInstance(), "Trending"); // this line can cause crashes
        viewPager= binding.popularMoviesViewpager;
        binding.popularMoviesViewpager.setAdapter(viewPagerAdapter);
        binding.popularMoviesTablayout.setupWithViewPager(viewPager);
    }
}

My Fragment:
public class PopularMoviesTabFragment extends Fragment {

    private List<Movie> movies = new ArrayList<>();
    private PopularMoviesGridviewLayoutBinding binding;
    private PopularMoviesAdapter adapter;

   public PopularMoviesTabFragment() {
        // Required empty public constructor
    }
    public static PopularMoviesTabFragment newInstance() {
        PopularMoviesTabFragment fragment = new PopularMoviesTabFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(getActivity(), R.layout.popular_movies_gridview_layout);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
        binding.popularMoviesGridview.setLayoutManager(layoutManager);
        .
        .
        .
        .
    }

How should I change my code to be able to avoid the no view for the fragment exception?

A: Eventually, I found out the problem. I called the bindings onCreate() instead of onCreateView(). After I changed all code from the onCreate() to onCreateView() in the PopularMoviesTabFragment, the code worked how it is supposed to.


text:
Q: observableArray not updating the UI I am facing a problem that the UI only updates with correct data after a refresh of the page. I am coming from here observableArray is not defined
My JS Code:
define(
    ['knockout'],
    function (ko) {
        "use strict";
        return {
            onLoad: function (widget) {
                widget.getDetails= function (prod) {
                    var abc = prod.DetailsNumbers();
                    console.log(abc);
                    var someArray= [];
                    someArray= abc.split(',');
                    //console.log(someArray);
                    widget.anotherObservableArray = ko.observableArray();

                    for (var i = 0; i < someArray.length; i++) {
                        var temp = {
                            "prodName": ko.observable(someArray[i])
                        };
                        var myKoObservableArray = widget.anotherObservableArray;
                        myKoObservableArray.push(temp);

                    }
                    console.log(myKoObservableArray());
                    this.myKoObservableArray = myKoObservableArray;
                };
            }
        }
    }
);

My HTML:

                Button Here
                <button data-bind="click: getDetails(product())">Click me</button>

// this here is working fine

              //this changes only after a refresh

The data-bind="text: prodName" changes value only after a refresh of the page.

A: Create the array once in onLoad, and then just update it.  Don't keep creating it each time.
define(
    ['knockout'],
    function (ko) {
        "use strict";
        return {
            onLoad: function (widget) {
                widget.myKoObservableArray = ko.observableArray();
                widget.getDetails= function (prod) {
                    var abc = prod.DetailsNumbers();
                    console.log(abc);
                    var someArray= [];
                    someArray= abc.split(',');
                    //console.log(someArray);

                    // empty the array
                    widget.myKoObservableArray([]);

                    for (var i = 0; i < someArray.length; i++) {
                        var temp = {
                            "prodName": ko.observable(someArray[i])
                        };
                        widget.myKoObservableArray.push(temp);

                    }
                    console.log(widget.myKoObservableArray());
                };
            }
        }
    }
);


text:
Q: Activesheet."SomeRange".RemoveDuplicates returns error if not "specific" range If I specify the range specifically such as:
ActiveSheet.Range("C3","G20").RemoveDuplicates Columns:=Array(1), Header:=xlNo

the code works perfectly. However, if I instead try to use:
ActiveSheet.Selection.RemoveDuplicates Columns:=Array(1), Header:=xlNo

or
Dim selRange as Range
Set selRange = Selection
ActiveSheet.selRange.RemoveDuplicates Columns:=Array(1), Header:=xlNo

it doesn't work. I get

Run-time error '438': Object doesn't support this property or method.

I cannot use a specific range since it changes all the time so I need to just remove duplicates for the current selection. Does anyone have any tips to solve this?

A: You can use:
ActiveSheet.Range(Selection.Address).RemoveDuplicates Columns:=Array(1), Header:=xlNo

The key is adding the .Address

A: Use:
Selection.RemoveDuplicates Columns:=Array(1), Header:=xlNo

without the ActiveSheet. ActiveSheet does not have a Selection property/method.


text:
Q: Can't get global variable of DFS in Python to return the right value I am learning to use Python to implement DFS algorithm.  The DFS will return the max value in a binary tree
There are 2 approaches I wrote.  The 1st approach is findMax function - it uses return values to track the max value in a tree.  The 2nd approach is findMax2 function - it uses a global variable to track the max value.
I googled around, but couldn't really understand why my 2nd approach doesn't work - the global variable, max_val, won't return the correct value, and the error msg is
UnboundLocalError: local variable 'max_val' referenced before
assignment

I'm not very good at Python, so any help is greatly appreciated.  :)  Here is the code.
class Node:
  def __init__(self, key):
    self.left = None
    self.val = key
    self.right = None

  def inorder(self, root):
    if root:
      self.inorder(root.left)
      print(root.val)
      self.inorder(root.right)

  def findMax(self, root):
    if root is None:
      return float('-inf')
    max_lv = self.findMax(root.left)
    max_rv = self.findMax(root.right)
    return max(root.val, max_lv, max_rv)

  max_val = float('-inf')
  def findMax_2(self, root):
    if root is None:
      return max_val
    max_val = max(max_val, root.val)
    dfs(root.left)
    dfs(root.right)

r = Node(5)
r.left = Node(1)
r.left.left = Node(8)
r.left.right = Node(11)
r.inorder(r)
print(r.findMax_2(r))

Update:
Thanks for everyone's comments.  I modified my code based on ggorlen's suggestion.
def findMax_2(self, root):
    def dfs(node):
      if node is None:
        return max_val
      max_val = max(max_val, node.val)
      print("max_val:", max_val)
      dfs(node.left)
      dfs(node.right)

    max_val = float('-inf')
    dfs(root)
    return max_val

But I still got the same error:
Traceback (most recent call last):
  File "dfs_findMax_2.py", line 56, in <module>
    print("max val:", r.findMax_2(r))
  File "dfs_findMax_2.py", line 44, in findMax_2
    dfs(root)
  File "dfs_findMax_2.py", line 38, in dfs
    max_val = max(max_val, node.val)
UnboundLocalError: local variable 'max_val' referenced before assignment

Did I miss anything?

A: Python scoping rules have a few sharp corners.
In the class and outside the function, max_val is a class variable.  Inside the function it is a lexical variable scoped to the function, which just happens to have the same name.  Your error is because you are accessing the lexical variable before it is assigned to, so Python knows you are confused (but didn't give enough context to unconfuse you).
To access the class variable inside the function you need to access self.max_val.
If it was truly a global variable, you'd need to have a global max_val declaration in the function before you do anything with it.  (It isn't, so don't try it.)  And in the case of one function inside another, you'd need to do a nonlocal max_val instead.
And, finally, because it is a class variable, it will be accessible through all instances of the class.  If you wanted it to be an instance variable instead, you'd have assigned to self.max_val inside of your init method, and you'd still access it through self.max_val in other methods.

A: Based on ggorlen's advice, here is the code that works.  Thank you!
def findMax_2(self, root):
    def dfs(node):
        nonlocal max_val
        if node is None:
            return
        max_val = max(max_val, node.val)
        dfs(node.left)
        dfs(node.right)

    max_val = float('-inf')
    dfs(root)
    return max_val


text:
Q: How to give Timeout time to SSH_SCP APIs (libssh) in C++ In my current project. I am working on ssh_scp APIs (more precisely ssh_scp_push_file, ssh_scp_write, ssh_scp_push_directory APIs). Here is the code snipet for it.
rc = ssh_scp_push_file(scp, file_name, size, S_IRUSR | S_IWUSR);
if (rc != SSH_OK) {
    fprintf(stderr, "Can't open remote file: %s\n", ssh_get_error(session));
    return rc;
}

rc = ssh_scp_write(scp, memblock, size);
if (rc != SSH_OK) {
    fprintf(stderr, "Can't write to remote file: %s\n", ssh_get_error(session));
    return rc;
}

When I interrupt the scp communication on my Ubuntu 18.04 using a command
$ sudo iptables -I INPUT -s [ip_address] -j DROP
The process completely stops for an unknown time period. Blocking complete process. And never resume the process.
So I want to ask, is there a way to set a timeout, so that if I didn't get the response from the ssh_scp server, it will wait for some time and, on timeout returns some SSH_ERROR and proceeds further. So that it will not block a complete process.


text:
Q: How to execute R language script from Android app? I'm writing an application for Android devices and try to find a capability to execute R script from Kotlin/Java/C++(NDK). Is there a way to do so or maybe somewhere there are tools that can help to convert R language into the language mentioned above?

A: You can use Rcaller with Java. I've heard about Renjin but i've had no experience with that one, I'm pretty sure there are other external libraries but I've used the first one.

RCaller is a production ready library for calling R functions from
within Java.

Renjin is a essentially a Java library that allows you to evaluate
scripts written in the R language.

EDIT:
You can add them with:
implementation group: 'com.github.jbytecode', name: 'RCaller', version: '2.8'

implementation "org.renjin:renjin-script-engine:XXX";


text:
Q: What will happen if I apply 220 dc voltage to a 220 ac load? Let say I have a lamp which is operated on 220 V ac.
Instead of applying 220 AC voltage I apply 220 DC voltage: what will happen? And if I want to convert this 220V dc to 220V ac then what should I do?

A: An incandescent bulb will do fine. The 220 V AC is the RMS value, for Root Mean Square. The sine's amplitude will be \$\sqrt{2}\$ higher than that, or 310 V. But the RMS value tells you what equivalent DC voltage you would need to get the same power, so that's exactly what you need. The bulb will use the same power and light as bright under 220 V AC as DC.
Switching on an incandescent bulb may cause a large current peak: the cold resistance is only about a tenth of what it is when the lamp is lit, and when the voltage applied is high at that time the lamp may break. You may have noticed that if a bulb breaks it always does when switching on. So at AC worst case is when you switch on at the peak of the sine, at 310 V. But there will be lots of cases when the voltage is lower when switching on, even zero if you just happen to switch on during a zero-crossing of the sine. In fact that's the best thing to do for the bulb's longevity.
At DC you don't have this; anytime you switch it on it will be 220 V. Not as bad as 310 V, but you can't use zero-crossing switching either.
about RMS
Why do we use RMS value instead of just the average? The average of a sine is just zero, so that doesn't help at all. If we want to know how much power a voltage generates in a load we have to use the power equation
\$ P = V \times I = \dfrac{V^2}{R} \$
It's the second form we're interested in. Power is proportional to voltage squared, that's what the "S" in RMS comes from, we square the voltage.

The blue sine is our AC voltage, 1 V peak. The purple curve is that voltage squared, and the yellowish is the average of that, or mean: the "M" in RMS. It's precisely 0.5 V\$^2\$. It has still the dimension of voltage squared, so to get to a voltage quantity we take the square root of that, that's \$\frac{\sqrt{2}}{2}\$ V. The "R" in RMS. So RMS spelled out in full means: "the square root of the average of the voltage squared".
This shows that the amplitude (1 V) is \$\sqrt{2}\$ higher than the RMS value. That's where the 310 V comes from: 220 V \$\times \sqrt{2}\$ = 310 V.

A: YES your incandescent lamp will run on DC  in fact Thomas Edison who had a design contract to improve the reliability of the lightbulb and hence commercialise it did all his experiments on DC Thomas Edison wanted all power to be DC but lost to Nicholas Tesla NOW a word of warning    DC arcs much worse than AC so unless your switch is huge and 100years old then check its rating  Many 230Vac switches are only rated for 28 Vdc


text:
Q: What does [something] in front of a method in c# does/used for? [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] myfunc(string a)
    {
          // do stuff
    }

What does the stuff inside the [] do or used for?

A: This is an attribute. Generally speaking,

Attributes provide a powerful method of associating declarative
  information with C# code (types, methods, properties, and so forth).
  Once associated with a program entity, the attribute can be queried at
  run time and used in any number of ways.

For further information on this, please have a look here.


text:
Q: Header Height Not Expanding to the Size of Child Elements My header element has no height. I have a navigation bar, like so:

nav {
  display: block;
}
.main_nav_bar {
  width: 100%;
  position: fixed;
  top: 0px;
  z-index: 3;
}
.drop-down-menu {
  float: right;
}
.drop-down-button {
  padding: 15px;
  font-size: 40px;
}
.drop-down-content {
  width: 100vw;
}
.drop-down-content a {
   text-align: center;
   font-size: 200%;
}
<!DOCTYPE html>

    Extra Unimportant Stuff

     Important

          <button class = "drop-down-button">  </button>

             Homepage
            ⋮ Some other similar anchor tags.

      ⋮
      Extra Unimportant Stuff

Of course, the snippet doesn't work, since it is an outline. When I check the elements with the .main_nav_bar and class the .drop_down_menu class (as seen in the respective images), I see that they both have a height:
Main Navigation Bar has Defined Height
Drop Down Menu Has Defined Height
But the header has no height? As seen in the image:
Header Has no Defined Height
Why is this the case? Why doesn't header change it's height to fit the child element? I tried overflow: auto but that didn't work.

A: When an element has a position value other than static (default), it is out of the normal flow of the layout. Meaning it's behavior and the behavior of it's ancestors, descendants, and siblings are very different. See this article on position and of course MDN
Make your  fixed not the
header {
  position: fixed;
  top: 0;
  z-index: 3;
  outline: 5px dashed red;
}

Remove position, top, and z-index from

header {
  position: fixed;
  top: 0;
  outline: 5px dashed red;
}

nav {
  display: block;
}

.main_nav_bar {
  width: 100%;
}

.drop-down-menu {
  float: right;
}

.drop-down-button {
  padding: 15px;
  font-size: 40px;
}

.drop-down-content {
  width: 100vw;
}

.drop-down-content a {
  text-align: center;
  font-size: 200%;
}
<!DOCTYPE html>

  Extra Unimportant Stuff

   Important

        <button class="drop-down-button">  </button>

           Homepage  ⋮ Some other similar anchor tags.

    ⋮ Extra Unimportant Stuff


text:
Q: Combining terms in a conditionally convergent series I am aware that one is unable to rearrange terms in a conditionally convergent series. But, take a conditionally convergent series, say
$$\sum_{n=1}^{\infty} \frac{(-1)^{n-1}}{n}$$
and group terms with a stride of two to produce
$$\sum_{n=1}^{\infty} \frac{1}{2n-1} - \frac{1}{2n}.$$
With this particular series, even if I take the absolute value of the terms, it converges to the same value. Does this imply the reformatted series is absolutely convergent, and that I can validly rearrange its terms arbitrarily?

A: Yes, the new series you have created is absolutely convergent, and rearranging its terms will not change its value. Note however, that the set of terms of the new series,
$$
b_n = \frac{1}{2n-1} - \frac{1}{2n} = \frac{1}{2n(2n-1)},
$$
is not the same as the set of terms of the old series, so this is not a rearrangement of the old series in the strict sense.


text:
Q: Arabic-English Transliteration using unsupported font I am working on language transliteration for Ar and En text.
Here is the link which displays character by character replacement : https://github.com/Shnoulle/Ar-PHP/blob/master/Arabic/data/Transliteration.xml
Now issue is:
I am dealing with font style robert_bold.ttf and robert_regular_0.ttf which has some typical characters with underline and overline as in this snap

I have .ttf file so I can see this fonts on my system. But in my application or in above Transliteration.xml characters are considered as junk like [, } [ etc.
How can I add support of this unsupported characters in Transliteration.xml file?
<pair>
  <search>ي</search>
  <replace>y</replace>
</pair>
<pair>
  <search>ى</search>
  <replace>a</replace>
</pair>
<pair>
  <search>أ</search>
  <replace>^</replace> // Here is one of the character s_ (s with underscore not supported)
</pair>

A: It seems that the font is not Unicode encoded but contains the underlined letters at some arbitrarily assigned codes. While this works up to a point, it does not work across applications, of course. It works only when that specific font is used.
The proper way is to use correct Unicode characters such as U+1E0F LATIN SMALL LETTER D WITH LINE BELOW "ḏ" and, for rendering, try to find fonts containing it.
An alternative is to use just basic Latin letters with some markup, say <u>d</u>. This means that the text must not be treated as plain text in later processing, and in rendering, the markup should be interpreted as requesting for a line under the letter(s).


text:
Q: Finding the area of this figure inside a circle? Let's say I have a unit circle and I draw a triangular sector with an angle $\pi/2$. Next to it, I draw a sector with an angle $\pi/8$, next $\pi/18$, so that the $n^{\text{th}}$ sector has an angle of $\pi/(2n^2)$. Now I am only looking at the area of the triangle inside each sector. What is the area of the triangles if I were to draw infinitely many of them, as shown in the figure below?
I was only able to find an approximation for this. I got $f(1)/2 + \int_1^\infty f(x)dx$, where $f(x)=(1/2)\sin(\pi/(2x^2)) \approx 1.95$. How would you find the exact area of this?

A: As you seem to know, the area of an isosceles triangle with common side length 1 and angle between them $\theta$ is $\sin(\theta)/2$.  Thus, your area is
$$\sum _{i=1}^{\infty } \frac{1}{2} \sin \left(\frac{\pi }{2 i^2}\right),$$
which is just a bit bigger than 1.  I don't see any easy reason to think that this is expressible in closed form; Mathematica, at least, can't seem to do so.

A: The union of the sectors should be a sector of angle
$$\sum_{n=1}^\infty\frac{\pi}{2n^2}=\frac{\pi}{2}\sum_{n=1}^\infty\frac{1}{n^2}=\frac{\pi}{2}\cdot\frac{\pi^2}{6}=\frac{\pi^3}{12}$$
and the area of a sector of angle $\theta$ in a circle of radius $r$ is $\frac{\theta}{2\pi}\cdot\pi r^2$, so the area of the union of the sectors is
$$\frac{\pi^3/12}{2\pi}\cdot\pi=\frac{\pi^3}{24}$$

A: Area of a sector with angle $\theta$ is $\frac{\theta}{2}$ (Can you see this?).
Now, in your case, the area is given by
$ A = \sum_{x=1}^{x=\infty}\frac{\pi}{4x^{2}} = \frac{\pi}{4}\sum_{x=1}^{\infty}\frac{1}{x^{2}}$
Do you know the value of the last sum? It is $\frac{\pi^{2}}{6}$.

A: The resulting shape is a sector of the circle.  It would be helpful to find the central angle of this sector.  This angle is equal to the following sum:
$$\theta=\frac{\pi}{2}+\frac{\pi}{8}+\frac{\pi}{18}+\ldots=\frac{\pi}{2}\left(\frac{1}{1}+\frac{1}{4}+\frac{1}{9}+\ldots\right)$$
Now here is a rather astonishing fact: the term inside the parentheses is equal to $\pi^2/6$.  This means we'd like to find the area of the sector of a unit circle ($r=1$) with central angle $\theta=\pi^3/12$.  The area is then given by:
$$A=\frac{1}{2}\cdot r\cdot\theta=\frac{1}{2}\cdot 1\cdot\frac{\pi^3}{12}=\frac{\pi^3}{24}$$


text:
Q: C# database compare one Date/Time field from a table with today To make the story short I have a table inside of which I have a column of type Date/Time. I used MS Acces 2013 to create the database. Now, I need at a certain point in my app to check and delete all the records that are having their date smaller than today. Let's say that conn is my connection to my database. I wrote:
conn.Open();
string delRec = "DELETE FROM myTable WHERE myDateTimeColumn < '" + DateTime.Now + "'";
ExecQuery(delRec);
conn.Close();

If I replace the string with, let's say:
string delRec = "DELETE FROM myTable WHERE anIntColumn < 21";

everything is running just fine. What am I doing wrong? Many thanks.

A: You could use the built in Now() function:
string delRec = "DELETE FROM myTable WHERE myDateTimeColumn < Now()";

A: ACCESS is not recognizing as a date passed in WHERE clause.
conn.Open();
string delRec = "DELETE FROM myTable WHERE myDateTimeColumn < '#" + DateTime.Now + "#'";
ExecQuery(delRec);
conn.Close();

There may be one more point to check that are you passing same date format in where clause parameter. e.g 'YYYY/MM/DD'
Can you try this one. Hope this will help

A: Have you tried DateTime.Now.Day method
i.e.
conn.Open();
string delRec = "DELETE FROM myTable WHERE myDateTimeColumn < '" + DateTime.Now.Day + "'";
ExecQuery(delRec);
conn.Close();
Hope it will help you.


text:
Q: Recommended error reporting for ember.js What is the ember.js community recommendation for reporting Ember app crashes?  I'm looking for the equivalent of the exception_notifier gem in Rails so that I can be notified if users are experiencing errors.
This Stack Overflow post recommends generic javascript error handling solutions including:

*

*Handle window.onerror yourself

*Use a hosted service that handles window.onerror for you like Airbrake.io or Muscula
I'm hoping there is some kind of Mixin that gives you all this error handling code, and provides richer error messages (such as the current route when the error occurred, etc).  Does this exist yet?  If not, what are people doing to solve this problem?

A: Any error reporting like the Rails gem is going to depend on some sort of server backend to handle the error, such as emailing admins, etc. It makes sense that Rails would have a whole gem dedicated to this sort of thing, since Rails is going to have the whole stack trace, session, and all sorts of other variables that are convenient(/necessary) to have for debugging the issue, but for front-end apps (e.g. Ember), all the error information is on the client side, so all the backend logic would do is expose an API that your Ember app can talk to which would forward whatever information you send to it from the app and send it to your email, or whatever you want to do with it.
To do this in Ember, you can specify the Ember.onerror function:
Ember.onerror = function(error) {
  caught = error;
  Em.$.ajax('/report-error', 'POST', {
     stack: error.stack,
     otherInformation: 'whatever app state you want to provide'
  });
};

This receives the JavaScript Error object that was thrown, which may or may not have the non-standard stack property that contains the stack trace which you could send to the server among any other App-specific state you'd want to send, though you'd probably want to keep it simple so that you don't cause other errors and end up in a crazy error loop from hell.


text:
Q: How to add and sort items in QComboBox I want to (in this analogical example) change QLabel's color by QPushButton click or select it from QComboBox representing the selection history. In real code there are more controls than one button, so there is a method setColor(self, color) that adds new color to the QComboBox as its first item, removes possible duplicates and changes the QLabel's color. This works.
The second option is to choose the color from the history QComboBox. I catch event when an item is pressed and call the same setColor(self, color). This cause a problem.
Problem is when there are colors in QComboBox e.g. ['red', 'blue', 'green'] I choose option 'blue' and the order of items is changed to ['blue', 'red', 'green'] (I still want this), there is some standard QComboBox behavior which finishes selection and the QComboBox selects 'green' item. So, QLabel has correct color, but QComboBox does not have the correct text.
How can I overwrite the "standard behavior" and fix this? Please try this example:
import sys
from random import random

from PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QVBoxLayout, QPushButton, QLabel

class MyCombo(QComboBox):
    def __init__(self, parent):
        super().__init__(parent)
        self.view().pressed.connect(self.handleItemPressed)

    def handleItemPressed(self, index):
        color = self.model().itemData(index)[0]
        self.parent().setColor(color)

    def removeDuplicates(self):
        unique = list()
        while len(unique) < self.model().rowCount():
            if self.itemText(len(unique)) in unique:
                self.removeItem(len(unique))
            else:
                unique.append(self.itemText(len(unique)))

class Gui(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.resize(300, 200)
        lay = QVBoxLayout()
        self.cmb = MyCombo(self)
        self.btn = QPushButton('Random', self)
        self.btn.clicked.connect(self.btnClicked)
        self.pnl = QLabel(self)
        lay.addWidget(self.cmb)
        lay.addWidget(self.btn)
        lay.addWidget(self.pnl)
        self.setLayout(lay)

    def setColor(self, color):
        self.cmb.insertItem(0, color)
        self.cmb.setCurrentIndex(0)
        self.cmb.removeDuplicates()
        self.pnl.setStyleSheet('background-color: %s' % color)

    def btnClicked(self):
        colors = ['red', 'green', 'blue', 'yellow', 'orange']
        self.setColor(colors[int(random() * len(colors))])

if __name__ == '__main__':
    app = QApplication(sys.argv)
    g = Gui()
    g.show()
    sys.exit(app.exec_())

A: With a logic similar to the other answer but focusing on the functionality of inserting and removing duplicates, the QComboBox has to do it and only send the information to the window when the item is selected. Also, instead of passing the name, the QColor can be passed as an additional data.
import sys
import random

from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import (
    QApplication,
    QWidget,
    QComboBox,
    QVBoxLayout,
    QPushButton,
    QLabel,
)

class ColorComboBox(QComboBox):
    colorChanged = pyqtSignal(str, QColor)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.currentIndexChanged.connect(self.handleCurrentIndexChanged)

    def handleCurrentIndexChanged(self, index):
        key = self.itemText(index)
        color = self.itemData(index)
        self.colorChanged.emit(key, color)

    def addColor(self, key, color):
        index = self.findText(key)
        if index != -1:
            self.removeItem(index)
        self.insertItem(0, key, color)
        self.setCurrentIndex(0)

class Gui(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.resize(300, 200)

        self.cmb = ColorComboBox()
        self.btn = QPushButton("Random")
        self.pnl = QLabel()

        lay = QVBoxLayout(self)
        lay.addWidget(self.cmb)
        lay.addWidget(self.btn)
        lay.addWidget(self.pnl)

        self.btn.clicked.connect(self.btnClicked)
        self.cmb.colorChanged.connect(self.updateColor)

    def btnClicked(self):
        colors = [
            ("red", QColor("red")),
            ("green", QColor("green")),
            ("blue", QColor("blue")),
            ("yellow", QColor("yellow")),
            ("orange", QColor("orange")),
        ]

        key, color = random.choice(colors)
        self.cmb.addColor(key, color)

    def updateColor(self, key, color):
        self.pnl.setStyleSheet('background-color: %s' % color.name())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    g = Gui()
    g.show()
    sys.exit(app.exec_())

A: Rearranging items during operations that include setting the current index is never a good thing, unless you're sure about keeping track of the correct index and know the sequence of operations that happen in between.
In your case, the problem is that the pressed signal of the view is handled before the current index of the combo box is changed, and the result is that when the mouse button is released the current index is wrong also due to the reordering of items.
Your implementation also has another problem: keyboard and mouse wheel navigation will not correctly update the color.
My suggestion is to leave the model unchanged (unless a new color is added), and reorder it only right before showing the popup.
In order to avoid recursion, always remember that you can block the signals of an object by using blockSignals().
class MyCombo(QComboBox):
    colorChanged = pyqtSignal(str)
    def __init__(self, parent):
        super().__init__(parent)
        self.currentIndexChanged.connect(self.emitChangedColor)

    def emitChangedColor(self, index):
        if index >= 0:
            self.colorChanged.emit(self.itemText(index))

    def setColor(self, color):
        blocked = self.blockSignals(True)
        for index in range(self.count()):
            if self.itemText(index) == color:
                break
        else:
            index = 0
            self.insertItem(index, color)
        self.setCurrentIndex(index)
        self.blockSignals(blocked)

    def showPopup(self):
        if self.currentIndex() > 0:
            blocked = self.blockSignals(True)
            current = self.currentText()
            self.removeItem(self.currentIndex())
            self.insertItem(0, current)
            self.setCurrentIndex(0)
            self.blockSignals(blocked)
        super().showPopup()

class Gui(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.resize(300, 200)
        lay = QVBoxLayout()
        self.cmb = MyCombo(self)
        self.cmb.colorChanged.connect(self.setColor)
        self.btn = QPushButton('Random', self)
        self.btn.clicked.connect(self.btnClicked)
        self.pnl = QLabel(self)
        lay.addWidget(self.cmb)
        lay.addWidget(self.btn)
        lay.addWidget(self.pnl)
        self.setLayout(lay)

    def setColor(self, color):
        self.cmb.setColor(color)
        self.pnl.setStyleSheet('background-color: %s' % color)

    def btnClicked(self):
        colors = ['red', 'green', 'blue', 'yellow', 'orange']
        self.setColor(colors[int(random() * len(colors))])


text:
Q: how to fix this error "increase LSAPI_CHILDREN" I use the python flask and received this error too much in my stderr.log in cpanel hosting server :
[UID:1015][630244] Reached max children process limit: 6, extra: 2, current: 8, busy: 8, please increase LSAPI_CHILDREN.

I called to my hosting server and they increase my PHP_LSAPI_CHILDREN to 100.
But I still received this error and my website get error 503 too much and i think this is because of that error i said.
what is your suggestion ؟

A: If you've increased the PHP_LSAPI_CHILDREN limit and you're still hitting it there are two primary causes:

*

*Your site is getting so much traffic that the limit needs to be raised further, but before raising the limit further your systems administrator (or hosting provider) would need to determine if the server has enough resources available to sustain the higher limit. If you check your access logs and you're not seeing an excessive number of requests for the site, then you are most likely experiencing the second potential cause below. A variation of this could also be that the site is experiencing an excessive number of requests due to a DoS attack of some sort, in which case you would need to address the DoS rather than increase the limit.

*Your site has a coding issue that is causing requests to take an excessive amount of time to complete. Because the requests are taking so long to complete they start to stack up and then exhaust the PHP_LSAPI_CHILDREN limit. One classic root cause is for a website script to make a request to an external server that is blocked by a firewall which causes the PHP/Python/etc process to hang while it waits for the connection to time out. Another common issue is an excessively long wait for a database query to complete. cPanel has a guide for enabling the MySQL Slow log if you suspect it could be a database query:

https://support.cpanel.net/hc/en-us/articles/360052538914-How-to-Enable-the-Slow-Query-Log-in-MySQL-or-MariaDB


text:
Q: Can I check variables in a constructor body that were set in the initialization list? I have doubts on how the constructor's body works in case of initialization lists. If the value passed by the constructor are not admitted value and an exception needs to be thrown, is it correct to do something like this?
Foo(int a_) : a(a_) {
  if (a>0)
    throw std::invalid_argument("positive value!");
};

I am having doubt on how this is evaluated, in case of more complex situations.

A: According to cppreference, it is absolutely safe to assume the initializer list will be completed before the 'body' of the constructor is executed (bolding of item 4 is mine):

The order of member initializers in the list is irrelevant: the actual
  order of initialization is as follows

*

*1 If the constructor is for the most-derived class, virtual base classes are initialized in the order in which they appear in
  depth-first left-to-right traversal of the base class declarations
  (left-to-right refers to the appearance in base-specifier lists)

*2 Then, direct base classes are initialized in left-to-right order as they appear in this class's base-specifier list

*3 Then, non-static data members are initialized in order of declaration in the class definition.

*4 Finally, the body of the constructor is executed

Now, although cppreference isn't the actual standard, it's normally accurate on such matters.
EDIT: The draft C++14 (§ 12.6.2) standard (pp. 283-284 of that PDF) confirms what cppreference states. (Yes, I know the OP specified C++11 - but I couldn't get a link to that standard online, and I very much doubt that the standard in that matter has changed between 11, 14 and 17!)


text:
Q: How to show equinumerosity of  the powerset of $A$ and the set of functions from $A$ to $\{0,1\}$ without cardinal arithmetic? How to show equinumerosity of  the powerset of $A$ and the set of functions from $A$ to $\{0,1\}$ without cardinal arithmetic?
Not homework, practice exercise.

A: Arturo Magidin has given an answer in symbols. In words it might be something like:
For any subset $S$ of $A$ (i.e. element of the powerset) there is a unique function which sends each element of $S$ to $1$ and everything else in $A$ to $0$; conversely, for any function $f$ from $A$ to $\{ 0,1 \}$ there is a unique subset of $A$ which contains all the elements of $A$ sent to $1$ and none of those sent to $0$.

A: For each subset $S$, define the characteristic function $\chi_S\colon A\to\{0,1\}$ by
$$\chi_S(a) = \left\{\begin{array}{ll}
1&\text{if }a\in S,\\
0&\text{if }a\notin S.
\end{array}\right.$$
The map $S\mapsto \chi_S$ is one-to-one: if $S\neq T$, then there exists $x\in S\triangle T$; hence $\chi_S(a)\neq \chi_T(a)$.
The map is onto: given $f\colon A\to\{0,1\}$, let $S=\{a\in A\mid f(a)=1\}$. Then $\chi_S = f$.
This gives the desired bijection.


text:
Q: Issue with file format with saveWorkbook (r package openxslx) I save an Excel workbook with the following code without any error
  DbSTATS <- loadWorkbook("D:/Documents/Db STATS.xlsx")
  saveWorkbook(DbSTATS,"D:/Documents/Db STATS.xlsx", overwrite = TRUE)

When I try to link this Excel file in Power Bi, I get the error : "We were unable to identify the entry as a valid Excel document."
It works when I open the Excel and save it. Comparing with the version saved by saveWorkbook, the file size is bigger and I have the information "no" in the properties: broken links and scale.
Do you have any idea what the problem is?
Thanks


text:
Q: I am a newbie to docker. How can we find which .net framework is installed in a docker image? I have copied .NET framework from my local directory and build an image by using the below Dockerfile
FROM mcr.microsoft.com/dotnet/framework/sdk:4.8-windowsservercore-ltsc2019

ADD setup C:\setup

RUN cmd.exe /c start /wait C:\setup\NDP471DevPack.exe /q

RUN powershell -Command rm C:\setup -r -Force

WORKDIR C:\\Project
ENTRYPOINT ["C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\msbuild.exe"]

Now I want verify that the .NET framework is whether installed or not in the image that was build?

A: You can run dotnet --version to see if there's a .NET runtime installed and which version it is. Something like this
docker run --rm --entrypoint=dotnet <image name> --version

A: You should be able to use:
reg query "HKLM\SOFTWARE\Microsoft\Net Framework Setup\NDP" /s

In Visual Studio I can select my container and click "Open Terminal Window" and paste the above command.


text:
Q: How to convert ColorDrawable into Bitmap? I need to convert solid color Drawable to Bitmap, because I need to use Bitmap in library. How to do that?
This is my ColorDrawable:
val blackColorDrawable = ColorDrawable(ContextCompat.getColor(this, R.color.colorPrimaryDark))

A: This is how I convert colorDrawable to bitmap
try {
      val bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888)

      val canvas = Canvas(bitmap)
      blackColorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight())
      blackColorDrawable.draw(canvas)
      return bitmap
} catch (e: Exception) {
      e.printStackTrace()
      return null
}


text:
Q: Check if string equals (at least the first 2 letters) and containing a number I've a list with some Strings, want to compare the strings and save the matching strings in a new list.
Matching means, that:

*

*the first 2 characters have to be letters

*the letters (at least the first 2 letters) have to be equal

*and it have to appear a number after the equal letters

List<String> items = new List<string>()
    {
        "ne1234",
        "ne2abc",
        "type",
        "12345"
        "12346"
        "s0",
        "s1",
        "numb4er",
        "numb5er",
        "numb8er",
        "tax1-0",
        "tax1-1"
    };

List<String> equalitems = new List<string>();

Content of equalitems

*

*ne*

*numb*

*tax*

I can't find a good approach to solve this. Has somebody an idea?

A: var rx = new Regex(@"^\p{L}{2,}(?=\d)");
var grouped = items.GroupBy(x => rx.Match(x).ToString())
                   .Where(x => x.Key != String.Empty)
                   .ToArray();

This will use a regular expression to "extract" the initial letters (and check if there is a digit after the letters) and then group by this key. In the end it "filters out" the groups that have an empty key (so a key that doesn't follow the rules you put out)
Note that as written it's a collection of collections (each "matching group" is in a separate collection)
If you want all the matching items together:
var allTogether = items.GroupBy(x => rx.Match(x).ToString())
                       .Where(x => x.Key != String.Empty)
                       .SelectMany(x => x)
                       .ToArray();

Note that as written for "letter" I used "Unicode" letters (so even àéèìòù and non-english letters, like arabic), and for digits I used "Unicode" digits.
if you want "standard" letters and digits:
var rx = new Regex(@"^[A-Za-z]{2,}(?=[0-9])");

As written, single elements that don't match anything else (xxxxxx9) are put in a group and returned. Add
.Where(x => x.Count() > 1)

after the
.Where(x => x.Key != String.Empty)

to filter out these items.

A: Another technique is to use a custom comparer that implements IEqualityComparer<string>.
The comparer looks like this:
public class MyComparer : IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return GetHashCode(x) == GetHashCode(y);
    }

    public string GetStringForHash(string x)
    {
        StringBuilder hashString = new StringBuilder();

        if (x.Length > 2 && x.Substring(0, 2).All(v => char.IsLetter(v)))
        {
            for (var i = 0; i < x.Length; i++)
            {
                if (char.IsLetter(x[i]))
                {
                    hashString.Append(x[i]);
                }
                else if (char.IsDigit(x[i]))
                {
                    return hashString.ToString();
                }
                else
                {
                    break;
                }
            }
        }

        return x;
    }

    public int GetHashCode(string x)
    {
        return GetStringForHash(x).GetHashCode();
    }
}

And the implementation looks like this
List<String> items = new List<string>()
    {
    "ne1234",
    "ne2abc",
    "type",
    "12345",
    "12346",
    "s0",
    "s1",
    "numb4er",
    "numb5er",
    "numb8er",
    "tax1-0",
    "tax1-1"
};

var comparer = new MyComparer();
var results = items.GroupBy(v => comparer.GetStringForHash(v), comparer).Where(v => v.Count() > 1);

List<String> equalitems = results.SelectMany(v => v).ToList();

Since @xanatos made the perfect regex, here is an alternate version of GetStringForHash that uses that regex
public string GetStringForHash(string x)
{
    var rx = new Regex(@"^\p{L}{2,}(?=\d)");

    var match = rx.Match(x);

    return match.Success ? match.ToString() : x;
}

A: I have quite an interesting idea :)
First create character sets:
    private static char[] chars = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    private static char[] nums = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };

Then create an extension method to strimg characters starting from a numeric character (We will use it later):
public static class Extensions
{
    public static string RemoveAfterNumber(this string str)
    {
        int ix = str.IndexOfAny("0123456789".ToCharArray());
        if (ix >= 0)
        {
            return str.Substring(0, ix);
        }
        else
        {
            return null;
        }
    }
}

Then follow this code :
// Filter string which have non-numeric characters for the the first two letters (Condition 1)
List<String> pass1 = items.Where(x => x.Length > 2 && x.Substring(0, 2).ToCharArray().Intersect(chars).Count() == 2).ToList();

// Get distinct two non-numeric character startings
List<string> pass2 = pass1.GroupBy(x => x.Substring(0, 2)).Where(c => c.Count() > 1).Select(s => s.Key).ToList();

// Get all records starting with these letters
List<string> pass3a = items.Where(x => pass2.Contains(x.Substring(0, 2))).Select(x => x).ToList();

// Remove characters after the first occurance of a numeric character from all records having at least one  numeric character and satisfying the Condition 1. This is also where e use the Extension method.
List<string> pass3b = pass3a.Where(x => x.RemoveAfterNumber() != null).Select(x => x.RemoveAfterNumber()).ToList();

// Group by the repetitions and format as you require
List<string> result = pass3b.Select(x => x + "*").Distinct().ToList();

I don't claim this is either the best solution, or the most logical one. But it was quite fun to code it :)


text:
Q: How to launch a subprocess in a new terminal? Hello I am a beginner & sorry for my bad English.
My question is how to launch a sub process in a new terminal?
For the moment I have launched a process Loop.py in a new terminal with a subprocess function:
Lo = subprocess.Popen(['gnome-terminal', '-x', 'python3', '/address/Loop.py'])
but it's not quit the same thing, I don't have access to the script Loop.py from the main script.
Thank you.
Update:
the main script is Main.py:
import subprocess, signal, os, time

Li = subprocess.Popen(['gnome-terminal'])
Lo = subprocess.Popen(['python3', '/address/Loop.py'])
time.sleep(0.1)
Qd = subprocess.Popen(['python3', '/adress/Qdial.py'])

if Qd.wait() != None:
    Lo.send_signal(signal.SIGINT)
    Li.send_signal(signal.SIGKILL)

The Qdial.pyis describe here:
Qdial
The Loop.py is :
import time, signal

def handler(signum, frame):
    print('Exit!')
    exit()

signal.signal(signal.SIGINT, handler)

def loop():
    with open('/addres/Data.py', 'r') as file:
        lines = file.readlines()
        A1 = lines[0]
        A1 = float(A1[4:-1])
    print('A1 = ', A1)

while True:
    loop()
    time.sleep(.1)

and the Data.py is a bunch of data, here I use just one:
A1 = 10


text:
Q: Error with splitbib and natbib : Undefined control sequence I am using {natbib} package for the bibliography style and {splitbib} package for separate my bibiography into categories at the end of my documents, for example :
 all articles in one group, all the books in an other group.
The author of {splitbib} advised to use the [export] argument when usign {natbib} package.
Everything is working, I have my final document as I wanted but the problem is that I get an error message from LaTeX : "Undefined control sequence \begin{thebibliography}"
If I don't use {natbib} package, I don't have any error.
If I use {natbib} package without [export] argument it is worth.
If I use {natbib} package with [export] argument it works but with an error message.
How can I solve this ?
Thank you
Here is an example :
\documentclass[a4paper,12pt]{book}

\usepackage[comma,longnamesfirst]{natbib}
\bibliographystyle{plainnat}
\usepackage[export]{splitbib}

\begin{category}{Articles}
\SBentries{Article1,Article2}
\end{category}
\begin{category}{Books}
\SBentries{Book1,Book2}
\end{category}

\usepackage{filecontents}

\begin{filecontents}{bibliography.bib}

@article{Article1,
author={Jhon Doe},
title={Blabla},
journal={Blabla},
year={2019},
volume={145},
number={4},
pages={1-25}
}
@book{Book2,
author={Fabrice Doe},
title={Blabla4},
journal={Blabla4},
year={2016},
volume={142},
pages={4-22}
}
\end{filecontents}

\begin{document}

I want to cite Article1~\cite{Article1} and then Book2~\cite{Book2}.

\bibliography{bibliography}

\end{document}

A: The undefined command is not \begin{bibliography} but \SBlongestlabel:
! Undefined control sequence.
\thebibliography ...\expandafter {\SBlongestlabel
                                                  } \immediate \write \NMSB@...
l.1 \begin{thebibliography}{2}

It is clearly a bug in the package, but it is not completly clear what the author intended.
The following patch could work:
\documentclass[a4paper,12pt]{book}

\usepackage[comma,longnamesfirst]{natbib}
\bibliographystyle{plainnat}
\usepackage[export]{splitbib}

\begin{category}{Articles}
\SBentries{Article1,Article2}
\end{category}
\begin{category}{Books}
\SBentries{Book1,Book2}
\end{category}

\usepackage{filecontents}

\begin{filecontents}{bibliography.bib}

@article{Article1,
author={Jhon Doe},
title={Blabla},
journal={Blabla},
year={2019},
volume={145},
number={4},
pages={1-25}
}
@book{Book2,
author={Fabrice Doe},
title={Blabla4},
journal={Blabla4},
year={2016},
volume={142},
pages={4-22}
}
\end{filecontents}
\makeatletter
\usepackage{xpatch}
\xpatchcmd\thebibliography
 {\expandafter\NMSB@tok\expandafter{\SBlongestlabel}}
 {\@ifundefined{SBlongestlabel}{\NMSB@tok{}}{\expandafter\NMSB@tok\expandafter{\SBlongestlabel}}}
 {}{\fail}
\makeatother
\begin{document}

I want to cite Article1~\cite{Article1} and then Book2~\cite{Book2}.

\bibliography{bibliography}

\end{document}


text:
Q: Variable is set as string but undefined as object property What is the explanation for this apparent contradiction?
When using isset the variable $city = ''; returns 'true'.
However I have to use an if statement in the following code to avoid the undefined error:
class Holiday {

public $city = '';

public function __construct() {
        if (isset($city)) {
        $this->city = $city;
        }
        }

public function get_city() {
        return $this->city;
}

public function set_city($city) {
        return $this->city = $city;
}
}

$germany = new Holiday;

$germany->set_city('Berlin');

function travel($a) {
echo "Visit " . $a->get_city();
}

I have searched for an explanation between 'is set' and undefined but can't find one. I would really appreciate any insights.

A: You don't have a $city variable in the constructor, that's why you are  getting that error.

A: It's a "variable scope" issue.
Inside __construct, local variable $city is not set.
You have to pass it through arguments:
 public function __construct( $city )

Or to declare it as global, depending by your goals:
 public function __construct()
 {
     global $city;

But I think that you are in search of first solution.

*

*Read more about Variable scope


text:
Q: Animation in framgent won't restart after rotation I have an animation which starts correctly the first time the fragment is displayed. However after an orientation change, it won't restart. The animation is an animation-list resource set as the background of an ImageView.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final View root = inflater.inflate(R.layout.fragment_lead_manual,
            container, false);
    final ImageView badgeEntryView = (ImageView) root
            .findViewById(R.id.manual_image);
    mAnimation = (AnimationDrawable) badgeEntryView.getBackground();
    return root;
}

@Override
public void onResume() {
    super.onResume();
    mAnimation.start();
}

@Override
public void onPause() {
    super.onPause();
    mAnimation.stop();
}

EDIT: I forgot to add that the animation is inside a tab, which makes things more difficult. However, I've figured out the problem and will add the answer below.

A: There are two cases that need to be solved, based on when the tab is created:

*

*FIRST the tab is created, and SECOND its Activity is attached to the Window

*FIRST the Activity is attached to the Window, and SECOND the tab is created

Case one occurs if the tab is the first one displayed or during rotation. Case two occurs when the user switches to that tab because it's not the first. Let's handle each case separately:
Case 1: a) Create tab b) Attach to window
Calling AnimationDrawable.start() before it is attached to the window (i.e. inside onCreate() or onResume()) breaks the animation. As stated in the Android docs :

It's important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged() method in your Activity, which will get called when Android brings your window into focus.

It's more difficult with Fragments, but basically the same. We override the method in the Activity and then call over to the Fragment:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        final FragmentManager fm = getFragmentManager();
        ManualLeadFragment manualFragment = (ManualLeadFragment) fm
                .findFragmentByTag(TAG_MANUAL);
        if (manualFragment != null) {
            manualFragment.startAnimation();
        }
    }
}

And then in the Fragment, implement startAnimation():
void startAnimation() {
    mAnimation.start();
}

Case 2: a) Attach to window b) Create tab
In this case, the call to onWindowFocusChanged() has already occurred and so the animation won't start. So we still need to start it during onResume(), but slightly differently:
@Override
public void onResume() {
    super.onResume();
    if (isVisible()) {
        startAnimation();
    }
}

This calls into the same startAnimation() method as in Case 1, but because the Fragment is already attached to the Window, it can be called during onResume().
Summary
AnimationDrawable.start() can only be called when the Fragment is visible. Sometimes it is visible during onResume(), and the animation can be started at that point. Other times it is not yet visible at that time, and then the overridden onWindowFocusChanged() method is called when when it becomes visible, and the animation is started then.


text:
Q: Setting up Ansible community.libvirt.virt Has anyone successfully made community.libvirt.virt module work with Ansible? I cannot find a complete guide with all the necessary steps. I am running Ubuntu 18 on an AWS EC2.
I have been trying to get this working all day and am not having success. I've tried using both python2 and python3. I've tried installing via pip and via apt. I've tried installing various packages based on google searches (such as build-essential, libvirt-dev, libvirt-python, etc.).
This is my current error:
{"changed": false, "msg": "The `libvirt` module is not importable. Check the requirements."}

A: Had the same problem. Vanished when I switched to python3. There was a long forgotten line:
ansible_python_interpreter: /usr/bin/python2

in my inventory.yml


text:
Q: MacBook unable to visit websites while connected to Wifi A month ago I made a wrong manipulation in the Network settings of my computer and since then I cannot browse any websites nor use the Mail app when I connect to my office's WiFi or at the local café. There, I need to connect to my phone's 4G in order to browse and check my emails normally, which obviously consumes a lot of data. Another way to be able connect there is to use a VPN. But without the VPN activated, I'm unable to connect.
When I am at home, it connects normally. So there is somewhere some incompatibility with other networks. Is it a DNS or proxy problem ? How can I solve this ?
Please help !

A: This seems to happen when software update of the Mac or update of the iPhone is necessary. Then it happens at other times.  So, I started synching my iPhone with the Mac through Music.  The problem stopped.  May be it is a way to remind us to synch the phone with the Mac air. The answers of bad charger wire, dirty charging point, etc. are probably valid, but not the final answer.


text:
Q: Can we implement AWS-Appsync ina project without using GraphQL? Can I implement AWS-Appsync without the use of GraphQl, Project's front end is based on Angular and by using Socket i'm getting the backend data stored in Database. I wanted to implement AWS-Appsync without any usage of GraphQL

A: Can you tell me more about your use case? AppSync is a graphql managed service so you can't use it without graphql. What are you trying to accomplish with AppSync?


text:
Q: Bibliography is not aligned I am using overleaf to write up my thesis. The work is almost done, yet I have a problem with my bibliography:

As you can see, the 25th entry just pops to the left without any reason. Through rearrangement, I noticed that this would follow with any entry below 25 in this page. I tried different citations for the same work; the entry would simply disappear and an empty entry would appear for the first reference.
I have generated these entries using Mendeley. I leave a copy of this entry below. Any help is much appreciated.
 @book{Murphy2012,
address = {Cambridge, Massachusetts},
author = {Murphy, Kevin},
isbn = {9780262018029},
publisher = {The MIT Press},
title = {{Machine Learning: A Probabilistic Perspective}},
year = {2012}
}


text:
Q: awk to remove lines starting with symbol without keyword in them I am trying to selectively remove lines that start with # but do not contain the keywords Build or Type in them. The lines that do not start with # are unchanged. I can remove all lines that starting with # using the first awk, but not sure how to selectively remove lines that start with # but do not contain a keyword. The second awk does execute but only leaves two lines (#CN Filters:
                                   #  Flags = 1,2,3). Thank you :).
awk
awk '!/#/' input < out  # will remove all lines with #

awk
awk '/#/ && !/Build|Length/' input < out  # remove lines starting with # but must not have Build or Length in them

input various spacing
#Build = NCBI Build 37
#CN Filters:
#  Flags = 1,2,3
#  Type = Lowess
Length  Event   ID
1   Gain    xxx
10  Loss    yyy

desired output
Build = NCBI Build 37
Type = Lowess
Length  Event   ID
1   Gain    xxx
10  Loss    yyy

A: You want to do something with lines that start with # and do not contain Build or Type, right? I'm sure you could write that condition:

*

*Start with # = /^#/

*AND = &&

*Do not contains Build or Type = !/Build|Type/
i.e.
/^#/ && !/Build|Type/

Now, what is it you wanted to do when that condition s true? Not print the current line. So you could just write that as simply:
awk '/^#/ && !/Build|Type/{next} 1'

but if you prefer to use awks default print given a true condition then you just need to negate your condition (a{next} 1 = !a):
awk '!(/^#/ && !/Build|Type/)'

which by boolean algebra ( !(a && b) = !a || !b) can be reduced to:
awk '!/^#/ || /Build|Type/'

A: $ awk '!/^#/ || /Build|Type/' file
#Build = NCBI Build 37
#  Type = Lowess
Length  Event   ID
1   Gain    xxx
10  Loss    yyy

If you want to remove those initial # characters and the spaces after them:
$ awk '!/^#/ || /Build|Type/ { sub("^#[[:blank:]]*", ""); print }' file
Build = NCBI Build 37
Type = Lowess
Length  Event   ID
1   Gain    xxx
10  Loss    yyy

A: Following awk may help you on same too.
awk '!(/^#/ && !/Build/ && !/Type/){gsub(/^#|^# +/,"");print}'  Input_file

Explanation:
awk '
!(/^#/ && !/Build/ && !/Type/){  ##Checking condition here if a line starts with # and NOT having string Build and Type in it, Negating this condition to work it as opposite, if this condition is TRUE then do following.
  gsub(/^#|^# +/,"");            ##Using gsub to remove hash in starting of a line OR remove a hash starting fr a line with space with NULL in current line.
  print                          ##Printing the current line here.
}' Input_file                    ##Mentioning the Input_file name here.

A: A sed solution:
$ sed 's/^# *\(.*\(Build\|Type\).*\)/\1/;/^#/d'  file
Build = NCBI Build 37
Type = Lowess
Length  Event   ID
1   Gain    xxx
10  Loss    yyy

A: awk '!/CN|Fl/{sub(/\43/,"")sub(/^\s*/,"");print}' file

Build = NCBI Build 37
Type = Lowess
Length  Event   ID
1   Gain    xxx
10  Loss    yyy


text:
Q: FluentAssertions: Assert that a collection contains any item that contains a string (case insensitive) I have a collection of strings
var greetings = new[] { "Hello boy", "Hello girl", "Hello all"};

I would like to create an assertion using FluentAssertions that verifies that the collection contains at least one item that contains a given string.
Example. For the previous collection,

*

*testing with "boy", should pass.

*testing with "Girl" should pass.

*testing with "hello" should pass.

*testing with "ouch" should NOT pass (because there is not item in the collection that contains this string).

I've tried with:
greetings.Should().ContainMatch("*" + str + "*");

But it doesn't work becuase it's case sensitive.


text:
Q: Error in generating ultimate-seed with yeoman I'm attempting to create my first Yeoman webapp using the ultimate-seed-generator. However I get the following errors:
C:\Users\Fidel\Desktop\Nueva carpeta\new-proyect>npm install

> ultimate-seed@0.3.12 preinstall C:\Users\Fidel\Desktop\Nueva carpeta\new-proyect
> node npm-scripts preinstall

npm preinstall script executed
\

> ultimate-seed@0.3.12 postinstall C:\Users\Fidel\Desktop\Nueva carpeta\new-proyect
> node npm-scripts postinstall

npm postinstall script executed
{ [Error: Command failed: cp: invalid option -- n
Try `cp --help' for more information.
] killed: false, code: 1, signal: null }
-
npm ERR! ultimate-seed@0.3.12 postinstall: `node npm-scripts postinstall`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ultimate-seed@0.3.12 postinstall script.
npm ERR! This is most likely a problem with the ultimate-seed package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node npm-scripts postinstall
npm ERR! You can get their info via:
npm ERR!     npm owner ls ultimate-seed
npm ERR! There is likely additional logging output above.
npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! cwd C:\Users\Fidel\Desktop\Nueva carpeta\new-proyect
npm ERR! node -v v0.10.29
npm ERR! npm -v 1.4.14
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Users\Fidel\Desktop\Nueva carpeta\new-proyect\npm-debug.log
npm ERR! not ok code 0

I am pretty sure that node js and yeoman were installed ok. I think it can be a problem with Window and yeoman. Anyone know anything about it?

A: The problem is that the post-install script uses the unix cp command to copy files. Being that you're on Windows, that is not going to work
You can run the npm install under cygwin or some other unix-type shell on windows.
However, That package has been deleted from npm -- you should try to find one that is up-to-date and use that one instead.


text:
Q: How to fix garbled characters in PHPMyAdmin My MySQL database contains some Chinese symbols and such (non-ASCII symbols). When I view them in PHPMyAdmin, they look garbled. However, if I display them on my website with PHP using the regular mysqli API, it looks fine so I assume the data is uploaded/stored properly in the database, so maybe the server connection collation is incorrect.
My PHP code for opening the database connection is:
function openConnection(): mysqli
{
    $databaseHost = "localhost";
    $databaseUser = "root";
    $databasePassword = '';
    $databaseName = "my-database-name";

    $connection = new mysqli($databaseHost, $databaseUser,
        $databasePassword, $databaseName);

    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }

    return $connection;
}

My PHPMyAdmin server connection collation is the default utf8mb4_unicode_ci which seems to be reasonable as well. My tables are also created with the default utf8mb4_general_ci. Shouldn't that work fine for any input users might make?
Calling $connection->get_charset() in PHP also returns the correct charset:

If I export the database data in MyPHPAdmin, the export is also garbled in Notepad++, I made sure to view it with UTF-8 encoding. If I import the garbled export again, the database will show the data as garbled once more and on the website the data now also shows as garbled. In this case, an actually corrupted export happened.
How can I solve this encoding problem? Clearly PHP can handle UTF-8 properly, my Apache web server is also serving UTF-8 and my database is configured seemingly correctly as well but there is an issue with PHPMyAdmin or the database/database table collation.

A: It looks like the issue was entirely elsewhere since I'm supplying data to PHP with C++ code. The C++ code uses the nlohmann JSON libary to build the data submitted to the PHP script. The issue was my inability to specifically encode std::strings to UTF-8 like described here when putting data into a C++ JSON object. With that said, everything is now working as expected.

A: ⚈  If using mysqli, do $mysqli_obj->set_charset('utf8mb4');
⚈  If using PDO do somethin like $db = new PDO('dblib:host=host;dbname=db;charset=utf8mb4', $user, $pwd);
⚈  Alternatively, execute SET NAMES utf8mb4

Any of these will say that the bytes in the client are UTF-8 encoded. Conversion, if necessary, will occur between the client and the database if the column definition is something other than utf8mb4.
More notes on PHP:  http://mysql.rjweb.org/doc.php/charcoll#php
If you have specific garbling, see Trouble with UTF-8 characters; what I see is not what I stored
If you suspect the data being fed from PHP to Notepad, dump a few Chinese characters in hex and shown to us.  I would expect every 4th character to be hex F0 or every 3rd to be between E3 and EA.  (These are the first byte for 4-char and 3-char UTF-8 encoding of Chinese characters.)
Does Notepad properly handle UTF-8, or does it need a setting?
If you are in the "cmd" in Windows, you may need chcp 65001; see http://mysql.rjweb.org/doc.php/charcoll#entering_accents_in_cmd  That way, more non-English characters will display correctly.


text:
Q: C# Unmanaged exports when multiple projects involved (Robert Giesecke) I have this situation where I need to create an unmanaged DLL in .Net that can be invoked from a delphi program. I've been doing some research and I found Robert Giesecke's library (RGiesecke.DllExport). I started with a pretty simple DLL that displays a windows form with a textbox, something like this:
[ComVisible(true)]
[DllExport("PlaceOrder", CallingConvention = CallingConvention.StdCall)]
public static IntPtr PlaceOrder(IntPtr lnpInXml)
{
    string inputXml = Marshal.PtrToStringAnsi(lnpInXml);
    StringBuilder sbOutputXml = new StringBuilder();

    Form1 pti = new Form1(inputXml, sbOutputXml);
    pti.ShowDialog();

    return Marshal.StringToHGlobalAnsi(sbOutputXml.ToString());
}

This works fine, I setup the delphi program to invoke my dll and it works just fine. The problem comes when I add a reference to another project in my solution and create an instance of an object inside that project. At that point, the delphi program stops displaying the form like it couldn't find the exported function but it doesn't throw any errors either:
using MyCommonCode;

namespace UnmanagedDLLTest
{
    [ComVisible(true)]
    public static class UnmanagedDLL
    {
        [ComVisible(true)]
        [DllExport("PlaceOrder", CallingConvention = CallingConvention.StdCall)]
        public static IntPtr PlaceOrder(IntPtr lnpInXml)
        {
            string inputXml = Marshal.PtrToStringAnsi(lnpInXml);
            StringBuilder sbOutputXml = new StringBuilder();

            Form1 pti = new Form1(inputXml, sbOutputXml);
            pti.ShowDialog();

            MyCommonCode.MyClass mc = new MyCommonCode.MyClass();

            return Marshal.StringToHGlobalAnsi(sbOutputXml.ToString());
        }
    }
}

This line:
MyCommonCode.MyClass mc = new MyCommonCode.MyClass();
is the source of my problem, as soon as I comment it everything works again. I've been looking for examples like this on google for a while, but everything I find is similar to my first piece of code. Any ideas would be really appreciated at this point, I'm starting to think it isn't possible :(.
Regards.

A: I have that same problem. In my case, I trying to call a C# DLL from a Visual FoxPro application. As long as a method makes a call to an external DLL, the FoxPro application returns an error/exception.
I recommend that you follow this guide from another StackOverflow question. Basically:

*

*Create the a COM visible C# dll

*Register the DLL on the deploy machine using regasm