text:
Q: How to cleanly close connection in Netty if ChannelOutboundBuffer is filled? After calling channel.disconnect() in Netty 4.x I've got a bunch of the following exceptions:
io.netty.channel.StacklessClosedChannelException: null
        at io.netty.channel.AbstractChannel.close(ChannelPromise)(Unknown Source) ~[netty-transport-4.1.53.Final.jar:4.1.53.Final]

They are probably created because ChannelOutboundBuffer is not empty.
How to clean ChannelOutboundBuffer before close() ?
How to avoid them or maybe I should catch them and ignore (if there is no way to avoid them) ?

A: close() should "clean" the ChannelOutboundBuffer, which means it will fail all the writes that are still sitting in there with a ClosedChannelException. This sounds totally normal.


text:
Q: High CPU during pymysql IO I am trying to debug high CPU usage on a mostly IO bound python application. The python application polls for messages from a queue, performs a bunch of MySQL queries and an external API call. It's not multi-threaded and we spawn multiple python processes (about 4x number of cores) to achieve parallelism. The multi-process app ends up consuming 90%+ CPU under load (when there are ample messages in the queue). Upon profiling the app, it seems to suggest that most CPU is consumed while pymsql writes or reads from socket. Is there a way to optimize pymysql to consume less CPU? Can it do zero copy I/O? Or is it acceptable for pymysql to consume high amount of CPU during I/O?

Environment:
python 3.7.7
pymysql 0.7.11
mysql 5.7

redpajama_set_name: RedPajamaStackExchange


text:
Q: class -> array undefined index PHP

*

*THIS IS UNSOLVED

I have a class that I've put together to do a CRUD for me. Here is the sections that are applicable to my issue.
I am returning the following errors.
[07-Apr-2017 15:45:40 America/Los_Angeles] PHP Notice:  Undefined index: placeholder in class/LeadStages.php on line 88
[07-Apr-2017 15:45:40 America/Los_Angeles] PHP Notice:  Undefined index: id in class/LeadStages.php on line 90
[07-Apr-2017 15:45:40 America/Los_Angeles] PHP Notice:  Undefined index: type in class/LeadStages.php on line 91
[07-Apr-2017 15:45:40 America/Los_Angeles] PHP Notice:  Undefined index: maxchar in class/LeadStages.php on line 93

Class
class LeadStage {

    /*
    * Create LeadStage. You will need to include the "LeadStage"
    * in which is being created, the date created,
    * time created, and the user who created it.
    */

    function __construct() {
        $this->FormFields = new FormFields;
    }

    // Input Field -> Stage
    function addInputError_New_Element($option) {
        var_dump($option);
        $element = $this->FormFields->InputError_NEW(
            $Error = $option['error'],
            $Value = $option['value'],
            $PlaceHolder = $option['placeholder'],
            $InputName = $option['name'],
            $InputID = $option['id'],
            $InputType = $option['type'],
            $InputLabel = $option['label'],
            $MaxChar = $option['maxchar'],
            $required = $option['required']
        );
        return $element;
    }

    // Select Option -> Status
    function addSelectError_New_Element($option) {

        $element = $this->FormFields->SelectError_NEW(
            $ErrorMSG = $options['error'],
            $InputLabel = $option['label'],
            $Class = $option['class'],
            $DataTargetDIVID = $option['targetid'],
            $SelectName = $option['name'],
            $SelectArray = $option['array'],
            $Value = $option['value'],
            $required = $option['required'],
            $Value = FALSE
        );

        return $element;

    }

    function addElementToForm($option) {

        if($option['FormField'] = 'stage') {

            // Build our Markup to input our new stage.

            $element = $this->addInputError_New_Element($option);

        }
        elseif($option['FormField'] = 'status') {

            // Build our Markup for selecting our status.
            $element = $this->addSelectError_New_Element($option);

        }

        return $element;

    }

    function makeEntireForm() { // next stage is to forget hard coding instead pass in array of elments you want made and cycle through array.

            /*
            * Create Input field -> Stage
            */
            $entireForm = '';
            $option = array(
                'FormField'     => 'stage',
                'error'         => FALSE,
                'value'         => FALSE,
                'placeholder'   => 'Stage (ie; Scheduled Inspection)',
                'name'          => 'stage',
                'id'            => FALSE,
                'type'          => 'text',
                'label'         => 'Stage',
                'maxchar'       => 50,
                'required'      => TRUE
            );
            // Build Element
            $entireForm .= $this->addElementToForm($option);

            /*
            * Create Input field -> Status
            */
            $arrayvalues = array('Test','Test2');
            $option = array(
                    'FormField' => 'status',
                    'error'     => FALSE,
                    'label'     => 'Status',
                    'class'     => FALSE,
                    'targetid'  => FALSE,
                    'name'      => 'status',
                    'array'     => $arrayvalues,
                    'value'     => FALSE,
                    'required'  => TRUE
                );
            // Build Element
            $entireForm .= $this->addElementToForm($option);

        return $entireForm;

    }

    function viewLeadStagesMarkup($title,$action,$return) {

        $Form = $this->makeEntireForm();

        $HTML____ = NULL;

        $HTML____ .= '<form class="form-horizontal" action="'. $action .'" method="post">' .
                     '
' .
                     '
' .
                     '
'. $title .'
' .
                     '
' .
                     '
' .
                     '
WARNING: Page under maintenance. Please do not use. Hit cancel and go back.
' .
                     '
' .
                     '
' .
                     $Form .
                     '
' .
                     '
' .
                     '
' .
                     '
' .
                     'Cancel ' .
                     '
' .
                     '<button type="submit" class="btn btn-sm btn-success">Create</button>' .
                     '
' .
                     '
' .
                     '
' .
                     '</form>';

        return $HTML____;
    }

}

I have double checked my array values and everything looks spot on? Can someone maybe get a second set of eyes on it and see what they think?
Let me know if you need explanation or need to see any functions that are not listed.
errors are populating from code section
// Input Field -> Stage
function addInputError_New_Element($option) {
    var_dump($option);
    $element = $this->FormFields->InputError_NEW(
        $Error = $option['error'],
        $Value = $option['value'],
        $PlaceHolder = $option['placeholder'],
        $InputName = $option['name'],
        $InputID = $option['id'],
        $InputType = $option['type'],
        $InputLabel = $option['label'],
        $MaxChar = $option['maxchar'],
        $required = $option['required']
    );
    return $element;
}

result from var_dump($option);
array(10) { ["FormField"]=> string(5) "stage" ["error"]=> bool(false) ["value"]=> bool(false) ["placeholder"]=> string(31) "Stage (ie; Scheduled Inspection" ["name"]=> string(5) "stage" ["id"]=> bool(false) ["type"]=> string(4) "text" ["label"]=> string(5) "Stage" ["maxchar"]=> int(50) ["required"]=> bool(true) } array(9) { ["FormField"]=> string(5) "stage" ["error"]=> bool(false) ["label"]=> string(6) "Status" ["class"]=> bool(false) ["targetid"]=> bool(false) ["name"]=> string(6) "status" ["array"]=> array(2) { [0]=> string(4) "Test" [1]=> string(5) "Test2" } ["value"]=> bool(false) ["required"]=> bool(true) }

FormFields Class Functions i am using.
function InputError_NEW($Error, $Value, $PlaceHolder, $InputName, $InputID, $InputType, $InputLabel, $MaxChar,$required) {
        $output = '
';
        if (!empty($Error)) {
                $output .='

                        '.$Error.'

                ';
        }
        $output .='' . $InputLabel . '' .
                '
' .
                '<input class="form-control"';
                    if (!empty($InputID)) {
                        $output .= ' id="' . $InputID . '"';
                    }
                    if (!empty($InputName)) {
                        $output .= ' name="' . $InputName . '"';
                    }
                    if (!empty($InputType)) {
                        $output .= ' type="' . $InputType . '"';
                    }
                    if (!empty($PlaceHolder)) {
                        $output .= ' placeholder="' . $PlaceHolder . '"';
                    }
                    if (!empty($Value)) {
                        $output .= ' value="' . $Value . '"';
                    }
                    if (!empty($MaxChar)) {
                        $output .=' maxlength="'. $MaxChar . '"';
                    }
                    if ($required) {
                        $output .= ' required';
                    }
                    $output .= '>' .
                '
' .
                '
';
        return $output;   // you will have to echo ($output); in the HTML file
    }

    function SelectError_NEW($Error, $InputLabel, $Class, $DataTargetDIVID, $SelectName, $SelectArray, $Value) {
        $output = '
';
        if (!empty($Error)) {
                $output .='

                        '.$Error.'

                ';
        }
        $output .='' . $InputLabel . '' .
                '
' .
                '<select class="form-control ' . $Class . '" data-target="' . $DataTargetDIVID .'" name="' . $SelectName .'"';
                if ($required) {
                $output .= ' required';
                }
                $output .='>
                    <option value="">-- Select One --</option>
                    '.makeOptions($SelectArray, $Value).'
                </select>' .
                '
' .
                '
';
        return $output;   // you will have to echo ($output); in the HTML file
    }

A: I meant this (sorry if you did not understand the comments)
class LeadStage {
    private $my_object;
    function __construct() {
        $this->my_object = new FormFields();
    }

    // Input Field -> Stage
    function addInputError_New_Element($option) {
        //$FormFields = new FormFields();
        $element = $this->my_object->InputError_NEW(
    //...............
    //.................

Similarly everywhere do same. To point a variable use $this keyword you should have that variable in your class.

A: The Method below was intended to do a quick validation of the input field to create. This posed an issue, and ultimately deprecated this method.
function addElementToForm($option) {
        if($option['FormField'] = 'stage') {

            // Build our Markup to input our new stage.
            $element = $this->addInputError_New_Element($option);

        }
        if($option['FormField'] = 'status') {
            // Build our Markup for selecting our status.
            $element = $this->addSelectNoBlank_New_Element($option);

        }

        return $element;

    }

When I was creating the makeEntireForm() method I was creating a
$entireForm .= $this->addElementToForm($stage_option);

which I changed to the following.
$entireForm .= $this->addInputError_New_Element($stage_option);

by removing this "middle man method" I was able to accomplish my end results.


text:
Q: Reduce gap between Report Footer and Page Footer There is a sizable gap between report footer and page footer. How can I reduce the blank space?

A: In the section expert, you'll note that the Page Footer has Print at Bottom of Page checked, and is grayed out. A page footer will always print at the bottom of the page.
If you want to move the Report Footer down you can check Print at Bottom of Page for both of them.
If you want to move the Page Footer up it's a little trickier. You might get by with suppressing the Page Footer on the last page only, and displaying a duplicate section at the end of the report (if there's more than one page.) This should handle both large and small page counts.


text:
Q: How to do I return an item from a custom event handler A project I'm working on requires me to be able to fire off an event everytime an item is added to a list. To achieve this, I created a custom List class inheriting from List and added a OnAdd event. I also want to return the item being added as EventArgs for which I added some more code (given below):
    public class ClientListObservable<Client>:List<Client>
    {
        public event EventHandler<EventArgs<Client>> OnAdd;

        public void Add(Client item)
        {
            if (null != OnAdd)
            {
                OnAdd(this, new EventArgs<Client>(item));
            }

            base.Add(item);
        }
    }

    public class EventArgs<Client> : EventArgs
    {
        public EventArgs(Client value)
        {
            m_value = value;
        }

        private Client m_value;

        public Client Value
        {
            get { return m_value; }
        }
    }

This is how I add a handler
clientList.OnAdd += new EventHandler<EventArgs<Client>>(clientList_OnAdd);

But, in the OnAdd method:
private void clientList_OnAdd(object sender, EventArgs e)
        {
            //want to be able to access the data members of the Client object added
        }

I can only access e.Equals, e.GetHashCode, e.GetType and e.ToString, and none of the members of Client class.

A: Change your event args  to:
public class ClientEventArgs : EventArgs
{
    public ClientEventArgs(Client value)
    {
        m_value = value;
    }

    private Client m_value;

    public Client Value
    {
        get { return m_value; }
    }
}

Then:
    private void clientList_OnAdd(object sender, ClientEventArgs e)
    {
        Client client = e.Value;
    }

A: Shouldn't your event handler be declared like this:
private void clientList_OnAdd(object sender, EventArgs<Client> e)

?

A: you should derive your custom class from EventArgs and have a member to host your custom objects in there, then you should invoke the event passing such specialized EventArgs which you would have created and initialized as needed.

A: Create your own event args that extends EventArgs and has a public property of a "Client" object. Then on add populate the custom EventArgs with the new item and return it.


text:
Q: Choosing random strings from an array in Java Using ten random numbers placed in an array, I want to pick ten random strings from another array, but I'm getting ArrayIndexOutOfBoundsException.
int[] RandomArray = new int[10]; // this is an array of random numbers between 0 and 21

String[] StringArray = new String[22]; //This array has 22 diffrent sentences and gets them from the string.xml

String[] ResultStringArray = new String[10]; //This array shall have now the 10 randomly picked sentences

for (int i = 0; i < ResultStringArray.length; i++) {
    ResultStringArray[i] = StringArray[ResultArray[i]];
}

What is the problem with the provided code?

A: Try this code instead:
int N=10;
int[] randomArray = new int[N]; // this is an array of random numbers between 0 and 21

String[] stringArray = new String[22]; //This array has 22 diffrent sentences and gets them from the string.xml

String[] resultStringArray = new String[N]; //This array shall have now the 10 randomly picked sentences

for (int i = 0; i < resultStringArray.length; i++) {
    // Pick the stringArray index from randomArray and not from resultArray
    resultStringArray[i] = stringArray[randomArray[i]];
}


text:
Q: How can I query a ScalarListType in flask_sqlalchemy I want to insert an integer list as a one column datatype in flask_sqlalchemy,
and I found ScalarListType in the package SQLAlchemy-Utils:
from sqlalchemy_utils import ScalarListType

class Foo():
    id = db.Column(db.Integer, primary_key=True)
    list = db.Column(ScalarListType(int))

I can query for foo by id:
foo = Foo.query.filter(Foo.id==1).first()

Then, foo.list is an integer list like [0, 0, 1, 0]
But, how can I build a query for an index in the list? E.g. something like Foo.list[3]==1
I can't find any clue, help me please!

A: I'm not sure a ScalarListType will be able to accomplish what you want -- it doesn't look like it's built to be queried by index. See the source code here -- it's just a text column with commas separating the values.
You might be able to hack something together with bare SQL, but it would probably mean using LIKE somewhere, or splitting strings which gets complicated quickly.
In the long run, you might be better off just making a separate columns for this data.


text:
Q: How to wrap subsection items in slide headline in beamer? My navigation bar is divided into 2 parts, which I have sections in one part and subsections in the other part. The number of sections and subsections is too much to fit in one line. I want them to be wrapped. I found the following code in a question answered some years ago, but it is written for wrapping sections. What change should I make on the code so that it works for subsections too?
Here is the code:
\makeatletter
\def\insertsectionnavigationhorizontal#1#2#3{%
 \hbox to #1{{%
   \def\slideentry##1##2##3##4##5##6{}%
   #2\hskip.3cm%
   \newdimen\tmp@parbox%
   \setlength\tmp@parbox{#1}%
   \addtolength\tmp@parbox{-.6cm}%
   \parbox{\tmp@parbox}{\raggedleft%
     \usebeamerfont{section in head/foot}\usebeamercolor[fg]{section in head/foot}%
     \setbox\beamer@sectionbox=\hbox{}%
     \ht\beamer@sectionbox=1.875ex%
     \dp\beamer@sectionbox=0.75ex%
     \hskip-1.875ex plus-1fill\dohead%
     \box\beamer@sectionbox}\hfil\hskip.3cm%
     #3}}}
\makeatother


text:
Q: XML serializing Enum type properties I'm trying to XML serialize a class containing a enum property.  If the property is declared using a specific enum, it works just fine.  But I need the property to be of type Enum, so I can set it to different enum types.  However, when doing this I get an exception.

The type [namespace].Simple may not be used in this context.

I've tried different attributes on the enum definition, but haven't gotten it right so far.  Is there a way to do this?
public enum Simple : byte
{
    one = 0x01,
    two = 0x02,
    three = 0x03
}

public class Foo
{
    public Enum Simple { get; set; }
}

public class Program
{
    static void Main(string[] args)
    {
        using (var writer = XmlWriter.Create(Console.OpenStandardOutput()))
        {
            try
            {
                var foo = new Foo
                {
                    Simple = Simple.three
                };
                var serializer = new XmlSerializer(foo.GetType());
                serializer.Serialize(writer, foo);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        Console.ReadLine();
    }
}

A: Enum is abstract and cannot be serialized. A possible approach to solve is presented in this answer.
The common primitive base type of enum is int (by default, can also be byte or long for instance).
So you could as well simply use this integer base type instead, like byte Simple in your Foo class.
In case you need the string representation to appear in xml (identical to the enum field name), expose it as string Simple.

A: You can try to set EnumMember attrubute on your DataContract that you want to serialize, for more specific info visit
https://msdn.microsoft.com/en-us/library/system.runtime.serialization.enummemberattribute(v=vs.110).aspx

A: Based on dlatikay's idea about splitting the enum into two strings for enum type and member name, I've come up with the following solution.  The example converts to from a Foo object to XML string, and back to a new Foo object again.
public enum SimpleEnum : byte
{
    one = 0x01,
    two = 0x02,
    three = 0x03
}

public class Foo
{
    private Enum _simple;
    [XmlIgnore]
    public Enum Simple
    {
        get { return _simple; }
        set {
            _simple = value;
            var type = Simple.GetType();
            var underlyingType = Enum.GetUnderlyingType(type);
            EnumType = Simple.GetType().FullName;
            EnumMember = Simple.ToString();
        }
    }

    private string _enumType;
    public string EnumType
    {
        get { return _enumType; }
        set { _enumType = value; }
    }

    private string _enumMember;
    public string EnumMember
    {
        get { return _enumMember; }
        set {
            _enumMember = value;
            _simple = (Enum)Enum.Parse(Type.GetType(EnumType), EnumMember);
        }
    }
}

public class Program
{
    static void Main(string[] args)
    {
        var str = new StringBuilder();
        using (var writer = XmlWriter.Create(str))
        {
            try
            {
                var foo = new Foo
                {
                    Simple = SimpleEnum.three
                };
                var serializer = new XmlSerializer(typeof(Foo));
                serializer.Serialize(writer, foo);
                Console.WriteLine(str.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        using (TextReader reader = new StringReader(str.ToString()))
        {
            try
            {
                var serializer = new XmlSerializer(typeof(Foo));
                var foo = (Foo)serializer.Deserialize(reader);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        Console.ReadLine();
    }
}


text:
Q: 404 error when I refresh page from browser in my single page application I got the 404 Exception when I refresh the page from a browser in my single page application. I am using the Spring and Hibernate and I want to reload the same page by hitting refresh.

A: Routing using javascript will make use of History API Pushstate, it will be seen as if you have been routed to a another page, but when you refresh the page, it is only the client which knows the routes and server wouldn't even recognize these routes so it signals a 404.
When you are using a client side routing, considering for example index.html is your entry point for the application, all the server routes need to hit only index.html inorder to avoid 404.
I strongly recommend using an API and a client code, integration of both will actually mislead when you are redirecting all requests to index.html


text:
Q: Duplicate Localized Resource Files I have an app that is intended to be localized into 5 languages via Localizable.strings files. When I view the Project > Info: Localizations information, I see duplicates of some languages (English, French, German) and an unintended language (Japanese).

My Resources in XCode, also appear off. But if I look at the Resources directory in Finder, they appear as I would expect.

I have tried:

*

*Delete one of the duplicate files, via the - button, both lines disappear and the resource is gone from my Resource tree in XCode and my Resources directory in Finder.

*Product > Clean Build Folder

*Viewing subversion file structure in Versions

I'd appreciate any suggestions and an explanation. I'm using XCode 6.1.1 on Mavericks. Thank you.

A: I was running in the same issue and it was fixed by manually editing the project.pbxproj file inside the .xcodeproj Xcode project file container.
Before:
...
knownRegions = (
    English,
    German,
    en,
    de,
    Base,
);
...

After:
...
knownRegions = (
    en,
    de,
    Base,
);
...


text:
Q: How can I make Firefox open magnet-links in Transmission? I can't find out how to make Firefox open magnet-links in Transmission.
There is no option to make it the standard program for magnet-links in its properties, and as I am not experienced with the filesystem so I can't add it as the standard program in Firefox either.

A: Open up Firefox and its preferences window.  Go to the "Applications" tab and you should see "magnet" on the list.  Click on "Always ask" and if Transmission does not appear as an option then click on  "Use other" and navigate to /usr/bin on your file system.  Look for "transmission" or "transmission-gtk" and click that.
Update: Firefox has changed so the above no longer works.  Instead, when you click on a magnet link, a "Launch Application" window will appear, from which you can choose to always associate an application (make sure to check the checkbox at the bottom to always use the chosen app).  To find the torrent app, choose "file system" on the left side, and then navigate to /usr/bin as described above.

A: How to set default apps in Chromium / Chrome / Firefox / Ubuntu Linux
Situation: You hate the default app that opens when you double click a file or when you open it with chromium browser and you want to change it.

*

*In Unity (and probably Gnome 3 Shell), some default apps can be changed through gnome-control-center: System settings > System info > Default applications

*You can also right-click on a file > select Properties > Open with. See what applications/programs are listed there. You can also add them and set them as default.

*If none of the above work, you can use xdg-utils (xdg-mime) to set a default application for a specific Mime Type
First, you have to figure out what text string to use as a "mime type". An easy way to find it is to look into the default application's desktop file.
Example: Chromium opens magnet links and bittorrent files with transmission-gtk by default. You want to use deluge. The .desktop files are usually in folder /usr/share/applications/. We use the cat command to look into the file /usr/share/applications/transmission-gtk (a line that starts with "MimeType"):
$ grep 'MimeType' /usr/share/applications/transmission-gtk.desktop
MimeType=application/x-bittorrent;x-scheme-handler/magnet;

Bingo! x-scheme-handler/magnet and application/x-bittorrent are the mime types we're after.
How to use the xdg-mime command? Simple: xdg-mime default myapp.desktop mymimetype
..where we substitute myapp.desktop and mymimetype with the values from above.
Following the example above, we want magnet links and bittorrent files to open with Deluge (deluge-gtk) application. First you have to install the deluge-gtk package (otherwise the .desktop file won't exist). Then you have to execute:
xdg-mime default deluge.desktop x-scheme-handler/magnet
xdg-mime default deluge.desktop application/x-bittorrent
grep -i deluge ~/.local/share/applications/*

The last command (grep) should return "application/x-bittorrent=deluge.desktop" and the other mime type for magnet. Otherwise, something went wrong (maybe the desktop file didn't exist?).
And that's about it! Close and open chromium-browser again (or logout/login).
For the sake of documentation, the files that have to do with mime types and default apps are:
~/.local/share/applications/defaults.list
~/.local/share/applications/mimeapps.list
~/.local/share/applications/mimeinfo.cache
/usr/share/applications/mimeinfo.cache
/usr/share/applications/mimeapps.list
/usr/share/applications/defaults.list

A: I tried a couple of approaches and the only on that worked for me is described here: https://support.mozilla.org/en-US/questions/1012864#answer-609391
All you have to do is to open about:config in Firefox, and add boolean value network.protocol-handler.expose.magnet with value false. The next time you click on a magnet link, you'll be prompted to choose your favorite application to open the link.
I'm using Ubuntu 17.10 and Firefox 56

A: For me, with transmission-daemon the solution was the following (according to this documentation).

*

*Create an executable file /usr/local/bin/magnet with these commands:
sudo tee /usr/local/bin/magnet >/dev/null <<EOF
#!/bin/sh
exec transmission-remote -n yourTransmissionUserName:YourTransmissionPassword --add "$1"
EOF
sudo chmod +x /usr/local/bin/magnet

*Then go to Firefox preferences (Alt + E + N) and select it after finding the magnet file type on the Applications tab:

A: For a solution that worked for me:
https://support.mozilla.org/en-US/questions/965921
"Click on the help menu and select "Restart with Add-ons Disabled" and then select the reset option in the dialog box."
Follow the on-screen prompts. Then restart Firefox.
When you click on a magnet link the usual "Choose a program" type of dialog box appears. Browse for /usr/bin/transmission-gtk
Works in Ubuntu 13.04

A: If you use Transmission for torrents the only thing you must do is when the window opens and ask you with which program you want that Firefox open magnet links with, you drag & drop the transmission icon from your side bar in the Firefox dialog box and that's all. I have Ubuntu 14.04 (Trusty Tahr), and it works fine.


text:
Q: python: comparing list of tuple Just wondering the following:
print [()] == list(tuple()) # prints False

The first is a list containing an empty tuple, the second is an empty list.
Why this code prints False instead of True (same result in python 2 and 3)?
Thanks in advance!

A: You compared a list with one element (an empty tuple) with an empty list. list(tuple()) does not do what you think it does.
That's because list(object) does not produce a list with that one object as an element. list() converts the object, which must be iterable, to a list. It copies the elements out of the object:
>>> dictionary = {'foo': 'bar'}
>>> list(dictionary)  # iteration over a dictionary produces keys
['foo']

You gave it an empty tuple, so the result is an empty list:
>>> empty = ()
>>> list(empty)
[]

tuple() does the same thing, by the way. And both list() and tuple() without an argument produce an empty object.


text:
Q: Separate internet router from LAN wifi I have a Linksys WRT54GL router running Tomato that I've been happy with for quite a while. I just purchased a TP-Link WDR3600 a/b/g/n + 4-port Gigabit ethernet router for better LAN throughput, and while it seems like a great performer so far, I'm quite disappointed with the factory firmware. Worse, even though it's advertized as "DD-WRT ready" it doesn't look like it's currently supported by any of the major open firmwares.
So I'm thinking about keeping the Linksys as my internet router, turning off its wifi, and using the TP-Link only for wifi connectivity. My reasoning is that my internet is only 10Mbps max anyway (which is fine for me), so the 100Mbps bottleneck shouldn't make a difference, right?
Are there any other pitfalls to this technique I'm not considering? I have a decent grasp on networking but am not familiar with "real-world" ramifications such as latency etc. FWIW I would then move the cable modem and Linksys physically farther from the TP-Link to keep them out of the way.
As far as setup, as long as the Linksys is still set as the DHCP server and gateway, and I turn off all routing features on the TP-Link, I can just connect the latter to one of the LAN ports on the former right? Then any wireless clients will just contact the Linksys to get their DHCP lease?

A: Just in case anyone comes across a similar situation, I tried this out and was indeed able to get it working as desired. Haven't noticed any slowdown so far. I should specify that I connected the two routers from one LAN port to another, through a gigabit switch I already had, though I probably could have used a crossover cable to link them directly.


text:
Q: How to make sqlite in-memory db join query as fast as MySQL I have a very complex sql query - the logic is simple, but I need to join 17 tables (each as 10-20 fields and 100 to 1 million records) so there're a lot of (LEFT) JOINs and WHERE clauses.
SELECT table1.column_A
       table2.column_B
       table3.column_C
       table4.column_D
       ....
FROM table1
LEFT JOIN table2 ON table1.column_a = table2.column_b
JOIN table3 ON table3.column_c = table1.column_d
LEFT JOIN table4.column_e = table3.column_f
    AND LENGTH(table4.column_g) > 6 AND (table4.column_h IN (123,234))
LEFT JOIN ....
....
WHERE table1.column_i = 21
    AND (table1.column_j IS NULL OR DATE(table1.column_k) <> DATE(table1.column_l))

The above query only takes 5 seconds to run in MySQL. But when I run it in sqlite in-memory db (using Perl on Linux), it takes about 20 min. This is still acceptable.
When I add a ORDER BY clause (I do need this), the execution time increases dramatically.
ORDER BY table1.column_m, table6.column_n, table7.column_o IS NULL;

It'll take 40 seconds in MySQL. In sqlite in-memory db (using Perl on Linux), I waited for over an hour, but it still didn't finish.
What kind of tuning do I need to do to make the query faster? My threshold is within 1 hour.
The reason I'm making it an in-memory db is that I receive SQL generated normalized data but we need to load data into a non-SQL db in the end, so I don't want to create a intermediate SQL db just for data loading - that makes the code ugly and increases maintenance complexity. Plus, the current timing issue I'm facing is just a one-time thing. In the future on a daily basis, the data volume we receive will be much much smaller (less than 1% of what I have today)
Thanks in advance for your help!!

A: Your ORDER BY clause is on columns from 3 different tables.  No amount of query optimization or index creation is going to change the fact that the DBMS must do an external sort, after (or as) the result set is produced.  If you've constrained the amount of memory that SQLite can use (I'm not a SQLite expert, but I assume this is at least possible, if not required), then that could be the cause (e.g. it's going through some incredible machinations to get the job done within its limits).  Or it's just hung.  What's the CPU utilization for that hour you were waiting?  What about I/O (is it thrashing because there was no limit on the amount of memory SQLite can use, as Sinan alluded to)?

A: To make your query faster , you need to do some changes in one of the following :

*

*method of writing query

*Database table structure

*making proper indexes

And all this you can find at http://www.perlmonks.org/?node_id=273952


text:
Q: springboot consumer wont consume any messages I have a springboot consumer app. When I ran it the first time, it was consuming messages from the Kafka topic. But when I ran it again, it stopped consuming. In the logs I see the following message.
2022-08-02 00:14:08.130  INFO 96561 --- [ntainer#0-0-C-1] o.a.k.c.consumer.internals.Fetcher       : [Consumer clientId=consumer-my-transformation-local-1, groupId=my-transformation-local] Fetch position FetchPosition{offset=17400, offsetEpoch=Optional.empty, currentLeader=LeaderAndEpoch{leader=Optional[localhost:9092 (id: 1 rack: null)], epoch=0}} is out of range for partition CraveVideoTestLog-0, resetting offset
2022-08-02 00:14:08.135  INFO 96561 --- [ntainer#0-0-C-1] o.a.k.c.c.internals.SubscriptionState    : [Consumer clientId=consumer-my-transformation-local-1, groupId=my-transformation-local] Resetting offset for partition CraveVideoTestLog-0 to position FetchPosition{offset=56464, offsetEpoch=Optional.empty, currentLeader=LeaderAndEpoch{leader=Optional[localhost:9092 (id: 1 rack: null)], epoch=0}}.

I understand that the consumer could not get the offset. In situations like this, the consumer will refer to auto-offset-reset property. As you can see, I have set it to earliest, hoping that the consumer would read from the beginning. But it does not.
application.yml
spring:
  application:
    name: my-transformation
  kafka:
    bootstrap-servers: ${BOOTSTRAP_SERVERS:localhost:9092}
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: io.confluent.kafka.serializers.KafkaAvroSerializer
      retries: 2
      compression-type: snappy
    consumer:
      group-id: ${GROUP_ID:my-transformation}
      auto-offset-reset: earliest
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

In my Java class
    @SendTo("output-topic-here")
    @KafkaListener(topics = "${my-transformation.input.topic}", errorHandler = "myErrorHandler")
    public Message<?> process(Message<String> in, ConsumerRecord<String, String> record) throws Exception {
        log.info("Going to process event for key: {} offset: {} partition: {}", record.key(), record.offset(), record.partition());
    }

I tried out a few of things.

*

*I set the auto-offset-reset value to none. As expected, it threw an exception complaining about the offset.

*I created a new consumer group. I could see that the new consumer group was created from the confluent UI. But, again, the messages were not consumed.

*I read through a lot of posts. Here are a few that are very close to the issue I am facing. Link 1 Link 2
I feel I am missing something really silly, but could not figure out what it is.

A: The auto.offset.reset property will work in the following ways.
Use Case 1:
A consumer starts and has auto.offset.reset=latest, and the topic partition currently has data for offsets going from some range to other. The consumer group has committed the some offset for the topic before. Where will the consumer read from?
Ans : The offsets are already committed for this consumer group and topic partition, so the property auto.offset.reset is ignored
Use Case 2:
A consumer starts and has auto.offset.reset=none, and the topic partition currently has data for offsets going from some range to other. The consumer group has committed some offsets for the topic before. Where will the consumer read from?
Ans: auto.offset.reset=none means that the consumer will crash if the offsets it's recovering from have been deleted from Kafka.
Use Case 3:
A consumer has auto.offset.reset=latest, and the topic partition currently has data for offsets going from some range to other. The consumer group never committed offsets for the topic before. Where will the consumer read from?
Ans: Latest means that data retrievals will start from where the offsets currently end.
Use Case 4:
A consumer has auto.offset.reset=earliest, and the topic partition currently has data for offsets going from some range to other. The consumer group never committed offsets for the topic before. Where will the consumer read from?
Ans: Earliest means that data retrievals will start from beginning of the partition
Use Case 5:
A consumer starts and has auto.offset.reset=earliest, and the topic partition currently has data for offsets going from some range to other. The consumer group has committed the some offset for the topic before. Where will the consumer read from?
Ans : The offsets are already committed for this consumer group and topic partition, so the property auto.offset.reset is ignored

A: Finally, I found out the reason for my consumer's behaviour. The topic's retention policy was set to delete and retention time was set to default(1 week).
The reason why the consumer stopped consuming records was because the topic's retention time had elapsed. So the entire data in the topic was deleted and hence the consumer had nothing to read. When I pushed new records into the topic again, the consumer started consuming.


text:
Q: (JAVA) Google API analytics - unable to obtain new "access token" using "refresh token" I want to obtain a new "access token" based on the "refresh token" saved in database.
Here is the code I wrote:
GoogleCredential.Builder credentialBuilder = new GoogleCredential.Builder()
        .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
        .setClientSecrets(CLIENT_ID, CLIENT_SECRET);
credentialBuilder.addRefreshListener(new MyCredentialRefreshListener());

credential = credentialBuilder.build();
credential.setRefreshToken("saved_refresh_token_from_database");

try {
    credential.refreshToken();
} catch (IOException e) {
    e.printStackTrace();
}

class MyCredentialRefreshListener implements CredentialRefreshListener {
    public void onTokenResponse(Credential cr, TokenResponse tr) {
       System.out.println("Credential was refreshed successfully.");
    }

    public void onTokenErrorResponse(Credential cr, TokenErrorResponse tr) {
        System.out.println(tr);
    }
 }

I get this message:

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad
Request {   "error" : "invalid_grant" }

I use the same CLIENT_ID, CLIENT_SECRET and "refresh token" in a php script and there I managed to get the new "access token" using "refresh token" when "access token" expired.
I wrote the code based on javadoc.google-oauth-java-client.
Any person here knows how to modify the code to obtain the new access token ?
Thanks in advance.
UPDATE: the problem was that I was saving in the database the refresh_token without doing a json_decode on it and it contained a "\" which is considered escaped character in JSON.

A: It looks like you may have found some out of date documentation. The JavaDoc you link is for version 1.8 of the client library. The current version is 1.12.
The client library authors recommend that you use GoogleAuthorizationCodeFlow to manage your OAuth credentials. It takes care of refreshes automatically. If you follow this path, the code will look something like this:
// Create the flow
AuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
    new UrlFetchTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET,
    Collections.singleton(OAUTH_SCOPES))
    .setAccessType("offline")
    .setCredentialStore(new AppEngineCredentialStore())
    .build();

// User Id: e.g. from session
Credential credential = authorizationCodeFlow.loadCredential(USER_ID);

// Make your API call. This example uses the Google+ API
// If the access token has expired, it will automatically refresh
Plus plus = new Plus(new UrlFetchTransport(), new JacksonFactory(), credential)
  .activities().list("me", "public").execute();

A: if you get http status 400, and message "invalid_grant".
I think you should check your instance of HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET.


text:
Q: Issue with @EnableCircuitBreaker annotation when running springboot service in local environment when using @EnableCircuitBreaker annotation with spring-cloud-services-dependencies 1.3.0 we are getting

"Caused by: java.lang.NoSuchMethodError:
  org.springframework.integration.amqp.support.DefaultAmqpHeaderMapper.outboundMapper()Lorg/springframework/integration/amqp/support/DefaultAmqpHeaderMapper;"
  exception. We are not using any Messaging functionality in our
  service.

We are using jetty embedded environment.
Can anyone suggest me how can I solve my issue?

A: The exception is thrown, cause your application tries to use some classes of spring integration for message queue, which cannot be found.
If you go further up the stacktrace you may find some classes with 'AutoConfiguration' that may show, which spring auto configuration has triggered the search for these missing classes.
You can also add the command line parameter --debug to see what auto config is actually doing.
Once you identified the culprit you can exclude it from the auto configuration like this :
@EnableAutoConfiguration(exclude = {...})


text:
Q: Sync Core Data to web server I developed an application which has a Core Data, now I am thinking to Synchronize it to my own server. and this is the first time I am doing it, I searched google a lot also StackOverflow but I couldn't find a clear approach to work on.
I have created the same core data on the server, but I don't know how to know if some row has been synced or not (how to arrange connection between the server and the Client), should I add another column to the core data as boolean to tell me the sync status?!! or by adding a timestamp?!!.. so please if anyone can help me with that or know how to do it, tell me!!
I need help with logic. and I am using REST API (POST,GET) methods.
Thanks.

A: You could take a look at using RestKit to help you with the communication with the server.
Yes, you will want to add some additional data to allow you to determine if the data has been edited since it was last synched with the server. A BOOL should be sufficient for this, just set it when any other attribute is changed (you can use KVO to assist with this).
You will need to create and control the logic for which updates are sent back to the server and when. If you post the individual object then RestKit could respond and automatically set the BOOL back to false for you (but whether you want to do that depends very much on how many objects are changing, how often and how big they are - you don't want to make lots of frequent small updates to the server).

A: Recently I blogged about syncing (sync algorithm for exchanging data in the "Client – Server" model via REST API). It might help you to get some ideas with building the sync logic for your specific requirements.

A: I have done this recently in one of my apps. In brief, what you should know is that your "Attributes" of the entities should be treated as separate columns where in the table name can be same as the "Entity Name". After that if you need to sync the data, it can be done by setting the data in the header of the API which can be retrieved on the server side.
e.g: Suppose there is an entity named PlaylistData with attributes playlist_name and songs in it. Same is the column name on server side. Now you want to save these on the server.
First you save your data in a playlistNameArray and songs in songArray.
After that -
NSString *api = [NSString stringWithFormat:SAVE_PLAYLIST_API,id1];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:api] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

[request setHTTPMethod:@"POST"];

NSMutableDictionary *requestDict = [NSMutableDictionary dictionary];

[requestDict setObject:self.playlistName forKey:@"playlist_name"];
[requestDict setObject:songIdArray forKey:@"songs"];

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestDict
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];
NSString *jsonStr =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:jsonData];

id response = nil;
NSError *error1 = nil;
NSData *recievedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error1];

NSString *dataReceived =[[NSString alloc] initWithData:recievedData encoding:NSUTF8StringEncoding];

NSError *error2 = nil;

// You can see the "recievedData" to review the response from server.

A: Have a look at these resources:
http://iphone2009.crowdvine.com/talk/presentation_file/5104/Grover_Syncing.pdf
http://www.raywenderlich.com/15916/how-to-synchronize-core-data-with-a-web-service-part-1


text:
Q: Get the array of items. Use CCMenu::createWithArray please help me, im a beginner in cocos2d-x.
i have the list of items.
how can i do this using array of items, using CCMenu::createWithArray to show this list at the end?
i want to control the menu array, to add/drop items from array(from my list menu).
here is the code:
``
    ...
CCLabelTTF* pp0BtnLabel = CCLabelTTF::create( string(ItemName[0]).c_str(), "Arial", TITLE_FONT_SIZE);
CCMenuItemLabel *pp0Item = CCMenuItemLabel::create(
            pp0BtnLabel,
            this,
            menu_selector(Window::CheckItemCallback));
pp0Item->setTag(ItemTag[0]);
CC_BREAK_IF(! pp0Item);
pp0Item->setPosition(ccp(size.width*0.3f, size.height*0.8));

CCLabelTTF* pp1BtnLabel = CCLabelTTF::create( string(ItemName[0]).c_str(), "Arial", TITLE_FONT_SIZE);
CCMenuItemLabel *pp1Item = CCMenuItemLabel::create(
            pp1BtnLabel,
            this,
            menu_selector(Window::CheckItemCallback));
pp1Item->setTag(ItemTag[0]);
CC_BREAK_IF(! pp1Item);
pp1Item->setPosition(ccp(size.width*0.3f, size.height*0.75));

CCLabelTTF* pp2BtnLabel = CCLabelTTF::create( string(ItemName[0]).c_str(), "Arial", TITLE_FONT_SIZE);
CCMenuItemLabel *pp2Item = CCMenuItemLabel::create(
            pp2BtnLabel,
            this,
            menu_selector(Window::CheckItemCallback));
pp2Item->setTag(ItemTag[0]);
CC_BREAK_IF(! pp2Item);
pp2Item->setPosition(ccp(size.width*0.3f, size.height*0.7));

CCMenu* pMenuChapter = CCMenu::create(pp0Item, pp1Item, pp2Item, NULL);
pMenuChapter->setPosition(CCPointZero);
CC_BREAK_IF(! pMenuChapter);

this->addChild(pMenuChapter, 1);

            ...

``

A: I'm not sure to understand your question... but here is how you can create a CCMenu using a CCArray.
CCLabelTTF*label = CCLabelTTF::create("label text", "Arial", 32);

CCMenuItemLabel *item1 = CCMenuItemLabel::create(label, this, menu_selector(CPhysicsLayer::itemCallback));
CCMenuItemLabel *item2 = CCMenuItemLabel::create(label, this, menu_selector(CPhysicsLayer::itemCallback));
CCMenuItemLabel *item3 = CCMenuItemLabel::create(label, this, menu_selector(CPhysicsLayer::itemCallback));

CCArray*array = CCArray::create(item1, item2, item3);
CCMenu*menu = CCMenu::createWithArray(array);

/// Iterate over the menu items
CCObject*obj = NULL;
CCARRAY_FOREACH(array, obj) {
    CCMenuItemLabel*item = (CCMenuItemLabel*)obj;
    /// Do something with the item...
}

To add item to the menu at "run-time" then use the CCMenu::addChild method (and removeChild to remove the item).
Hope it helps.


text:
Q: I want to remove this Login and SignUp link once one of them is been selected in reactjs Here is my APP.JS code and I want to remove this Login and SignUp link once this is being selected to open the components.

  return (

     <Router>
     <Link to="/login">
Login
</Link>
     <Link to="/signup">
SignUp
</Link>
      <Routes>
        <Route exact path="/login" element={<Login/>} />
        <Route path="/signup" element={<SignUp />} />
      </Routes>
    </Router>

  );
}

A: import { useLocation } from 'react-router-dom'

....inside component....
const location = useLocation();

return (

 <Router>
 { location.pathname !== '/login' && location.pathname !== '/signup' ? <>
 <Link to="/login">
Login
</Link>
 <Link to="/signup">
SignUp
</Link>
 </> : null }
  <Routes>
    <Route exact path="/login" element={<Login/>} />
    <Route path="/signup" element={<SignUp />} />
  </Routes>
</Router>

this will do the trick


text:
Q: Dimension of pluripolar sets Let $\Omega$ be an open set in $\mathbb C^n$, and let $A$ be a closed pluripolar set in $\Omega$. Is there a notion of dimension of $A$ such that the following theorem is true?
Theorem.
Let $\phi$ be a plurisubharmonic function on $\Omega \setminus A$ (not necessarly assumed to be  locally bounded above near $A$), and assume that the (real) codimension of $A$ is at least $3$. Then the function $\phi$ extends to a plurisubharmonic function on $\Omega$.
I think I can prove the theorem in case $A$ is complex analytic.


text:
Q: How to search pattern in certain range of text and replace with another string? $ NAME : corry
$$.Inc s d
$$.Oc s
$$.TO

G1 ty n1 EE EE M T1 T2 $$SRU
G2 n1 y OO OO M T3 T4 $$SRU
.EON

$ NAME : patrick
$$.Inc c d
$$.Oc c
$$.TO

G1 td n3 EE EE M T5 T6 $$SRU
G2 n3 y OO OO M T7 T8 $$SRU
.EON

$ NAME : danny

$$.Inc a b
$$.Oc b
$$.TO

@lc1 corry
@lc2 patrick
1 to n0 EE EE M S1 S2 $$SRU
G2 n0 y OO OO M S3 S4 $$SRU
.EON

$ NAME : sandy
$$.Inc m n
$$.Oc n
$$.TO

G1 te n1 EE EE M b1 b2 $$SRU
G2 n1 o OO OO M b3 b4 $$SRU
.EON

$ NAME : manager
$$.Inc o e
$$.Oc e
$$.TO

@lc3 danny
@lc4 sandy
G1o ty n1 EE EE M T1 T2 $$SRU
G2o n1 y OO OO M T3 T4 $$SRU
.EON

How to search for a certain pattern in a certain range? For example, I want to search G1o at range between the section from $ Name : manager until the end of End of name (.EON) and replace it with G1o.corry.n.

A: perl -pe 's/G1o/G1o.corry.n/ if /\$ NAME : manager/ .. /\.EON/' file

From perlop documentation:

In scalar context, ".." returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and various editors. Each ".." operator maintains its own boolean state, even across calls to a subroutine that contains it. It is false as long as its left operand is false.

A: sed '/^\$ NAME : manager/,/\.EON/s/G1o/G1o.corry.n/'


text:
Q: data-binding isn't working I'd like to know what's wrong in common code.
Here it is:
namespace Morse_Mail{

public partial class MainWindow : Window
{

    public ObservableCollection<Message> Messages { get; set; }

    public MainWindow()
    {
        Messages = new ObservableCollection<Message>();

        InitializeComponent();
    }

    // some code here

}

public class Message : INotifyPropertyChanged
{
    private string subject;
    private string date;
    private string sender;
    private string id;

    public string Subject
    {
        get { return subject; }
        set { subject = value; OnPropertyChanged("Subject"); }
    }
    public string Date
    {
        get { return date; }
        set { date = value; OnPropertyChanged("Date"); }
    }
    public string Sender
    {
        get { return sender; }
        set { sender = value; OnPropertyChanged("Sender"); }
    }
    public string ID { get; set; }

    public Message(string _Subject, string _Date, string _Sender, string _ID)
    {
        Subject = _Subject;
        Date = _Date;
        Sender = _Sender;
        ID = _ID;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}}

And i want to bind the listview content to the Messages ObserverableCollection.
Here comes my xaml code:
<Window x:Class="Morse_Mail.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="864.5" Width="1203.5" ResizeMode="NoResize" Title="Morse Mail" WindowStartupLocation="CenterScreen">
<Grid Height="830" VerticalAlignment="Top">
    <ListView x:Name="ListView" HorizontalAlignment="Left" Height="704" Margin="47,39,0,0" VerticalAlignment="Top" Width="600" IsSynchronizedWithCurrentItem="True"
              ItemsSource="{Binding Messages}">
        <ListView.View >
            <GridView AllowsColumnReorder="true">
                <GridViewColumn Width="300" Header="Subject"
                                DisplayMemberBinding="{Binding subject}"/>
                <GridViewColumn Width="150" Header="Date"
                                DisplayMemberBinding="{Binding date}"/>
                <GridViewColumn Width="120" Header="Sender"
                                DisplayMemberBinding="{Binding sender}"/>
                <GridViewColumn Width="20" Header="ID"
                                DisplayMemberBinding="{Binding id}"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

My app works, but if I use the button to add new items to Messages Collection they appear in that Collection, but nothing changes in the window.
Why isn't my data-binding working and how to

A: You do not appear to have set a DataContext. (It needs to be the object holding the property you bind to, here that is the window)


text:
Q: Capturando parâmetro de URL com jQuery Atual estou capturando a URL da seguinte forma:
$(this).attr('href')

Vamos supor que a URL seja: http:/teste.com/login
Como faço para capturar somente o fim: /login

A: Caso queira pegar somente a ultima "string" ('login') voce pode utilizar a propriedade split('/') que ira transformar a URL em um array baseado na '/' utilizada pelo mesmo, e a partir deste, vc pode pegar a ultima posicao deste array.
var URL = 'http://teste.com/login';
var URLArr = URL.split('/'); // ["http:", "teste.com", "login"]
var URLPath = URLArr[URLArr.length -1]; // "login"

Ou,
pode usar o replace
$(this).attr('href').replace(/^.*\/\/[^\/]+/, '');


text:
Q: IllegalArguementException - State Arguement : 5 on BottomSheet I am facing this issue using a BottomSheet with GoogleMap.
When cicked on any marker, I show the BottomSheet.
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            return false;
        }
    });

And I hide it when clicked somewhere on the Map.
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng arg0) {
            // TODO Auto-generated method stub
                mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

        }
    });

But as soon as i click on the map, and expect it to hide, my application crashes with the following error
java.lang.IllegalArgumentException: Illegal state argument: 5
 at android.support.design.widget.BottomSheetBehavior.startSettlingAnimation(BottomSheetBehavior.java:629)
 at android.support.design.widget.BottomSheetBehavior.setState(BottomSheetBehavior.java:552)
 at app.iwiz.windrock.activities.HomeNavigationActivity$3.onMapClick(HomeNavigationActivity.java:278)
 at com.google.android.gms.maps.GoogleMap$23.onMapClick(Unknown Source)
 at com.google.android.gms.maps.internal.zzq$zza.onTransact(Unknown Source)
 at android.os.Binder.transact(Binder.java:507)
 at er.b(:com.google.android.gms.DynamiteModulesB@11975448:20)
 at com.google.android.gms.maps.internal.ay.a(:com.google.android.gms.DynamiteModulesB@11975448:5)
 at com.google.maps.api.android.lib6.gmm6.vector.af.c(:com.google.android.gms.DynamiteModulesB@11975448:212)
 at com.google.maps.api.android.lib6.gmm6.vector.cr.onSingleTapConfirmed(:com.google.android.gms.DynamiteModulesB@11975448:28)
 at com.google.maps.api.android.lib6.impl.gesture.h.onSingleTapConfirmed(:com.google.android.gms.DynamiteModulesB@11975448:124)
 at com.google.maps.api.android.lib6.impl.gesture.d.handleMessage(:com.google.android.gms.DynamiteModulesB@11975448:26)
 at android.os.Handler.dispatchMessage(Handler.java:102)
 at android.os.Looper.loop(Looper.java:154)
 at android.app.ActivityThread.main(ActivityThread.java:6692)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

I have discovered that the state 5 is for the Hidden Behaviour of the BottomSheet, But I am not able to understand why is it crashing and how to fix it.

A: I've encountered the same problem too and I found out that it was because I've set the bottom sheet's hideable bahaviour to false.

SO, Make sure you add app:behavior_hideable="true" attribute to your
  bottom sheet layout

or if you intend to make your bottom sheet not hideable by user itself and only hideable programmatically, simply call bottomSheetBehaviour.setHideable(true) before you hide it like this:
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

    @Override
    public void onMapClick(LatLng arg0) {
         mBottomSheetBehavior.setHideable(true);
         mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

    }
});

A: you should add
if(BottomSheetBehavior.STATE_COLLAPSED){
 mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
}


text:
Q: MySQL - complex query using left join to fetch unassigned resource I have the following fiddle http://sqlfiddle.com/#!2/5c089/2
Here's the schema for the DB tables:
classes:
id
school_id

classes_academic_years:
id
class_id
name
academic_year_id
grade

classes_subjects:
id
class_academic_year_id
subject_id

class_masters:
id
class_academic_year_id
professor_id

professors:
id
school_id
first_name
last_name

professors_subjects:
id
professor_id
subject_id

professors_classes_subjects:
id
professor_id
class_academic_year_id
subject_id

subjects:
id
name
school_id
default

I've got two queries:
select subjects.* from subjects
inner join professors_subjects on professors_subjects.subject_id = subjects.id
where professors_subjects.professor_id = 198;

and
SELECT DISTINCT `subjects`.*
FROM `subjects`
INNER JOIN `classes_subjects` ON classes_subjects.subject_id = subjects.id
INNER JOIN `classes_academic_years` ON classes_academic_years.id = classes_subjects.class_academic_year_id
LEFT JOIN `professors_classes_subjects` ON professors_classes_subjects.class_academic_year_id = classes_subjects.class_academic_year_id and professors_classes_subjects.subject_id = classes_subjects.subject_id
left join `class_masters` on class_masters.class_academic_year_id = classes_academic_years.id
WHERE ((professors_classes_subjects.id is null or professors_classes_subjects.professor_id = 198) and class_masters.professor_id = 198 )
AND (classes_academic_years.academic_year_id = 3)
AND (subjects.default = 0)
ORDER BY `name` asc;

The first one simply fetches all of the subjects assigned to a certain professor (professor_id = 198).
The second one fetches all the subjects assigned to a certain professor (professor_id = 198) to the class that the professor is a class master of, as well as all of the subjects of that class that are unassigned to any other professor. (e.g. professor_id = 198 has assigned the subject_id = 67 for class_id = 426, but there are two more unassigned subjects from that class which have to be fetched).
In the given example, the first query fetches the subjects having IDs 76 and 67, and the second one fetches the subjects having IDs 86, 72 and 67.
Both of these queries work just fine. However, I need a third query which combines these two (e.g. it should fetch subjects having IDs 76, 67, 86 and 72). I would prefer using left joins, thus avoiding the UNION operator.
Do you have any thoughts for the third query?

A: try this:
SELECT DISTINCT `subjects`.*
FROM `subjects`
INNER JOIN `classes_subjects` ON classes_subjects.subject_id = subjects.id
INNER JOIN `classes_academic_years` ON classes_academic_years.id = classes_subjects.class_academic_year_id
LEFT JOIN `professors_classes_subjects` ON professors_classes_subjects.class_academic_year_id = classes_subjects.class_academic_year_id and professors_classes_subjects.subject_id = classes_subjects.subject_id
left join `class_masters` on class_masters.class_academic_year_id = classes_academic_years.id

left join professors_subjects on professors_subjects.subject_id = subjects.id

WHERE (((professors_classes_subjects.id is null or professors_classes_subjects.professor_id = 198) and class_masters.professor_id = 198 )
AND (classes_academic_years.academic_year_id = 3)
AND (subjects.default = 0))

OR professors_subjects.professor_id = 198

ORDER BY `name` asc;

I introduced another left join (to join the table you have in the first query), and added OR logic to the whole WHERE clause.


text:
Q: How to map another server through SQL Server Management Studio I am trying to map another server by giving the  command
EXEC xp_cmdshell
    'NET USE H:\\568.256.8.358\backup_147 1234abc /USER:cranew /PERSISTENT:yes'

I got an error with this:

network path not found

But I am able to map another server manually. Please help me in sorting this out.

A: This is more of a NET USE question than a SSMS/SQL Server question.
NET USE has the syntax:
net use [{DeviceName | *}]
   [\\\\ComputerName\ShareName[\volume]] [{Password | *}]]
   [/user:[DomainName\]UserName] [/user:[DottedDomainName\]UserName]
   [/user: [UserName@DottedDomainName] [/savecred] [/smartcard]
   [{/delete | /persistent:{yes | no}}]

So, I would expect your command to look like this:
EXEC xp_cmdshell
    'NET USE H: \\568.256.8.358\backup_147 1234abc /USER:cranew /PERSISTENT:yes'

A: Don't map network drives and expect them to be there.  Just backup to the network path directly.
Using mapped drives gets tricky fast as you start to make assumptions that the drive letter will be available next time.  What happens when you add another hard drive to the server later and want to use that drive letter?  What happens when Windows disconnects the drive to reclaim the network socket?

A: after restart server must execute command plase solution save command...
Use Master
GO

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
GO

exec xp_cmdshell 'net use  \\ip\xxx pass /user:xxx /persistent:no'

Use Master
GO

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXEC master.dbo.sp_configure 'xp_cmdshell', 0
RECONFIGURE WITH OVERRIDE

A: I want to save my backups on an QNAP NAS.
The net use command was ending in error 1312
Solution for me was to just add a ".\" to the username...
exec xp_cmdshell 'net use  \\192.168.0.2\Folder pass /user:.\Peter /persistent:yes'


text:
Q: Using S3Image from aws-amplify-react-native I am using React Native / Expo to build an app. I have AWS S3 set up, as well as cognito with user sign in using withAuthenticator. I have got image uploading working fine, but when I try to display the images it just does not work. Here is the code I am using:
const ImageList = ({
  imageId,
  getImages,
  images = [],
}) => {
  useEffect(() => {
    getImages(imageId);
  }, []);

  return (
    <View>
      <Card title="Images">
        {images.map((value, idx) => (
          <S3Image imgKey={value.key} level="private" />
        ))}
      </Card>
    </View>
  );
}

My getImages function ( redux action ) using Storage.list to get a list of images in the S3 bucket. It returns the values fine. But the S3Images component isn't rendering anything. I have also tried just getting the URL from S3 using Storage.get, and then using Image from react-native, but that also is not working. Any Ideas?

A: You need to add width and height in a style prop to the S3Image component. If either width or height are 0, the component does not show.
<S3Image imgKey={value.key} level="private" style={{ width: 100, height: 100 }}/>


text:
Q: Compare 2 custom dimensions using filters On first sight it seems impossible to compare one custom dimension to another using filters.
Case:
I've got 2 custom dimensions, I want a report where I can see how many of my visitors have CD1 = CD2, generic that is , so no specific cases.
In other words : show me every record where CD1 is exactly the same as CD2.
Is this possible?

A: In my answer, I am making the assumption that CD1 and CD2 are session scoped custom dimensions. These really aren't perfect answers to your question, but no other natural way springs to mind. To find how many sessions match this criteria, you could:
1 - Use BigQuery
Not available for free users, but with premium access, you could run simple SQL to list all users WHERE CD1 = CD2
2 - Custom Report Then Filter
Using a custom report feature, you would enter both CD1 and CD2 as dimensions, and select sessions as the metric. This would give you a report that may look like:
CD1   CD2    Users
---   ---    -----
A     A      100
A     B      200
B     A      100
B     B      200

From that, you can see that CD1=CD2 for 300 users.


text:
Q: Using Android Nougat's shared memory for media decoding I am porting my Android AOSP-based distribution from Android K to Android N. It includes a modified version of the Media Player that decodes DVD subtitles.
The architecture of the Media Player evolved a lot between those 2 versions. In particular, it is now split into 3 processes (see https://source.android.com/devices/media/framework-hardening).
I am thus trying to use Shared Memory to make the MediaCodecService send decoded bitmap subtitles to the MediaServer. I modified the contents of the structure that was previously created by MediaCodecService and added a subtitle_fd attribute, file descriptor to the decoded bitmap subtitle. When a message is received by the MediaServer's Nuplayer for rendering, the code tries to map the aforementioned file descriptor.
Unfortunately, the result of the call to ::mmap is always MAP_FAILED.
Do you have an idea of what I missed ?

*

*Code of the MediaCodecService part
AVSubtitleRect *rect = sub->rects[0];
size_t len = sizeof(*rect);
int fd = ashmem_create_region("subtitle rect", len);
ashmem_set_prot_region(fd, PROT_READ | PROT_WRITE);
void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
    ALOGI("%s[%d] dvb ptr == MAP_FAILED", __FUNCTION__, __LINE__);
} else {
    ALOGI("Success creating FD with value %d", fd);
}
memcpy(ptr, rect, len);
sub->subtitle_fd = fd;
sub->subtitle_size = len;

*Code of the MediaServer part
int fd = mSubtitle->subtitle_fd;
size_t len = mSubtitle->subtitle_size;
ALOGI("Trying to map shared memory with FD = %d", fd);
void* ptr = ::mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
    ALOGI("Subtitle mmap ptr==MAP_FAILED %s", strerror(errno));
} else {
    ALOGI("Subtitle get ptr %p", ptr);
}
AVSubtitleRect *rect = (AVSubtitleRect *)ptr;

Thank you so much !


text:
Q: How to interpret the sum of two series? I am confused a bit while I am recalling the infinite series.
Thomas' Calculus says: Sum of two divergent series can be convergent by giving an example: $\sum1 + \sum-1 = \sum0=0$. We also know that $\sum(-1)^n$ is divergent.
However, can not we think the series $\sum(-1)^n=-1+1-1+1\cdots$ equals to $\sum1 + \sum-1$? What distinguishes these series exactly?

A: Suppose that we have two sequences $\{a_n:n\ge1\}$ and $\{b_n:n\ge1\}$ and we want to find the limit of the sum of these two sequences. Then
$$
\lim_{n\to\infty}(a_n+b_n)=\lim_{n\to\infty}a_n+\lim_{n\to\infty}b_n
$$
provided that both of the sequences $\{a_n:n\ge1\}$ and $\{b_n:n\ge1\}$ converge. If this is not the case, the equality might not hold.
Let us recall that a series is the limit of the sequence of the partial sums.
What you are actually doing in your example is the rearrangement of the terms of the series, which does not necessarily give you the same limit unless the series is absolutely convergent. By rearranging a conditionally convergent series you could actually get anything. This is the famous Riemann series theorem.
I hope this helps.


text:
Q: instantiate subclass by string na C# I have a Class and a Sub Clas
namespace MyCode
{
    public class Class1
    {
        int a = 1;
        int b = 2;
        public class SubClass1
        {
            int a = 1;
            int b = 2;
        }
    }
}

Now I need to instantiate each class by string name. I can do this from the class, but not for the subclass.
This works:
var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1"));

But this, din´t work:
var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1.SubClass1"));

What I need to do for the second option?

A: Whenever you don't know what a name should be you can see the name by checking typeof(MyCode.Class1.SubClass1).FullName.
When you have a subclass you use the + sign.
var myObj = Activator.CreateInstance(Type.GetType("MyCode." + "Class1+SubClass1"));

A: var myObj = Activator.CreateInstance(Type.GetType("MyCode.Class1+SubClass1"));

Its + when dealing with nested types, not .


text: Q: restrict user when select from ajax calendar I had Ajax calendar for birth date on registeration form  and I tried to restrict user from select now date also I tried to limit user to select from calendar birth date equal 6 years or greater than6 years.I user rang validator but I couldnot .So please any one help me.


text:
Q: PHP Count from File (Certain Words) I have a strange problem to overcome, it simple but I cannot seem to find any solutions or get my head around this: I have a .html file that I want to read certain "words" and count how many of the certain words there are.
Thanks in advance
Just trying to get count of certain words to prevent glitches in my application.

A: You didn't specify if you're searching for multiple words, or just certain one, so I'm gonna go for multiple.
$count = 0; //Create a variable for counting
$contents = file_get_contents("yourfile.html"); //Load your file into a string
$words = array('word1', 'word2', 'word3');  //Specify which words you want to search for

foreach($words as $word) {  //For each word in array do
$place = strpos($contents, $word); //Get the position of searched word
if (!empty($place)) { //if a word has been found, increment the count variable
    $count++;
}
}
echo 'Number of filtered words: ' . $count; //Print out the number of words


text:
Q: Upload File to OpenStack Using Python Swift Client Would someone have a complete example of how to upload a file to an OpenStack container using the Python Swift client: https://pypi.org/project/python-swiftclient/
Something that would include:

*

*Authenticate against the OpenStack instance

*Call the relevant function(s) to upload the file to an OpenStack container

Thanks

A: I was able to do it with the following piece of code
from keystoneauth1 import session
from keystoneauth1.identity import v3
from swiftclient.client import Connection

# Create a password auth plugin
auth = v3.Password(
    auth_url='https://cloud.company.com:5000/v3/',
    username='myaccount',
    password='mypassword',
    user_domain_name='Default',
    project_name='myproject',
    project_domain_name='Default'
)

# Create session
keystone_session = session.Session(auth=auth)

# Create swiftclient Connection
swift_conn = Connection(session=keystone_session)

# Create container
swift_conn.put_container('test')

# Read file
with open('myfile.txt', 'rb') as f:
    file_data = f.read()

# Upload file
swift_conn.put_object('test', 'myfile.txt', file_data)


text:
Q: Using two different Schemas in NodeJS Express I have a nodeJs application which is working fine with one schema from MSSQL, but i have a requirement where i need to use another schema and do some api calls.
first API is working fine and giving out result.
 But when I tried with another get api named "/stockOrderDetails" it is just giving empty data like this:
Can anyone please let me know how to use different schemas in a single JS file for nodeJS
{
  "code": 200,
  "status": "OK",
  "message": "Data Operation Success",
  "data": {
    "orderDetail": [

    ]
  }
}

Here is my actual code:
const express = require("express");
var sql = require("mssql");

const { json, urlencoded } = require("body-parser");

const multer = require("multer");

var config = {
  user: "jsudjac",
  password: "********",
  server: "********",
  database: "JSULLC_Test",
};
var dataSource = {
  user: "jsudjac",
  password: "*****",
  server: "*********",
  database: "Stock_Test",
};

const dbconn1 = sql.connect(config, (err) => {
  if (!err) {
    console.log("Connected to the database");
  } else {
    console.log("Problem in connecting to database");
    console.log(err);
    console.log("testing");
  }
});

const dbconn2 = sql.connect(dataSource, (err) => {
  if (!err) {
    console.log("connected");
  } else {
    console.log(err);
  }
});

const storage = multer.diskStorage({
  destination: "./uploads",
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const app = express();
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});
const upload = multer({
  storage: storage,
  dest: "./uploads/",
}).single("file");
app.use(json());
app.use(urlencoded({ extended: true }));

app.get("/jsuOrderDetails/:jsuOrder", (req, res) => {
  const request = new sql.Request(dbconn1);
  request.input("jsuOrder", sql.VarChar, req.params.jsuOrder);
  request.execute("mobile_getOrderDetails", (err, result) => {
    if (!err) {
      var out = {
        code: 200,
        status: "OK",
        message: "Data Operation Success",
        data: {
          orderDetail: result.recordsets[0],
        },
      };
    } else {
      var out = {
        status: 404,
        data: {},
      };
    }
    res.send(out);
  });
});

app.get("/stockOrderDetails/:jsuOrder", (req, res) => {
  const request = new sql.Request(dbconn2);
  console.log("hithithit");
  request.input("jsuOrder", sql.VarChar, req.params.jsuOrder);
  console.log(req.params.jsuOrder);
  request.execute("mobile_getOrderDetails", (err, result) => {
    if (!err) {
      var out = {
        code: 200,
        status: "OK",
        message: "Data Operation Success",
        data: {
          orderDetail: result.recordsets[0],
        },
      };
    } else {
      var out = {
        status: 404,
        data: {},
      };
    }
    res.send(out);
  });
});

app.get("/validate", (req, res) => {
  let query = "select * from ma_smallpipe_coating_details";
  console.log("hithit");
  dbconn2.query(query, (err, rows) => {
    if (!err) {
      console.log(rows.recordsets[0]);
    }
  });
});```


text:
Q: IntelliJ Application testing on Android device Hy Everybody!
I am starting to learn android development and I would like to try my applications on my HTC (wildfire s) android device(smartphone). My big big problem is a can't do that.
The intellij provide the following after i am clicking a run button:
Waiting for device.
Target device: SH1A3TR00615
Uploading file
    local path: D:\javas\MyActivity\out\production\MyActivity\MyActivity.apk
    remote path: /data/local/tmp/com.example.MyActivity
Installing com.example.MyActivity
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/com.example.MyActivity"
pkg: /data/local/tmp/com.example.MyActivity
Failure [INSTALL_FAILED_INSUFFICIENT_STORAGE]

I am - using IntelliJ,
     - installed HTC Sync
     - installed Android SDK Tools(1.16)
     - installed ADBDriver
The way how I am creating and running my first app:
File->new project
In the popup window I choose - under android secion - Application Module
Project SDK: Android 4.4 Platform(java version 1.7.0_45)
At more settings Project format: .idea(directory based)
...and my project created, there is an AndroidMainfest.xml, the src folder, and some other file and folder too.
My AndroidMainfest.xml looks:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.MyActivity"
          android:versionCode="1"
          android:versionName="1.0">
    <uses-sdk android:minSdkVersion="19"/>
    <application android:debuggable="true" android:label="@string/app_name" android:icon="@drawable/ic_launcher">
        <activity android:name="MyActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

When I am click on the android icon at the bottom, it opens a window and I see a "running rows" when I am touching my phone, so I suppose the IntelliJ known about my phone.
I tried to exit and start Intellij again, but the probel was still there.
If I choose a target device at startup "Choose a running device", I see there my phone, but: Compatible: no
Please somebody help me to get started android developing on my device....

A: That error looks to me like you lack sufficient space on your internal memory. You might need to clean up some of the data internally before it will let you flash the apk onto the device. Alternately, you can take that apk which sits at the path listed, and by mounting your sd card, assuming you have an external microSD in your phone, place it there before installing manually from your phone.

A: You need to change your  uses-sdk android:minSdkVersion="19" to  uses-sdk android:minSdkVersion="16" and set your compiler to 1.6 (you can find this under settings - compiler - Java Compiler - and then select 1.6 (a project bytecode version(right hand side)).
Hope this helps
Chow


text:
Q: pg-promise format default - not existing Property to null I would like to be able to have the formatting.formatValue function convert undefined into null.
But there does not appear to be a way that I can set the default function from the initOptions given to pg-promise as pgFormatting is a boolean, format value wants it as an argument. But the library does not appear to pass it for normal queries.
vitaly-t wrote

But i'm not sure how much value it would add, since you do not have access to formatting options from query methods.

And that is true. But I kind of just want to set a default of null for all missing values being formatted into queries. Partial does not mater I don't use it?
Using coalesce to have "optional" values in some of the queries, to default not set variables anyway.
Example:
UPDATE sometable SET value = COALESCE(${value}, value)

How can I stop getting the "Property  doesn't exist Error?
I think that I need a way to pass a value to this options for all calls to the format.
if ('default' in options) {
    const d = options.default, value = typeof d === 'function' ? d.call(obj, v.name, obj) : d;
    return formatValue(value, v.fm, obj);
}

Related issue that led to creation of options.default.
https://github.com/vitaly-t/pg-promise/issues/173
I can't over-ride the format value function  as it is added as a non configurable read only property.
Do I just have to bite the bullet and put the variables in as null everywhere I want them to be optional...

A:
I kind of just want to set a default of null for all missing values being formatted into queries...

Here's your formatting function for this, if you want to format queries manually:
function format(query, values) {
    return pgp.as.format(query, values, {'default': null});
}

And for automatically generated queries within the helpers namespace, you would provide the value for property def, as per the Column API.
Other than that, the query methods make use of the format function on their own, so you cannot override that, neither you should, it is generally not needed, if you make the right use of the library's API, i.e. if you can give me a specific example of where you think you need it, then I can advise you of the better approach that avoids it.
One other approach - method helpers.concat can consume the formatting options, as it implements a specific case of joining queries.


text:
Q: Output from API automatically stops I am making an application in java in which I am required to get latitude and longitude of certain locations listed in the csv file. All is going smooth but the response stops coming after sometime. Sometimes it parses the complete set of locations and sometimes it stops in between. I am not able to catch the flaw, please help me. The code is written below
 `int count=0;
 JFileChooser  jfc;
String path_of_chosen_file;
File directory_of_chosen_file;
ArrayList<String> locations;
FileWriter writer = null;

 private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {

    jfc = new JFileChooser();
    if(jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        //code to handle choosed file here.
        jfilenametxt.setText(jfc.getName(jfc.getSelectedFile()));
        path_of_chosen_file = jfc.getSelectedFile().getAbsolutePath();
        directory_of_chosen_file=jfc.getCurrentDirectory();
        System.out.println(path_of_chosen_file);
    }
}
   private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    FileInputStream fileIn = null;
    locations=new ArrayList();

    Scanner scanner = null;
    try {

        scanner = new Scanner(new File(path_of_chosen_file));
        scanner.useDelimiter(",");
        while(scanner.hasNextLine())
        {
            locations.add(scanner.nextLine());
        }
        locations.removeAll(Arrays.asList("", null));
 }
    catch(FileNotFoundException e1){
    }

      String writepath=directory_of_chosen_file.toString()
    +"/newfile"+jfc.getName(jfc.getSelectedFile());

   FileWriter writer = null;

 try {

 writer = new FileWriter(writepath);
     try{
         Iterator itr=locations.iterator();
         while(itr.hasNext())
         {

             String pointLocation=(String) itr.next();
             System.out.println(pointLocation);
        String latLongs[] = getLatLongPositions( pointLocation);

        writer.append(pointLocation);
        writer.append(',');
        writer.append(latLongs[0]);
        writer.append(',');
        writer.append(latLongs[1]);
           writer.append('\n');
            writer.flush();

        System.out.println("Your excel file has been generated for " + pointLocation);
         }
         Object[] options = { "OK" };
 int input = JOptionPane.showOptionDialog(null, "Excel generation is
  completed. Click OK to continue", "",
   JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
   null, options, options[0]);
          if(input == JOptionPane.OK_OPTION)
            {
                 System.out.println("AASHIMA");
            }
     }

     catch(Exception e1){
                  }

    } catch (IOException e) {
    e.printStackTrace();
    } finally {
     try {
     writer.flush();
     writer.close();
     } catch (IOException e) {
    e.printStackTrace();
 }
    }
   }

 `

public static String[] getLatLongPositions(String address) throws Exception
   {
  int responseCode = 0;
  String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=" +
  URLEncoder.encode(address, "UTF-8") + "&sensor=true";
System.out.println("URL : "+api);
URL url = new URL(api);
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();

httpConnection.connect();

responseCode = httpConnection.getResponseCode();

if(responseCode == 200)
{
  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document document = builder.parse(httpConnection.getInputStream());
  XPathFactory xPathfactory = XPathFactory.newInstance();
  XPath xpath = xPathfactory.newXPath();
  XPathExpression expr = xpath.compile("/GeocodeResponse/status");
  String status = (String)expr.evaluate(document, XPathConstants.STRING);
  if(status.equals("OK"))
  {
     expr = xpath.compile("//geometry/location/lat");
     String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
     expr = xpath.compile("//geometry/location/lng");
     String longitude = (String)expr.evaluate(document, XPathConstants.STRING);

     return new String[] {latitude, longitude};
  }
  else
  {
     throw new Exception("Error from the API - response status: "+status);
  }
}

return null;
}

The output on console is this
`Guwahati Assam india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Guwahati+Assam+india&sensor=true
Your excel file has been generated for Guwahati Assam india
Muzaffarpur Bihar india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Muzaffarpur+Bihar+india&sensor=true
Your excel file has been generated for Muzaffarpur Bihar india
Forbesganj Bihar india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Forbesganj+Bihar+india&sensor=true
Your excel file has been generated for Forbesganj Bihar india
Ambikapur Chhattisgharh india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Ambikapur+Chhattisgharh+india&sensor=true
Your excel file has been generated for Ambikapur Chhattisgharh india
Raipur Chhattisgharh india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Raipur+Chhattisgharh+india&sensor=true
Your excel file has been generated for Raipur Chhattisgharh india
Surat Gujarat india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Surat+Gujarat+india&sensor=true
Your excel file has been generated for Surat Gujarat india
Vadodara Gujarat india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Vadodara+Gujarat+india&sensor=true
Your excel file has been generated for Vadodara Gujarat india
Rajkot Gujarat india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Rajkot+Gujarat+india&sensor=true
Your excel file has been generated for Rajkot Gujarat india
Panchkula Haryana india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Panchkula+Haryana+india&sensor=true
Your excel file has been generated for Panchkula Haryana india
Deogharh Jharkhand india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Deogharh+Jharkhand+india&sensor=true
Your excel file has been generated for Deogharh Jharkhand india
Jamshedpur Jharkhand india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Jamshedpur+Jharkhand+india&sensor=true
Your excel file has been generated for Jamshedpur Jharkhand india
Hosur karnataka india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Hosur+karnataka+india&sensor=true
Your excel file has been generated for Hosur karnataka india
Belgaum karnataka india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Belgaum+karnataka+india&sensor=true
Your excel file has been generated for Belgaum karnataka india
Gwalior Madhya Pradesh india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Gwalior+Madhya+Pradesh+india&sensor=true
Your excel file has been generated for Gwalior Madhya Pradesh india
Narsimhapur Madhya Pradesh india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Narsimhapur+Madhya+Pradesh+india&sensor=true
Your excel file has been generated for Narsimhapur Madhya Pradesh india
Pune Maharashtra india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Pune+Maharashtra+india&sensor=true
Your excel file has been generated for Pune Maharashtra india
Nanded Maharashtra india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Nanded+Maharashtra+india&sensor=true
Your excel file has been generated for Nanded Maharashtra india
Nagpur Maharashtra india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Nagpur+Maharashtra+india&sensor=true
Your excel file has been generated for Nagpur Maharashtra india
Kolhapur Maharashtra india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Kolhapur+Maharashtra+india&sensor=true
Your excel file has been generated for Kolhapur Maharashtra india
Sangali Maharashtra india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Sangali+Maharashtra+india&sensor=true
Your excel file has been generated for Sangali Maharashtra india
Navi Mumbai Maharashtra india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Navi+Mumbai+Maharashtra+india&sensor=true
Your excel file has been generated for Navi Mumbai Maharashtra india
Ri Bhoi Meghalaya india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Ri+Bhoi+Meghalaya+india&sensor=true
Your excel file has been generated for Ri Bhoi Meghalaya india
Sambalpur Orissa india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Sambalpur+Orissa+india&sensor=true
Your excel file has been generated for Sambalpur Orissa india
Chunni Punjab india
URL : http://maps.googleapis.com/maps/api/geocode/xml?address=Chunni+Punjab+india&sensor=true
here it stops and is not progressing. Also the control is returned back to the UI where the button again attains the unpressed state.
it completely executes randomly. Here is the screenshot

The response code is 200 and still I am facing the same problem

I have found the problem, please suggest a solution so that I can get the desired result

A: I have solved the problem. The issue was due to OVER_QUERY_LIMIT , so I checked the status of it and called the function recursively after some timeout. Here is the code.
    public static String[] getLatLongPositions(String address) throws Exception
 {
  int responseCode = 0;
  String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=" +
 URLEncoder.encode(address, "UTF-8") + "&sensor=true";
System.out.println("URL : "+api);
URL url = new URL(api);
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();

httpConnection.connect();

responseCode = httpConnection.getResponseCode();
System.out.println("The response code is: " +responseCode);

if(responseCode == 200)
{

  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

  Document document = builder.parse(httpConnection.getInputStream());

  XPathFactory xPathfactory = XPathFactory.newInstance();
  XPath xpath = xPathfactory.newXPath();
  XPathExpression expr = xpath.compile("/GeocodeResponse/status");

  String status = (String)expr.evaluate(document, XPathConstants.STRING);

  System.out.println("the status is " +status);
  if(status.equals("OK"))
  {

     expr = xpath.compile("//geometry/location/lat");
     String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
     expr = xpath.compile("//geometry/location/lng");
     String longitude = (String)expr.evaluate(document, XPathConstants.STRING);

     return new String[] {latitude, longitude};
  }
  if (status.equals("OVER_QUERY_LIMIT")) {
       TimeUnit.SECONDS.sleep(20);
           return( getLatLongPositions(address));

    }
  else
  {
     throw new Exception("Error from the API - response status: "+status);
  }
}

return null;
}`


text:
Q: Switching Apple ID on iPad (without losing progress) My family has shared an iPad for many years using my mom's Apple ID.  Recently my mom got an iPhone for herself.  She needs to now keep her Apple ID for personal use.  We would like to create a new Apple ID for the iPad now and continue to use the iPad shared among the entire family.  The concern is over losing app progress when the switch is made.

*

*How will app ownership be affected by this change?  Will apps disappear because the original purchaser is no longer logged in on the iPad?

*Will saved progress disappear when a new Apple ID takes over the iPad?  Or does progress remain saved on the iPad hard drive?

*What will happen to achievements in Gamecenter?  Will they update to where they were when the new Apple ID launches a game that has already been there for years?
Thanks!

A: I think most people worry about this when they stop sharing an iPad. I used to hear these concerns all the time at the AASP I worked at. Let's address each issue in turn.

*

*Apps will still remain associated to your mom's Apple ID, but they won't disappear. If you sign out of your mom's account and sign in with the new one, the apps stay exactly where they are. The only snag is, when it comes time to update, you will be asked for your mom's Apple ID and password to update them.

*None of the data saved in apps will disappear when you switch an Apple ID as it is all saved locally on the device (except in the case of online games such as Clash of Clans etc, but they usually require you to log in with a 3rd Party service such as Facebook which then stores your save data instead).

*Unfortunately, the Game Centre achievements are linked to your mom's Apple ID and if you sign out of hers and in with another, those achievements will disappear. Often, games feature a local achievement board which will remain on the device, and there is a chance it would sync to the new Apple ID, but in most cases I'm afraid you'll have to get those achievements again. But hey, look at it this way, that old game you haven't played in months? You can have some more fun with it again trying to set your old high score! ;)

You can have a look at another post of mine here where I talk about backing up and restoring save games on an iPad when switching users. You can use the information in there to backup your saves, then delete the games and re-download them with the new Apple ID to circumvent the annoying need for your mom's Apple ID whenever they need to be updated.
Obviously, any purchased apps and games would need to be re-purchased if you do this, so I would recommend your mom enable Family Sharing on her Apple ID and add the new Apple ID to the family so you can access her purchases without paying for them again.

A: 1. How will app ownership be affected by this change? Will apps disappear because the original purchaser is no longer logged in on the iPad?

Apps won't disappear. You can combine apps on the same device from different Apple ID's. Just switch Apple ID in the App Store at the bottom of the screen and download an app. The only downside is having to type different passwords when updates are available.
2. Will saved progress disappear when a new Apple ID takes over the iPad? Or does progress remain saved on the iPad hard drive?

Progress remains. Game Center achievements might not, though they are in the cloud anyway. If you want to take the app data from the old Apple ID to a different device, make sure iCloud is on with app data enabled.
3. What will happen to achievements in Gamecenter? Will they update to where they were when the new Apple ID launches a game that has already been there for years?

That depends on the game. Often they won't, as they're linked to the other Apple ID and the game mostly won't check if past achievements have been entered into Game Center. The achievements will remain on the old Apple ID, as stated in answer #1.
Summary: app data is often stored in iCloud and always on the device, so don't worry about losing progress. You might lose achievements, though they remain on the old Apple ID and as they don't align to your game progress anymore it will be a bit messy.