text:
Q: What's the best way to reuse code for performance while keeping a good Object Oriented design? I am developing a scientific program where there are several time consuming
functions that are called from different other functions. I want to optimize
these calls by avoid calling the same function with the same parameters more than
once without breaking OO concepts such as encapsulation.
I tried to formulate a basic example of what I have. Class A has an object of
class B from where I calculate intermediate results needed by class A functions.
For example, in order for the functionA and functionB to calculate its results,
each function needs to call the  time_consuming_function on the object from B.
Usually this functions are called from within a loop so the parameters (1 and 2)
are the same among calls to functionA and functionB.
class ClassA {
  ClassB obj // member object

  return_type functionA(parameter1, parameter2) {
    value1 = obj.time_consuming_function(parameter1)
    value2 = obj.time_consuming_function(parameter2)

    return some_operation_with(value1, value2)
  }

  return_type functionB(parameter1, parameter2) {
    value1 = obj.time_consuming_function(parameter1)
    value2 = obj.time_consuming_function(parameter2)

    return some_operation_with(value1, value2)
  }
}

One solution would be create a structure to hold the calculated values among
calls to ClassA functions, such as this example:
class ClassA {
  ClassB obj // member object

  return_type functionA(data) { // data is a structure to hold the values
    if (data.is_empty()) {
      data.value1 = obj.time_consuming_function(parameter1)
      data.value2 = obj.time_consuming_function(parameter2)
    }

    return some_operation_with(data.value1, data.value2)
  }

  return_type functionB(data) { // same data obj as before

    // this time data is not empty, so no calculation needed
    if (data.is_empty()) {
      data.value1 = obj.time_consuming_function(parameter1)
      data.value2 = obj.time_consuming_function(parameter2)
    }

    return some_operation_with(data.value1, data.value2)
  }
}

Another solution would be create a class Data to hold the data beforehand.
In this case, having the parameters 1 and 2, I would update all properties that
change with this parameter on class Data and when executing my functions from
class A I would only need to use the values calculated previously. The class
A would provide an interface to the Data class.
class Data {
  ClassA class_a_obj

  void update_values_that_depend_on_parameter1(class_a_obj, parameter1) {
    value1 = class_a_obj.time_consuming_function(parameter1)
  }

  void update_values_that_depend_on_parameter2(parameter2) {
    value2 = class_a_obj.time_consuming_function(parameter2)
  }
}

class ClassA {
  ClassB obj // member object

  return_type functionA(data) {
    return some_operation_with(data.value1, data.value2)
  }

  return_type functionB(data) { // same data obj as before

    return some_operation_with(data.value1, data.value2)
  }

  return_type time_consuming_function(parameter) {
    return obj.time_consuming_function(parameter)
  }
}

I wanted to know what you think of this problem and the proposed solutions.
Are there other suitable and efficient solutions?
TL;DR:
I have a program that makes several calculations and each of this calculations
calls functions to get intermediate values. These values are the same when
called from functions that receive the same parameters, I am looking for a way
to optimize these calls reusing those intermediate values.
What is the best way to reuse those values while still keeping a good Object
Oriented design??

A: Encapsulate the acces to these methods/ objects via a proxy that caches recent results and returns the cached result.


text: Q: I dual booted Ubuntu with Windows 10 and now my Ubuntu is running very weird and making a lot of sounds I recently Dual Booted Ubuntu with Windows 10 and now my Ubuntu machine is running slower than I expected and its really weird, sometimes out of nowhere it just makes tons of noise like overheating and getting no airflow, and I have no idea why. I do actually think it could be because an application I installed called "Hollywood" and I installed it and then unexpected crashes started to happen and pop up on my screen and now I need some help to make my PC run normal again like it should be doing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exporting Rally grid information to CSV I am trying to export rally grid data to csv. Here's my code:
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
items:[{ xtype: 'container', itemId: 'print_button_box', padding: 5},{xtype: 'container', itemId: 'grid_box'}],
count: 0,
globalStore: null,
launch: function() {
    this.globalStore = null;
    this.count = 0;
    this._addPrintButton();
     list = [];
    //Write app code here
    this._get_stories_of_feature();
},
_addPrintButton: function() {
    var me = this;
    this.down('#print_button_box').add( {
        xtype: 'rallybutton',
        itemId: 'print_button',
        text: 'CSV',
        disabled: false,
        handler: function() {
           console.log('globalStore ',me.globalStore);

            me._onClickExport();
        }
    });
},
_onClickExport: function () { //using this function to export to csv

     if (document.getElementById('grid_box')) {

        //Ext.getBody().mask('Exporting Tasks...');
        console.log('inside export');
        setTimeout(function () {
            var template = '' +
                '
{table}' +
                '
';

            var base64 = function (s) {
                return window.btoa(unescape(encodeURIComponent(s)));
            };
            var format = function (s, c) {
                return s.replace(/{(\w+)}/g, function (m, p) {
                    return c[p];
                });
            };
            var table = document.getElementById('grid_box');
            console.log("Exporting table ",table);
            var excel_data = '
';
            Ext.Array.each(table.innerHTML.match(/.*?<\/span>/gm), function (column_header_span) {
                excel_data += (column_header_span.replace(/span/g, 'td'));
            });
            excel_data += '
';
            Ext.Array.each(table.innerHTML.match(/<tr class="x-grid-row.*?<\/tr>/gm), function (line) {
                excel_data += line.replace(/[^\011\012\015\040-\177]/g, '>>');
            });
            console.log("Excel data ",excel_data);
            var ctx = {worksheet: name || 'Worksheet', table: excel_data};
            window.location.href = 'data:application/vnd.ms-excel;base64,' + base64(format(template, ctx));
            Ext.getBody().unmask();
        }, 500);
    }else{
        console.log("grid_box does not exist");
    }
},
_createStore: function(){
    var me = this;
    //var f = [{property: 'UserStories', operator: '!=', value: null}];
    Ext.create('Rally.data.WsapiDataStore',{
        autoLoad: true,
        model: "PortfolioItem/Feature",
        limit: 5000,
        fetch: ['FormattedID','Name','UserStories','c_DIteration','c_DPSI'],

        listeners:{
            load: function(store,data,success){

                console.log("Store ",store);
                var data_length = data.length;
                console.log('Data length is '+data.length);
                Ext.Array.each(data,function(item){
                    if(item.get('UserStories')==null){
                        store.remove(item);
                    }else{
                        var data = {
                            id: item.get("FormattedID"),
                            name: item.get("Name"),
                            UserStories: item.get("UserStories")._type,
                            DIteration: item.get("c_DIteration"),
                            DPSI: item.get("c_DPSI")
                        };
                        //list.push(data);
                    }

                    me._get_stories_of_feature(item.get("ObjectID"),item.get("Name"),data_length);
                });

            },
            scope: this
        }
    });
},
_showGrid: function(store){
    var me = this;
    if(!this.grid){
        this.grid = Ext.create('Rally.ui.grid.Grid',{
            store: store,
            columnCfgs:[
                {text: 'Feature_ID', dataIndex: 'ide'},
                {text: 'Feature Name', dataIndex: 'name'},
                {text: 'Feature DIteration', dataInfex: 'fDIteration'},
                {text: 'Story Name', dataIndex: 'UserStories'},
                {text: 'Story ID', dataIndex: 'FormattedID'},

                {text: 'Story DIteration', dataIndex: 'DIteration'},
                {text: 'Story DPSI', dataIndex: 'DPSI'},
                {text: 'Unscheduled', dataIndex: 'Unscheduled'}
            ]
        });
        me.globalStore = this.grid;
        this.down('#grid_box').add(this.grid);
    }
},
_get_stories_of_feature: function(){
    var me = this;
    Ext.create('Rally.data.WsapiDataStore',{
        autoLoad: true,
        model: "hierarchicalrequirement",
        limit: 5000,
        fetch: ['Name','ObjectID','FormattedID','Feature','c_DIteration','c_DPSI','DragAndDropRank'],
        sorters:[{
            property: 'DragAndDropRank', direction: 'ASC'
        }],
        filters:{
            property: 'Feature', operator: '!=', value:null
        },
        listeners:{
            load: function(store,data,success){
                var data_length = data.length;

                if(data_length>0){
                    console.log("Total stories ",data_length);
                    for(var i=0;i<data_length;i++){

                            var flag;
                            if(data[i].data.Feature.c_DIteration==null || data[i].data.Feature.c_DIteration.toString().indexOf("*")!=-1)
                                 flag = "YES";
                            else flag = "NO";

                            var element = {
                                ide: data[i].data.Feature.FormattedID,
                                name: data[i].data.Feature.Name,
                                fDIteration: data[i].data.Feature.c_DIteration,
                                UserStories: data[i].data.Name,
                                FormattedID: data[i].data.FormattedID,
                                DIteration: data[i].data.c_DIteration,
                                DPSI: data[i].data.c_DPSI,
                                Unscheduled: flag
                            };
                            list.push(element);

                            console.log("me count is ",me.count);
                            console.log("Found ",data[i].data);
                            me.count++;
                    }
                }

                if(me.count==data_length){
                    console.log("Building store");
                    //once all the stories and feature data is computed
                    var myStore = Ext.create("Rally.data.custom.Store",{
                    data: list,
                    pageSize: 100
                });
                me._showGrid(myStore);
                }

            }

        }
    });
},
 exportGrid: function(grid) {
    if (Ext.isIE) {
        this._ieToExcel(grid);

    } else {
        var data = this._getCSV(grid);
        var a = document.createElement('a');
        a.href     = 'data:attachment/csv,' + data;
        a.target   ='_blank';
        a.download = 'myFile.csv,' + encodeURIComponent(data); ;
        a.innerHTML = "Click me to download the file.";
        window.location = a;
    }
},

_escapeForCSV: function(string) {
    if (string.match(/,/)) {
        if (!string.match(/"/)) {
            string = '"' + string + '"';
        } else {
            string = string.replace(/,/g, ''); // comma's and quotes-- sorry, just loose the commas
        }
    }
    return string;
},

_getFieldText: function(fieldData) {
    var text;

    if (fieldData == null || fieldData == undefined) {
        text = '';

    } else if (fieldData._refObjectName && !fieldData.getMonth) {
        text = fieldData._refObjectName;

    } else if (fieldData instanceof Date) {
        text = Ext.Date.format(fieldData, this.dateFormat);

    } else if (!fieldData.match) { // not a string or object we recognize...bank it out
        text = '';

    } else {
        text = fieldData;
    }

    return text;
},

_getFieldTextAndEscape: function(fieldData) {
    var string  = this._getFieldText(fieldData);

    return this._escapeForCSV(string);
},

_getCSV: function (grid) {
    var cols    = grid.columns;
    var store   = grid.store;
    var data    = '';

    var that = this;
    Ext.Array.each(cols, function(col, index) {
        if (col.hidden != true) {
            data += that._getFieldTextAndEscape(col.text) + ',';
        }
    });
    data += "\n";

    store.each(function(record) {
        var entry       = record.getData();
        Ext.Array.each(cols, function(col, index) {
            if (col.hidden != true) {
                var fieldName   = col.dataIndex;
                var text        = entry[fieldName];

                data += that._getFieldTextAndEscape(text) + ',';
            }
        });
        data += "\n";
    });

    return data;
},

_ieGetGridData : function(grid, sheet) {
    var that            = this;
    var resourceItems   = grid.store.data.items;
    var cols            = grid.columns;

    Ext.Array.each(cols, function(col, colIndex) {
        if (col.hidden != true) {
            console.log('header: ', col.text);
            sheet.cells(1,colIndex + 1).value = col.text;
        }
    });

    var rowIndex = 2;
    grid.store.each(function(record) {
        var entry   = record.getData();

        Ext.Array.each(cols, function(col, colIndex) {
            if (col.hidden != true) {
                var fieldName   = col.dataIndex;
                var text        = entry[fieldName];
                var value       = that._getFieldText(text);

                sheet.cells(rowIndex, colIndex+1).value = value;
            }
        });
        rowIndex++;
    });
},

_ieToExcel: function (grid) {
    if (window.ActiveXObject){
        var  xlApp, xlBook;
        try {
            xlApp = new ActiveXObject("Excel.Application");
            xlBook = xlApp.Workbooks.Add();
        } catch (e) {
            Ext.Msg.alert('Error', 'For the export to work in IE, you have to enable a security setting called "Initialize and script ActiveX control not marked as safe" from Internet Options -> Security -> Custom level..."');
            return;
        }

        xlBook.worksheets("Sheet1").activate;
        var XlSheet = xlBook.activeSheet;
        xlApp.visible = true;

       this._ieGetGridData(grid, XlSheet);
       XlSheet.columns.autofit;
    }
}

});
I am using the "_onClickExport" function that I read about here to export my grid data to CSV but when I execute that function, it can't find ElementId "grid_box", although I have defined it.

A: I was able to export with your code after making these changes:
line 31, change to
if (this.down('#grid_box')){

line 52, change to
var table = that.getComponent('grid_box');

where that is defined on the top of _onClickExport
var that = this;

line 57, and a similar line below it, replace table.innerHTML.match with table.getEl().dom.outerHTML.match
Ext.Array.each(table.getEl().dom.outerHTML.match


text:
Q: Terminal won't accept username when setting up git for mac I have git installed but the following code:

git config --global imadahmad97 "Imad Ahmad"

returns with:
error: key does not contain a section: imadahmad97

I do have a github account and have checked my username multiple times.

A: In your code you are trying to set a variable called imadahmad97 to the value Imad Ahmad. There is no such variable in git config.
imadahmad97 seems to be your GitHub account name. Git and GitHub are not the same thing. GitHub is to Git what Gmail is to email. Git signs commits using your user.name and user.email. You set them like this:
git config --global user.name "FIRST_NAME LAST_NAME"
git config --global user.email "MY_NAME@example.com"

But this is not how you authenticate yourself from the terminal when pushing to a repo hosted on GitHub. Google "authenticate github in git cli" if that is what you are trying to do.


text:
Q: dataprovider testing values from database How to pass a values that reads from mysql db to @DataProvider?
In my case i have to pass values that read from db to test method through @DataProvider

A: The dataprovider is meant to pass values from your data source to your tests.  You can put the code of reading from your db and creating Objects in your method annotated with @DataProvider and specify this DataProvider in your test method.
Something to the effect
@DataProvider(name = "dbreaddata")
public Object[][] readDBData() {

//read from db -
//create object[][]
// return Object[][];
}

@Test(dataProvider = "dbreaddata")
public void useAndTestData(Object a) {
 //Use data read from db
}

Read more @ http://testng.org/doc/documentation-main.html#parameters-dataproviders


text:
Q: How do I populate a listview based on 2 boolean table columns? I have a database table containing scripts for plays/dramas. The scripts can be categorized under 'Theatre and Education', 'Plays for Young People' or both (by using bools to determine whether they belong to said categories);

*

*scriptID: int

*theatreAndEducation:bit

*playsForYoungPeople: bit

*scriptTitle: varchar

*scriptSample:text

*thumbImageUrl: varchar

In the main menu I have a drop down list which contains the following links;

*

*a runat="server" href="~/WebForm/scriptList">theatre & education

*a runat="server" href="~/WebForms/scriptList">plays 4 young people

When the user clicks one of these links, they are taken to a page which contains a listview. I would like this listview to be populated with the records that correspond to the link that was clicked.
I'm guessing that a querystring is needed but I can't think an appropriate one that can be used.
Below is the listview in its current state. Any ideas on a query string and how the sql datasource should be configured to display the appropriate script records based on the link which is clicked?
<asp:ListView ID="scriptsListView" runat="server" DataSourceID="SqlDataSource1">
    <LayoutTemplate>

                title
                summary
                image

                <asp:PlaceHolder ID="itemPlaceholder" runat="server">
                </asp:PlaceHolder>

    </LayoutTemplate>

    <ItemTemplate>

            <%# Eval ("scriptTitle") %>
            <%# Eval ("scriptSample") %>
            <asp:Image ID="image" runat="server"
                     ImageUrl='<%# "~/Images/Scripts/" + Eval("thumbImageUrl") %>' />

    </ItemTemplate>
</asp:ListView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    SelectCommand="">
    <SelectParameters>
    </SelectParameters>
</asp:SqlDataSource>

A: set the select statement for the sqldatasource on page_load
a runat="server" href="~/WebForm/scriptList?type=theatre">theatre & education
a runat="server" href="~/WebForms/scriptList?type=plays">plays 4 young people
protected void Page_Load(object sender, EventArgs e)
if (Page.IsPostBack == false)
{
  string s;
if (Request.QueryString["type"]=="theatre")
    {
      s="select * from scripts where theatreAndEducation = 1";
    }
else
    if (Request.QueryString["type"]=="plays")
    {
      s = "select * scripts where playsForYoungPeople = 1";
    }
    SqlDataSource1.SelectCommand = s;

}
}

A: You could pass a query string parameter that differentiates between the two views.
Also, in the code behind, on the SqlDataSource's Select event , you can swap out the select command.


text:
Q: How to make SysRq working on laptop? My /proc/sys/kernel/sysrq contains the number 502, but Alt+SysRq+... seems not to work on my HP Pavilion laptop. How can I fix that?
Update 1: By the way: neither my print-screen-key nor any other key has an additional label like "SysRq".
Update 2:

*

*Hardware model: HP Pavilion 17 Notebook PC

*Keyboard layout: German, QWERTZ

A: Most laptops require pressing Fn to get the SysRq key. Pressing Fn usually doesn't affect the Alt key (at least the left one) but may affect the letter that you press after SysRq. Fortunately, you don't need to press SysRq and the third key together, it's enough to hold Alt down. The following sequence works on all the laptops I've seen:

*

*Press and hold Alt.

*Press Fn, press the SysRq key, and release both.

*Briefly the letter or punctuation key, e.g. S to sync.

*Release Alt.

The SysRq key is usually the same key as PrintScreen. If your keyboard doesn't have a key labeled SysRq or PrintScreen, it may not have a key that sends the scan code that Linux expects. For the purpose of magic SysRq, the SysRq key is whichever key sends the scan code 99.
With a PS/2 keyboard (including a laptop's internal keyboard), to find out what scan code a key sends, log into a text console (press Ctrl+Alt+F1 to switch to a text console, and usually Ctrl+Alt+F7 to go back to the GUI), and run the command showkey -s. showkey -s displays the scan code of each key as you type it. That's usually one byte (two hexadecimal digits) for a key press, then another byte for the key release. For a few keys, you'll get a byte sequence consisting of two bytes starting with e0. Press the key you're interested in, then wait 10 seconds and showkey will exit.
Now that you've identified a scan code, run setkeycodes … 99 as root to assign that scan code to key code 99. For example, if showkey -s prints 0xe0 0x6f 0xe0 0xef for the key you've chosen, run setkeycodes e06f 99.
To make this change permanent, either add the setkeycodes command to /etc/rc.local, or configure udev to change the keycode mappings. Configuring udev is the only solution for a USB keyboard, setkeycodes doesn't affect USB keyboards.

A: I've been using a newer HP pavilion Laptop, same issue.
What worked for me, was pressing the AltGr key with the printscreen key


text:
Q: xtext: How to disable textual input validation for generated xtext plugins (dsl) In Xtext there are few different kinds of validations which xtext takes care automatically. Is there any possibility to disable them?

*

*Lexer/Parser: Syntactical Validation

*Linker: Crosslink Validation

I am trying to disable the parser/lexer for being able to edit very huge files into a dsl editor. As far as I can see it is not possible to do from mwe2 workflow, as following fragment is the entry point for being able to open the editor.
fragment = parser.antlr.XtextAntlrUiGeneratorFragment auto-inject {}
I have mentioned that InternalMysDslLexer class is instantiated many times while I am typing something.
Should I override this class? what would be the correct approach?
Thank you.

A: To disable linking override ILinker in your Runtime module:
public Class<? extends ILinker> bindILinker() {
    return MyLinker.class;
}

And then override doLinkModel() to do noting (only for huge files I guess):
public class MyLinker extends LazyLinker {
    protected void doLinkModel(final EObject model, IDiagnosticConsumer consumer) {}
}

Not sure what you mean by saying you want to disable syntax validation. This would disable all the Xtext features. Isn't it better to simply edit huge files using a regular text editor instead of Xtext one?
There's also a lot of resources on Xtext performance on SO, Eclipse Xtext community forum,
and various blogs.


text: Q: ubuntu mate 16.04 mate tweak doesn't allow vertical workspace I enabled compiz in mate tweak, but it does not allow create vertical workspace. I can do it when I choose other windows manager, but I would like to use compiz. I wanto 6 workspaces with 2 vertical rows.


text:
Q: App crashes when presenting UIActivityController in iPad I have create a view in my app and once a button is clicked the UIActivityController should popup on screen. however, the app crashes only on iPad but on iPhone it is working fine. Anyone knows whats this behavior and how to fix it? this is the code im using:
@IBAction func send(_ sender: AnyObject)
{
    var image: UIImage!
    image = UIImage(named: "image.png")
    var urlfinal:NSURL!
    urlfinal =  URL.init(string:url as String)! as NSURL
    let items = [mytitle , image , urlfinal] as [Any]

    let controller = UIActivityViewController(activityItems: items, applicationActivities: .none)

    controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem

    self.present(controller, animated: true, completion: nil)
}

this is the error in the console im getting:

Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController () should have a non-nil sourceView or barButtonItem set before the presentation occurs.'

A: As the error suggests, you need to add a sourceView to your popoverPresentationController.
controller.popoverPresentationController?.sourceView = sender as! UIView


text:
Q: Media player with circular ProgressBar I wanna connect my media player to the progress bar Here is my code :
var media55 :MediaPlayer
var progressBar55 :ProgressBar

        progressBar55=findViewById(R.id.progressBar)
        media55 = MediaPlayer()
        media55.setDataSource("SONG URL HERE")
        media55.prepare()

I wanna when I start media player the progress bar progress with the media player

A: Define Handler in class scope.
private val handler = Handler()

Then set your ProgressBar max value to duration of the MediaPlayer data source.
progressBar55.max = media55.duration

Finally add a Runnable object to set progress on your ProgressBar every X milliseconds.
val interval: Long = 1000
val statusChecker = object : Runnable {
    override fun run() {
        progressBar.progress = media.currentPosition
        handler.postDelayed(this, interval)
    }
}

When you run your audio you should call statusChecker.run() to start updating porgress, and when you are done remove Handler callbacks by calling handler.removeCallbacksAndMessages(null)

A: I hope Its Hepls You

Using Handler

private lateinit var mHandler: Handler
private lateinit var mRunnable:Runnable

Just Create Function For This

fun startedSong()
{
mRunnable = Runnable {
                // Do something here
    if(media55.isPlaying)
    {
       progressBar55.progress=media55.currentPosition
    }
}
                // Schedule the task to repeat after 1 second
                mHandler.postDelayed(
                        mRunnable, // Runnable
                        1000 // Delay in milliseconds
                )
}

Call This Function In Your Code

    progressBar55=findViewById(R.id.progressBar)
    media55 = MediaPlayer()
    media55.setDataSource("SONG URL HERE")
    media55.prepare()
    progressBar55.max=media55.duration
    mHandler = Handler()
    startedSong()


text:
Q: How to use cached credentials in Samba/Winbind on Debian Buster? While using Debian and Windows in mixed environments for a huge amount of time now I am stuck on trying to use cached credentials for logging in within a domain environment. Once I used the credentials to login, I still want to login when the machine isn't connected to the domain controller anymore.
This behaviour is implemented by Windows clients, so that a laptop user can still login. Only mount points can't be used unless a connection is there. I want to achieve the same on my Debian/GNU Linux client.

Further explanation
The workstation is using Debian Buster with GUI (Xorg, XFCE, LightDM) and Samba (Winbind). It's a pretty much default installation.
:~$ uname -a
Linux client-ph-wkst 4.19.0-8-amd64 #1 SMP Debian 4.19.98-1 (2020-01-26) x86_64 GNU/Linux
:~$ sudo samba -V
Version 4.9.5-Debian

The workstation is sucessfully connected to a domain controller (Samba 4). Everything is working fine. I'm using this setup since Jessie and it's nice. All domain users can login on that machine, are having an auto-created home directory and so on. The only exception to that is the missing offline authentication.
According to the Samba Wiki (https://wiki.samba.org/index.php/PAM_Offline_Authentication) the smb.conf has been modified to contain winbind offline logon = yes.
While testing this it works as expected. When setting winbind to offline manually(sudo smbcontrol winbind offline), I can verify that PAM is using cached credentials. Even by unplugging the cable physically I can achieve the same.
Problem
But when I unplug the cable and reboot the system, I can't login. It hangs on LightDM logon screen. I can switch to console by pressing Ctrl+Alt+F1. I can logon with the system's root account, because this doesn't request the domain controller. When I look into the services with root I can see, that nmbd is not running. By examining it's logs with journalctl -xe I see, that it's not starting because of No local IPv4 non-loopback interfaces available.
The default network configuration tool in Debian's GUI installation is NetworkManager. With nmcli general I can see that I'm not connected.
Solution quick-and-dirty
Without plugging in the cable physically I manually activate the interface by entering nmcli connection up pewpewdefaultconnection. I restart samba and nmbd service. Voilà! It's working. I can enter my credentials, even restart lightdm service and enter everything with my cached credentials.
Solution nice and clean to be found
Since I don't want such an ugly solution as described before I am asking you to help me. Is there anyone who as accomplished this in a clean way? I would really appreciate any help.
I don't want to setup a script that makes the calls, that I described before, since they seem to be ugly. I'd like to prefer something in a configuration style if possible.
Note: I tried to use auto eth0 in network interfaces and make it being grabbed by NetworkManager's configuration file with managed=true. This doesn't show any improvement.

A: I reverted everything and only left winbind offline logon = yes in smb.conf. Some days later when the eth cable was unplugged I recognized it's working. Huh!?
On another client computer in the network I did the same configuration change in smb.conf and I can confirm it's working there, too.


text:
Q: jekyll on windows ,why can't work? I type jekyll serve
And:
E:\blog>jekyll serve
Configuration file: E:/blog/_config.yml
            Source: E:/blog
       Destination: E:/blog/_site
 Incremental build: disabled. Enable with --incremental
      Generating...
Error reading file C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/minima-1.0.1/_layouts/default.html: No such file or directory @ rb_sysopen - /Ruby23-x64/lib/ruby/gems/2.3.0/gems/minima-1.0.1/_layouts/default.html
Error reading file C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/minima-1.0.1/_layouts/page.html: No such file or directory @ rb_sysopen - /Ruby23-x64/lib/ruby/gems/2.3.0/gems/minima-1.0.1/_layouts/page.html
Error reading file C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/minima-1.0.1/_layouts/post.html: No such file or directory @ rb_sysopen - /Ruby23-x64/lib/ruby/gems/2.3.0/gems/minima-1.0.1/_layouts/post.html
                    done in 3.54 seconds.
  Please add the following to your Gemfile to avoid polling for changes:
    gem 'wdm', '>= 0.1.0' if Gem.win_platform?
 Auto-regeneration: enabled for 'E:/blog'
Configuration file: E:/blog/_config.yml
    Server address: http://127.0.0.1:4000/
  Server running... press ctrl-c to stop.

It requires minima so I installed the minima, but nothing seems to work.I visited server address but nothing.
Help please.

A: You don't mention your version, but Jekyll 3.2.0 is broken on Windows. Updating to 3.2.1 fixes some known issues. Update Jekyll with the following command:
$ gem update jekyll

From http://jekyllrb.com/news/2016/08/02/jekyll-3-2-1-released/

Well, 3.2.0 has been a success, but with one fatal flaw: it doesn't work on Windows! Sorry, Windows users. Hot on the trail of 3.2.0, this release should squash that :bug:. Sorry about that!
This release also fixes an issue when using gem-based themes where the theme was rejected if it existed behind a symlink. This is a common setup for the various ruby version managers, and for Ruby installed via Homebrew.

A: Please copy the _includes and _layouts folders under C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/minima-1.0.1/ to your repo E:/blog/ and try to rerun this cmd 'jekyll serve'.
Now, preview your local Jekyll site in your web browser at http://localhost:4000.
Good luck.

A: My portable Ruby/Jekyll kit:
Download ruby-2.3.1-i386-mingw32.7z
Some gems require DevKit. Download the 7z version.
Decompress both and add to your PATH. I've added the following (I use Cmder)
@set iii=%cli%\Ruby\bin
@set jjj=%cli%\RubyDevKit\bin\
@set kkk=%cli%\RubyDevKit\mingw\bin\
@set PATH=%PATH%%aaa%;%bbb%;%ccc%;%ddd%;%eee%;%fff%;%ggg%;%hhh%;%iii%;%jjj%;%kkk%;%lll%;

Test Jekyll with a known good website:
git clone https://github.com/plusjade/jekyll-bootstrap/ testsite
cd testsite
jekyll serve

If Jekyll works, the problem is with something else.


text:
Q: How the presence of a critical level is related to the existence of a critical point? I am trying to understand one of the most important concept in Calculs of Variations. I have often heard that the change of topology implies the existence of a critical point. In this context, critical (subcritical) levels have a fundamental role. I don't know something more.
Could anyone please explain me (also intuitively) how critical levels are related to critical points of a functional? What is a critical level of minimax type?
Some examples or references will be appreciated, too. Thank you in advance!


text:
Q: Installing Rasterio on Ubuntu fails with ImportError I have an AWS EC2 p2.xlarge instance running on Ubuntu 16.04.4 LTS that was created using the AWS Deep Learning AMI (DLAMI). I am using the keras/Tensor Flow conda environment:
$ source activate tensorflow_p36

I am attempting to install Rasterio and GDAL on top of the Keras - Tensor Flow AMI installations using these commands (source):
$ sudo add-apt-repository ppa:ubuntugis/ppa
$ sudo apt-get update
$ sudo apt-get install python-numpy gdal-bin libgdal-dev
$ pip install rasterio

The GDAL install seems to work:
$ gdalinfo --version
GDAL 2.1.3, released 2017/20/01

However, when I try to import rasterio in Python, it yields the following error:
(tensorflow_p36) ubuntu@ip-171-11-7-03:~$ python
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 18:10:19)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import rasterio
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36_test/lib/python3.6/site-packages/rasterio/__init__.py", line 15, in <module>
    from rasterio._base import (
ImportError: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name
>>>

How can I clear this error so that I can import and use rasterio in Python?

A: I had a similar issue trying to import rasterio with GDAL 2.x installed. You should try to install GDAL 1.11 instead.


text:
Q: C can I open a directory's files using open dir in an alphabetical order? In windows when you are opening files using open dir and dirent it will give you the files in an alphabetical order but in linux it does not is there any way to get the files sorted too in linux?

A: No, readdir() returns directory entries in an arbitrary order, generally the order that they exist in the filesystem. If you want them ordered by some criteria, sort them yourself.


text:
Q: Throw a game object via C# Unity Having a little trouble of getting a game object thrown. I had a 2d game where by the game object i want thrown is a grenade. At the moment, I have the following code:
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]

public class SoldierController : MonoBehaviour
{

    public GameObject grenadeObject;

     void Start()
        {
            grenadeObject.SetActive(false);
        }

    void Update()
    {
     if (Input.GetKeyDown(KeyCode.I))
                    {
                        grenadeObject.SetActive(true);
                        animator.SetBool("Grenade", true);
                        GrenadeThrow();
                        //speed = Mathf.Lerp(10, 0, Time.deltaTime);
                       // grenadeObject.transform.Translate(Vector3.forward * 10);
                        StartCoroutine(GrenadeCooldown());
                    }

     }

    void GrenadeThrow()
        {
            StartCoroutine(COPlayOneShot("Grenade"));
            Instantiate(grenadeObject, new Vector3(10 * 2.0F, 0, 0), Quaternion.identity);
        }

        IEnumerator GrenadeCooldown()
        {
            canFire = false;
            yield return new WaitForSeconds(0.01f);
            //rifleMuzzle.GetComponent<ParticleSystem>().top();
            canFire = true;
            animator.SetBool("Grenade",false);
        }
}

I would expect the object to at least be thrown out of the character hand except nothing happens at all. Any help/?

A: You need to have a component on the grenadeObject prefab, e.g. Grenade script. In there you would have a Vector3 for the direction it should go and a float for the speed. In that script's Start(), you would use the speed and direction to fire the grenade. The speed and direction are assigned by the class you provided in the question.
Here is an example Grenade class:
public class Grenade : Monobehaviour {

    public Vector3 direction;
    public float speed;

    void Start () {

        // initiate movement of the grenade

    }

}

Your class updated from the question:
public GameObject grenadeObject;

void Update() {

   if (Input.GetKeyDown(KeyCode.I)) {

       animator.SetBool("Grenade", true);
       GrenadeThrow();

    }

}

void GrenadeThrow() {

    StartCoroutine(COPlayOneShot("Grenade")); // unknown function
    Grenade grenade = Instantiate(grenadeObject, new Vector3(10 * 2.0F, 0, 0), Quaternion.identity).GetComponent<Grenade> ();
    grenade.direction = Vector3.one; // change this to the appropriate direction
    grenade.speed = 10f; // change this to the appropriate speed

}

IEnumerator GrenadeCooldown() {

    canFire = false;
    yield return new WaitForSeconds(0.01f);
    //rifleMuzzle.GetComponent<ParticleSystem>().top();
    canFire = true;
    animator.SetBool("Grenade",false);
}


text:
Q: How does AJAX handle multiples instances of a variable? I am currently editing a WordPress plugin, which allows you to filter posts by category, once a category is selected, the posts for that caregory are displayed as a checklist on the widget, the user can select the posts they wish to display in their sidebar/widget area of the theme.
I have taken the widget to the point that the user can select their post, the widget allows a single post to be selected, however if more than one is selected and the save button is pressed, the form returns only the last slected post.
After some searching, I have found the problem to be on the form return.
It is either to do with the update, or the way AJAX handles multiple instances of a variable.
the information posted to the server is as follows:
action  save-widget
add_new
id_base single_post_super_widget
multi_number
savewidgets 9bc3d79f1c
sidebar lcp-sb
widget-height   200
widget-id   single_post_super_widget-2
widget-single_post_super_widget[2][object_to_use]   5005
widget-single_post_super_widget[2][object_to_use]   4892
widget-single_post_super_widget[2][object_to_use]   4607
widget-single_post_super_widget[2][object_type] 72
widget-single_post_super_widget[2][paged]   1
widget-single_post_super_widget[2][tab] all
widget-single_post_super_widget[2][title_override]
widget-width    400
widget_number   2

Where object_to_use is the post(s) being selected.
the information being sent is defined here:
var theArgs = {
    action: jQuery('input.widget_class:hidden', widgetDiv).first().val() + '-get-metabox',
    widget: widgetDivId,
    number: widgetNumber,
    blog_id: jQuery(widgetInputBase + 'blog_id').val(),
    object_type: jQuery(widgetInputBase + 'object_type').val(),
    tab: currentTab,
    paged: currentPage,
    object_to_use: jQuery('input[type=checkbox][name$="[object_to_use]['+currentTab+']"]:checked', widgetDiv).first().val(),
    title_override: jQuery(widgetInputBase + 'title_override').val(),
    excerpt_override: jQuery(widgetInputBase + 'excerpt_override').val(),
    searched: ('search' == currentTab) ? jQuery('input.quick-search', widgetDiv).first().val() : ''
};

and the jQuery.post action:
jQuery.post(
    ajaxurl,
    theArgs,
    function( r ) {
        jQuery('.ajax-feedback').css('visibility', 'hidden');
        if ( r && r.length > 2 ) {
            jQuery('div.widget-content', widgetDiv).html(r);
        }
    }
);

In relation to the question, widget-single_post_super_widget[2][object_to_use] is being posted multiple times, how does AJAX handle this? Does each post/variable have to be unique?

A:
widget-single_post_super_widget[2][object_to_use] is being posted multiple times, how does AJAX handle this?

There is nothing Ajax specific about this. You just get multiple copies of the key in the data submitted to the server.

Does each post/variable have to be unique?

No.
In most server side environments, you can get all the data just by using the right function. For example with Perl's CGI.pm module, you just get the parameter in list context:
my @thing = $cgi->param('widget-single_post_super_widget[2][object_to_use]');

… and it will 'just work'.
PHP is special. If the name ends in [] then it will just create an array in $_POST and friends. If it doesn't, then it will discard all but the last item. (Unless I'm misremembering and it keeps the first instead).

A: You can use ajax using jQuery.. then you can pass multiple instances of variable :-
like this :-
 if(roleId !=''  && roleId != '16'){
                jQuery('#user_id_div').hide();
                jQuery('#loading_image').show().html("<label>   </label> <img src='<?php echo $this->webroot; ?>img/ajax-loader.gif' alt='Loading...'>");
                urlData = "<?php echo Router::url(array('controller' => 'users', 'action' => 'getmultipleVendors')) ?>" ;
                postData = "vendorType=" + roleId;

                jQuery.ajax({
                    url: urlData,
                    data: postData,
                    success: function(data) {
                        jQuery('#PromoCodeUserId').html(data);
                        jQuery('#user_id_div').show();
                        jQuery('#loading_image').hide();

                    }
                });

in postdata field you can post many data as avariables..


text:
Q: New to Python. Need info on the environment for it I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started.

A: Under Unix, Emacs is a good choice, to which I always come back, because it is convenient to have a single editor for everything, and because it's open source.
What is best for you depends on your past experience with IDEs.  I'd say: stick with what you've been using, or take this opportunity to try an even better IDE.
Note: Python comes with Idle, which is a very simple (if limited) IDE.

A: Be sure to check out IPython. It's an enhanced interactive python shell with a bunch of useful features such as Tab-Completion using introspection (eg, type "my_object." to see a list of its attributes and methods), logging your interactive session to an executable python-file, defining macros, etc. The documentation page has a link to the tutorial as well as screencasts showing it in action.

A: On my mac/Linux machines, python came pre-installed. On windows I use both jython under the eclipse IDE and ActivePython with their IDE/eclipse.   With eclipse you'll want PyDev.

A: It all depends on what you are looking for and what you are already using.
For instance, if you are using a more 'simple' editor at the moment: as long as it's got Python syntax you've got the basics.
If you are used to e.g. Eclipse you can just continue to use that, combined with Pydev. Besides syntax highlighting you'll also get more fancy features to help you debug and refactor your code.
Personally I use Emacs with python-mode (and a few other modes to interface with Subversion and Git). In the past I used Vim which also worked quite well.
My advice would be to start out with your current environment as long as it has some rudimentary support for Python. Once you are familiar with the language, start exploring what your environment is missing and either add it or if you cannot, switch to an enviroment which does support the feature.

A: I use gvim with some plugin in order to have better support for python.
If you like IDE, look at wing IDE wich is the best I have tested so far. Especially the debuger included is really helpful.

A: The Python Beginner's Guide and the official Python Tutorial both seem like good places to start.

A: Geany is a good option for a Linux setup, it's intellisense isn't that great but syntax highlighting is good and it can compile your code directly from inside the editor, plus it handles other languages such as C/C++, PHP, Java etc...  Eric is another popular choice as it's a full IDE and I know some people use Eclipse.
On windows I use Notepad++, but it's mostly because I like text editors instead of fully blown IDE's.
Reference wise Daniel's choices are very good places to start, also check out Green Tea Press who do free computer books, there are two Python choices on there but the "Python for Software Design" book hasn't yet been published properly although you can download the manuscript.  The "How to Think Like a Computer Scientist" book is a good one and not as scary as it sounds.

A: IDLE is nice to try out things. Other tools that people like are Eclipse with the Pydev plugin which seems to work ok, although it has crashed a few times (Eclipse, that is) and NetBeans (which I haven't tried) but some people seem to like.

A: I can only help you if you're running a Mac. Download Xcode. I believe that Python 2.3 comes bundled with these development tools. Luckily enough, this is all you really need to get started, unless you want a newer version of Python.
All you need to do is open up Terminal and type python. You're done!


text:
Q: How to assign a list of numbers into letter grades Here is my list:
collection = {76.6256, 51.9264, 50.238, 14.4203, 80.9205, 12.2036, 2.39568,
              38.2747, 12.4422, 29.9621}

collection /. {x_ /; x < 50 -> "F"}

and this gives me

{76.6256, 51.9264, 50.238, "F", 80.9205, "F", "F", "F", "F", "F"}

as expected. But I want to add more rules with ranges like that. I'm not sure how to do this. I've tried:
collection /. {{x_ /; x < 50 -> "F"}, {x_ /; 50 <= x < 56 -> "D"},
               {x_ /; 56 <= x < 71 -> "C"}, {x_ /; 71 <= x < 85 -> "B"},
               {x_ /; 85 <= x <= 100 -> "A"}}

and that yields

{{76.6256, 51.9264, 50.238, "F", 80.9205, "F", "F", "F", "F", "F"},
   {76.6256, "D", "D", 14.4203, 80.9205, 12.2036, 2.39568, 38.2747, 12.4422, 29.9621},
   {76.6256, 51.9264, 50.238, 14.4203, 80.9205, 12.2036, 2.39568, 38.2747,
         12.4422, 29.9621},
   {"B", 51.9264, 50.238, 14.4203, "B", 12.2036, 2.39568, 38.2747,
         12.4422, 29.9621},
   {76.6256, 51.9264, 50.238, 14.4203, 80.9205, 12.2036, 2.39568, 38.2747,
         12.4422, 29.9621}}`

and I've tried a few others which don't even work at all. What is the simplest way of going about this? My real question is, how do I construct a list of rules where I can determine which range (0-50, 50-60, etc.) each number in the list is in?

A: More handy in case of more notes (?).
notes = {"F", "D", "C", "B", "A"};
bl = BinLists[collection, {{0, 50, 56, 71, 85, 100}}];

collection /. Flatten@MapThread[Thread[# -> #2] &, {bl, notes}]

{"B", "D", "D", "F", "B", "F", "F", "F", "F", "F"}

or
notes = {"F", "D", "C", "B", "A"}
levels = {50, 56, 71, 85, 100}
Block[{x},
 Function[note[x_] := Which[##]] @@ Flatten[MapThread[{x <= #, #2} &,
                                                      {levels, notes}]]

     ]

note /@ collection

A: You can use Fold to successively apply a list of rules.
Fold[#1 /. #2 &, collection, {{x_ /; x < 50 -> "F"},
    {x_ /; 50 <= x < 56 -> "D"}, {x_ /; 56 <= x < 71 -> "C"},
    {x_ /; 71 <= x < 85 -> "B"}, {x_ /; 85 <= x <= 100 -> "A"}}]

{"B", "D", "D", "F", "B", "F", "F", "F", "F", "F"}

A: collection /.
 x_?NumberQ :> Which[x < 50, "F", x < 56, "D", x < 71, "C", x < 85, "B", x <= 100, "A"]

{"B", "D", "D", "F", "B", "F", "F", "F", "F", "F"}

Timing comparison for 1000 random reals repeated 1000 times

A: ClearAll[gradesF];
gradesF[x_: {49, 59, 79, 89, 100}, y_: {"A", "B", "C", "D", "F"}] :=
  Function[{z}, Piecewise[{#, z < #2} & @@@ (Flatten /@ Thread[{Reverse@y, x}])], Listable];

gradesF[][collection]
(* {"C","D","D","F","B","F","F","F","F","F"} *)

gradesF[{50, 56, 71, 85, 100}][collection]
(* {"B","D","D","F","B","F","F","F","F","F"} *)

gradesF[{69, 100}, {"Pass", "Fail"}][collection]
(* {"Pass","Fail","Fail","Fail","Pass","Fail","Fail","Fail","Fail",\
"Fail"} *)

A: Clear[grade]

grade[x_?NumericQ] = Piecewise[{
    {"F", x < 50}, {"D", x < 56},
    {"C", x < 71}, {"B", x < 85}},
   "A"];

collection = {76.6256, 51.9264, 50.238,
   14.4203, 80.9205, 12.2036, 2.39568,
   38.2747, 12.4422, 29.9621};

grade /@ collection

{"B", "D", "D", "F", "B", "F", "F", "F", "F", "F"}

A: Just put all your rules in a list. You don't need the lower bounds. The first matching rule in the list is applied:
s = {x_ /; x < 50 -> "F", x_ /; x < 56 -> "D", x_ /; x < 71 -> "C",
     x_ /; x < 85 -> "B", x_ /; x <= 100 -> "A"};

collection /. s

(* {"B", "D", "D", "F", "B", "F", "F", "F", "F", "F"}*)

A: For a large number of values a better method is to use Interpolation with an order of zero.
First build the InterpolatingFunction:
points = {{50, "F"}, {56, "D"}, {71, "C"}, {85, "B"}, {100, "A"}};

fn = Interpolation[points, InterpolationOrder -> 0];

Then:
fn[collection] // Quiet

{"B", "D", "D", "F", "B", "F", "F", "F", "F", "F"}

Performance
I claimed that for "a large number of values" the method above is superior to replacement rules.  Here is a BenchmarkPlot  to support that assertion:
letters = StringJoin /@ Tuples[CharacterRange["A", "Z"], 3];
numbers = Sort @ RandomSample[Range[100000], 26^3];
points = {numbers, letters}\[Transpose];
rand = RandomReal[100000, 50000];
f1 = ReplaceAll[rand, (x_ /; x < # -> #2) & @@@ #] &;
f2 = Interpolation[#, InterpolationOrder -> 0][rand] &;
Off[InterpolatingFunction::dmval]

Needs["GeneralUtilities`"]

BenchmarkPlot[{f1, f2}, Sort@RandomSample[points, #] &, 2^Range[14],
 "IncludeFits" -> True, TimeConstraint -> 30]

*

*Note the logarithmic scale.

*The x axis is the number of levels (letters) in the assignment.

*Time to construct each InterpolatingFunction is included; reuse would be faster.
ReplaceAll is faster with only a few levels, but from eight and up InterpolatingFunction is faster, and with many levels orders of magnitude faster.


text:
Q: Can't parse JSON property "null" I faced with one trouble when tried to parse JSON "null" property, please help me to understand what's the real problem. I had a following JSON:
{
  "properties" : {
    "null" : {
      "value" : false
    }
  }
}

I used http://jsonlint.com to validate that this JSON is valid. I tried to parse it from java:
import net.sf.json.JSONObject;
import java.io.IOException;

public class Test {
    public static void main(String[] args) throws IOException {
        String st = "{" +
                "      'properties' : {" +
                "        'null' : {" +
                "          'value' : false" +
                "        }" +
                "      }" +
                "}";
        JSONObject.fromObject(st);
    }
}

But got the exception:
Exception in thread "main" java.lang.ClassCastException: JSON keys must be strings.
    at net.sf.json.JSONObject._fromJSONObject(JSONObject.java:927)
    at net.sf.json.JSONObject.fromObject(JSONObject.java:155)
    at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:108)
    at net.sf.json.AbstractJSON._processValue(AbstractJSON.java:238)
    at net.sf.json.JSONObject._processValue(JSONObject.java:2655)
    at net.sf.json.JSONObject.processValue(JSONObject.java:2721)
    at net.sf.json.JSONObject.element(JSONObject.java:1786)
    at net.sf.json.JSONObject._fromJSONTokener(JSONObject.java:1036)
    at net.sf.json.JSONObject._fromString(JSONObject.java:1201)
    at net.sf.json.JSONObject.fromObject(JSONObject.java:165)
    at net.sf.json.JSONObject.fromObject(JSONObject.java:134)

I used json-lib-2.4-jdk15.jar from http://json-lib.sourceforge.net to parse it. Could anybody please clarify this? Why this library throws exception, but online validator said that it's valid JSON? It is a bug in the library or I made something wrong?

A: JSON-lib initially parses and populates a Java Map with the input JSON.  Unfortunately, JSON-lib then checks whether every JSON object element name is a JSON null.  It's null check is performed in the JSONNull.equals(Object) method.  This method returns true for a "null" JSON string, which of course is not actually a JSON null value.
I recommend filing a bug with the JSON-lib project for this issue.  The implementation of JSONNull.equals(Object) is flawed.
Unfortunately, it's not possible to handle this with a custom PropertyNameProcessor.
Options available for a more immediate solution include altering the JSON-lib code yourself, or switching libraries.
If you can switch libraries, I highly recommend Jackson.  Following is an example of using it to deserialize the example JSON in the original question.
/*
{
  "properties" : {
    "null" : {
      "value" : false
    }
  }
}
 */
String json = "{\"properties\":{\"null\":{\"value\":false}}}";

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(json, Map.class);
System.out.println(map);
// output: {properties={null={value=false}}}

Map<String, Object> propertiesMap = (Map) map.get("properties");
System.out.println(propertiesMap);
// output: {null={value=false}}

Map<String, Object> nullMap = (Map) propertiesMap.get("null");
System.out.println(nullMap);
// output: {value=false}

A: The first JSON posted is valid JSON: the JSON in the Java, however, is not valid -- only " is valid for the [required] key quote. From json.org:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes....

However, that sounds like a bug, assuming it was not triggered by the invalid JSON fed to it (the library can do whatever it wants with invalid JSON)... one would have to look at the source (or bug reports / user experience) to say conclusively if this is indeed a "bug". I have added some suggestions of things to try below which may either show expected behavior or outline the cause/issue in further detail.
Consider this minimal test-case (with valid JSON):
String st = "{ \"null\": \"hello world!\" }";

This may also shed more light, depending on if the first item is "null" or null when extracted:
String st = "[ \"null\" ]";

Happy coding.

A: The gson library link is:
http://code.google.com/p/google-gson/
I normally usr gson to generate the josn string,so I found some example someone else posted in stackoverflow to parse json string with gson,see the link:
Converting JSON to Java

A: suggest you to use Gson,
and construct the json string using java Map and List,
then use Gson to output the Map or List object


text:
Q: Validity of Friedmann's equation Recently, a friend gives me the Friedmann's equations under the following form:
\begin{gathered}
\left(\frac{\dot{a}}{a}\right)^{2}=\frac{8 \pi G}{3 c^{4}} \rho+\frac{\Lambda}{3}-\frac{k}{3 a^{2}}\quad(1) \\
\frac{\ddot{a}}{a}=-\frac{4 \pi G}{c^{4}} P-\frac{1}{2}\left(\frac{\dot{a}}{a}\right)^{2}-\frac{k}{2 a^{2}}+\frac{\Lambda}{2}\quad(2)
\end{gathered}
I have difficulties to convince myself that they are right since from side I know them under the form :
\begin{aligned}
&\frac{R^{\prime \prime}}{R}=-\frac{4 \pi G}{3}\left(\rho+\frac{3 p}{c^{2}}\right)+\frac{\Lambda}{3}\quad(3) \\
&\left(\frac{R^{\prime}}{R}\right)^{2}=\frac{8 \pi G \rho}{3}+\frac{\Lambda}{3}-\frac{k}{R^{2}}\quad(4)
\end{aligned}
In order to make the link, I think I have to take $a(t)=\dfrac{R(t)}{R_{0}}$ but even with this convention, I can't get to find the equations (1) and (2). There are factors and terms that differs between eq(2) and eq(3), like between eq(1) and eq(4).
EDIT : so finally, Could someone tell me if (1) and (2) are wrong and if (3) and (4) are right ?

A: (1) and (4) are almost the same, except for factors of $c^4$ and $3$ in the first and third terms on the right hand side.
If you add zero in the form $\frac12(8πGρ/3 + Λ/3 - k/R^2) - \frac12(R'/R)^2$ to the right hand side of (3), you get (2), except for a factor of $c^2$ difference in the first term.
So (1) and (2) are almost right, aside from a wrong factor of $3$ and some misplaced factors of $c$.


text:
Q: GROUP BY Collapse Dates into CSV separated column Assuming I had a data-set like the following:
╔═══════╦══════════════════╦══════════════════╦═══════════════════╗
║ Count ║    Min(Time)     ║    Max(Time)     ║      Domain       ║
╠═══════╬══════════════════╬══════════════════╬═══════════════════╣
║   647 ║ 2021-01-06 13:08 ║ 2021-01-12 16:25 ║ mail.yahoo.com    ║
║   350 ║ 2021-01-06 13:08 ║ 2021-01-12 16:24 ║ mail.google.com   ║
║   133 ║ 2021-01-06 13:08 ║ 2021-01-12 16:28 ║ www.google.com    ║
║    27 ║ 2021-01-06 13:10 ║ 2021-01-12 15:49 ║ t.fluff.com       ║
║    22 ║ 2021-01-06 15:52 ║ 2021-01-12 15:55 ║ www.thethings.com ║
╚═══════╩══════════════════╩══════════════════╩═══════════════════╝

And a simple GROUP BY statement like this:
SELECT COUNT(DOMAIN), MIN(TIME), MAX(Time), Domain
FROM TABLE
GROUP BY DOMAIN
ORDER BY COUNT(DOMAIN) DESC

Is there a way in SQLLite to flatten the Time Column so I could get all Time listed as CSV column from oldest to newest.  Know this is possible in SQL Server and Oracle with XML Path and other fanciness, whats the simplest way to accomplish this that I could run against a simple SQLLite Database.  Thanks

A: You can use group_concat as follows:
SELECT COUNT(DOMAIN), MIN(TIME), MAX(Time), Domain  ,
     Group_concat(time)
FROM TABLE
GROUP BY DOMAIN
ORDER BY COUNT(DOMAIN) DESC

A: SQLite's aggregate function GROUP_CONCAT() does not support an ORDER BY clause, so you can't have the Times listed from oldest to newest.
But you can do it with GROUP_CONCAT() window function:
SELECT Domain, counter, min_time, max_time, times
FROM (
  SELECT Domain,
         COUNT(*) OVER (PARTITION BY DOMAIN) counter,
         MIN(TIME) OVER (PARTITION BY DOMAIN) min_time,
         MAX(Time) OVER (PARTITION BY DOMAIN) max_time,
         GROUP_CONCAT(Time) OVER (PARTITION BY DOMAIN ORDER BY Time DESC) times,
         ROW_NUMBER() OVER (PARTITION BY DOMAIN ORDER BY Time) rn
  FROM tablename
)
WHERE rn = 1
ORDER BY counter DESC


text:
Q: InputManager ignores cut/copy/paste when initiated from menu I'm using the InputManager to check if changes to controls are done by user or code. This works fine, except when user uses the context menu for cut/copy/paste. If the user do ctrl+v in a textbox, InputManager correctly notices it. However, if the paste is done from the context menu of the textbox, the InputManager never fires the PreNotifyInput or PostNotifyInput events. Anyone knows why? Or how to detect that these user actions? Below is a working sample. The lower textblock never gets updated when user uses the cut/copy/paste menu in the above textbox since PreNotifyInput never fires.
XAML:
<Window x:Class="InputMgrDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <StackPanel>
        <TextBox TextChanged="TextBox_TextChanged" />
        <TextBlock Name="_text" />
    </StackPanel>
</Window>

Code behind:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace InputMgrDemo
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            InputManager.Current.PreNotifyInput += ((sender, e) => _userInput = true);
            InputManager.Current.PostNotifyInput += ((sender, args) => _userInput = false);
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_userInput)
            {
                _text.Text = (sender as TextBox).Text;
            }
        }

        private bool _userInput;
    }
}

A: Actually the PreNotifyInput event does fire on the MouseLeftButtonUp event, but then the PostNotifyInput fires before the actual paste occurs.
Here is the sequence of operations:

*

*The user releases the mouse button on the menu item

*Your PreNotifyInput event handler is called

*The MouseLeftButtonUp event is raised, which bubbles up to the MenuItem

*The MenuItem handles the MouseButtonUp and converts it to OnClick

*The OnClick raises a PreviewClickEvent, then schedules a dispatcher callback to raise the Click event and execute the command

*Your PostNotifyInput event handler is called since the MouseLeftButtonUp event is handled

*Any rendering scheduled by the Dispatcher completes

*The Dispatcher invokes the callback in MenuItem

*MenuItem fires the Click event, which does nothing

*MenuItem executes the Paste command

*TextBox handles the Paste command and pastes the data

*TextBox fires the TextChanged event
In WPF the effects of "user input" can be arbitrarily delayed by dispatcher callbacks, etc, so you cannot know whether a change is due to user input or not.
In fact, theoretically speaking this is generally true.  Consider the following scenarios:

*

*The user clicks a button elsewhere in your application which causes a new data to be loaded which updates your value.

*The user clicks a button in another application which writes a file, causing your application to refresh and display new data.

*The user walks to another computer and updates some data on a web site somewhere.  Your application is monitoring this web site and detects the change.

Clearly in each of these cases the change was caused by user input ;-)  Do you see where I'm going with this?  Philosophically there is no fundamental way to decide whether a change was made by your user or someone else.
If what you really want is "any changes that occur between the time the user clicks the mouse or uses the keyboard in this application and the time the application goes idle," you can implement this:
InputManager.Current.PreNotifyInput += (sender, e) =>
{
  _userInput = true;
  Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(() =>
  {
    _userInput = false;
  }));
};

But in this case if you have data coming in dynamically from an external feed it may be erroneously considered to be user input.
Another approach is to flip yours upside down:  Any time you refresh data from an external data source, set a flag saying you are doing so.  Then any time you see changes with that flag not set, you assume it was user interaction.  This may be easier to implement if you can ensure that all your external data updates happen above DispatcherPriority.Render.


text:
Q: How to broadcast message to a single client using nestjs? I am using nestjs websockets to build a chat app for a multi-vendor application but whenever I broadcast/emit a message from the server to the client, it gets broadcasted to all the clients. Is it possible to emit a message to a single client? And how to do that?
export class ChatGateway implements OnGatewayInit {
    constructor(private conversationService: ConversationService) {}
    @WebSocketServer()
    server: Server;

    @SubscribeMessage('sendMessage')
    async handleMessage(
        client: Socket,
        payload: {
            senderProfileId: ID;
            recieverProfileId: ID;
            conversationId: ID;
            message: string;
            createdAt: Date;
        },
    ) {
        await this.conversationService.createMessage({
            message: payload.message,
            createdAt: payload.createdAt,
            senderProfileId: payload.senderProfileId as string,
            conversationId: payload.conversationId as string,
        });
        // Want to emit this to a single client
        this.server.emit('recieveMessage', payload);
    }
}

Currently, I am using the recieverProfileId to make sure if the message is displayed to the correct reciever.

A: server side:
@SubscribeMessage('message')
onEnvent(@MessageBody() message: any){
    this.server.to(message.to).emit("message", message);
}

client:
socket.emit('message', { to: socket.id, data: message })


text:
Q: Exportar dados do mysql para csv Estou tentando fazer a exportação de dados específicos de um banco de um cliente para csv, pesquisei na internet e falaram que iria conseguir usando o código abaixo.
SELECT * FROM escola
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

Porém quando eu utilizo aparece: "error SQL 1045" Access denied for user 'forms'@'%'(using password: YES)". Fui pesquisar no proprio forum da mysql, e achei uma informação dizendo que eu teria que entrar como administrador no banco para alterar o usuário com problema, porem eu não consigo ter esse acesso. Teria outra forma para realizar a exportação? ou para resolver esse erro?
Estou pensando em fazer com python, utilizando vários selects e tratando os dados para a criação do csv, porem acho que é um esforço desnecessário.
Estou usando o HeidiSQL 9.5.0


text:
Q: How to Calculate inverse of GCD? How to Calculate inverse of GCD ?
for example if we have GCD(a,b) = 7
how do we determine the values of a,b .
note : a,b have given bound and the given result of the GCD is always a prime.
am actually trying to solve this problem and reversing GCD is the first Idea that came to my mind since a,b limit are <$10^7$

A: You don't, because it doesn't have an inverse.  For example, there are infinitely many pairs $(a,b)$ with GCD$(a,b) = 1$ (these numbers are called "relatively prime" or "co-prime".)
EDIT: Perhaps more to the point, there are infinitely many pairs $(a,b)$ with GCD$(a,b) = 7$.  For example, $(7a, 7b)$ for every pair of co-prime integers $a$ and $b$.

A: In general, $\text{gcd}(a,b) = d$ (with $d \in \mathbb{Z}^+$) if and only if there exist $x,y \in \mathbb{Z}$ which are coprime and such that $ax+by=d$. So take any coprime $x,y \in \mathbb{Z}$, then we can calculate $a,b \in \mathbb{Z}$ such that $ax+by=d$ using the some kind of algorithm, such as the reverse-Euclidean algorithm. However, $a,b$ are highly non-unique.
If you just want a solution (rather than all solutions), given $d$ and a bound, then since $\left| a \right|$ and $\left| b \right|$ must be $\ge d$, you could just take $a=b=d$ (unless the bound is $<d$, in which case no solutions exist). This is the solution corresponding to $x=1, y=-1$ above.

Edit: Here's an algorithm for finding all $a,b$ with gcd $d$ given a bound $M>0$.
Let $S=\varnothing$. For each $-M \le a \le M$ and $-M \le b \le M$, calculate $\text{gcd}(a,b)$ (using, say, the Euclidean algorithm). If $\text{gcd}(a,b) = d$, append $(a,b)$ to $S$; if not, discard it. The resulting set $S$ contains all pairs $(a,b)$ within the given bound such that $\text{gcd}(a,b)=d$.

A: Hint $\rm\ (a,b) = c\!\iff\! c\:|\:a,b\,$ and $\rm\,(a/c,b/c) = 1.\:$ So $\rm\:(a,b) = c\!\iff\! a = c\,j,\ b = ck,\,$ $\rm\, (j,k)=1.\:$  Choosing $\rm\: j=k+1,\,\ k\in \Bbb N\:$ shows that there are infinitely many solutions.


text:
Q: Reactjs: How to use Window.postMessage() from window.open() to my parent component I am trying to communicate with my window.open() with my parent page with a simple "Test done" post message.
I have gone through some examples as well but not sure how to replicate it here.
Any suggestion what I can do here to make it possible.
//homepage
class HomePage extends React.Component {

handleTestVisibleClick = () => {
    const testUrl = process.env.PUBLIC_URL+"/test.html";

    document.getElementsByClassName('connect-dialog')[0].style.visibility = 'hidden';

    var leftPosition, topPosition;
    var width = 410;
    var height = 460;
    leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
    topPosition = (window.screen.height / 2) - ((height / 2) + 10);
    var windowOpen = window.open(testUrl, "Window2",
    "status=no,height=" + height + ",width=" + width + ",resizable=yes,left="
    + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY="
    + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no");

    var timer = setInterval(function() {
      if(windowOpen.closed) {
          clearInterval(timer);
          document.getElementsByClassName('connect-media-dialog')[0].style.visibility = 'visible';
      }
    }, 100);
  }
  render() {
    return (
      <dialog open={open} className="section">
          <Button  className="connect-test-button"
            onClick={()=>{ this.handleTestVisibleClick() }}>
            Test
          </Button>

      </dialog>
    );

  }
};

export default HomePage;

//testpage.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Cache-Control" content="no-store" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    <meta charset="UTF-8">
    <title>Test Device</title>
    <script>
      function testdone() {
          self.close();
          window.opener.postMessage("Test Done", '*');
      }

    </script>
</head>
<body>

<button onclick="testdone()"> End Test </button>

</body>
</html>

A: You can do this by accessing the child window's postMessage property.
var child = window.open('https://www.example.com')

child.postMessage('something')

JSFiddle - https://jsfiddle.net/8850s/ev1xj8uc/


text:
Q: difference with import for simple piece Filee.py
a = 5
i = 6

def f(x):
    print(x*x)

from Filee import *

then I can call f(a)
import Filee

then I need to call Filee.f(Filee.a)
How are the two import different?

A: It can be for convenience. If you use import Filee to import Filee.f into your namespace, then you need to type out Filee.f every single time you want to use the function f.
However, if you also have a function f in your current namespace and you also want to use the function f from Filee.f, then you might want to use Filee.f to call it so that you're not overwriting your function f (as python doesn't support function overloading). For example:
import Filee

def f(x):
    return x

x = f(2)
y = Filee.f(x)

Here it is useful to have the library/module name to avoid overloading the function f. Also, it's best to import only the functions you need from a module. from Filee import * is considered a bad practice.

A: from Filee import * means from Filee import everything. By default, I don't like this approach unless you are aware what you are importing. That is because you are on risk of having two different function from two different library but with same name. In your case, other Filee2.py might contain function f with completely different code.
In the other hand, import Filee force you to use Filee.f, so if there is Filee2.f, you can use both separately.

A: from Filee import * will import everything from that module into the current, so you can directly call the function f(a)
If you import as import Filee you'll need to prefix the module name.
Don't exclusively use the first import case, as it can be very inefficient for some modules


text:
Q: How to write a function in MATLAB I want to write a function that returns the value of f(y) for any value of y:
f(y) =tan( sin(y) - sin(tan(y)) )

How can I write this as a function in MATLAB?

A: Here is an example function for your purpose
function y = f(x)
   y = tan(sin(x)-sin(tan(x)));
end

A: You could use an anonymous function, as elluded to in the comments by
obchardon:
f = @(y) tan(sin(y) - sin(tan(y)))

% usage like any other function:
f(1)

Note that you do not include the (y) on the left hand side of the =, this syntax is reserved for indexing into variables, or symbolic math.


text:
Q: If a polynomial $f$ is zero at $(a_1,...,a_k,x_{k+1},...,x_{n})$ then $f$ lies in the ideal $(x_1-a_1,...,x_n - a_n)?$ I saw this question:
Is a polynomial $f$ zero at $(a_1,\ldots,a_n)$ iff $f$ lies in the ideal $(X_1-a_1,\ldots,X_n-a_n)$?
I was wondering if a polynomial $ f $ of a ring $ K [x_1, ..., x_n] $, where $ K $ is a field, is zero at $(a_1, ..., a_k, x_{k+1}, ..., x_n)$ then $f$ lies in the ideal $(x_1-a_1, ..., x_n-a_n)?$ I tried to adapt the answer given there, but no success. If this is not true, what can we say about the relationship between $f$ and the ideal $(x_1-a_1, ..., x_n-a_n)$?

A: One has a homomorphism $\phi:K[x_1,\ldots,x_n]\to K[x_{k+1},\ldots,x_n]$
given by $$\phi:f(x_1,\ldots,x_n)\mapsto f(a_1,\ldots,a_k,x_{k+1},\ldots,x_n).$$
You are asking its kernel is $I=(x_1-a_1,\ldots,x_k-a_k)$.
Yes it is. Each $x_i-a_i\in \ker\phi$, Conversely suppose $f\in\ker\phi$.
Then
$$f(x_1,\ldots,x_n)=f(x_1,\ldots,x_n)-f(a_1,\ldots,a_k,x_{k+1},\ldots,x_n).$$
We claim that $g(x_1,\ldots,x_n)-g(a_1,\ldots,a_k,x_{k+1},\ldots,x_n)\in I$
for any polynomial $g$.
It suffices to prove this for $g=x_1^{i_1}\cdots x_n^{i_n}$. This is just
a calculation:
$$g(x_1,\ldots,x_n)-g(a_1,\ldots,a_k,x_{k+1},\ldots,x_n)
=(x_1^{i_1}\cdots x_k^{i_k}-a_1^{i_1}\cdots a_k^{i_k})x_{k+1}^{i_{k+1}}\cdots x_n^{i_n}$$ and the bracketed expression is in $I$. To see this set $y_i=x_i-a_i$
and in terms of $y_i$, the bracket has zero constant term.


text:
Q: Use Boto3 to find subnets route through virtual private gateway Need to find a way to identify AWS VPC Subnets that route through virtual private gateway by using Python Boto3. In another word, how can I use python boto3 to identify Private Subnets within a VPC?
The goal is to create a Lambda function that will identify private subnets within a given VPC, and then to launch another Lambda function within those Private Subnets.
Below is the code I got so far. It lists all subnets within a VPC that has a Virtual Private Gateway attached.
import boto3

def get_vpn_gateways():
    ec2_client = boto3.client('ec2')
    response = ec2_client.describe_vpn_gateways()
    return response

def get_vpc_subnets(VpcId):
    ec2 = boto3.resource('ec2')
    vpc = ec2.Vpc(VpcId)
    subnets = vpc.subnets.all()
    return subnets

# Get VPC Ids associated with the virtual private gateway
vpc_list = []
virtual_gateways = get_vpn_gateways()
for virtual_gateway in virtual_gateways["VpnGateways"]:
    vgwId = virtual_gateway["VpnGatewayId"]
    vpcAttach = virtual_gateway["VpcAttachments"]
    vpc_list.append(vpcAttach[0]["VpcId"])
for vpc in vpc_list:
    print(vpc)
    subnets = get_vpc_subnets(vpc)
    for subnet in subnets:
        print(subnet)

The code so far lists all the subnets within the VPC. I am thinking to use routetable as the key identifier for Private subnet. If there are routes going through VGW, then I will deem the subnet as Private. Does that make sense?

A: I think the routing for 0.0.0.0/0 is not an internet gateway, then that is the private subnet. The private subnet could be routed to NAT gateway or Virtual gateway but not the internet gateway directly. So, I wrote code as below.
import boto3

ec2 = boto3.resource('ec2')
route_tables = ec2.route_tables.all()

for route_table in route_tables:
    for ra in route_table.routes_attribute:
        if ra.get('DestinationCidrBlock') == '0.0.0.0/0' and ra.get('GatewayId') is None:
            for rs in route_table.associations_attribute:
                if rs.get('SubnetId') is not None:
                    print(rs.get('SubnetId'))

A: Here's the final working code that looks up private subnets within each VPC that has Virtual Private Gateway attached. It checks if the private subnets is in the VPC's subnet list, then proceeds to save it later for another Lambda function. This probably not the most effective/efficient way to achive my goal. Keen to see any other better solutions.
import boto3

def get_vpn_gateways():
    ec2_client = boto3.client('ec2')
    response = ec2_client.describe_vpn_gateways()
    return response

def get_vpc_subnets(VpcId):
    ec2 = boto3.resource('ec2')
    vpc = ec2.Vpc(VpcId)
    subnets = vpc.subnets.all()
    return subnets

def get_private_subnets():
    priv_subnet_list = []
    ec2 = boto3.resource('ec2')
    route_tables = ec2.route_tables.all()
    for route_table in route_tables:
        for ra in route_table.routes_attribute:
            if ra.get('DestinationCidrBlock') == '0.0.0.0/0' and ra.get('GatewayId') is None:
                for rs in route_table.associations_attribute:
                    if rs.get('SubnetId') is not None:
                        priv_subnet_list.append(rs.get('SubnetId'))
    return priv_subnet_list
def lambda_handler(event, context):
    vpc_list = []
    vpc_subnet_list = []
    virtual_gateways = get_vpn_gateways()
    lambda_subnets = []
    # Get VPC Ids associated with the virtual private gateway
    for virtual_gateway in virtual_gateways["VpnGateways"]:
        vgwId = virtual_gateway["VpnGatewayId"]
        vpcAttach = virtual_gateway["VpcAttachments"]
        vpc_list.append(vpcAttach[0]["VpcId"])
    # Get subnets within the VPC
    for vpc in vpc_list:
        subnets = get_vpc_subnets(vpc)
        for subnet in subnets:
            vpc_subnet_list.append(subnet.id)
        # Get Private subnets from the subnet list
        for privsubnet in get_private_subnets():
            if privsubnet in vpc_subnet_list:
                lambda_subnets.append(privsubnet)


text:
Q: Vba code for keeping chart object on one sheet when using range.exporttopdf method I have code that outputs a range and a pivotchart to pdf. At this point I am struggling to have the chart element on one page instead of it possibly being cutoff. Here is my code:
With nxraySheet.PageSetup
        .FitToPagesWide = 1
        .FitToPagesTall = False
        .Orientation = xlLandscape
        .Zoom = 85
        .LeftMargin = 0
        .RightMargin = 0
        .CenterHorizontally = True
        End With

        nxraySheet.Columns("A:H").HorizontalAlignment = xlCenter
        nxraySheet.Range("A:H").ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:="Blah Blah Blah\Test Location\AVITEST\PDFs\X-Rays\" & "X-Ray-" & facilityList.Cells(i, 1) & "-" & Format(Date, "mm-dd-yy") & ".xlsx", _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=True, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=False

[]

A: In Excel, unfortunately you can not tell a chart to be printed as a whole (would be like "Excel, please move the chart some rows up or down to get printed altogether").
Here are some options:
Overall Zoom
You can not have both FitToPagesWide = 1 and Zoom = 85 at the same time. This doesn't raise an error, but these settings conflict with each other and zoom factor wins.
So you may decide for a lower zoom factor:
With nxraySheet.PageSetup
    .Zoom = 75

Fit vertically on 1 Page
If you want it to fit vertically on 1 page, reset the zoom factor first:
With nxraySheet.PageSetup
    .Zoom = False
    .FitToPagesWide = False
    .FitToPagesTall = 1

Fit horizontally on 1 Page, add Page Break
You can print with 1 page width and add a manual horizontal page break directly before the PivotChart:
With nxraySheet
    .PageSetup.Zoom = False
    .PageSetup.FitToPagesWide = 1
    .PageSetup.FitToPagesTall = False
    .ResetAllPageBreaks
    .HPageBreaks.Add Before:=.ChartObjects(1).TopLeftCell.Row


text:
Q: Asp.net count user attempt I am new to ASP.net It might be a simple question but I  dont know how to do it.
I have a asp.wizard control on my page where On "step 1" I have one textbox that accept a order number
If user enter the order number  in textbox and it match with the database it move user to wizard step 2. If user  entered wrong value or  kept it blank then  validator controls warn to enter value or entered value is wrong.
However my concern it that if user try to input value more then three time it should show the popup window and say the message "you have tried three times and you dont have a valid order number"
I tried to  increment my counter in  serverValidate event function but its reseting the counter value to 0 on every postback of the page.
I dont now how to do it as  everytime my page postback after clicking next button o my wizard page my counter value reset to 0

A: You can save it in a session variable that one would not reset.

A: <input type="hidden" id="hdn" runat="server" value="0" />

On code behind, after each failed attempt:
hdn.Value=""+(ConvertToInt32(hdn.Value)+1);
if(hdn.Value=="3")
// do something

A: Store your counter in a hidden text field. This way the value will survive postbacks. You can either increment the counter in javascript (when the user presses the button) or on the server.
Here is a rough framework:
Add a field to your page similar to the following:
    <input type="hidden" runat="server" id="txtCounter" />

In your code-behind:
if String.IsNullOrEmpty(txtCounter.Value) {
   txtCounter.Value = "1";
} else {
   int wCounter;
   wCounter = Convert.ToInt32(txtCounter.Value);
   if (wCounter >= 3) {
     Page.ClientScript.RegisterStartupScript(Page.GetType(), "Count Exceeded", "alert('The number of tries has been exceeded.');", True)

   } else {
     wCounter += 1;
     txtCounter.Value = wCounter.ToString();
   }
}

A: if (Wizard1.ActiveStepIndex == 0)
    {
        if ((HiddenField1.Value == "0")){
            HiddenField1.Value = "1";
    }
        else if ((HiddenField1.Value == "1"))
      {
          HiddenField1.Value = "2";
      }

      else if ((HiddenField1.Value == "2"))
      {
          HiddenField1.Value = "3";

          Response.Write("<script language='javascript'>alert('you tried 3 times')</script>");
          }

    Label21.Text = HiddenField1.Value;
    }


text:
Q: ubuntu usb sound card sometimes recognized and sometimes not at boot I have a linux ubuntu 12.04 server machine which works with an usb sound card.
When rebooting the machine, sometimes the usb sound card is recognized and sometimes not, I cannot figure out a reason for this.
I understand when the sound card is recognized because when I issue the command:
cat /proc/asound/modules

I can see listed or not the line snd_usb_audio.
Analyzing the /var/log/kernel.log I can see sometimes (when it works)
kernel: [    6.236564] usbcore: registered new interface driver snd-usb-audio

and other times (when it is not recognized and listed):
kernel: [    7.126855] snd-usb-audio: probe of 2-1.2:1.0 failed with error -5
kernel: [    7.126876] usbcore: registered new interface driver snd-usb-audio

Does anybody know how to ensure that the usb sound card is always recognized?

A: Ok this solved the problem:
1) blacklist the integrated audio card
sudo nano /etc/modprobe.d/blacklist.conf

and add the line
blacklist snd_hdma_intel

where the name snd_hdma_intel is retrieved after issuing the command
cat /proc/asound/modules

(for example the output for me was)
0 snd_hdma_intel
1 snd_usb_audio

2) edit the following file:
sudo nano /etc/modprobe.d/alsa-base.conf

comment the lines regarding snd-usb-audio this way:
#options snd-usb-audio index=-2

3) just reboot


text:
Q: How to load HTML in a div tag using JavaScript I am just practicing to make a college website. There are 3 tags in a body one as a  and second as a div and third as a footer.  I have some HTML in another about.html without  and tags. In my style.css file I have styled for about.html. I want only one thing that whenever I click on About it replace the code with the

 that is in about.html. How do I load an HTML page in a
 using JavaScript?

Note: The CSS provided in snippet is not responsive. I want to decided
to done this step than ahead to responsive

Here is code that i want to replace with the given in snippet.

The Biggest

Educational

Network

Punjab Group

Of Colleges

Hafizabad

Khizar Abbas

IT Manager At PGC-Hafizabad

Hafiz Fahad

Principal At PGC-Hafizabad

Salman Butt

Vice Principal At PGC-Hafizabad

Sohail Afzal

Executive Director PGC

Mian Amer Mahmood

Chairman PGC

:root {
  --blue-color: #2c2b6f;
  --red-color: #e13a27;
  --red_2_color: #e13b28;
  --blue_2-color: #2c2b6d;
  --white-color: #ffffff;
  --font-light: GalanoGrotesque;
  --font-bold: GalanoGrotesque-Bold;
}

* {
  font-family: var(--font-light);
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  color: var(--white-color);
  background-color: var(--blue-color);
}

/* Styling NavBar */

#navbar {
  position: relative;
  display: flex;
  width: 100%;
  height: 75px;
  align-items: center;
  justify-content: space-between;
  min-width: 100%;
}

#navbar::before {
  content: "";
  position: absolute;
  min-width: 100%;
  background-color: var(--red_2_color);
  z-index: -1;
  height: 100%;
}

/* Styling Logo */

.logo {
  margin-left: 10px;
  width: 120px;
}

/* Styling Nav-Links */

#nav-links {
  display: flex;
  list-style: none;
}

#nav-links a {
  text-decoration: none;
  color: var(--white-color);
}

.nav-links {
  margin: 0 15px;
  font-size: 1.08rem;
  position: relative;
  cursor: pointer;
  text-transform: uppercase;
}

/* Styling Social Links */

#social-links {
  margin-right: 10px;
}

.social-links {
  filter: invert();
  margin: 0 5px;
}

.social-links img {
  width: 25px;
  transition: all 300ms ease;
}

.social-links img:hover {
  transform: scale(1.5);
}

/* Styling NavBar Finished */

/* Styling Default Content */
#content {
  position: relative;
  margin-top: 10px;
  height: 100vh;
}

#content::before {
  content: "";
  width: 100%;
  height: 100%;
  position: absolute;
  background: url("../PGC_Stock/sldier-bg-gradient1.jpg") center center/cover
    no-repeat;
  z-index: -1;
}

#content {
  background-image: url(../PGC_Stock/slide-bg.png);
  background-size: 900px;
  background-repeat: no-repeat;
  background-position: bottom right;
}

#content div {
  position: absolute;
  left: 5%;
  top: 20%;
  display: flex;
  flex-direction: column;
}

#content span h1 {
  text-transform: uppercase;
  font-size: 4rem;
  line-height: 1;
}

.para {
  margin-top: 5px;
  font-size: 1.3rem;
}

.btn {
  margin-top: 5px;
  color: var(--blue-color);
  padding: 5px 5px;
  font-family: "Times New Roman", Times, serif;
  font-weight: 700;
  background-color: var(--white-color);
  border: none;
  border-radius: 5px;
  font-size: 1.5rem;
  width: 150px;
}

#footer {
  height: 60px;
  background-color: var(--red-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Punjab Group Of Colleges | Hafizabad</title>
  <link rel="stylesheet" href="./css/style.css">

About

Programmes

Life At Campus

Gallery

Contact Us

A Legacy Of

Excellence

      Pre 1st Year Admissions Open
      <button class="btn" id="apply">Apply Now!</button>

Punjab Colleges Hafizabad

© 2021 Punjab Colleges. All Rights Reserved.

A: If you modify the about list element slightly to add a new class called about and remove the inline click handler, like so:

About

Programmes

Life At Campus

Gallery

Contact Us

Note that the hyperlink/anchor is within the li element - it is invalid as a direct child of ul!
Then attach an event listener in a script at the end of the body section like so:

This will send an ajax request that reads about.html and returns it as a string. This string of HTML is then inserted into the DOM before the section id='content' and that section is then removed.

A: So far from all, I understand that you want content of about.html to appear on current html page. If I am not wrong then I would suggest you to look over bootstrap V5 where you can implement modals where you can place any html elements it will pop up based on actions.
1: this link will take you to introduction page where you will see pre-requisite to use Bootstrap 5 Introduction · Bootstrap v5.1
2: this link will take you to modals explained perfectly (it may look at first Unrelated to topic but give a try copy the code and run on ur localhost or any server and try to explore)
Modal · Bootstrap v5.1 Hope that helped you atleast some extent. If not also do explore through different benifits of Bootstrap 5 (if u have not explored). Thank you


text:
Q: MongoDB - find() with 5 filters and conditions gives different results than no conditions I'm wrote and tested a query to retrieve the documents and it works just fine it gets exactly what I asked for and when I take out each of the filters it retrieves the corrent documents. Now instead of manually commenting each filter I want to base it on the index as it goes down, so at index = 4 it should use all filters and at index = 3 it should use one less filter until at index = 0 where it should just get the documents.
The code that works just fine:
    users = await User.find({
      $and: ignoreUsers.map((id) => {
        return { _id: { $ne: new ObjectId(id) } };
      }),
      objectives: { $in: objectives },
      ranking: ranking,
      expLevel: { $gte: expLevel - 1, $lte: expLevel + 1 },
      industries: { $in: industries },
      "skills.self": { $in: skills },
      interests: { $in: interests },
    });

This produces 1 document which is correct, however when I add the if conditions it produces 5 documents which is not corrent. The ranking.<variable> are numbers 1-4 so if the index = 4 then all the if conditions should be true right? but none of them are being executed. only the objectives and ranking filters work, the whole $expr conditions are being ignored
        let index = 4;

        // supposed to be in while loop but testing just once does not produce just the 1 document it's supposed to

        const fetchCondUsers = await User.find({
          $and: ignoreUsers.map((id) => {
            return { _id: { $ne: new ObjectId(id) } };
          }),
          objectives: { $in: objectives },

          $expr: {
            $cond: {
              if: { $gte: [index, 0] },
              then: {
                ranking: ranking,
              },
              else: "$$REMOVE",
            },
            $cond: {
              if: { $gte: [index, ranking.expLevel] },
              then: {
                $and: [
                  { $gte: ["$expLevel", expLevel - 1] },
                  { $lte: ["$expLevel", expLevel + 1] },
                ],
              },
              else: "$$REMOVE",
            },
            $cond: {
              if: { $gte: [index, ranking.industry] },
              then: {
                industries: { $in: ["$industries", industries] },
              },
              else: "$$REMOVE",
            },
            $cond: {
              if: { $gte: [index, ranking.skills] },
              then: {
                skills: { $in: ["$skills", skills] },
              },
              else: "$$REMOVE",
            },
            $cond: {
              if: { $gte: [index, ranking.interests] },
              then: {
                interests: { $in: ["$interests", interests] },
              },
              else: "$$REMOVE",
            },
          },
        }).limit(limit);

Ideally this is what I'm trying to do
      users = await User.find({
        $and: ignoreUsers.map((id) => {
          return { _id: { $ne: new ObjectId(id) } };
        }),
        objectives: { $in: objectives },
        if (index === 0) ranking: ranking,
        if (index === 1) expLevel: { $gte: expLevel - 1, $lte: expLevel + 1 },
        if (index === 2) industries: { $in: industries },
        if (index === 3) "skills.self": { $in: skills },
        if (index === 4) interests: { $in: interests },
      });

A: So after staring in to the abyss I realized javascript........ AN OBJECT IS BEING PASSED IN TO THE find()... So I simply just took out the object in to its own variable and broke it down like so:
      while (users.length < limit) {
        const query = {
          $and: ignoreUserObjectIDs.map((oID) => {
            return { _id: { $ne: oID } };
          }),
          objectives: { $in: objectives },
        };

        if (index >= 0) {
          query["ranking"] = ranking;
        }
        if (index >= ranking.expLevel) {
          query["expLevel"] = { $gte: expLevel - 1, $lte: expLevel + 1 };
        }
        if (index >= ranking.industry) {
          query["industries"] = { $in: industries };
        }
        if (index >= ranking.skills) {
          query["skills.self"] = { $in: skills };
        }
        if (index >= ranking.interests) {
          query["interests"] = { $in: interests };
        }

        const fetchCondUsers = await User.find(query).limit(
          limit - users.length
        );

        users = users.concat(fetchCondUsers);
        ignoreUserObjectIDs = ignoreUserObjectIDs.concat(
          fetchCondUsers.map((user) => {
            return new ObjectId(user.id);
          })
        );

        if (index === 0) break;
        index--;
      }

In my defence I'm working on 3 different projects in three different languages so I tend to forget about the simple things... Anyways, if anyone else had similar issues, here you go!


text:
Q: Firebird 2.5.8, 3.0.4 unicode_ci_ai index problems I'm using Firebird 3.0.4 x64 in Linux and Windows, Superserver
The databases that I have migrate to utf8 with colation unicode_ci_ai are much slower in use, the problem is the indexes with various varchar fields.
example of the problem
data:
CREATE TABLE TEST_UNICODE (
    S1  VARCHAR(10) NOT NULL COLLATE UNICODE,
    S2  VARCHAR(10) NOT NULL COLLATE UNICODE
);

CREATE TABLE TEST_UNICODE_CI_AI (
    S1  VARCHAR(10) NOT NULL COLLATE UNICODE_CI_AI,
    S2  VARCHAR(10) NOT NULL COLLATE UNICODE_CI_AI
);

INSERT INTO TEST_UNICODE (S1, S2) VALUES ('A', 'A');
INSERT INTO TEST_UNICODE (S1, S2) VALUES ('A', 'B');
INSERT INTO TEST_UNICODE (S1, S2) VALUES ('B', 'A');
INSERT INTO TEST_UNICODE (S1, S2) VALUES ('B', 'B');

COMMIT WORK;

INSERT INTO TEST_UNICODE_CI_AI (S1, S2) VALUES ('A', 'A');
INSERT INTO TEST_UNICODE_CI_AI (S1, S2) VALUES ('A', 'B');
INSERT INTO TEST_UNICODE_CI_AI (S1, S2) VALUES ('B', 'A');
INSERT INTO TEST_UNICODE_CI_AI (S1, S2) VALUES ('B', 'B');

COMMIT WORK;

CREATE INDEX TEST_UNICODE ON TEST_UNICODE (S1, S2);
CREATE INDEX TEST_UNICODE_CI_AI ON TEST_UNICODE_CI_AI (S1, S2);

COMMIT WORK;

Query:
SELECT S1,S2 FROM test_unicode WHERE S1 = 'B' AND S2 = 'A'
UNION ALL
SELECT S1,S2 FROM test_unicode_ci_ai WHERE S1 = 'B' AND S2 = 'A'

Isql Plan:
Select Expression
    -> Union
        -> Filter
            -> Table "TEST_UNICODE" Access By ID
                -> Bitmap
                    -> Index "TEST_UNICODE" Range Scan (full match)
        -> Filter
            -> Table "TEST_UNICODE_CI_AI" Access By ID
                -> Bitmap
                    -> Index "TEST_UNICODE_CI_AI" Range Scan (partial match: 1/2)

I get 2 indexed reads with test_unicode_ci_ai and 1 indexed read with test_unicode, with millions of records the problem escalates.
What I'm doing wrong ? Thank you
Tested in 2.5.8 x64 Windows Superserver, has the same bug


text:
Q: How should I encapsulate my MVC-Action in order to avoid code duplication? I have two classes - MVC-Controlles in this particular case – that have one common controller action (a JSON action that will be called from JavaScript). Because of code duplication, I would like to put this action in a parent controller class. We already have a controller base class that inherits from Controller and is used as base class, with common functionality, from 6 other Controllers. My JSON action is actually common only for 2 controllers, so I think that it's not a good idea to put my JSON action in the base controller that is already used by the other 6 controllers. Here's the existing class hierarchy graph:
Existing Controller class hierarchy
Where should I put my JSON action in order to avoid code duplication? My idea is to inherit the class ControllerBase – let's say ControllerBaseExtended – and to place my JSON action in here. So now, my 2 Controllers can inherit from ControllerBaseExtended instead of ControllerBase. This is how the class hierarchy would look like at the end:
Final Controller class hierarchy
Is there any better way to solve this problem?

A: Change all your controllers to inherit BaseController instead of Controller.
It sounds like you are already doing this.... but for some reason its not good, could you explain a little better as to why this is not working for you...
public class [my]Controller : BaseController
{
    public ResualtAction [my]Action
        return Base.Something();
    }
}

public class BaseController : Controller
{
    public CustomeReturnAction Something()
    {
        return new CustomeReturnAction();
    }
}

or is it that your just trying to organize it better....
if that is the case then just move all the return action types into another class and let your BaseController inherit from that, I think your saying that already, if you are then yes that is good.

A: It depends on the functionality of the duplicate code. You can use anything from inheritance or composition (with an injected class) to reuse code in different controllers.
For instance: we have a Calculation class for calculating the prices of products and use Dependancy Injection to inject this logic into different controllers. The controller then uses this Calculator to present the output.
Maybe look into dependancy injection with ASP.Net MVC. I recommend Simple Injector. It integrates nicely into the ASP.Net MVC framework.

A: Instead of creating another base controller, extract code from both actions into another class, e.g. JsonActionProcessor. Then you will need to call that implementation.
public class JsonActionHelper
{
    public JsonResult Something()
    {
        //do something common
        return new JsonResult();
    }
}

Then you can call it from your actions
public JsonResult Action1()
{
    return new JsonActionHelper().Something();
}

public JsonResult Action2()
{
    return new JsonActionHelper().Something();
}

If you have UnitTests then you should extract interface from JsonActionHelper and inject it into your Controllers.
However if you have 2 identical actions, why just not to have one action and call it via JavaScript from different views?