text:
Q: How to throw same exception thrown by external endpoint in springboot I'm accessing an external api and I'm expecting to get an image as response (byte[]). My method that connects to this endpoint looks like this:
 private byte[] retrieveImage(String uri) {
     byte[] imageBytes = null;
     try {
            URL url = new URL(uri);
            BufferedImage bufferedImage = ImageIO.read(url);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            imageBytes = baos.toByteArray();
        } catch (Exception ex) {
            throw new ImageNotReadException(ex.getLocalizedMessage());
        }
        return imageBytes;
    }

It turned out that if I pass the wrong parameters to the target endpoint I get this error message:

So basically I would like to throw the same error above but I also would like to throw an ImageNotReadException (java.lang.IllegalArgumentException: image == null! ) in case the program fails to read the image (byte[]). So basically, my method  private byte[] retrieveImage(String uri) would have to throw my read image exception and the endpoint response exception.
Any tips?
Appreciate the help!

A: As i have commented see below options
private Response retrieveImage(String uri) {
     byte[] imageBytes = null;
Response r=new Response();
     try {
            URL url = new URL(uri);
            BufferedImage bufferedImage = ImageIO.read(url);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            imageBytes = baos.toByteArray();
            r.setImage(imageBytes);
            r.setStatus(1);
        } catch (Exception ex) {
            r.setStatus(0);
        }
        return r;
    }

Response :
class Response{
String status;
byte[] image;

//getters setters
}

Or :
  private Response retrieveImage(String uri)throws CustomException {
         byte[] imageBytes = null;
         try {
                URL url = new URL(uri);
                BufferedImage bufferedImage = ImageIO.read(url);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos);
                imageBytes = baos.toByteArray();
            } catch (Exception ex) {
                throw new CustomException(ex.getLocalizedMessage());
            }
            return imageBytes;
        }


text:
Q: To replace email domain with some different email domain Trying to replace multiple email domains separated by commas , with some different domain e.g.: - 'yopmail.com'.
'test1@gmail.com','test2@yahoo.in','test3@something.org','test4@gmail.com','test5@gmail.co.in','test6@gmail.com'

So I want a RegEx for my WebStorm IDE to replace those email domain.
Any help will be appreciated.

A: Considering you have a list of those strings
import re
a=['test1@gmail.com','test2@yahoo.in','test3@something.org','test4@gmail.com','test5@gmail.co.in','test6@gmail.com']
b=[re.sub(r'@[\w]+','@yopmail',i) for i in a]
#THIS WILL SEARCH AND REPLACE ALPHANUMERIC VALUES AFTER @ WITH YOUR TEXT
print(b)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nvidia drivers suddenly not working Today I started up my laptop with Ubuntu 18.04 and suddenly I can't go through the login page, as soon as I insert the credentials the screen freezes, the mouse pointer is stuck and I can't do a thing. I searched a little and, after trying some stuff I found in this forum, I think the problem is the Nvidia drivers (I have a 1050Ti Mobile): as soon as I do the  sudo apt-get purge nvidia* I can login, but I can't use the system at all, it freezes after a while. In the case I can login, if I look at the additional drivers the graphic card is using the Nuveau one, and if I try to set another one it gets stuck. I tried the ubuntu-drivers autoinstall but it didn't work, I tried to do the nomodeset thing and install the drivers with "Additional drivers" tool but it gets stuck again, I tried to remove the ppa repository and add it again to get the recommended driver (it gives me the 430 driver as recommended) and then install it but nothing. What could it be? Thank you

A: Have you tried booting into a Wayland session instead of Xorg ? I had exactly the same  problem as you but with  nvidia-430 installed. I had a black screen  and frozen mouse when using Xorg, and Wayland worked normally.
If you load a session successfully, whats happens when you run   sudo nvidia-settings ?


text:
Q: How to figure out an IPv6 address (by name) of a host in my LAN I have two computers plugged in the same router of a network which I know supports IPv6. Let's call them "PC-A" and "PC-B
I want "PC-A" to figure out "PC-B"s IPv6 address and vice-versa
The first thing I do is
setSystem.setProperty("java.net.preferIPv6Addresses", "true");

If I then say
InetAddress IPAddress = InetAddress.getLocalHost();

I can get my own address which will be in IpV6 format
However, neither of the following two statements gives me "PC-B"s IPv6 address:
Inet6Address IPAddress6 = (Inet6Address)InetAddress.getByName("PC-B");
InetAddress IPAddress = InetAddress.getByName("PC-B");

I also tried to import
import com.lavantech.net.dns.SimpleDNSLookup;
import com.lavantech.net.dns.DNSLookup

The first one I am using as:
SimpleDNSLookup d = new SimpleDNSLookup();
System.out.println(d.getInet6Address("PC-B"));

and the second one as:
DNSLookup dnsLookup = new DNSLookup("PC-B", DNSLookup.QTYPE_AAAA, DNSLookup.QCLASS_IN, 3000, null);
// Get all Address Records.
ResourceRecord[] ansRecords = dnsLookup.getAAAARecords();
System.out.println(ansRecords[0]);

none of which works.
I also tried to use the following
import org.xbill.DNS.*;

int type = Type.AAAA;
Name name = Name.fromString("PC-B");
Lookup lookup = new Lookup(name, type);
lookup.run();
int result = lookup.getResult();
Record[] answers = lookup.getAnswers();
System.out.println(answers[0]);
// (where, for brevity, i am skipping the parts where I check whether result == Lookup.SUCCESSFUL

*

*Note that if I substitute "PC-B" for, say, "ipv6.google.com" I get all the desired results!

*Also note that if I just use InetAddress and Type_A wherever applicable in the above approaches, my program returns "PC-B"s IPv4 address without problem.

What am I missing?
Any help is greatly appreciated!

A: Your question is -unfortunately- a yet unsolved network problem dealing with host discovery on a local subnet (regardless if that subnet has a router or not).
Your desired output is clearly an IPv6 address, but it is unclear what exactly your input is.
Let's focus on PC-B. How exactly do you identify PC-B? It clear that you call it "PC-B", but that name should be configured somewhere before your PC know that that's its name. Where exactly is that configured? Is that the hostname you set on PC-B itself, or is there a domain name server (DNS) where you have given that name? If it is the name in the DNS system, you can indeed query the DNS system for the AAAA record to get the IPv6 address, but you need the fully qualified domain name (FQDN). E.g. "PC-B.yourdomain.com" rather than just "PC-B".
If you know the MAC address of PC-B, you can use the neighbour discovery protocol (NDP) to find out the IP address of PC-B.
There are network protocols that allow PC-A and PC-B to announce their names themselves, once you configured them on the local machines. Such protocols are called "service discovery" protocols, and your options here are (1) multicast DNS (mDNS) and possibly DNS service discovery (DNS-SD) on top of that; or (2) Simple Service Discovery Protocol (SSDP) in UPnP on the other hand. The advantage is that some operating systems already implement this. E.g. if PC-B is a Mac OS X host, all you need to do is query DNS for "pc-b.local" to get the answer. Unfortunately, while implementations of mDNS exist for Linux (Avahi) and Windows (Bonjour), they're not installed by default. A third alternative is to write your own host discovery protocol, and have your hosts run that protocol.
Considerations are which platforms you want to support, if installing third-party software is an option, if the discovery needs to be secure (the above options are not, look into Secure Neighbour Discovery -SEND- if this is a concern), and what input you have in the first place (the hostname "PC-B", or the type of service that runs on PC-B, e.g. _http._tcp for a webserver).


text:
Q: How to shorten these duplicate JavaScript code into a loop? I had ten rows which each rows contain 4 column, now I want to get the value which I had import using localStorage. I find a way to put all these value independently but the code is all the repeat one. These will cause to redundancy of code. I wonder if there are a way to shorten the code using loop?
Here is my code
 var res = {};
    $(function(){
     $('#subbtn').click(function() {
      console.log($('#tab').find('tr'))
      $('tr').each(function(){
          var tmp = [];
          var cl ;
          $(this).find('select').each(function(){
            cl = $(this).attr('class');
            //console.log(cl);
            tmp.push($(this).val());
          })

          res[cl] = tmp
      })
        console.log(res);
       localStorage.setItem("testingvalue",JSON.stringify(res));
       document.getElementById("results__display").innerHTML = (localStorage.getItem("testingvalue"));
     })

    })
    $( document ).ready(function(){
   var res = {};
   try {
    console.log('existed');
      res = JSON.parse(localStorage.getItem("testingvalue"));

   //alert(res.r1[2]);
   document.getElementsByClassName("r1")[0].selectedIndex=res.r1[0];
   document.getElementsByClassName("r1")[1].selectedIndex=res.r1[1];
   document.getElementsByClassName("r1")[2].selectedIndex=res.r1[2];
   document.getElementsByClassName("r1")[3].selectedIndex=res.r1[3];

   document.getElementsByClassName("r2")[0].selectedIndex=res.r2[0];
   document.getElementsByClassName("r2")[1].selectedIndex=res.r2[1];
   document.getElementsByClassName("r2")[2].selectedIndex=res.r2[2];
   document.getElementsByClassName("r2")[3].selectedIndex=res.r2[3];

   document.getElementsByClassName("r3")[0].selectedIndex=res.r3[0];
   document.getElementsByClassName("r3")[1].selectedIndex=res.r3[1];
   document.getElementsByClassName("r3")[2].selectedIndex=res.r3[2];
   document.getElementsByClassName("r3")[3].selectedIndex=res.r3[3];

   document.getElementsByClassName("r4")[0].selectedIndex=res.r4[0];
   document.getElementsByClassName("r4")[1].selectedIndex=res.r4[1];
   document.getElementsByClassName("r4")[2].selectedIndex=res.r4[2];
   document.getElementsByClassName("r4")[3].selectedIndex=res.r4[3];

   document.getElementsByClassName("r5")[0].selectedIndex=res.r5[0];
   document.getElementsByClassName("r5")[1].selectedIndex=res.r5[1];
   document.getElementsByClassName("r5")[2].selectedIndex=res.r5[2];
   document.getElementsByClassName("r5")[3].selectedIndex=res.r5[3];

   document.getElementsByClassName("r6")[0].selectedIndex=res.r6[0];
   document.getElementsByClassName("r6")[1].selectedIndex=res.r6[1];
   document.getElementsByClassName("r6")[2].selectedIndex=res.r6[2];
   document.getElementsByClassName("r6")[3].selectedIndex=res.r6[3];

   document.getElementsByClassName("r7")[0].selectedIndex=res.r7[0];
   document.getElementsByClassName("r7")[1].selectedIndex=res.r7[1];
   document.getElementsByClassName("r7")[2].selectedIndex=res.r7[2];
   document.getElementsByClassName("r7")[3].selectedIndex=res.r7[3];

   document.getElementsByClassName("r8")[0].selectedIndex=res.r8[0];
   document.getElementsByClassName("r8")[1].selectedIndex=res.r8[1];
   document.getElementsByClassName("r8")[2].selectedIndex=res.r8[2];
   document.getElementsByClassName("r8")[3].selectedIndex=res.r8[3];

   document.getElementsByClassName("r9")[0].selectedIndex=res.r9[0];
   document.getElementsByClassName("r9")[1].selectedIndex=res.r9[1];
   document.getElementsByClassName("r9")[2].selectedIndex=res.r9[2];
   document.getElementsByClassName("r9")[3].selectedIndex=res.r9[3];

   document.getElementsByClassName("r10")[0].selectedIndex=res.r10[0];
   document.getElementsByClassName("r10")[1].selectedIndex=res.r10[1];
   document.getElementsByClassName("r10")[2].selectedIndex=res.r10[2];
   document.getElementsByClassName("r10")[3].selectedIndex=res.r10[3];

    }

    catch (error){
       console.log(error.message);
   }

});

A: Looking at this repeated line:
document.getElementsByClassName("r1")[0].selectedIndex=res.r1[0];

...a simple first pass improvement would be to just use a nested for loop with variables instead of "r1" and 0:
for (var r = 1; r <= 10; r++) {
  for (var i = 0; i < 4; i++) {
    document.getElementsByClassName("r" + r)[i].selectedIndex = res["r" + r][i];
  }
}

Notice, though, that this means the .getElementsByClassName("r" + r) call happens four time for each value of r, which is not very efficient - it would be better to move that into the outer loop:
var els;
for (var r = 1; r <= 10; r++) {
  els = document.getElementsByClassName("r" + r);
  for (var i = 0; i < 4; i++) {
    els[i].selectedIndex = res["r" + r][i];
  }
}

In the second version the inner loop could say i < els.length rather than i < 4, although note that either way you need to be sure you match the number of HTML elements to the number of items in your res object.

A: Code below will work regardless the size of your data in storage:
res = JSON.parse(localStorage.getItem("testingvalue"));
  // Let's start with checking 'res' type.
  // - if it's an Array, get the the length from .length
  // - if it's Object, get the the length from Object.keys().length
  var resLength = Array.isArray(res) ? res.length : typeof res === 'object' ? Object.keys(res).length : 0;
  // loop throw the rows.
  for (var i = 0; i < resLength; i++) {
    // Do the same as above: get type of the row and calculate it length for the loop.
    var rowLength = Array.isArray(res[i]) ? res.length : typeof res[i] === 'object' ? Object.keys(res[i]).length : 0;
    // loop throw the columns on the row.
    for (var j = 0; j < rowLength; j++) {
      document.getElementsByClassName('r'+i)[j].selectedIndex=res['r'+i][j];
    }
}

A: You've seem to have the jQuery library loaded. Using jQuery makes this much easier.
Here is an example:
var res = JSON.parse(localStorage.getItem("testingvalue"));
$("tr select").each(function(){
   $(this).val(res[$(this).attr("class")][$(this).index()]);
});

Of course, this will only work if the select elements have only one class name and the res object contains values for all the select elements that are inside tr elements. Based on the jQuery code in your question that seems to be the case.
And this is a safer approach
Object.keys(res).forEach(function(key){
    res[key].forEach(function(val, index){
        $("tr select." + key).eq(index).val(val);
    });
});


text:
Q: Is there a function that returns a default value for a string that is not a valid number I would like to know if there is an nvl function for alphabetic characters, or I have to use a case in the select statement?
Ex :
EMPNO
-----
73A69
7369B
C7369
7369
736,9
73,69
73e,69
73,e69

I want to get this as a result:
0
0
0
7369
736,9
73,69

A: Oracle 12cR2 and above :
select TO_NUMBER ( EMPNO DEFAULT 0 ON CONVERSION ERROR ) FROM t;

A: I'm not sure why you're referring to this as nvl, but if you're just trying to convert a non-numeric string to 0, I'd indeed use a case  expression with a regexp_like call:
SELECT CASE WHEN REGEXP_LIKE(empno, '^[0-9]+$') THEN TO_NUMBER(empno) ELSE 0 END
FROM   emp;

A: Are you looking for a regular expression?
select (case when regexp_like(empno, '[^0-9,]' then 0 else empno end)

If you want to avoid case, you can play tricks, such as:
select coalesce(regexp_substr(empno, '^[0-9,]+$', 1, 1), '0')

But this is essentially the same logic.

A: this is my final solution
    SELECT CASE WHEN REGEXP_LIKE(empno, '^[0-9]+([\,\.][0-9]+)?$') THEN
        TO_NUMBER(empno) ELSE 0 END
      FROM   emp;

A: Your main problem is that the numbers you find can contain a point or a comma and both represent the decimal separator. You've posted an answer yourself:
SELECT
  CASE WHEN REGEXP_LIKE(empno, '^[0-9]+([\,\.][0-9]+)?$')
   THEN TO_NUMBER(empno) ELSE 0 END
FROM emp;

but that will fail on either the comma or the point, because the DBMS does not by default interprete both as a decimal separator.
You could of course simply select the string:
SELECT
  CASE WHEN REGEXP_LIKE(empno, '^[0-9]+([\,\.][0-9]+)?$')
   THEN empno ELSE '0' END
FROM emp;

If you need to select the string converted to a number, make the string consistent (i.e. replace the point with a comma or vice versa) and display the appropriate format when using TO_CHAR:
SELECT
  CASE WHEN REGEXP_LIKE(empno, '^[0-9]+([\,\.][0-9]+)?$')
    THEN TO_NUMBER(REPLACE(empno, ',', '.'), '90.9999999') ELSE 0 END
FROM emp;

Accordingly, as of Oracle 12c Release 2 you could use:
SELECT TO_NUMBER(REPLACE(empno, ',', '.') DEFAULT 0 ON CONVERSION ERROR, '90.9999999')
FROM emp;

(This latter query would, however, accept '12,' and '12.' as valid numbers (namely as the number 12), which your regular expression forbids.)


text:
Q: Hiding buttons when not needed I use Jquery in my page to hide buttons which i dont want to show unless needed. In this case its a table with several rows i hide the remove button unless i select a row to be removed... similarly i hide the button that control row manipulation until there is more then one row. I use the following code for it.
jQuery(document).ready(function() {
                if (jQuery(tableId).find("input[type='checkbox']").length == 1) {
                    jQuery(headerCheckbox).hide();
                    jQuery(removeButtonId).hide();
                    jQuery(upButtonId).hide();
                    jQuery(downButtonId).hide();
                } else if (jQuery(tableId).find("input[type=checkbox]:checked").length == 0) {
                    jQuery(removeButtonId).hide();
                    jQuery(upButtonId).hide();
                    jQuery(downButtonId).hide();
                    jQuery(headerCheckbox).click(function() {
                        jQuery(tableId).find("input[type='checkbox']").attr('checked', jQuery(headerCheckbox).is(':checked'));
                    });
                }

                jQuery(tableId).find("input[type='checkbox']").each(function() {
                    if (jQuery(this).attr('id') != headerCheckbox) {
                        jQuery(this).click(function() {
                            if (jQuery(headerCheckbox).is(':checked')) {
                                if (jQuery(tableId).find("input[type=checkbox]:checked").length != 1) {
                                    jQuery(removeButtonId).show();
                                    if (rowCount > 1) {
                                        jQuery(upButtonId).show();
                                        jQuery(downButtonId).show();
                                }
                            } else if (jQuery(tableId).find("input[type=checkbox]:checked").length > 0) {
                                jQuery(removeButtonId).show();
                                if (rowCount > 1) {
                                    jQuery(upButtonId).show();
                                    jQuery(downButtonId).show();
                                }
                            } else {
                                jQuery(removeButtonId).hide();
                                jQuery(upButtonId).hide();
                                jQuery(downButtonId).hide();
                            }
                        }
                    });
                    }
                });
            });

This code without the
if (rowCount > 1) {
                                jQuery(upButtonId).show();
                                jQuery(downButtonId).show();
                            }

works fine for the remove button but the moment i add this line the behavior goes haywire and works only when the select all is selected...
To explain the variables used most of them are just ID's from there corresponding elements... except rowcount which is a number which is generated by other code... i checked in chrome(Firebug) and the number is generated correctly. But still the code only seem to work when i click on the select all other times it doesnt work also the hide no longer works when unselected,... where am i going wrong?

A: I think you're missing a closing brace on the first if(rowCount > 1), it should look like this:
jQuery(tableId).find("input[type='checkbox']").each(function() {
                    if (jQuery(this).attr('id') != headerCheckbox) {
                        jQuery(this).click(function() {
                            if (jQuery(headerCheckbox).is(':checked')) {
                                if (jQuery(tableId).find("input[type=checkbox]:checked").length != 1) {
                                    jQuery(removeButtonId).show();
                                    if (rowCount > 1) {
                                        jQuery(upButtonId).show();
                                        jQuery(downButtonId).show();
                                    }  // <----This one was missing
                                }
                            } else if (jQuery(tableId).find("input[type=checkbox]:checked").length > 0) {
                                jQuery(removeButtonId).show();
                                if (rowCount > 1) {
                                    jQuery(upButtonId).show();
                                    jQuery(downButtonId).show();
                                }
                            } else {
                                jQuery(removeButtonId).hide();
                                jQuery(upButtonId).hide();
                                jQuery(downButtonId).hide();
                            }
                        }
                    });
                    }
                });

That missing brace would certainly cause some strange problems.


text:
Q: How to create a nested dictionary which having same key values its childrens Well am trying to create a dictionary like below
Output
{
'user1':{
'user':'amal_jose',
'mark':100,
'subject':English
},
'user2':{
'user':'denil_jose',
'mark':100,
'subject':English
},
'user3':{
'user':'james_jose',
'mark':100,
'subject':English
},
'user4':{
'user':'hendry_jose',
'mark':100,
'subject':English
},
'user5':{
'user':'denil_jose',
'mark':100,
'subject':English
}

from this input
Users_Inputs=
{
'amal_jose':(100,'English'),
'denil_jose':(100,'English'),
'james_jose':(100,'English'),
'hendry_jose':(100,'English'),
'ladest_jose':(100,'English')
}

Well I tried  with following code but it did'nt worked and it prints only the last values
            for name,subject_Details in Users_Inputs.items():
                for details in subject_Details:
                    data['SchoolID']=5
                    data['name']=name
                    data['mark']=details[0]
                    data['subject']=details[1]
             print(data)

I would like to know how to get the result in such a way of nested dictionary

A: You are close to a correct solution.
It prints only the last value because data is outside of the for loop
Assuming data is a dict you can use:
for index,name,subject_Details in enumerate(Users_Inputs.items()):
                data["user"+index] = dict()
                for details in subject_Details:
                    data["user"+index]['SchoolID']=5
                    data["user"+index]['name']=name
                    data["user"+index]['mark']=details[0]
                    data["user"+index]['subject']=details[1]
             print(data)

this will create a data variable that contains all the users

A: This is very close to your code I just did some minor tweaks.
Users_Inputs= {
'amal_jose':(100,'English'),
'denil_jose':(100,'English'),
'james_jose':(100,'English'),
'hendry_jose':(100,'English'),
'ladest_jose':(100,'English')
}
i=1
ans = {}
for k,v in Users_Inputs.items():
    dic = {}
    dic['user'] = k
    dic['mark'] = v[0]
    dic['subject'] = v[1]
    ans['user'+str(i)] = dic
    i+=1
ans

Output:
{'user1': {'user': 'amal_jose', 'mark': 100, 'subject': 'English'},
 'user2': {'user': 'denil_jose', 'mark': 100, 'subject': 'English'},
 'user3': {'user': 'james_jose', 'mark': 100, 'subject': 'English'},
 'user4': {'user': 'hendry_jose', 'mark': 100, 'subject': 'English'},
 'user5': {'user': 'ladest_jose', 'mark': 100, 'subject': 'English'}}


text:
Q: Firefox blocks my nvidia drivers MOZ_GLX_IGNORE_BLACKLIST When I load a WebGL website on Firefox 5 in my Ubuntu 11.04 system, I get a grey screen and a warning on the terminal like this:
[GLX] your GL driver is currently blocked. If you would like to bypass this, define the MOZ_GLX_IGNORE_BLACKLIST environment variable.

Acceleration works fine on Google Chrome. How can I enable back acceleration for Firefox?

A: I don't know why the driver is on the blacklist, but you can do what's suggested: try running MOZ_GLX_IGNORE_BLACKLIST=1 firefox.
If this works, you can modify the .desktop file /usr/share/applications/firefox.desktop and change the line
Exec=firefox %u`

to
Exec=env MOZ_GLX_IGNORE_BLACKLIST=1 firefox %u

A: Have you installed the proprietary drivers or are you using the default ones that come with Ubuntu. Nouveau for what I know does not support the requirements for WebGL... yet. But if you install for the time being the nvidia Proprietary ones you will get full support. If i may ask, what video card are you using. You only need one that support OpenGL ES 2.0. Test here: http://doesmybrowsersupportwebgl.com/ to see what support you have and if you can install the proprietary ones if not yet installed.


text:
Q: wpColorPicker - problem with implementation to post meta I need your help as I am stuck and Google does not return anything, so I must be doing something obiusly wrong here, I just don't know what.
Basically, I need color input in one of my custom post types meta and I am trying to use a new WordPress 3.5 colorpicker for that. I could simply find another script and use it, but if it's already bundled with WP, that's what I should use.
So anyway, this is what I have done:
I have this input field in custom metabox:
<input name="mv_cr_section_color" type="text" id="mv_cr_section_color" value="<?php echo $sections_color; ?>" data-default-color="#ffffff">

I have this piece for enqueueing the script needed:
wp_enqueue_script( 'wp-color-picker' );

and finally I have this custom js:
jQuery('#mv_cr_section_color').wpColorPicker();

wrapped in .ready()
Result is this:
Input field gets hidden (it gets display: none inline urle applied to it), if I uncheck that (using Google Chrome), when I click the field nothing happens (:focus should trigger colorpicker). If I then unhide colorpicker (it is spawned, I see it in source) I can use it and it functions normally, default color also works well but I just can't find the reason why field gets hidden and why it does not open colorpicker on focus.
Anyone have any idea, I am really ... about this :)
Thanks
EDIT: Just the note, no error in console.

A: I tried the following and it works:
function wpse_80236_Colorpicker(){
    // you forgot this probably it's the bundled CSS
    wp_enqueue_style( 'wp-color-picker');
    //
    wp_enqueue_script( 'wp-color-picker');
}

add_action('admin_enqueue_scripts', 'wpse_80236_Colorpicker');

Then your input:
<input name="mv_cr_section_color" type="text" id="mv_cr_section_color" value="#ffffff" data-default-color="#ffffff">

Then the following js:
jQuery(document).ready(function($){
    $('#mv_cr_section_color').wpColorPicker();
});


text:
Q: What does set -e command does in Unix? What does the set -e command do in SHELL scripting?
Like the following command:
set -e

Can we do any other things with set -e operation?

A: The 'set' command is used set and examine shell options, as well as set positional parameters.
The -e flag does the following:
  -e  Exit immediately if a command exits with a non-zero status.

Hope this helps :)

A: Using the flag -e you ensure stops the execution if a command during the execution has an error.
The default behaviour is to ignore the errors in script executions.
If you want to manage this errors, you can use the command "trap".


text:
Q: AWS DynamoDB and Nodejs integration - how to filter between two dates? I have a small nodejs script connected to my DynamoDB and one of my primary sort keys is datetime, which is represented in UTC.
I would like to filter the results by a certain date and time and am having issues with my Filter Expression.
var params = {
  TableName: "realtimeusers",
  ProjectionExpression: "brand, datetime, activeusers",
  KeyConditionExpression: "brand = :brand",
  FilterExpression: "datetime > :today",
  ExpressionAttributeValues: {
    ":brand": "BRAND A",
    ":today": 1464705900
  },
};

I get the error message:
 "message": "Invalid FilterExpression: Attribute name is a reserved keyword; reserved keyword: datetime",

I think I am missing something in my filter expression that I don't fully grasp.
Can some one please help?

A: "datetime" is a reserved dynamo keyword. The reserved keywords are not allowed in dynamo query expressions.
The way around this is to use Expression attribute names when querying for such properties.
Reference:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html#ExpressionAttributeNames


text:
Q: How to force method to use a mock? My application consists of various concrete Job-classes (all inheriting from the abstract Job class). In their Run() method they usually call external services.
I'd like to test my job classes and mock the service results.
Here's how a typical concrete Run() method looks:
    InstallWpJobResult result = new InstallWpJobResult();
    WpManager wpManager = new WpManager();
    if (!WpManager.InstallWp(Domain, SiteTitle, WpUsername, WpPassword, WpEmail))
        result.Error = "Error installing WordPress";
    return result;

I'd like the WpManager.InstallWp to return true (in the mocked version).
I know how to mock the object and method but how do I make my job use the mocked version? (Right now it creates an instance within the method itself).
Btw I'm using the Moq framework for mocking.

A: A few options:

*

*Define a factory service IWpManagerFactory that is injected into your job class, with a method to construct your mocked WpManager.

*Define a virtual method BuildWpManager in your job and override the method in your test to inject your mock.

Quick example of the factory service approach:
public interface IWpManagerFactory
{
    WpManager BuildWpManager();
}

public sealed class Tests
{
    public void Test()
    {
        var manager = new Mock<WpManager>();
        //Set up mock manager here...

        var factory = new Mock<IWpManagerFactory>();
        factory.Setup(f => f.BuildWpManager()).Returns(manager.Object);

        //Inject factory to class under test and execute the method under test...
    }
}

This assumes of course that your WpManager has virtual methods that can be mocked.  If not, you'll need to extract an IWpManager interface as well, then mock that instead.

A: Instantiating concrete classes inside consumer classes goes against one of the SOLID principles (the "D" or "Dependency Injection"). One of the reasons is the one you ran across: testability.
I suggest you make the WpManager take an instance of IInstallWpJobResult (note it is an interface) as part of its construction, rather than instantiating one. This way you can easily change the behavior of the class given different IInstallWpJobResult implementations, e.g. passing in a Mock<IInstallWpJobResult> with predefined behavior for easier testing.
This will also come in handy once you start using Dependency Injection frameworks to resolve all those dependencies at runtime, since they usually look at the arguments of a constructor to get an idea of dependencies to inject.


text:
Q: How Do I Read Raw Input in C++/CLI Here's my problem.
I am trying to get raw input from attached devices. I am using the information on MSDN to figure it out, but it's been very difficult for me to make sense of some of it.
I believe I have successfully created a RAWINPUTDEVICE object and registered a device with RegisterRawInputDevices(). Now I am trying to figure out how to use the GetRawInputDeviceList() and GetRawInputDeviceInfo() functions. The big trouble is trying to understand the parameters they take, which includes a RAWINPUTDEVICELIST object, a HANDLE, a LPVOID, and a PUINT.
What are those variables and how do I use them?
Here's what I've gotten to work:
Important stuff in the header file:
#include <Windows.h>
#include <Winuser.h>

Important thing in the CPP file:
// I do not know where I found this not what it does, but it fixed some errors
   // that I could not solve. MSDN did not mention it.
#pragma comment(lib, "user32.lib")

And the stuff that works, and the thing that does not:
RAWINPUTDEVICE rid[1];

rid[0].usUsagePage = 1;
rid[0].usUsage = 6;
rid[0].dwFlags = 0;
rid[0].hwndTarget = NULL;

// awesomeSauce returned true, so it works
bool awesomeSauce = RegisterRawInputDevices(rid, 1, sizeof(RAWINPUTDEVICE) );

// Nothing past this point works
UINT numDevices = GetRawInputDeviceList(NULL, NULL, sizeof(RAWINPUTDEVICELIST));

How do continue?
I am a little bit rusty at C++, and what you see here is pretty much the sum of my knowledge with raw input. I do not know if it will effect anything, but I am using C++/CLI, not regular C++. How do I go from this, to getting some kind of unbuffered raw input (preferably from the keyboard)?
Edit:
Most examples I find have a switch statement. I don't understand how it works though. I have something like this:
UINT msg; // How does this work?
switch(msg)
{
case WM_CREATE:
    executeCase = 1;
    break;
case WM_INPUT:
    executeCase = 2;
    break;
}

How does the msg variable work? How can I create and assign one correctly?

A: According to the MSDN page for GetRawInputDeviceList, here's the documentation for the first parameter (which you're passing as null):

An array of RAWINPUTDEVICELIST structures for the devices attached to the system. If NULL, the number of devices are returned in *puiNumDevices.

And here's the documentation for the return value:

If the function is successful, the return value is the number of devices stored in the buffer pointed to by pRawInputDeviceList.

You're passing null for the first parameter, and expecting the number of devices to be present in the return from the method. The documentation doesn't say it will do that.
Pass an actual variable for the second parameter, and read that instead of the return code.
If that doesn't solve your problem, please be more specific with "this is the thing that doesn't work". Tell us how it doesn't work: does it throw an exception, is there an error return code, does a black hole open up and swallow your computer whole?

Edit
In your comment, you're still storing the return value in numDevices. Also, you're using the second parameter as an array. An array of length 1 is basically the same thing, but it'd be better to think of it as a pointer to an integer.
Here's a copy of the sample code from the MSDN page, with my comments added in. Give this a try.
UINT nDevices;
PRAWINPUTDEVICELIST pRawInputDeviceList;

// Pass a null pointer to find out how many devices there are.
if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVCELIST)) != 0) { Error();}

// Now, malloc the needed storage, based on the output parameter, NOT the return value.
if ((pRawInputDeviceList = malloc(sizeof(RAWINPUTDEVICELIST) * nDevices)) == NULL) {Error();}

// Finally, call for real, passing in the newly allocated buffer.
if (GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST)) == (-1) {Error();}

// after the job, free the RAWINPUTDEVICELIST
free(pRawInputDeviceList);


text:
Q: Gtk3 Popover outside the window How can i make Popover appears outside application window like menu in gnome-shell panel? Or should i use another GTK widget?

A: This should be possible (at least on wayland).
gtk_popover_set_constrain_to (GtkPopover *popover,
GtkPopoverConstraint constraint);
"GTK_POPOVER_CONSTRAINT_NONE"
and
gtk_popover_set_pointing_to (GtkPopover *popover,
const GdkRectangle *rect);


text:
Q: Windows command line - filter lines with non-zero values I have a file.data whose content is as below:
140919071513,10,0,1,0,0
140919071513,11,0,1,0,0
140919071513,12,67,1,0,0
140919071513,13,89,1,0,0
140919071513,14,0,1,0,0
140919071513,15,32,1,0,0
140919071513,16,0,1,0,0
140919071513,17,0,1,0,0
140919071513,18,78,1,0,0
140919071513,19,0,1,0,0
140919071513,20,34,1,0,0

I need to run a one-line command in Windows-DOS to get the below output:
(non-zero values in 3rd column)
140919071513,12,67,1,0,0
140919071513,13,89,1,0,0
140919071513,15,32,1,0,0
140919071513,18,78,1,0,0
140919071513,20,34,1,0,0

I used this command to try to get something, but couldn't get the desired result.
for /f "tokens=* delims=," %i in file.data do echo %i

Thanks

A: Just for the case that you have Powershell at hand:
Import-Csv .\file.data -Header "A","B","C","D","E","F"|where {$_.C -ne 0}|foreach-object {Write-host("$($_.A),$($_.B),$($_.C),$($_.D),$($_.E),$($_.F)")}

The last part with the "foreach-object {Write-Host..." might be optimized, but it works in this case.

A: findstr /v /r /c:"^[^,]*,[^,]*,0," file.data

This will list all the lines that does not match (/v) the regular expression (/r) : from the start of the line (^) any sequence of zero or more characters that does not contain a comma ([^,]*), followed by a comma, any sequence of zero or more characters that does not contain a comma, a comma, a zero and a comma.

A: In cmd.exe you can do the following:
for /f "tokens=1-3,* delims=," %i in (tst.txt) do @if %k GTR 0 echo %i,%j,%k,%l

Almost, what you tried, but a few changes:
... do @if ..// The @ will disable echo of the command itself ...
tokens=1-3,* // the first three tokens will be translated into variables
delims=,     // %i, %j and %k. The rest of each line ends up in %l

%k GTR 0     // GTR="greater", is a comparison of the third column against 0

This will get you
140919071513,12,67,1,0,0
140919071513,13,89,1,0,0
140919071513,15,32,1,0,0
140919071513,18,78,1,0,0
140919071513,20,34,1,0,0


text:
Q: How to pass data from url without a ? like domaintools.com/domainname.com using PHP What is the code in PHP
How to pass data from a URL using a ? is straight forward.
http://localhost/raw.php?topic=news
What is needed is to pass data like domaintools.com does just with the data after the /
news.com/football
news.com/politics
A. domaintools.com/stackoverflow.com
B. gives the whois on file (from domaintools database) and even changing the url to fit there system
C. https://whois.domaintools.com/stackoverflow.com
I have googled many permutations of keywords, php code passing via url not a using a ? and many variations of the such with other terms like $path etc
My guess is we missing something easy and/or we just don't know the right question to ask.

A: Using "?" is called GET parameter, you can use POST parameters to post data to an endpoint


text:
Q: Ocaml Opam install camlbz2 Error while installing camlbz2
%opam install camlbz2
...
...
. checking bzlib.h usability... no
. checking bzlib.h presence... no
. checking for bzlib.h... no

awk: line 1: regular expression compile failed (syntax error ^* or ^+)
^+
configure: error: not found 'opam install camlbz2' failed.
I can not find anything for opam to install something like "libbz2" or whatever, any suggestions?

A: OPAM only deals (currently) with OCaml source packages.
Here, your problem comes from the ./configure script of the OCaml package detecting that a system package is missing, not an OCaml package (you can see that it has searched for files with a .h extension, i.e. a C include file).
To fix your problem, you need to install this system package. As Ontologiae said, the missing package is related to the libbz2 library, and include files are usually provided in development packages, so you should probably try to install libbz2-dev using the system installer of your OS. This package is not in OCaml, so there is no risk of messing up with OPAM installation.
Note that, since you use opam config -env to set your OCaml environment, even if you install OCaml packages with your system installer, there should be no bad interaction with packages installed in your homedir by OPAM.

A: You need to install the libbz2 C library. So, check your package system and install it.
In Debian, it's the package "libbz2-dev" (so sudo apt-get install libbz2-dev)


text:
Q: Webpack: ExtractTextPlugin: Not to generate separate empty JS file when have several css entry points? I have several CSS entry points:
entry: {
  ...
  styles: [
    ...
  ],
  fonts: [
    ...
  ]
},

and I'm using ExtractTextPlugin to bundle CSS separately:
  new ExtractTextPlugin({
    filename: `[name].bundle.css`
  }),

So like output I have 2 CSS files: styles.css and fonts.css that is correct but also empty styles.js and fonts.js. Is there a way to not generate empty JS files?

A: I put together a webpack plugin to remove extra files based on their final output size as I had the same issue - given these files tend to be very small, it seems to just be a case of checking how large they are and removing the small, useless ones.
Install using npm or yarn
npm install webpack-extraneous-file-cleanup-plugin --save-dev
yarn add webpack-extraneous-file-cleanup-plugin --dev

In your webpack.config.js file:
const ExtraneousFileCleanupPlugin = require('webpack-extraneous-file-cleanup-plugin');

module.exports = {
  ...
  plugins: [
    new ExtraneousFileCleanupPlugin({
      extensions: ['.js']
    })
  ]
}

You can see the full list of options on the Webpack Extraneous File Cleanup Plugin Github Page

A: Only add the main javascript files as entries and require all fonts and style via require('./style.css')
webpack.config.js:
entry: {
  'main': 'app/main',
},
output: {
  path: 'static',
  publicPath: '/static/',
  filename: '[name].bundle.js',
  chunkFilename: '[chunkhash].bundle.js',
},
module: {
  rules: [
    {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: 'css-loader'
      }),
    }]
},
plugins: [
  new ExtractTextPlugin('[name].bundle.css'),
],

That would give you a /static/main.bundle.css with all css (transitively) included from your app/main.js.
Same for fonts, but you would need a second ExtractTextPlugin instance like:
const extractCSS = new ExtractTextPlugin('stylesheets/[name].bundle.css');
const extractFonts = new ExtractTextPlugin('stylesheets/[name].bundle.woff');

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: extractCSS.extract([ 'css-loader', 'postcss-loader' ])
      },
      {
        test: /\.woff$/i,
        use: extractFonts.extract([ 'url-loader' ])
      },
    ]
  },
  plugins: [
    extractCSS,
    extractFonts
  ]
};

See the Documentation - Multiple Instances for more info about that.

A: I don't think there's any way to do what you are trying to do, the same question has been asked on the github issue tracker, without any solution. If the problem is with the html-webpack-plugin adding the empty js files, you should be able to fix that by explicitly specifying what chunks to include or exclude.


text:
Q: pagefile and disk space monitoring on server 2012 I have had a server crash recently because of the disk space.
Here is what I have:
a Hyper-V 2012 server with 1 win 2012 image
physical disk is 500GB server uses 800GB
It was OK for half a year but recently users started to upload all sort of data and 3 of my local drive got nearly 90% full. It this time the page file got bigger and the server went pause:critical disk space mode
I have now started to monitor the disk space on the hyper-v, image disks and the pagefile through powershell.
Would someone give some explanation what do I need to check from these csv log files?
I know this is weak explanation but I am a newbie and I am learning what to do. My aim is to prevent another crash by monitoring the usage and when it gets 90% of the usage I would alert users to act. This is a temporary solution for school time and I will 'reformat' or buy new disks to be able to cope with the load. However I would like to know how much I need to buy and what is the dynamic of usage of the school.
Please feel free to ask specific questions and I will dig out to make the question more precise. I also keen to learn to monitor page file usage which is auto setup by the server at this point.
Any hint or direction would greatly appreciate. (I inherited this server so I need to know what information to gather to get the full picture).

A: As a first step I would adjust all the clients so the page file is a fixed size, then you don't have to worry about it growing out of control:
You can use GPO to deploy this fix to many machines as described in this post.

A: This may not be the best answer, but I would configure some monitoring platform like Nagios to watch the servers. Stuff like this happens all the time, and if this is a client, you need to know there's an issue before the users do. I have used Nagios for years to watch my servers, and it sends emails if there's anything that goes sideways. I have configured it to watch the local disk storage as well. You could look into other similar solutions.
Another way to do this would be to script your powershell check as a scheduled task that will send an email using sendmail if there's an issue with space. Really, anything you do going forward will be a time investment into learning. I honestly think you should learn something like Nagios, but learning some PS Scripts that also generate email alerts would be good as well.
Good Luck!


text:
Q: PHP global keyword and assignment I have defined a $foo global variable.
Later, I want to set $foo to something else.
public function bar()
{
    global $foo;
    $foo = 'hello';
}

Are there any unexpected side effects to shortening this to one line?
public function bar()
{
    global $foo = 'hello';
}

I have looked in the documentation and don't see them declaring and assigning the variable on the same line. Therefore, I'm wondering if anyone else has experienced issues doing this, or if it's just bad coding practice to put it on one line?

A: If you attempt to run the code you suggested in your question, you will get a syntax error. You cannot define a global variable like you have above.
If you wanted to still define that value in a single line you could use the $GLOBALS array instead like this:
public function bar(){
    $GLOBALS['foo'] = 'hello';
}

Here's the documentation if you want to have a look.

You could set the variable up here:
function bar(){

    global $hello;
    $hello = "hello";

}

Then later on edit it like this:
function foo(){
    $GLOBALS['hello'] = "world";
}

If you ran this code:
bar();
foo();

print_r($GLOBALS);

The value of $GLOBALS['hello'] will be 'world'. When run the other way around with foo(); executing before bar(); you'll get 'hello' as the global value instead.

A: My solution in one line without using $GLOBALS:
global $foo; $foo = 'hello';
A bit messy, but still looks better in some cases, than 2 lines of code for one assignment.


text:
Q: pip.install has stopped working: "Could not find a version that satisfies the requirement " I have seen a few related questions, and I've tried all of their recommendations:

*

*I'm using anaconda, so I downgraded from 3.7 to 3.6

*I upgraded pip using curl https://bootstrap.pypa.io/get-pip.py | sudo python

*I installed the latest version of openssl (1.1.1)

*I updated all Anaconda libraries

*I am connected to the Internet (obviously, since I'm posting here) and not behind a firewall.

And yet, every time I run "pip install " or "pip install ==" I get the following error:
ERROR: Could not find a version that satisfies the requirement  (from versions: none)
ERROR: No matching distribution found for
I'm on a Mac, Mojave v10.14.4
I recently installed prodigy.ai, which seemed to replace a bunch of packages with (perhaps) older versions, but I still cannot figure out how to fix this issue.  The one thing I haven't tried is uninstalling Anaconda and reinstalling it.
Thanks for any help on this.

A: Yes, it happened to me also.
A common case in this procedure is to check if you have not made a typo when entering the package name.


text:
Q: How to pass args to aspnet_regiis via powershell I have 2 scripts:
Launch.ps1
Deploy.ps1

Launch simply runs deploy as administrator:
clear
$scriptPath      = split-path -parent $MyInvocation.MyCommand.Definition
$scriptPathToRun = "$scriptPath\Deploy.ps1"
Start-Process -Verb runAs PowerShell -ArgumentList '-noexit','-File', $scriptPathToRun

I am trying to pass arguments to aspnet_regiis, I have tried the following:
Start-Process -NoNewWindow "$env:windir\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis" -ArgumentList '–ga',  'domian\serviceAccount'

Start-Process -NoNewWindow "$env:windir\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis" -ArgumentList '–ga domian\serviceAccount'

Start-Process -NoNewWindow "$env:windir\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis" -ArgumentList @('–ga', 'domian\serviceAccount')

& "$env:windir\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis" '–ga domian\serviceAccount'

& "$env:windir\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis" '–ga', 'domian\serviceAccount'

& "$env:windir\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis" @('–ga', 'domian\serviceAccount')

In all these attempts, aspnet_regiis is run but it appears no args are passed to it because the output is just a listing of available aspnet_regiis parameters.
Can someone point out what I'm missing?  Thanks.

A: The simplest answer is probably to just run the command using the call/invocation (&) operator:
& "$env:SystemRoot\Microsoft.Net\Framework64\v4.0.30319\aspnet_regiis" -ga domain\serviceAccount

If you really wanted to use Start-Process, you should be able to write it this way:
Start-Process "$env:SystemRoot\Microsoft.Net\Framework64\v4.0.30319\aspnet_regiis" "-ga","domain\serviceAccount" -NoNewWindow

The first token on that command line is the executable to run (i.e., -FilePath). The -ArgumentList parameter is an array (i.e., "-ga","domain\serviceAccount").


text: Q: Huion pen not working I just bought a huion 420 and no matter what I do the pen won't work. It won't move the mouse at all. I think maybe it's the battery and I'm trying to take it out but I can't. How do i take out the battery? And if any of you had a huion tablet that wasn't working, how'd you fix that problem?


text:
Q: Why does RGoogleDocs need to allocate a vector of 3.2Gb to run? I recently installed RGoogleDocs from github:
> devtools::install_github("duncantl/RGoogleDocs")

The package compiled and installed successfully, apart from the last line of output:
...
** building package indices
** testing if installed package can be loaded
* DONE (RGoogleDocs)
Making 'packages.html' ... done
Reloading installed RGoogleDocs
Error : cannot allocate vector of size 3.2 Gb

Whenever I try to use the library, I get that same error:
> library(RGoogleDocs)
Error : cannot allocate vector of size 3.2 Gb
In addition: Warning messages:
1: In .registerS3method(fin[i, 1], fin[i, 2], fin[i, 3], fin[i, 4],  :
  restarting interrupted promise evaluation
2: In get(method, envir = home) :
  restarting interrupted promise evaluation
Error: package or namespace load failed for 'RGoogleDocs'

3.2 Gb seems an awful lot of RAM. Is there some mistake I am making or is this just a very memory-hungry package? I only have 2 Gb available in this machine.

A: Restarting the R session fixed this issue.


text:
Q: How to make a bump app in android? I would like to add a bump feature in my app in android but since its gaining momnentum now only,I couldn't get a proper implementation pattern for it.Any expertise on it,please help me with your valuable suggestions.Thanks

A: Take a look at Bump Technologies Bump API http://bu.mp/api

A: Your question is too broad.
First : the newer phones may have NFC support. So you have to learn How to NFC
Second : In the case that the phones don't have NFC, you'll have to do with GPS and the gryo sensor based information. To improve the algo, you should consider using Bearing, Altitude etc.


text:
Q: Openvpn is very slow After installation openvpn and dnsmasq, I found the web browsing is very slow. I tried to configure the server.conf, and then use http://speedof.me/  to test.  Here is the result:
 Download   Upload
   34         15       NO VPN
   13         17
   1.06       890k     VPN-    no comp-lzo
   900k       1.08m  VPN -   comp-lzo
   1.04      530
   370        1.24
   610      910    nocomp_lzo + sndbuf 393216  + rcvbuf 393216
    630       870
    0.99    860
    790   790
     870   1.07       sendbuf+recebuf   mtu mssfix   with different buf size.
     1.11  1.13
     1     1.18
     1.09    970
     250     360        mtu+mssfix with different value
     260     540
     1.06    860
     1.07    900

Both server and client are Ubuntu 1404. From the table, the performance is degraded significantly. Without VPN, the download can easily go to 15M, while it becomes 1M or less after connection.
sendbuf and recebuf
I do not think this is issue, since the fix for it has been included in 2.3.9 (change discussion and Change commit), while the VPN version on my side are both 2.3.10.
I tried some values and push both to client (Sample configuration), but little performance is improved.
MTU+mssfix+fragment :
I tried many combinations for these three values (6000, 0, 0), (6000, 0, 1440), (48000, 0, 0), and change the cipher method accordingly. But still little helps (Tunning).
Since it is too slow, and experience of web browser is very BAD. Does anyone have a good suggestion, or optimized configuration values, or suggestion? Thanks in advance.
My current server.conf
#################################################
# Sample OpenVPN 2.0 config file for            #
# multi-client server.                          #
#                                               #
# This file is for the server side              #
# of a many-clients <-> one-server              #
# OpenVPN configuration.                        #
#                                               #
# OpenVPN also supports                         #
# single-machine <-> single-machine             #
# configurations (See the Examples page         #
# on the web site for more info).               #
#                                               #
# This config should work on Windows            #
# or Linux/BSD systems.  Remember on            #
# Windows to quote pathnames and use            #
# double backslashes, e.g.:                     #
# "C:\\Program Files\\OpenVPN\\config\\foo.key" #
#                                               #
# Comments are preceded with '#' or ';'         #
#################################################

# Which local IP address should OpenVPN
# listen on? (optional)
;local a.b.c.d

# Which TCP/UDP port should OpenVPN listen on?
# If you want to run multiple OpenVPN instances
# on the same machine, use a different port
# number for each one.  You will need to
# open up this port on your firewall.
port 1194

# TCP or UDP server?
;proto tcp
proto udp

# "dev tun" will create a routed IP tunnel,
# "dev tap" will create an ethernet tunnel.
# Use "dev tap0" if you are ethernet bridging
# and have precreated a tap0 virtual interface
# and bridged it with your ethernet interface.
# If you want to control access policies
# over the VPN, you must create firewall
# rules for the the TUN/TAP interface.
# On non-Windows systems, you can give
# an explicit unit number, such as tun0.
# On Windows, use "dev-node" for this.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel if you
# have more than one.  On XP SP2 or higher,
# you may need to selectively disable the
# Windows firewall for the TAP adapter.
# Non-Windows systems usually don't need this.
;dev-node MyTap

# SSL/TLS root certificate (ca), certificate
# (cert), and private key (key).  Each client
# and the server must have their own cert and
# key file.  The server and all clients will
# use the same ca file.
#
# See the "easy-rsa" directory for a series
# of scripts for generating RSA certificates
# and private keys.  Remember to use
# a unique Common Name for the server
# and each of the client certificates.
#
# Any X509 key management system can be used.
# OpenVPN can also use a PKCS #12 formatted key file
# (see "pkcs12" directive in man page).
ca ca.crt
cert server.crt
key server.key  # This file should be kept secret

# Diffie hellman parameters.
# Generate your own with:
#   openssl dhparam -out dh2048.pem 2048
dh dh2048.pem

# Network topology
# Should be subnet (addressing via IP)
# unless Windows clients v2.0.9 and lower have to
# be supported (then net30, i.e. a /30 per client)
# Defaults to net30 (not recommended)
;topology subnet

# Configure server mode and supply a VPN subnet
# for OpenVPN to draw client addresses from.
# The server will take 10.8.0.1 for itself,
# the rest will be made available to clients.
# Each client will be able to reach the server
# on 10.8.0.1. Comment this line out if you are
# ethernet bridging. See the man page for more info.
server 10.8.0.0 255.255.255.0

# Maintain a record of client <-> virtual IP address
# associations in this file.  If OpenVPN goes down or
# is restarted, reconnecting clients can be assigned
# the same virtual IP address from the pool that was
# previously assigned.
ifconfig-pool-persist ipp.txt

# Configure server mode for ethernet bridging.
# You must first use your OS's bridging capability
# to bridge the TAP interface with the ethernet
# NIC interface.  Then you must manually set the
# IP/netmask on the bridge interface, here we
# assume 10.8.0.4/255.255.255.0.  Finally we
# must set aside an IP range in this subnet
# (start=10.8.0.50 end=10.8.0.100) to allocate
# to connecting clients.  Leave this line commented
# out unless you are ethernet bridging.
;server-bridge 10.8.0.4 255.255.255.0 10.8.0.50 10.8.0.100

# Configure server mode for ethernet bridging
# using a DHCP-proxy, where clients talk
# to the OpenVPN server-side DHCP server
# to receive their IP address allocation
# and DNS server addresses.  You must first use
# your OS's bridging capability to bridge the TAP
# interface with the ethernet NIC interface.
# Note: this mode only works on clients (such as
# Windows), where the client-side TAP adapter is
# bound to a DHCP client.
;server-bridge

# Push routes to the client to allow it
# to reach other private subnets behind
# the server.  Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
;push "route 192.168.10.0 255.255.255.0"
;push "route 192.168.20.0 255.255.255.0"

# To assign specific IP addresses to specific
# clients or if a connecting client has a private
# subnet behind it that should also have VPN access,
# use the subdirectory "ccd" for client-specific
# configuration files (see man page for more info).

# EXAMPLE: Suppose the client
# having the certificate common name "Thelonious"
# also has a small subnet behind his connecting
# machine, such as 192.168.40.128/255.255.255.248.
# First, uncomment out these lines:
;client-config-dir ccd
;route 192.168.40.128 255.255.255.248
# Then create a file ccd/Thelonious with this line:
#   iroute 192.168.40.128 255.255.255.248
# This will allow Thelonious' private subnet to
# access the VPN.  This example will only work
# if you are routing, not bridging, i.e. you are
# using "dev tun" and "server" directives.

# EXAMPLE: Suppose you want to give
# Thelonious a fixed VPN IP address of 10.9.0.1.
# First uncomment out these lines:
;client-config-dir ccd
;route 10.9.0.0 255.255.255.252
# Then add this line to ccd/Thelonious:
#   ifconfig-push 10.9.0.1 10.9.0.2

# Suppose that you want to enable different
# firewall access policies for different groups
# of clients.  There are two methods:
# (1) Run multiple OpenVPN daemons, one for each
#     group, and firewall the TUN/TAP interface
#     for each group/daemon appropriately.
# (2) (Advanced) Create a script to dynamically
#     modify the firewall in response to access
#     from different clients.  See man
#     page for more info on learn-address script.
;learn-address ./script

# If enabled, this directive will configure
# all clients to redirect their default
# network gateway through the VPN, causing
# all IP traffic such as web browsing and
# and DNS lookups to go through the VPN
# (The OpenVPN server machine may need to NAT
# or bridge the TUN/TAP interface to the internet
# in order for this to work properly).
push "redirect-gateway def1"

# Certain Windows-specific network settings
# can be pushed to clients, such as DNS
# or WINS server addresses.  CAVEAT:
# http://openvpn.net/faq.html#dhcpcaveats
# The addresses below refer to the public
# DNS servers provided by opendns.com.
push "dhcp-option DNS 10.8.0.1"
push "dhcp-option DNS 208.67.222.222"
push "dhcp-option DNS 208.67.220.220"

# Uncomment this directive to allow different
# clients to be able to "see" each other.
# By default, clients will only see the server.
# To force clients to only see the server, you
# will also need to appropriately firewall the
# server's TUN/TAP interface.
;client-to-client

# Uncomment this directive if multiple clients
# might connect with the same certificate/key
# files or common names.  This is recommended
# only for testing purposes.  For production use,
# each client should have its own certificate/key
# pair.
#
# IF YOU HAVE NOT GENERATED INDIVIDUAL
# CERTIFICATE/KEY PAIRS FOR EACH CLIENT,
# EACH HAVING ITS OWN UNIQUE "COMMON NAME",
# UNCOMMENT THIS LINE OUT.
;duplicate-cn

# The keepalive directive causes ping-like
# messages to be sent back and forth over
# the link so that each side knows when
# the other side has gone down.
# Ping every 10 seconds, assume that remote
# peer is down if no ping received during
# a 120 second time period.
keepalive 10 120

# For extra security beyond that provided
# by SSL/TLS, create an "HMAC firewall"
# to help block DoS attacks and UDP port flooding.
#
# Generate with:
#   openvpn --genkey --secret ta.key
#
# The server and each client must have
# a copy of this key.
# The second parameter should be '0'
# on the server and '1' on the clients.
;tls-auth ta.key 0 # This file is secret

# Select a cryptographic cipher.
# This config item must be copied to
# the client config file as well.
;cipher BF-CBC        # Blowfish (default)
;cipher AES-128-CBC   # AES
;cipher DES-EDE3-CBC  # Triple-DES
;cipher none
# Enable compression on the VPN link.
# If you enable it here, you must also
# enable it in the client config file.
;comp-lzo

# The maximum number of concurrently connected
# clients we want to allow.
;max-clients 100

# It's a good idea to reduce the OpenVPN
# daemon's privileges after initialization.
#
# You can uncomment this out on
# non-Windows systems.
;user nobody

;group nogroup

# The persist options will try to avoid
# accessing certain resources on restart
# that may no longer be accessible because
# of the privilege downgrade.
persist-key
persist-tun

# Output a short status file showing
# current connections, truncated
# and rewritten every minute.
status openvpn-status.log

# By default, log messages will go to the syslog (or
# on Windows, if running as a service, they will go to
# the "\Program Files\OpenVPN\log" directory).
# Use log or log-append to override this default.
# "log" will truncate the log file on OpenVPN startup,
# while "log-append" will append to it.  Use one
# or the other (but not both).
;log         openvpn.log
;log-append  openvpn.log

# Set the appropriate level of log
# file verbosity.
#
# 0 is silent, except for fatal errors
# 4 is reasonable for general usage
# 5 and 6 can help to debug connection problems
# 9 is extremely verbose
verb 3

# Silence repeating messages.  At most 20
# sequential messages of the same message
# category will be output to the log.
;mute 20
;sndbuf 393216
;rcvbuf 393216
;push "sndbuf 393216"
;push "rcvbuf 393216"

tun-mtu  64800
mssfix  1440
;fragment 0

Another configurations at server side about IP forward:
#!/bin/sh -e

#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -s 10.8.0.0/24 -j ACCEPT
iptables -A FORWARD -j REJECT
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

service dnsmasq restart
exit 0

and net.ipv4.ip_forward=1


text:
Q: VS 2017 Setup Project wouldn't install in C:\DestFolder\ Due to the administrative privilege of the application, I need to install my program including .exe and .dll in C:\DestFolder\SubFolder\ but I keep getting C:\Program Files\\[Manufacturer]\\[Product Name]\ where the placeholders are specified in the properties window.
I tried this article but no good.
Please don't give me answer like try changing the defaultlocation to C:\Destination\ of the Application Folder as I have already tried. Also I don't want solution like just change the installation destination path manually during the installation.

A: I have found the answer from this article:
"[ProgramFilesFolder] is built in, and correctly leads to the Program Files directory on the target machine, no matter how customized the setup of Window is..."
There might be tools out there that allow installing outside of Program Files.
[Edit] Infact I've found out this great extension for VS 2017 community called Wix. There's a guy who did a fabulous tutorial on it.


text:
Q: How can we select data when we used key words as access database table names and field name in delphi I am using delphi and access database. I used a keyword as a table name and field name.
Ex : User \ Date \ Password.
How can i access it from delphi?
Below is the code i tried. It is working when i run it in Access. but same query can not run from delphi. it says syntax error in query.
select * from "User"
select * from User

A: try this :
select * from [user]

Maybe this link is something for you to read :
https://support.office.com/en-us/article/Access-SQL-basic-concepts-vocabulary-and-syntax-444d0303-cde1-424e-9a74-e8dc3e460671


text:
Q: Is my modulus logic for this loop correct? So here's the pattern i'm looking for
out of a finite set, I want to retrieve the first 2 values for one set, then followed by the next 4 for another set, then 2 for that first set, and then 4 for the other set, and so on..
grab 2 | grab 4 | grab 2 | grab 4 ...
$count = 0;
foreach ($listing as $entry){
  if ($count % 4 == 0){
       // add to 4-item set
  } else if ($count % 2 == 0){
       // add to 2-item set
  }
  $count++;
}

My confusion is that when $count%4=0 then $count%2 will also = 0.
So should i be safe by not reaching the wrong modulus case (since both are true for any arbitrary number divisible by 4) by checking first if $count%4 == 0?

A: Not correct
You should grab to set 1 when count is 2, 8, 14, etc
Currently you are grabbing when count is 2, 4, 8, etc
And to set 2 when count is 6, 12, 18, etc
Currently it's when count is 4, 8, 12, etc
So condition 1 is ((count-2) % 6) == 0
And condition 2 is (count != 0) && (count % 6) == 0
Here's something that should work
$count = 0;
foreach ($listing as $entry){
  if ($count < 2){
       // add to 2-item set
  } else {
       // add to 4-item set
  }

  if ($count < 6) $count++;
  else $count = 0;
}

Or if you want to grab 2/4 items at a time:
$count = 0;
foreach ($listing as $entry){
  if ($count == 2){
       // add 2 items to 2-item set
  } elseif ($count == 6) {
       // add 4 items to 4-item set
  }

  if ($count < 6) $count++;
  else $count = 0;
}

A: If I get it right, your desired distribution is actually:
A A, B B B B, A A, B B B B, A A, B B B B, ...

So you want to group them into six and then pick the first two into basked A, the other four into B:
if ($count % 6 < 2){
   // add to 2-item set
}
elseif ($count % 6 < 6){
   // add to 4-item set
}

Splitting it into if/elseif will ensure that the items only end up in either one. The < n comparison on the % 6 distribution would mean:
$count % 6 =    0  1  2  3  4  5  0
        if =   <2 <2 <6 <6 <6 <6 <2
    basket =    A  A  B  B  B  B  A

A: This wouldn't work, for the exact reason that you specified.
Ways that this could be made to work are

*

*Use a modulo of 6, and then each time its module 6, add the first two elements starting from count - 6 to set1, and the next 4 to set2.

*Use a boolean switch, when the switch is true, add the elements to set 1, after 4 elements set the switch to false, and when the switch is false add elements to set2 flipping the value of the switch when you're done adding elements to set2.


text:
Q: Передача данных по TCP через интернет Подскажите пожалуйста, как реализовать передачу данных между двумя программами, установленными на разных ПЭВМ по протоколу TCP через интернет. (то есть айпишники публичные, не локальные). Как поднять локальный TCP сервер я знаю, но когда речь идет о сетевом взаимодействии, увы... Что делаю не так или может я о чем-то не догадываюсь, помогите.
СЕРВЕР:
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Any, 8888);
using Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
socket.Bind(ipPoint);
socket.Listen(100);

КЛИЕНТ:
            using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //тут указал условный публичный айпишник сервера
                await socket.ConnectAsync("94.103.226.200", 8888);
                IPEndPoint ipPoint = new IPEndPoint(IPAddress.Any, 9999);
                MessageBox.Show($"Подключение к {socket.RemoteEndPoint} установлено");
            }
            catch (SocketException)
            {
                MessageBox.Show($"Не удалось установить подключение");
            }

A: Код данного ПО вполне рабочий, действительно, но вот достучаться до сервера, который развернут на ПК, который в свою очередь имеет выход в инет только через роутер, не вариант без дополнительных танцев. Существует такая штука как NAT, которая отвечает за переадресацию трафика. Публичный айпишник - это айпишник не ПК, а роутера, а роутер уже внутри сети раздает всем свои айпишники по типу 192.168.0.1 и т.д. Так вот что бы все было ок - нужно зайти в настройки роутера -> настройки NAT -> добавить порт (в моем случае был 13400) и настроить переадрисацию на ПК с сервером. Вуаля!


text:
Q: How do I make truncate log script as dynamic SQL in SQL Server? I am using the below script to truncate the log files of a database. But I have to execute the below script results in separate window due to this I am not able to schedule the jobs .
SET NOCOUNT ON

SELECT
      'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
    + 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY)'
    + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
         sys.master_files mf
    JOIN sys.databases d
        ON mf.database_id = d.database_id
WHERE d.database_id > 4 and mf.type_desc = 'LOG'

Expected O/P is script has to run instead of copy pasting the above query results

A: SET NOCOUNT ON

DECLARE @LOG TABLE (
  QUERY varchar(max)
)
DECLARE @QUERY varchar(max)

INSERT INTO @LOG
  SELECT
    'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
    + 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY)'
    + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
  FROM sys.master_files mf
  JOIN sys.databases d
    ON mf.database_id = d.database_id
  WHERE d.database_id > 4
  AND mf.type_desc = 'LOG'

DECLARE C CURSOR FOR
SELECT
  QUERY
FROM @LOG
OPEN C
FETCH NEXT FROM C INTO @QUERY
WHILE @@FETCH_STATUS = 0
BEGIN
  PRINT @QUERY
  EXEC (@QUERY)
  FETCH NEXT FROM C INTO @QUERY
END
CLOSE C
DEALLOCATE C

A: You can achieve this with Dynamic SQL, without using a cursor:
SET NOCOUNT ON

DECLARE @SQL VARCHAR(MAX) = ''

SELECT @SQL = @SQL +
      'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
    + 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY);'
    + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
         sys.master_files mf
    JOIN sys.databases d
        ON mf.database_id = d.database_id
WHERE d.database_id > 4 and mf.type_desc = 'LOG'

PRINT   (@SQL)
EXEC    (@SQL)

Does the same thing...


text:
Q: ajax call with jquery asp.net mvc I have a button with the class "btn" and span with id "ajaxtest". When I click on the button I want to put text "test" in my span tag. And this to be done in ASP.NET MVC.
In the View I have the following ajax call:

<input type="submit" class="btn" name="neverMind" value="Test BTN"/>

In MyController I have the following code:
    public string MyAction()
    {
        return "test";
    }

I know how Ajax works, and I know how MVC works. I know that maybe the error is because we are expecting something like this in the controller:
public ActionResult MyAction()
    {
        if (Request.IsAjaxRequest())
        {
              //do something here
        }
        //do something else here
    }

But actually that is my problem. I don't want to call some partial View with this call. I just want to return some string in my span and I'm wondering if this can be done without using additional partial views.
I want to use simple function that will only return the string.

A: Change dataType: 'string'  to dataType: 'text'

I check it my local it will work for me


text:
Q: When triple count is very large, why is sparql federated query so slow, but local query so fast? I set up SPARQL endpoints on several linux servers (RDF database: fuseki 4.4.0, Number of triples: 6,000,000), and then queried several SPARQL endpoints through SPARQL Federated Query.
Results: sparql federated query is so slow, but local query so fast.
Sparql federated query (very slow: Several hours passed and there was no response):
SELECT * WHERE {
    {
        SERVICE SILENT <fuseki endpoint 1> {
            SELECT * WHERE {
                ?s ?p ?o .
            }
        }
    }
    UNION
    {
        SERVICE SILENT <fuseki endpoint 2> {
            SELECT * WHERE {
                ?s ?p ?o .
            }
        }
    }
} OFFSET 0 LIMIT 5

Local query (very fast, used 0.02 s):
SELECT * WHERE {
    ?s ?p ?o .
} OFFSET 0 LIMIT 5

However, querying Virtuoso with the same sparql statement is very fast. Such as DBpedia, although there are hundreds of millions of triples.

A: SERVICE will return all results (a single HTTP request) for the SERVICE block. It does not know there is an overall query limit and a more complex query may be locally filtering of joining SERVICE results so they may need to be more than 5 returned.
Apache Jena 4.6.1 has new support for enhancing SERVICE: https://jena.apache.org/documentation/query/service_enhancer.html


text:
Q: Mongodb c#driver - AggregateToCollectionOperation I'm using the library MongoDB.Driver 2.8.1 (i'm planning to upgrade to the latest version, it's an old project).
I'm trying to use the operator $out for a query in my code so I wrote this piece of code (it's not wonderful, but it's not a problem)
await collectionAcc.Aggregate().AppendStage<BsonDocument>(@"{
                    $unwind: {
                        path: ""$Packs"",
                        preserveNullAndEmptyArrays: false
                    }
                }")
            .AppendStage<BsonDocument>(@"{
                    $replaceRoot: {
                                 newRoot: { $mergeObjects: [ ""$$ROOT"", {""Sku"" : ""$Packs.Sku"" }, {""SizePack"" : ""$Packs.Size"" } ] }
                            }
                }")
            .AppendStage<BsonDocument>(@"{ $out: ""accessoryPacks"" }").FirstOrDefaultAsync();

I run it and this error appear:
"The pipeline for an AggregateOperation contains a $out operator. Use AggregateOutputToCollectionOperation instead"
Good, I try to use AggregateOutputToCollectionOperation class but I found no documentation at all, nor a decent example.
Someone can help me?

A: oh, I missed that you call FirstOrDefault. $out and $merge should be the last stages in pipeline, but FirstOrDefault additionally adds { limit : 1 } stage after them. You should add this stage inside pipeline before $out


text:
Q: Basic question on how to redirect users to third party payment sites My sincere apologies, if this question is too vague but I am really curious in understanding how payment redirection works in web development without exposing data in url parameters.
In detail with example:

*

*I go to Jet blue website(jetblue.com), search for flight, choose flight, fill all the necessary information and select paypal as the payment option and click next.

*Browser redirects me to paypal website(paypal.com) and on the paypal website, it shows the correct amount from Jet Blue.

*I had chrome developer network tab opened and I don't see any POST requests to Paypal also nothing on the URL parameters relating to amount.

How is this done usually in Web development?

A: There are a number of ways.
The two most common are, data out of band, and data in band.
For "data in band" you would send the proposed information (like amount) at the time of the paypal button creation. I won't go too far into the process, but essentially you send the transaction information, then get back a token. That token is then passed at the time of the actual redirection. The servers code is responsible for tracking the PayPal token against the actual transaction.
For "out of band" method, you would essentially create a static button. This works great for payments that don't vary in price.  There is no need to get a token because you made the button years or months in advance.
You can see more info at https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/create_payment_button/
In both cases, PayPal will  send a notification back to the site, or it's administrators, when the transaction completes.
There are tons of ways this can work,  and many different ways to accomplish all the steps, but that is the basics.


text:
Q: Add range is not working with list I am having payee contact details object like this
public class PayeeContactDetails
{

    //[JsonProperty("id")]
    //[DefaultValue("")]
    //public int ID { get; set; }

    [JsonProperty("contact_name")]
    [DefaultValue("")]
    public string ContactName { get; set; }

    [JsonProperty("contact_email")]
    [DefaultValue("")]
    public string ContactEmail { get; set; }
    ........
    ........
}

and here i am having PayeeContactGroup class like this
 public class PayeeContactGroup
 {
    [JsonProperty("payee_contacts")]
    public List<PayeeContactDetails> PayeeContact { get; set; }

 }

here i am getting data from api response on page by page after completion of all pages i need to send all data at a time to DB
for this purpose i am doing like this
 PayeeContactGroup payeeContactDetails = new PayeeContactGroup();

  var response = httpClient.GetAsync(uri).Result;
  if (response.IsSuccessStatusCode)
  {
     string data = response.Content.ReadAsStringAsync().Result;
     var payeeContactGroupDetails = JsonConvert.DeserializeObject<PayeeContactGroup>(data);

     if(payeeContactGroupDetails.PayeeContact != null && payeeContactGroupDetails.currentPage == 1)
      {
         payeeContactDetails.PayeeContact = payeeContactGroupDetails.PayeeContact.ToList();
      }
      else if(payeeContactGroupDetails.PayeeContact != null && payeeContactGroupDetails.currentPage > 1)
      {
         payeeContactDetails.PayeeContact.AddRange(payeeContactGroupDetails.PayeeContact); // error at this line
      }
      .......
      ......
  }

But i am getting error at
    this line
"payeeContactDetails.PayeeContact.AddRange(payeeContactGroupDetails.PayeeContact);"
    Error  : "Object reference not set to an object"
Could any one please help on this ....
    Many thanks in advance

A: You need to create the List first:
public class PayeeContactGroup
 {
    [JsonProperty("payee_contacts")]
    public List<PayeeContactDetails> PayeeContact { get; set; } = new List<PayeeContactDetails>();

 }

Or create the List only when necessary:
PayeeContactGroup payeeContactDetails = new PayeeContactGroup();

var response = httpClient.GetAsync(uri).Result;
if (response.IsSuccessStatusCode)
{
   string data = response.Content.ReadAsStringAsync().Result;
   var payeeContactGroupDetails = JsonConvert.DeserializeObject<PayeeContactGroup>(data);

   if(payeeContactGroupDetails.PayeeContact != null && payeeContactGroupDetails.currentPage == 1)
    {
       payeeContactDetails.PayeeContact = payeeContactGroupDetails.PayeeContact.ToList();
    }
    else if(payeeContactGroupDetails.PayeeContact != null && payeeContactGroupDetails.currentPage > 1)
    {
         if(payeeContactDetails.PayeeContact == null)
         {
              payeeContactDetails.PayeeContact = new List<PayeeContactDetails>();
         }
         payeeContactDetails.PayeeContact.AddRange(payeeContactGroupDetails.PayeeContact); // error at this line
    }
      .......
      ......
}

A: Initialise the empty list first before adding. Or the AddRange method is trying to add to null. This could be done in code:
PayeeContactGroup payeeContactDetails = new PayeeContactGroup();

payeeContactDetails.PayeeContact = new List<PayeeContactDetails>();


text:
Q: How to map references in different VB.Net solutions I just come to a small company.
There are more than 500 solutions in different VS.Net versions and even VB 6.0 projects. They share several dll.
Is there a way to map relation between each program? How can I know in advance what solutions references to a DLL and will have an impact if I change this dll solution.

A: In your situation, I would probably write a few small utility programs that can iterate though your stored source code and list which programs reference which dlls.
For example, in VB6, the .vbp file lists which dlls are used:
Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\stdole2.tlb#OLE Automation
Reference=*\G{420B2830-E718-11CF-893D-00A0C9054228}#1.0#0#C:\WINDOWS\system32\scrrun.dll#Microsoft Scripting Runtime
Reference=*\G{50A7E9B0-70EF-11D1-B75A-00A0C90564FE}#1.0#0#C:\WINDOWS\system32\SHELL32.dll#Microsoft Shell Controls And Automation

In VB.NET, similar information is stored within the .vbproj file:
<ItemGroup>
<COMReference Include="IWshRuntimeLibrary">
  <Guid>{F935DC20-1CF0-11D0-ADB9-00C04FD58A0B}</Guid>
  <VersionMajor>1</VersionMajor>
  <VersionMinor>0</VersionMinor>
  <Lcid>0</Lcid>
  <WrapperTool>tlbimp</WrapperTool>
  <Isolated>False</Isolated>
  <EmbedInteropTypes>True</EmbedInteropTypes>
</COMReference>

Where I work it is also common to reference custom dlls from Excel VBA.  To find these, you would open the Excel (or other MS Office) files and read the VBA Add-in Model "References" collection and the "Office.COMAddins" collection.


text:
Q: EditText very ugly with appcompat I recently updated appcompat and this caused EditText to look very bad on pre-Lollipop versions.
Here is the theme I use :
 <style name="Theme.Launcher" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowShowWallpaper">true</item>
</style>

It doesnt look like Material Design EditText at all
Please help me
Thanks


text:
Q: Unable to load resource from jar on latest JVM versions Loading resource files from a jar file (a png to build an ImageIcon) worked well for 18 years. Still works with Hotspot java version "1.8.0_333". Running with Hotspot java version "18.0.1.1" fails to load the resource... All this with the same jar file, that I did check and contains the resource file.
String fileName = "/images/logo.png";
ImageIcon image = new ImageIcon();

byte[] imageBytes = null;
InputStream in = image.getClass().getResourceAsStream(fileName);
if (in == null) {
  System.out.println("could not find " + fileName);
}

Above - code snippet. in is effectively null when using 18.0.1.1... Anyone has seen difference in processing getResourceAsStream from one version to the other ?


text:
Q: How to get a seekbar after clicking button I made an application on paint. I want to control the size of brush being used in paint using seek-bar.
In the menu(options) ,I have an option of changing brush size. So, by clicking on it, a seek bar should appear and I should be able to control that using save button (to set) and then use that value inside paint.
How do I do that?

A: Make seekbar visible inside xml or when you get its reference in onCreate method.
on button click make it visible.
Use latest values by registering OnSeekBarChangeListener on your Seekbar.


text:
Q: multi word href link placing words on top of each other in HTML/CSS? This is kinda hard to describe on the question title, but basically I am setting up a link that is from my mysql database.
When I print out the link here is an example of what is happening:
Link is in a table cell.
Red
Bull
Here is what I am trying to do:
 Red Bull
For some reason any multi-word links are putting the words on top of each other.
I have tried:
CSS a:
display: inline- block;
dislay: inline;

I've tried setting up a width, maybe the table cell was limiting the link space, but its not working either.
Even worse for my little issue here is the fact that the jsfiddle is working perfectly fine. http://jsfiddle.net/68xSj/ at least you can see what I am basically trying to accomplish

A: Literally just found the answer to this issue.
I'm not sure if this is on mysql serverside end or on how css reacts to a php call.
Basically, on mysql database I had written the "itemName" as eg. Red Bull.
when I made the php call in the second Cell div for some reason it placed Red on top of Bull as a link. To fix it, (i tried this right after posting) I simply had itemName =
Red&nbspBull.
This fixed the little bug.
As we all know   is a space in html, mysql pastes this into html and walaa.


text:
Q: jQuery - each function I currently have a list of thumbnails that is located in a ul tag as li's.
I am using the Galleria image gallery, but I have more than six images in my gallery, so am I trying to implement a page system.
What I am trying to do is the following:
I have a row of images, row1, when you click on page 2 row1 should hide using this function hide("slide"), and after all of them have hid, row2 should show using show("slide"), but these hide and show functions occur at the same time, I want the hide function to finish before the show function executes, here is my code:
$("a[href^='#']").click(function() {
    if (($(this).attr("href") == "#") && ($(this).attr("rel") != "gallery") && ($(this).attr("href").indexOf("row") < 0)) {
        return false;
    }
    else if ($(this).attr("href").indexOf("row") < 0) {
        $.scrollTo($(this).attr("href"),1000);
        return false;
    } else {
        var href = $(this).attr("href");
        href = href.replace("#","");
        $("ul.galleria li").each(function() {
            if ($(this).is(":visible")) {
                $(this).hide("slide");
            }
        }).;

        $("ul.galleria li."+href).each(function() {
            $(this).show("slide", 800);
        });
        return false;
    }
});

How can I have the hide function execute while the show function waits for a go ahead?
// edit
I have changed my code to the following:
$("ul.galleria li:visible").hide("clip", {direction : "horizontal"},function(){
    $("ul.galleria li."+href).show("clip", {direction : "horizontal"}, 800);
});

But now, the show function runs exactly the number of times as the number of li's that was visible on the previous 'page'. How can I have that function execute only once?

A: Use your call-backs. They run immediately after an effect is finished.
$(".item1").slideUp("fast", function(){
  // this is the callback. It will run only when .slideUp completes
  $(".item2").slideDown("fast");
});

A: Please try changing this:
$("ul.galleria li").each(function() {
                if ($(this).is(":visible")) {
                        $(this).hide("slide");
                }
        }).;

        $("ul.galleria li."+href).each(function() {
                $(this).show("slide", 800);
        });

to this:
    $("ul.galleria li:visible").hide("slide",function(){
            $("ul.galleria li."+href).stop().show("slide", 800)
     });

A: Solved it like so:
var counter = 0;
$("ul.galleria li:visible").hide("blind", {direction : "horizontal"},function(){
    counter++;
    if (counter <= 1) {
        $("ul.galleria li."+href).show("blind", {direction : "horizontal"}, 800);
    }
});

Thanks for all the help everyone!


text:
Q: Use custom pipe in multiple modules without sharedModule Is it possible to use CustomPipe in lazy modules without using common or shared modules. I don't want to write pipe for every module.
Below is my CustomPipe.ts
    import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'bypassHtml'
})

export class BypassHtmlPipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }

  transform(value: any): any {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }

}

Thank you in advance