Q:

Proper Way to Document Class in Netbeans PHP

For reasons of ease of maintenance AND IDE class auto-completion and member hinting, I've used PHPDoc in my project. Given this example class:
class my_class {
    public $id;
    public $name;
    public $number;

    public function __construct() {
        //Do something
    }

    public function Rename($name) {
        $this->name = $name;
    }
}

I would prefer to document all properties ($id, $name and $number) with the class documentation itself, which is above the class declaration, and then place documentation for methods (if necessary) above each method. Here is what I ultimately want my class to look like:
/**
 * Represents an example class for Stackoverflow
 *
 * @property int $id The id of the object
 * @property string $name The name of the object
 * @property int $number The number of the object
 */
class my_class {
    public $id;
    public $name;
    public $number;

    public function __construct() {
        //Do something
    }

    /**
     * Renames the object
     * @param string $name Name to rename object
     */
    public function Rename($name) {
        $this->name = $name;
    }
}

This is precisely what I prefer to have as documentation, however Netbeans' autocomplete fails to operate correctly, as it lists each property twice. For example, if I start typing $my_class_object->i the auto-complete will list two $id properties: one as described in my PHPDoc, and another is described as an unknown variable with "PHPDoc Not Found".
There is a solution that works to solve the Netbeans issue - add a @var PHPDoc block above each property, however I think it unnecessarily clutters up my class, especially some of my classes that have 10+ properties.
Is there a [good] solution to both of my issues (clean doc, proper Netbeans hinting), or am I going about this incorrectly?

A:

The "property" tag is specifically and explicitly for "magic" properties, meaning any that don't actually appear in the code itself.  That's the key reason why the tag occurs only in the class docblock.  As such, I'm guessing IDEs that recognize the "property" tag do so from that "it's NOT seen in the code" perspective.  Granted, I could understand an expectation that autocomplete should recognize the existence of such a property, and therefore make it available for you.  However, my bet is that the IDEs will stick with using only the code itself to build a model, and only use docblock info to supplement the elements that it already sees in the code.
Using the "var" tag is the one proper way to document your "coded" properties.  If you want to minimize the lines required in order to use that tag on all the properties, use a one-line docblock:
/** @var int */
public $id;

Also, you could use the docblock template to cut down on docblocks, where tag similarity fits your code:
/** @var string */
public $name;

/**#@+ @var int */
public $id;
public $number;
/**#@-*/

That doesn't seem like much savings in this short list, but it does help when there are lots of properties.  Also, it works fine around methods.

A:

I prefer to use @var above each property and no @property at all. I feel that this allows you to more closely associate the comments with the thing that is being commented on. I.e., the comments for a property are always right next to the property. If you're using the @property style and you've got a big class with a ton of properties, it's entirely possible that the comment which describes a property is pages away from it.


Q:

Central data storage for apps in Software Center

I am trying to make a package for the Software Center, but so far the problem is that there seems to be no central place to store data for all users.
We need that to store license files that the application can later add if the users want to use the non-free parts of our software. Also we use this for storing document templates that some users edit and make them available for all users on the system.
Is there any solution for this kind of problems? From what I see on this page:
http://developer.ubuntu.com/publish/

Write all configuration settings to ~/.<pkgName>
  (This can be one file or a directory containing multiple configuration files.)

EDIT: While talking to the Ubuntu staff it turns out there is no way you can have a central file storage for all users. At least not at the moment. I tried adding scripts to the debian source package that would create folders, but the staff looked at them and did not approve the version. At the moment we are saving the common files in the user .config folder.

A:

For licenses, you will want to use the license key mechanism built into Oneiric and the http://myapps.developer.ubuntu.com application submission portal.
I think you answered your own question as you want to store user space configuration settings to ~/.<somedir> or ~/.config/<somedir> - following the XDG standards would be suggested.


Q:

Ubuntu 14.04 - Redshift fails to launch on startup

I am posting this as a solution to a problem that I could not find anywhere on Google.
Redshift will not launch on startup as it has issues gathering longitude and latitude from geoclue. The issue appears to be with geoclue failing to get the users location.
Trying the following in terminal DOES NOT work for me:
redshift-gtk -l 55.7:12.6

I get an error stating too many arguments.

A:

Here's what I did to get it to work:
1) Under applications, go to Startup Applications. If an entry for Redshift already exists then click on it and then click on edit. Otherwise, click add. Set name to Redshift and set the comment to whatever you want. For the command, enter:
gtk-redshift -l manual

Click save.
2) In your home folder press ctrl+h and that should list all of the hidden folders(folders beginning with a '.'). Go into your .config folder and create a new file and call it redshift.conf. Paste the following:
; Global settings
[redshift]
temp-day=6500K
temp-night=5000
transition=1
;gamma=0.8:0.7:0.8
gamma=1.000:1.000:1.000
location-provider=geoclue
;location-provider=manual
adjustment-method=vidmode
;brightness=1.0:0.5

; The location provider and adjustment method settings
; are in their own sections.
; This is an example lat long for Portland, OR
[manual]
lat=YOURLAT
lon=YOURLON

; In this example screen 1 is adjusted by vidmode. Note
; that the numbering starts from 0, so this is actually
; the second screen.
;[vidmode]
;screen=1

Go here to get your latitude and longitude and replace 'YOURLAT' and 'YOURLON' with the respective values. Save and close the file. Restart computer and Redshift should have started(indicated by the lightbulb icon the the menu bar).
So, hopefully this helps someone. If this is against the rules or anything for whatever reason I apologize. Hopefully this helps someone out there.


Q:

Create new variables according length list

I've a follow list below. I'd like to transfer each item from list to different variables individually without to know its length
For example, consider the following list:
list1 = ['item1', 'item2', 'item3', 'item4']

The result expected is:
var1 = 'item1'
var2 = 'item2'
var3 = 'item3'
var4 = 'item4'

The real objective is avoid "out of range" error. Because I won't know the list length, and it can vary.
In another moment, for example, the list could be:
list1 = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7']

In this case, the result expected would be:
var1 = 'item1'
var2 = 'item2'
var3 = 'item3'
var4 = 'item4'
var5 = 'item5'
var6 = 'item6'
var7 = 'item7'

Let me give you a real case. My script connect to a firewall and execute the following command:

nameif = net_connect.send_command("show nameif")

MM1MDA-VRJRAE-SM01/act# show nameif
Interface                Name                     Security
Management0/0            mgmt                      99
TenGigabitEthernet1/7    dmzncl                    75
Port-channel1.279        dmz3                      80
Port-channel1.291        dmz5                      50
Port-channel1.293        dmz4                      70
Port-channel1.295        dmzvdi                    60
Port-channel1.2021       dmzvdi1                   60

The output from this command can vary, depending how many interfaces there is on device. There are cases that it can have 3 interfaces, 4 interfaces or much more... So,  I filter to a list:

nameif_entry = nameif.split()

After I remove other information that it doesn't matter:

del nameif_entry[0:4]
nameif_edited = nameif_entry[::3]
print (nameif_edited)
['mgmt', 'dmzncl', 'dmz3', 'dmz5', 'dmz4', 'dmzvdi', 'dmzvdi1']

After I run the following lines and send to many lists as below:

int_0 = net_connect.send_command("show route %s %s" %(nameif_edited[0],src_ip))
int_1 = net_connect.send_command("show route %s %s" %(nameif_edited[1],src_ip))
int_2 = net_connect.send_command("show route %s %s" %(nameif_edited[2],src_ip))
int_3 = net_connect.send_command("show route %s %s" %(nameif_edited[3],src_ip))
int_4 = net_connect.send_command("show route %s %s" %(nameif_edited[4],src_ip))
int_5 = net_connect.send_command("show route %s %s" %(nameif_edited[5],src_ip))
int_6 = net_connect.send_command("show route %s %s" %(nameif_edited[6],src_ip))
int_7 = net_connect.send_command("show route %s %s" %(nameif_edited[7],src_ip))
int_8 = net_connect.send_command("show route %s %s" %(nameif_edited[8],src_ip))
int_9 = net_connect.send_command("show route %s %s" %(nameif_edited[9],src_ip))
int_10 = net_connect.send_command("show route %s %s" %(nameif_edited[10], src_ip))

So it's here where the problem occurs. I receive a following error:

int_7 = net_connect.send_command("show route %s %s"
%(nameif_edited[7], src_ip)) IndexError: list index out of range

A:

If you do not know how long the list is beforehand, how do you plan to put enough variables into your source code to hold them?
Generally speaking if you have a list
list1 = ['item1', 'item2', 'item3', 'item4']

and you want to do something with each element, you would do:
for elem in list1:
    print(elem)  # this prints each element on a new line

You do not need an index at all (80+% of the time). If you need the index as well, use enumerate():
for index,elem in enumerate(list1):
    print(index, elem)

Output:
0 item1
1 item2
2 item3
3 item4

If you have an upper bound for your elements and "harmless" defaults you can cheat a bit:
a,b,c,d,e,f,g,h,i,k, *_ = list1 + [""]* 11

In this case the letters will be filled with the elements of list1 and any "non-present" element will take one of the empty strings. *_ will consume the rest of the list.
This only works for small ranges though - f.e. if you get 3-8 strings, and want to have "" for any that is not provided. I might use that if I need several of those strings together at once and not after one another.
Example:
list1 = ['item1', 'item2', 'item3','item4']
a,b,c,d,e,f,g,h,i,k, *_ = list1 + [""]* 11    # extract into 11 vars

for elem in [a,b,c,d,e,f,g,h,i,k,_]:    # stuff all of them back into a list to print
    print(elem)                         # using less code - lists are cool

Output:
item1  # a
item2  # b
item3  # c
item4  # d
       # e
       # f
       # g
       # h
       # i
       # k
['', '', '', '', '']  # _

Doku:

for loops
enumerate()
list of built in functions

Example for using the list decomposition (and a smarter way to do it - there almost always is a better way then resorting to the "cheaty" list decomposition with default values).
Task: calculate   f(x) = k_0 + k_1*x +k_2*x**2 + ... for up to x**5 from a user inputted list, that has 1 to 6 elements:
def calc_f(my_coeff, x):
    # padd list with enough 0 (neutral in our case) to avoid indexerrors
    """Using decomposition"""
    padded_list =  my_coeff + [0] * 6
    # extract into vars
    a,b,c,d,e,f,*_ = padded_list
    return a + b*x +c*x**2 + d*x**3 + e*x**4 + f*x**5

def calc_f_loop_1(my_coeff,x):
    """Using simple loop and manual sum"""
    s = 0
    idx = 0
    # basic approach without enumerate
    for elem in my_coeff:
        s += elem*x**idx
        idx+=1
    return s

def calc_f_loop_2(my_coeff,x):
    """Using better loop, still manual sum"""
    s = 0
    for idx, elem in enumerate(my_coeff):
        s += elem*x**idx
        idx+=1
    return s

all of those work ... but this is smarter (and more conceise):
calc_f_smarter = lambda l,x: sum( pl*x**idx for idx,pl in enumerate(l) )

Test:
list1 = [5, 3, 3, 4] # variable input - max. 6 numbers
for method, f in (
          ("calc_f",calc_f),
          ("calc_f_loop_1",calc_f_loop_1),
          ("calc_f_loop_2",calc_f_loop_2),
          ("calc_f_smarter",calc_f_smarter)):

    print(f"{method:<15}:", [f(list1,x) for x in range(-5,5)])

Outputs:
calc_f         : [-435, -215, -85, -21, 1, 5, 15, 55, 149, 321]
calc_f_loop_1  : [-435, -215, -85, -21, 1, 5, 15, 55, 149, 321]
calc_f_loop_2  : [-435, -215, -85, -21, 1, 5, 15, 55, 149, 321]
calc_f_smarter : [-435, -215, -85, -21, 1, 5, 15, 55, 149, 321]


Q:

How to save code doing it with OOP?

I'm writing a program to extract some data from txt files with regular expressions.
I'm new in OOP and want to save reiterative code. I want to retrieve about 15 data in each txt file, so I wrote a Class definition for each data.  The patters to match can come in several formats, so I'll need to try several regex patters.  By now, I only implements one regex patterns by data, but in future I need to try more in order to match the specific format used in that txt file, I plan to use a list with de patterns for each data.
I've just wrote 3 classes, but I've realized that I'm repeating too much code.  So, I believe that I'm doing something wrong.
import re
import os
import glob
import csv

class PropertyNumber(object):
    pattern_text = "(?<=FINCA Nº: )\w{3,6}"
    regex_pattern = re.compile(pattern_text)

    def __init__(self, str):
        self.text_to_search = str
        self.text_found = ""

    def search_p_number(self):
        matched_p_number = PropertyNumber.regex_pattern.search(self.text_to_search)
        print(matched_p_number)
        self.text_found = matched_p_number.group()
        return self.text_found

class PropertyCoefficient(object):
    pattern_text = "(?<=Participación: )[0-9,]{1,8}"
    regex_pattern = re.compile(pattern_text)

    def __init__(self, str):
        self.text_to_search = str
        self.text_found = ""

    def search_p_coefficient(self):
        matched_p_coefficient = PropertyCoefficient.regex_pattern.search(self.text_to_search)
        print(matched_p_coefficient)
        self.text_found = matched_p_coefficient.group()
        return self.text_found

class PropertyTaxIDNumber(object):
    pattern_text = "(?<=Referencia Catastral: )\d{7}[A-Z]{2}\d{4}[A-Z]\d{4}[A-Z]{2}"
    regex_pattern = re.compile(pattern_text)

    def __init__(self, str):
        self.text_to_search = str
        self.text_found = ""

    def search_tax_id(self):
        matched_p_taxidnumber = PropertyTaxIDNumber.regex_pattern.search(self.text_to_search)
        print(matched_p_taxidnumber)
        self.text_found = matched_p_taxidnumber.group()
        return self.text_found

def scan_txt_report(fli):
    data_retrieved = []
    file_input = open(fli, mode='r', encoding='utf-8')
    property_report = file_input.read()
    property_number = PropertyNumber(property_report)
    data_retrieved.append(property_number.search_p_number())
    property_coefficient = PropertyCoefficient(property_report)
    data_retrieved.append(property_coefficient.search_p_coefficient())
    property_tax_id_number = PropertyTaxIDNumber(property_report)
    data_retrieved.append(property_tax_id_number.search_tax_id())

    return data_retrieved

def main():
    if os.path.exists("./notas_simples/ns_txt"):
        os.chdir("./notas_simples/ns_txt")
        list_txt_files = glob.glob("*.txt")
        print(list_txt_files)
        with open("..\..\listado_de_fincas.csv", mode='w', newline='') as fiout:
            file_writer = csv.writer(fiout, delimiter=';')
            for file_name_input in list_txt_files:
                data_line = scan_txt_report(file_name_input)
                file_writer.writerow(data_line)

if __name__ == '__main__':
    main()

# TODO Idufir: "(?<=IDUFIR: )\d{14}"
# TODO calle: "(?<=Calle ).*"   Break down in street name and number of address
# TODO piso: "(?<=piso ).*,"    Break down in floor number and door number (or letter), without boundaries
# TODO titularidad: "(?<=TITULARIDAD\n\n).*"    Break down in owner name, VAT number, % and domai type.

As you can see above, the 3 classes I've already wrote: PropertyNumber(object), PropertyCoefficient(object) and PropertyTaxIDNumber(object), has a lot of repeated code.  Thus, when I add some regex patterns to each class will be worse.

A:

Yes, you are repeating much of your code, and yes, it is a sign of a weak design. I'll take this as an OOP exercise, because this is an overkill.
First, we can see that the only difference between the different classes is their essence, and their regex pattern. So we can have a base class which handles all the repetitive code. Now each subclass simply handles the different pattern:
class BaseProperty(object):
    def __init__(self, search_str, pattern):
        self.text_to_search = search_str
        self.text_found = ""
        self.regex_pattern = re.compile(pattern)

    def search_property(self):
        matched_property = self.regex_pattern.search(self.text_to_search)
        print(matched_property)
        self.text_found = matched_property.group()
        return self.text_found

class PropertyNumber(BaseProperty):
    def __init__(self, search_str):
        super(PropertyNumber, self).__init__(search_str, "(?<=FINCA Nº: )\w{3,6}")

class PropertyCoefficient(BaseProperty):
    def __init__(self, search_str):
        super(PropertyCoefficient, self).__init__(search_str, "(?<=Participación: )[0-9,]{1,8}")

Second, it doesn't appear that you're actually using the self.text_found field, so why store it? Now you can init all the properties in a single place, and make your scan_txt_report much simpler.
class BaseProperty(object):
    def __init__(self, pattern):
        self.regex_pattern = re.compile(pattern)

    def search_property(self, search_str):
        matched_property = self.regex_pattern.search(search_str)
        print(matched_property)
        return matched_property.group()

...
class PropertyCoefficient(BaseProperty):
    def __init__(self):
        super(PropertyCoefficient, self).__init__("(?<=Participación: )[0-9,]{1,8}")

properties = [PropertyNumber(), PropertyCoefficient(), ...]

def scan_txt_report(fli):
    file_input = open(fli, mode='r', encoding='utf-8')
    property_report = file_input.read()
    data_retrieved = [prop.search_property(property_report) for prop in properties]
    return data_retrieved

And unless you add some specific functionality for each subclass, you can even let go of the specific properties classes, and just do like this:
properties = [BaseProperty("(?<=FINCA Nº: )\w{3,6}"), BaseProperty("(?<=Participación: )[0-9,]{1,8}")]

And one last thing - please see the comment by @JonClements - it's a bad idea to use reserved words (such as str) as variable names.


Q:

"work for" / "work in" / "work at"

I would like to know what usually follows after each proposition in sentences with the word "work".
These are what i understand so far.
I work for my boss. ( usually for certain person )
I work in a accouting corporation. (usually for business area )
I work at Samsung. ( usually for specific name of company )
Could you please tell me kow if i understand rightly?

A:

I work for my boss.

This is OK grammatically, but feels odd to me because it seems rather tautological: by definition the person you work for is your boss, so there's no need to say so. It would be better to indicate the specific person who is your boss:

I work for him
I work for Amanda Jones
I work for Dr Jenkins
I work for the CEO (you'd only say this if you report directly to the CEO)

(Of course if you are self-employed, or unemployed, then you wouldn't be talking about working for somebody in the first place.)

I work in a accouting corporation. (usually for business area )

You wouldn't say that you work in a corporation, you'd say at or for them. It is correct to say in when talking about which part of the company you work for, or if you are talking about a place. So:

I work for an accounting company.
I work at a famous legal firm.
I work in the accounting department at Samsung.
I work in the cafeteria.
I work in London.
I work for Samsung in London.

(Also, note that it's an accounting corporation, not a accounting corporation.)

I work at Samsung.

This is correct. It would also be correct to say I work for Samsung.


Q:

jquery same ajax call kill

I have ajax request
  result = $.ajax({
              url: '/live-sell-search.php?id=123',
              success: function(result) {
              $('.results-list').html(result);
                }
            });

I call this on change and I am trying to kill previous call if it is in progress with somthing like this
if(result!='undefined'){resul.abort();}
and several variations of this but it is always braking at some point. Can anyone tell me how this can be done?

A:

As other people have stated, you need to start accepting answers.
Updated
I use this on a website and it works quite well for me.
When the onChange event is called, it checks if there is already an AJAX call in affect. If so, it aborts it and starts a new AJAX call.
Once the AJAX call has completed the xhr variable gets nulled. Simple really.
var xhr = null;

$("#textbox").change(function(){

    if( xhr != null ) {
         xhr.abort();
    }

    xhr = $.ajax({
              url: '/live-sell-search.php?id=123',
              complete: function( xhr ){
                  xhr = null; // empty xhr object
              },
              success: function( data ) {
                  $('.results-list').html( data );
              }
          });
});


Q:

Is it necessary to use addTestDevice?

I am using testAd ID (ca-app-pub-3940256099942544/1033173712) from admob not my admob ID, do I need to use addTestDevice() too while testing in mobile device?
It was even showing testAds screen, not the live ads.
Because I did this, and I used my app whole day for testing purpose, and I got account suspension mail at night.
Interstitial mInterstitial= new InterstitialAd(this);

    mInterstitial.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
    mInterstitial.loadAd(new AdRequest.Builder().build());

A:

There is no need to use addTestDevice () while using test ids. You only need it when you are using the live ads. There might be some other reason for your account suspension. Test ad ids have no link to your admob account.
Check the details here https://developers.google.com/admob/android/test-ads
As they have clearly mentioned
"The quickest way to enable testing is to use Google-provided test ad units. These ad units are not associated with your AdMob account, so there's no risk of your account generating invalid traffic when using these ad units"


Q:

Enforce transactions in firebase

I'm currently building my first app with firebase. So far so good, the database is flexible and easy to use, I love it.
I'm building a full web app, meaning that all the code and logic will be executed in the browser. For some updates, I'll need transactions to make sure that the data remains consistent.
But not everybody likes order and consistent data, and I'm worried that some people may try to create their own faulty client to attack my application.
tl;dr: Is there a way to enforce transactions for certain updates, when we're only using web clients?

A:

You can't enforce transactions per-se, but you can enforce what their effects on the data will be. For example, if you want a particular field to be only incremented by 1 at a time, you can write security rules like:
{
  "rules": {
    "counter": {
      ".write": "newData.val() == data.val() + 1"
    }
  }
}

In your client code, you can use the transaction() function to propertly increment counters, but if someone tries to write data outside of what your security rules enforce that would fail.


Q:

Angular remote form not displaying error

I have created an angular form that displays input validation errors received from the server. My solution works fine except for one small issue.
If I submit the form with no value, after the page loads, I am receiving the correct response from my server i.e. 422, but the validation error is not displayed. If I then start typing a value in the input the validation error flashes and disappears.
I am almost certain that it has something to do with my directive, but I'm not sure how to fix it. This is my current directive code:
var appServices = angular.module('webFrontendApp.directives', []);

appServices.directive('serverError', function(){
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope,element,attrs,ctrl){
      element.on('change keyup', function(){
        scope.$apply(function(){
          ctrl.$setValidity('server', true);
        });
      });
    }
  };
});

I think the issue is with the element.on('change keyup'.... section of this code. That's why the error message flashes when I start typing. Also when I change this to 'change' instead of 'change keyup', the error message is displayed permanently when I start typing.
Does anybody have an idea of how I can display the error message even if I did not type any value into the input before submitting it the first time?
UPDATE AS PER COMMENT
Here is my form:
<form ng-submit="create(memberData)" name="form" novalidate>

     <input type="text" ng-model="memberData.email" placeholder="janedoe@mail.com"  name="email" class="col-xs-12 form-control" server-error>

       {{errors.email}}

    <button type="submit" class="btn btn-danger col-xs-12">Join Private Beta</button>

</form>

And my controller:
$scope.memberData = {};
$scope.create = function() {
    var error, success;
    $scope.errors = {};
    success = function() {
      $scope.memberData = {};
    };
    error = function(result) {
        angular.forEach(result.data.errors, function(errors, field) {
            $scope.form[field].$setValidity('server', false);
            $scope.errors[field] = errors.join(', ');
        });
    };

    BetaMember.save({ beta_member: { email: $scope.memberData.email || "" }}).$promise.then(success, error);

};

A:

It seems that there was an extremely simple workaround. Since I had the filter form.email.$dirty in my view, the error would not be displayed if the user clicked submit without clicking on the form first.
After removing form.email.$dirty and only having form.email.$invalid, it works perfectly. I think this is sufficient in my case, as this validation is dependant on a server response and will not be triggered before the form is submitted. The error object is also cleared up in my controller ensuring that the page does not load an error when it's first loaded.


Q:

How to overcome loading chunk failed with Angular lazy loaded modules

If I make changes to my angular app the chunk names will change on build and the old version will be remove from the dist folder. Once deployed if a user is currently on the site and then navigated to another part of the site I get a loading chunk failed error as the old file is no longer there.
My app is built using angular cli so it's packaged using webpack.
Is there anyway this can be overcome.

A:

PWA SOLUTION BELOW
I had the same problem and found a pretty neat solution that is not mentioned in the other answers.
You use global error handling and force app to reload if chunks failed.
import {ErrorHandler, Injectable} from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  handleError(error: any): void {
   const chunkFailedMessage = /Loading chunk [\d]+ failed/;

    if (chunkFailedMessage.test(error.message)) {
      window.location.reload();
    }
  }
}

It is a simple solution and here (Angular Lazy Routes & loading chunk failed) is the article I got it from.

EDIT: Convert to PWA
Another solution can be to convert your Angular site to a PWA (Progressive Web App). What this does is add a service worker that can cache all your chunks. Every time the website is updated a new manifest file is loaded from the backend, if there are newer files, the service worker will fetch all the new chunks and notify the user of the update.
Here is a tutorial on how to convert your current Angular website to a PWA. Notifying the user of new updates is as simple as:
import { Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Injectable()
export class PwaService {
  constructor(private swUpdate: SwUpdate) {
    swUpdate.available.subscribe(event => {
      if (askUserToUpdate()) {
        window.location.reload();
      }
    });
  }
}

A:

I keep my old chunks in place for a couple days after an update for just this purpose. My app also consists of mini-SPAs, so as they move around, they're likely to pick up the new version during a page load.


Q:

How do I get all input args combined without redundancy?

I want to get all combinations without replacement for args (files) A, B and C.
That is I want to get the combinations
A B
B C
A C

without redundant ones like B A.
Is it possible to do that easily with GNU parallel?
My current command looks like:
 parallel 'echo {1} {2}' ::: (ls *txt) ::: (ls *txt)

but this prints all combos.
Ps. there are many more files than three, so general solutions only please.

A:

There is no elegant solution:
parallel 'test "{1}" \< "{2}" && echo {1} {2}' ::: *txt ::: *txt


Q:

jqGrid toolbar search and Django

i'm using jqGrid to add Toolbar Search like the example in the Toolbar Search Example
and already implemented basics and advanced examples like site tutorials and my page is like this
but i don't know how to use this feature in Django !!! what's the name of those input types on the top of my grid !??
the example is not clear  ! can you help me ??
[here's my source code on github][4]
{% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Index Page</title>

    <link rel="stylesheet" type="text/css" media="all" href="{% static "css/bootstrap.min.css?id=1" %}"/>

    <link rel="stylesheet" type="text/css" media="screen" href="{% static "css/ui.jqgrid.css" %}" />
    <link rel="stylesheet" type="text/css" media="screen" href="{% static "css/ui-lightness/jquery-ui.min.css" %}" />

models.py:
from django.db import models
from datetime import datetime

class room_type(models.Model):
    id = models.IntegerField(primary_key = True)
    code = models.CharField(max_length = 40)
    name = models.CharField(max_length= 40 )
    title = models.CharField(max_length = 40)
    english_title = models.CharField(max_length=40)
    capacity = models.IntegerField()
    extra_capacity = models.IntegerField()
    description = models.CharField(max_length=255)

    class Meta:
        db_table = 'room_types'
    def __unicode__(self):
        return u'%d' % (self.id)

class room_icon(models.Model):
    id = models.IntegerField(primary_key = True)
    status  =  models.IntegerField()
    color_of_icon =  models.CharField(max_length=40)
    path_of_icon  =  models.CharField(max_length=255)

    #foreign_key : a room has only one icon
    rt_id = models.ForeignKey(room_type)
    class Meta:
        db_table = 'room_icons'
    def __unicode__(self):
        return u'%d' % (self.id)

class attachment(models.Model):

    id = models.IntegerField(primary_key = True)
    path_of_pic = models.CharField(max_length=255)

    #foreign key : a room has many images
    rt_id = models.ForeignKey(room_type)
    class Meta:
        db_table = 'attachments'
    def __unicode__(self):
        return u'%d' % (self.id)

views.py:
from django.shortcuts import render
from django.utils import simplejson
from django.http import HttpResponse
from rooms.models import *
from django.db.models import Q
from django.core import serializers

def index(request):
    return render(request, 'index.html')

def getdata(request):
    data=room_type.objects.all()
    json=[]
    for o in data:
        json.append({'id':o.id, 'name':o.name, 'english_title':o.english_title, 'capacity':o.capacity})

    return HttpResponse(simplejson.dumps(json), mimetype='application/json',content_type='application/json' )

def getpricelist(request):

    requested_room_id = request.GET.get('id', '')

    room = room_type.objects.get(id = requested_room_id)
    price_list_set = room.price_list_set.all()

    json=[]
    for price_list in price_list_set:
        json.append({'from':price_list.from_date, 'to':price_list.to_date, 'price':price_list.price})

    return HttpResponse(simplejson.dumps(json), mimetype='application/json',content_type='application/json' )

    class price_list(models.Model):

        id = models.IntegerField(primary_key = True)
        from_date = models.CharField(max_length=10)
        to_date   = models.CharField(max_length=10)
        price = models.IntegerField()
        #foreign key : a room has a pricee list
        rt_id = models.ForeignKey(room_type)
        class Meta:
            db_table = 'price_lists'
        def __unicode__(self):
            return u'%d' % (self.id)

Final Edit :
if I've edited the html file , and now all the files are correct , if you need django source code for jqGrid examples(toolbar search , advanced master detail , and load json data) you can use mine , just work fine ;) !!
Tnx again @Oleg for great help ;)

A:

I'm not Django developer, but the server side code looks like it returns the array of all unsorted items. In the case you should use loadonce: true option of jqGrid. In the case jqGrid saves all data in internal parameters data and _index and change datatype option to "local" after the first load. After that the searching works on the client side and you don't need to make any changes in the server code.
If you use loadonce: true option and you need reload the data from the server (for example after changing url) then you have to reset datatype to its original value datatype: "json":
$("#list_d").jqGrid("setGridParam", {
    url: "getpricelist?q=1&id=" + encodeURIComponent(ids),
    page: 1,
    datatype: "json"
}).trigger("reloadGrid");

I would recommend to consider to use additionally datatype: "local" in the second (details grid). The current code use url:'getpricelist?q=1&id=2', datatype: "json". So the second grid will be filled before a row in the first grid selected. Using datatype: "local" prevents the loading.
I recommend you to use gridview: true and autoencode: true options in the both grids and to add key: true property to the definition of "id" column in the first grid. If you do this then id of
 elements (the rows of the grid) will be assign to the values from id column. It can simplify editing operations.
The last remark: jqGrid assign always id attribute (known as rowid) to every row of the grids. id have to be unique over the whole page. If you have more as one grid you could have id conflicts in the grids. To be sure that you don't have the problem you can consider to use different idPrefix parameters (for example idPrefix: "g1_" and idPrefix: "g2_") for different grids (of for one from the grids). In the case the rowid values will be build from the idPrefix and the id assigned from your data (for example id column in the first grid). If you need to cut the prefix (for example to use it as a parameter in the URL) you can use $.jgrid.stripPref method. For example you can use $.jgrid.stripPref($(this).jqGrid("getGridParam", "idPrefix"), ids) instead of id during building url of detailed grid.


Q:

Add form elements after Ajax call

I'm building a form that allows users to enter a word, and when they tab off I query a dictionary(Wordnik.com) to retrieve the definitions, and add the definitions as radio button selections to the form. The javascript picks up the word, calls the get_definition function in my WordsController and queries the dictionary API, but I can't seem to get the partial to render (right now it just prints out "<%= escape_javascript.....%>")
PS: I also tried querying the api directly with jquery (so I'm not hitting the get_definitions function) but I couldn't get the request to send, so I'm sticking with the above method for now.
words_controller:
def index
    @words = Word.where(user_id: current_user)
    @word = current_user.words.new
    @defs = Array.new
end

def get_definition
    @defs = Wordnik.word.get_definitions(params['word'])
    render nothing: true
end

javascript:
$('input#word_name').blur(function(){
    var word = $('input#word_name').val();
    $.ajax({
            url: '/words/get_definition',
            data: 'word='+word
    })
    $('#addDefinitionContainer').html("<%= escape_javascript(render partial: 'words/definitions', locals: {f: f}) %>")
})

_definitions partial:
<% @defs.each do |definition| %>

   <%= f.label definition %>
   <%= f.radio_button :definition, "yes" %>

<% end %>

A:

Instead of trying to render the ruby partial in javascript I decided to manually add the form elements instead, in js. After the ajax call to my ruby method, I call the following method as the callback:
function addDefsToForm(data){
    $.each(data, function(index,item){
        var radio = $('<input />', { id: 'word_definition_'+index, name: 'word_definition', type: 'radio', value: item['text']});
        $('#addDefinitionContainer').append(radio);
        $('#addDefinitionContainer').append(item['text']+"
");
    });

};

This adds a radio button (with associated text) to the page for each definition I receive. However, the radio button chosen by the user doesn't get send along with the word in the POST request. The solution of which is to call the jquery serialize() function on the form upon submission:
$('form').submit(function(){
    $(this).serialize();
});

I suppose since these added form elements (radio buttons) aren't in the DOM when the page first renders, they won't be looked for upon form submission. The serialize function goes over the form as it is now and prepares a new string to be sent.


Q:

How Can I Reproduce the Chevron in Windows 7 as a CheckBox Control?

I've been working on trying to recreate the section header that is used in the Computer section of Windows Explorer in Windows 7.
(This can be found by opening a new Explorer window and selecting Computer.  View should be Tiles and Group By should Type.  This will give a section for "Hard Disk Drives".  I'm trying to recreate that chevron and header
I've created the following resource dictionary:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:Framework.Commons.Controls">

    <Style x:Key="ChevronBase" TargetType="{x:Type Path}">
        <Setter Property="StrokeThickness" Value=".75" />
        <Setter Property="Stretch" Value="Fill" />
        <Setter Property="RenderTransformOrigin" Value="0,0" />
        <Setter Property="Width" Value="6" />
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="Data" Value="M 0 3 L 6 3 L 3 6 Z" />
    </Style>

    <Style x:Key="ChevronOpen"
           BasedOn="{StaticResource ResourceKey=ChevronBase}"
           TargetType="{x:Type Path}">
        <Setter Property="Fill" Value="Black" />
        <Setter Property="LayoutTransform">
            <Setter.Value>
                <TransformGroup>
                    <ScaleTransform />
                    <SkewTransform />
                    <RotateTransform Angle="-45" />
                    <TranslateTransform />
                </TransformGroup>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="ChevronClosed"
           BasedOn="{StaticResource ResourceKey=ChevronBase}"
           TargetType="{x:Type Path}">
        <Setter Property="Stroke" Value="#FF808080" />
        <Setter Property="Fill" Value="Transparent" />
        <Setter Property="LayoutTransform">
            <Setter.Value>
                <TransformGroup>
                    <ScaleTransform />
                    <SkewTransform />
                    <RotateTransform Angle="-90" />
                    <TranslateTransform />
                </TransformGroup>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="ChevronCheckBox" TargetType="{x:Type CheckBox}">
        <Setter Property="SnapsToDevicePixels" Value="true" />
        <Setter Property="OverridesDefaultStyle" Value="true" />
        <Setter Property="IsChecked" Value="True" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type CheckBox}">
                    <Grid Background="Transparent">
                        <Path x:Name="ChevronOpen"
                              Style="{StaticResource ResourceKey=ChevronOpen}"
                              Visibility="Collapsed" />

                        <Path x:Name="ChevronClosed"
                              Style="{StaticResource ResourceKey=ChevronClosed}"
                              Visibility="Collapsed" />

                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CheckStates">
                                <VisualState x:Name="Checked">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ChevronOpen" Storyboard.TargetProperty="(UIElement.Visibility)">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Unchecked">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ChevronClosed" Storyboard.TargetProperty="(UIElement.Visibility)">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Indeterminate" />
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

I've added the style to a checkbox as such:
<Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="25" />
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <CheckBox x:Name="Xpander" Style="{DynamicResource ResourceKey=ChevronCheckBox}" />

            <ContentPresenter Grid.Column="1"
                              VerticalAlignment="Center"
                              Content="{TemplateBinding Header}"
                              ContentTemplate="{TemplateBinding HeaderTemplate}" />

            <Separator Grid.Column="2"
                       Height="12pt"
                       Margin="7,0,0,0"
                       VerticalAlignment="Center"
                       Visibility="{TemplateBinding LineBreakVisibility}" />

            <ContentPresenter Grid.Row="1"
                              Grid.ColumnSpan="3"
                              Margin="8,5,5,5"
                              Visibility="{Binding ElementName=Xpander,
                                                   Path=IsChecked,
                                                   Converter={StaticResource ResourceKey=BooleanToVisibilityConverter}}" />
        </Grid>

The problem I am running into is that the chevron always comes out super funky (and not in a good funky).
This is one of the few times I've worked with Path objects.  Is there something I'm doing wrong that is making the chevron skew odd when it is placed in the grid along with my other header items?
It currently seems like it's either skewed too wide or the layout rotation isn't correct.  I've tried coming up with the correct path in a blank page in Expression Blend 4 but I'm just not understanding on how to come up with a correct path.  I can use two different path data sets but I thought just rotating the triangle would work.
BTW, I know I don't have all the styles for the current Explorer behavior.  Right now I'm trying to mimic collapse and uncollapsed state.  I'm open to taking suggestions if there is a better way to do this than using the CheckBox and overriding it's Template.
EDIT
Windows 7 Example:

The left side shows the expanded state of the header and the right collapsed.  The top portion is when the chevron is hovered.
My current "super funky" chevron (there is no glory):

The top is expanded and the bottom is collapsed.
A quick elaboration on what my idea was trying to accomplish.  I wanted to have path and change its layout rotation, fill, and stroke depending on the visual state of the checkbox (and later the path for the mouse over style).
Another quick note, since this is overriding a checkbox ControlTemplate I'm using the visual state manager for the checked and unchecked states.  When the "checkbox" is checked it is expanded.  When it is not the header appears collapsed.

A:

Ditch the Path object. Use a RegularPolygon with points set to three. You'll need the Expression Blend SDK to get the RegularPolygon class.


Q:

Как делать классы-обёртки во FreePascal?

Я хочу задать дефолтное поле класса, к которому бы обращалась программа, при обращении напрямую к классу, например, так:
var
  Numbers: IntArr;

begin
  Numbers := IntArr.Create; //Создаём целочисленный динамический массив
  Numbers.add(5); //Добавляем число в конец массива
  Numbers.pull(42); //Добавляем число в начало массива
  Writeln(Numbers[0]); //Печатаем 42
  Numbers[1] := 84;
  Writeln(Numbers[1]); //Печатаем 84
end.

Можно ли реализовать такое?

A:

Для этого вам надо определить для своего класса IntArr свойство (property) с директивой default, установив ему методы чтения и записи из определённого там же поля, в котором вы храните ваш массив, вот так:
type
  IntArr = class
    private //Поля и методы из этого блока не могут быть вызваны из-за пределов класса.
      var
        IntArray: Array of integer; //Наш массив
      function GetEl(i: integer):integer; //Получить элемент массива
      procedure SetEl(i,Value: integer); //Задать элемент массива
    public //А из этого - могут
      property DefProp[i:integer]: integer read GetEl write SetEl;default;
      procedure add(Value: integer); //Добавить число в массив
      procedure pull(Value: integer); //Добавить число в начало массива
  end;

function IntArr.GetEl(i: integer):integer;
begin
  GetEl := IntArray[i];
end;

procedure IntArr.SetEl(i,Value: integer);
begin
  IntArray[i] := Value;
end;

procedure IntArr.add(Value: integer);
var
  l: integer;
begin
  l := length(IntArray)+1;
  SetLength(IntArray, l);
  IntArray[l-1] := Value;
end;

procedure IntArr.pull(Value: integer);
var
  i,l: integer;
  arr: Array of integer;
begin
  l := length(IntArray);
  SetLength(arr, l);
  for i:=0 to l-1 do arr[i] := IntArray[i];
  inc(l);
  SetLength(IntArray, l);
  IntArray[0] := Value;
  for i:=0 to l-2 do IntArray[i+1] := arr[i];
end;

К сожалению, есть два существенных ограничения:

Директива default применима только к индексированным свойствам
(переменные-индексы перечисляются в квадратных скобках, после имени
свойства, в нашем случае - i:integer). Попытка использовать её с
обычным свойством, например так:
property DefProp: integer read DefaultValue write DefaultValue;default;

где DefaultValue - поле (переменная) класса, типа integer,
вызовет ошибку компиляции.
Вытекает из первого: Как видно из примера в пункте 1, свойства могут
обращаться при чтении и записи не только к методу (функции, для
чтения, процедуре - для записи), но и к полю (переменной или
константе, если для чтения) класса. Однако, индексированные свойства
при чтении или записи обязаны передать, как параметр, индекс,
поэтому могут обращаться только к методам.

Обратите внимание: Индексированные свойства могут иметь и более одного индекса,
property DefProp[n,m:integer]: integer read GetEl write SetEl;default;

что, для нашего примера, позволяет оборачивать в класс, в том числе, двумерные и многомерные массивы. Однако, синтаксис указания индексов у свойств и массивов отличается. Вместо
Writeln(Numbers[0][0]);

Для обращения к свойству следует писать:
Writeln(Numbers[0,0]);

Кроме того, вы не сможете получить весь массив, или строку двумерного массива простым обращением к свойсту так Numbers или так Numbers[0] (для двумерного массива), потому что свойство не хранит никаких данных, а лишь служит указателем, к какому методу или полю класса должна обратиться программа. Таким образом, опуская индекс вы лишь опустите обязательный аргумент функции, что, разумеется, приведёт к ошибке компиляции или выполнения.


Q:

Rails 5: ActiveRecord OR query

How do you do an or query in Rails 5 ActiveRecord? Also, is it possible to chain or with where in ActiveRecord queries?

A:

The ability to chain or clause along with where clause in ActiveRecord query will be available in Rails 5. See the related discussion and the pull request.
So, you will be able to do the following things in Rails 5:
To get a post with id 1 or 2:
Post.where('id = 1').or(Post.where('id = 2'))

Some other examples:
(A && B) || C:
    Post.where(a).where(b).or(Post.where(c))

(A || B) && C:
    Post.where(a).or(Post.where(b)).where(c)

A:

We don't need to wait for rails 5 to use this OR query. We can also used it with rails 4.2.3. There is a backport here.
Thank to Eric-Guo for gem where-or, Now we can add this OR functionality in >= rails 4.2.3 also using this gem.

A:

(Just an addition to the answer by K M Rakibul Islam.)
Using scopes, the code can become prettier (depending on the eyes looking):
scope a,      -> { where(a) }
scope b,      -> { where(b) }

scope a_or_b, -> { a.or(b) }


Q:

Assign value to a string dereference operator

I'm new to go, pardon me if this is a regular question, How does the assignment to a string dereference operator works below?
package main

import "fmt"

func main() {
    course := "Docker Deep Dive"
    changeCourse(&course)
}

func changeCourse(course *string) {
    fmt.Println(course) // prints the memory address of course since it is a pointer
    fmt.Println(*course) // prints the value since * is dereferenceing the pointer

   // Issue
    *course = "Docker Extended" // *course is a string, how does the assignment works here.
    fmt.Println(*course) // prints "Docker Extended"
}

A:

* (also know as indirection operator) is used to “dereference” pointer variables, dereferencing a pointer gives us access to the value the pointer points to.
In this case: *course = "Docker Extended" basically you are saying to the compiler: store the string "Docker Extended" in the memory location course refers to.


Q:

Как преобразование строки в дату на примере?

Приветствую. Мне необходимо перевести из строки в дату переменную. Ниже сам код...
$arFilter = array("ID" => 16104);
$arSelect = array('NAME', 'PROPERTY_PAR_ID', 'PROPERTY_P_DATE', 'PROPERTY_P_NUMBER',
    'PROPERTY_P_GIVER', 'PROPERTY_PAR_ID', 'PROPERTY_STATUS', 'ID', 'DATE_ACTIVE_FROM',
    'DATE_ACTIVE_TO', 'DATE_CREATE', 'PROPERTY_DATE_IN', 'PROPERTY_DATE_OUT', 'PROPERTY_TYPE',
    'PROPERTY_AUTHOR', 'PROPERTY_RESP_USER', 'PROPERTY_P_IS_ONETIME');
$res = CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect);
$res = $res->Fetch();
$canget = true;

if($res['DATE_ACTIVE_TO'] < date('d.m.Y H:i')) {
    $canget = false;
    }else{};

echo gettype(date($res['DATE_ACTIVE_TO']));
echo "\n";
echo date('d.m.Y H:i');

на выходе я получаю следующее:
string
14.11.2017 11:08
Подскажите пожалуйста, что необходимо написать? Пробовал вариант из статьи Как преобразовать строку в дату php?
К сожалению на моём варианте он не отработал почему-то....

A:

Что бы преобразовать строку в timestamp можно воспользоваться функцией strtotime, а функция time вернет текущий timestamp.
Скорее всего, сравнение вам надо делать таким образом
if(strtotime($res['DATE_ACTIVE_TO']) < time()) {

Функция date нужна для преобразования timestamp'a в символьно представление


Q:

Securing WMS against unauthorized access?

In a project the customer wants the images of the WMS to be secured against unauthorized access.
What are the common solutions to realize that?
Are they compatible with the OGC-standards?

A:

The OGC spec only mandates the use of http.  If it is compliant http it should be okay.
Some possible methods:

HTTP Basic Authentication (password sent as plain text, may have limited client support)
HTTP Digest Authentication (more secure, may have limited client support)
Filter IP address of client (easy to implement but not particularly secure).
Secret URL.  Use a GUID to generate an un-guessable URL.  Assumes that clients will keep URL secret.  Much simpler for user to use than password entry.  Guaranteed client support.

A:

This OGC post from 2005 says:

There are no specific security aspects
  that are part of the OGC WMS/WFS/WCS
  Interface Specifications. Instead,
  security and authentication is best
  handled at another layer in the
  processing stack.

A:

If security through obscurity is enough for your purposes you might configure a false extend for the layer :
Just use coordinates on the other side of the Earth. The layer will still appears in the layer list, requests will still be possible but if a user simply select it in a GIS software and choose "zoom to layer" he will not see anything and might think that this layer is simply empty or does not work. An application knowing the correct extend of the layer should still be able to access it.
I have already seen this solution applied on some WMS sites, but it is probably not completly conform to OGC-standards as the server returns an incorrect extend.


Q:

Combining large strings in PHP for HTML email

Im working on a project where I receive a webhook of JSON data that I will then send an email notification based on the JSON. I have all the sorting of the JSON worked out. I know how to send an HTML email via php, but I'm lost on how to build such a large email.
I will need to use some logic to build out parts of the HTML email. But I know something like this will fail because I'm trying to use an If statement inside a variable...
    $email = $vendorEmail;
    $email_subject = "Order Slip ";
    $email_message = '

Bill To:

                              ' . $orderInfo->billing_address->first_name . ' ' . $orderInfo->billing_address->last_name . '

                              ' . if(isset($orderInfo->billing_address->company)){$orderInfo->billing_address->company };. '

                              ' . $orderInfo->billing_address->address1 . '

                              ' . $orderInfo->billing_address->address2 . '

This is a small section of my overall email. The logic will become much more complex further in the email. An example would be running a for statement to run through all the lines items of a completed order.
Is there a standard way of creating larger more complex HTML emails? Or if not, Does anyone have a suggestion on the smarter way to go about this?

A:

Your question is not about composing emails, but about combining larger strings - it might help to rename the question better so it attracts the "correct" answers.
If your only problem is using if/else inside a variable you can use two approaches.
First uses normal if/else clause with adding to a variable using the .= operator
$string = 'xxx'
if($a) {
    $string .= 'yyy';
}
else {
    $string .= 'zzz';
}

OR use ternary operators to straightforward define the variable in one go. Output of the second option is exactly the same as the first one.
$string = 'xxx' . ($a ? 'yyy' : 'zzz');

Ofc you can combine these two approaches.
More about ternary operators: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

EDIT:
to put it into context, your code should look like this (ternary approach which I would recommend in this piece of code)
$email = $vendorEmail;
$email_subject = "Order Slip ";
$email_message = '

Bill To:

                        ' . $orderInfo->billing_address->first_name . ' ' . $orderInfo->billing_address->last_name . '

                        ' . ((isset($orderInfo->billing_address->company) ? $orderInfo->billing_address->company : NULL). '

                        ' . $orderInfo->billing_address->address1 . '

                        ' . $orderInfo->billing_address->address2 . '

EDIT2:
When dealing with really large HTML strings I also use output buffering approach, you might find it useful too.
<?php
ob_start();
$phpVariables = 'phpVariables';
?>
HERE GOES LARGE HTML, <?=$phpVariables?>, or <?php echo 'chunks of PHP that output stuff'?>
<?php
$string = ob_get_clean();
?>

$string would then be "HERE GOES LARGE HTML, phpVariables, or chunks of PHP that output stuff.".
Of course you can use normal php code, including your if/else in the output.
If you want to use that approach though, I suggest you first get familiar with output buffering http://us2.php.net/manual/en/function.ob-start.php


Q:

Average Q/A score?

Is it currently possible to get a mean score for either questions or answers for yourself, or other users? The motivation behind asking, is that sometimes total reputation is not always a clear indication of the quality of the average post by a given user.
In some instances for example, a user has offered so many bounties, so that their total reputation is unrepresentative of the quality of their usual post. Similarly, some MO users have a relatively low score on MSE owing to their infrequent contributions. The same principle applies to some new users.

A:

If you are looking for statistics about this site then data.stackexchange.com is the place to go. You can query the SE database about practically anything. If you don't know SQL you can run some of the other queries that people have made.
Here are some relevant queries for your question:
What is my average question score?
What is my average answer score?

To have something to compare against; below is a histogram of the average answer score (pure votes, not including accepts) for all high rep. users (arbitrarily defined as $>50$k reputation)


Q:

ubuntu iso sha256 checksum

I've been having some troubles with my newly installed Ubuntu system (random freezing) and I wanted to verify that the iso I received was not corrupted by checking the sha256 hashes (I know I should have done that first).  I followed the instruction on the Ubuntu website but I keep getting the same warning, shown below:
user@user-System-Product-Name:~/Downloads/ubuntu_isos$ sha256sum -c SHA256SUMS
sha256sum: ubuntu-16.04-desktop-amd64.iso: No such file or directory
ubuntu-16.04-desktop-amd64.iso: FAILED open or read
sha256sum: ubuntu-16.04-desktop-i386.iso: No such file or directory
ubuntu-16.04-desktop-i386.iso: FAILED open or read
sha256sum: ubuntu-16.04-server-amd64.img: No such file or directory
ubuntu-16.04-server-amd64.img: FAILED open or read
sha256sum: ubuntu-16.04-server-amd64.iso: No such file or directory
ubuntu-16.04-server-amd64.iso: FAILED open or read
sha256sum: ubuntu-16.04-server-i386.img: No such file or directory
ubuntu-16.04-server-i386.img: FAILED open or read
sha256sum: ubuntu-16.04-server-i386.iso: No such file or directory
ubuntu-16.04-server-i386.iso: FAILED open or read
ubuntu-16.04.1-desktop-amd64.iso: OK
sha256sum: ubuntu-16.04.1-desktop-i386.iso: No such file or directory
ubuntu-16.04.1-desktop-i386.iso: FAILED open or read
sha256sum: ubuntu-16.04.1-server-amd64.img: No such file or directory
ubuntu-16.04.1-server-amd64.img: FAILED open or read
sha256sum: ubuntu-16.04.1-server-amd64.iso: No such file or directory
ubuntu-16.04.1-server-amd64.iso: FAILED open or read
sha256sum: ubuntu-16.04.1-server-i386.img: No such file or directory
ubuntu-16.04.1-server-i386.img: FAILED open or read
sha256sum: ubuntu-16.04.1-server-i386.iso: No such file or directory
ubuntu-16.04.1-server-i386.iso: FAILED open or read
sha256sum: WARNING: 11 listed files could not be read

To let you know what I've done, I downloaded the Ubuntu desktop iso and the SHA256SUMS/SHA256SUMS.gpg files from http://releases.ubuntu.com/xenial/ into the same directory.  I then ran the command sha256sum -c SHA256SUMS from this directory to get the output.  I have downloaded 5 different images and they all give this same exact output, that does not seem correct to me.  I did exactly as instructed on the Ubuntu website, but I must be doing something wrong, right?

A:

The important line here is this one:
ubuntu-16.04.1-desktop-amd64.iso: OK

Your ISO is OK.
The checksum file contains sums for all the images; sha256sum warns you about the ones you haven't downloaded, because it can't verify them.


Q:

Dynamic/static language and compiler/interpreter

I have some questions:

A dynamic programming language is always interpreted? I think so, but why?
Are there any dynamic languages with static typing system?
A programming language with static typing system is always compiled?

In others words, are there really a link between :

Static / dynamic typing system and static / dynamic language
Static / dynamic typing system and compiler / interpreter
Static / dynamic language and compiler / interpreter

A:

There is no inherent connection between the type system and the method of execution. Dynamic languages can be compiled and static languages can be interpreted. Arguably static type systems make a lot of sense with programs which are compiled before execution, as a method of catching certain kinds of errors before the program is ever executed. However, dynamic type systems solve different problems than static type systems, and interpreted execution solves different problems than compilation.
See What to know before debating type systems.


Q:

c# struct with no reference types

Consider a struct which does not contain any reference fields (only basic types and other structs).
Consider this struct will be used in collections and I want it to behave like a value type (ie int).

do I need to override operator== and operator!=?
do I need to override Equals?
do I need a copy constructor?
do I need to worry about assignment?
do I need to override GetHashCode?

A:

Depends on you, by default == and != will redirect to the default Equals implementation but it's considered better practice to use Equals directly instead of == or !=
You should, by default Equals performs bitwise comparison on value types and reference equality on reference types, so if your struct contains fields that are reference types, you will need to override Equals to perform a proper comparison on them. Besides that, MSDN recommends to override Equals anyway, for performance benefits as well.

Particularly if your value type contains fields that are reference
  types, you should override the Equals(Object) method. This can improve
  performance and enable you to more closely represent the meaning of
  equality for the type.

Structs are copied by default when passed between variables/methods, so there is no need to write a copy constructor. The only case I can think of is if your structs contains fields that are reference types and you want to create a copy constructor that performs deep copy on them, up to you.
What do you mean worry about assignment?
Yes. If you're going to use your struct as a member of HashSet or as a key in a Dictionary, you would want to provide a custom implementation of GetHashCode.

It is best to implement IEquatable to avoid boxing (default Equals accepts an object type, so your struct will have to undergo boxing to fit that type).
Collections (Arrays, Dictionaries, etc...) will usually check if their members implement IEquatable, and will use IEquatable.Equals, so it's best to implement it.
It is also recommended to implement the default Equals (from System.Object) and direct to to the IEquatable.Equals implementation.
Example:
struct MyStruct : IEquatable<MyStruct>
{
    public int A { get; set; }

    public int B { get; set; }

    public bool Equals(MyStruct other)
    {
        return A == other.A && B == other.B;
    }

    public override bool Equals(object obj)
    {
        if (!(obj is MyStruct)) return false;
        return ((MyStruct)obj).Equals(this);
    }

    public override int GetHashCode()
    {
        return (A, B).GetHashCode();
    }
}

I also provided an example of how to implement GetHashCode, best way is to use the implementation of Tuple.
Again, implementing == and != is up to you
The standard library (System, System.Collections, etc...) uses System.Equals or IEquatable.Equals to do comparison, and you should too.
So no, implementing == and != is not necessary.


Q:

Linux route command. Two gatways on the same subnet range

I have a Linux box with two interfaces.
eth0 has ip 192.168.71.82/255.255.252.0
eth1 has ip 192.168.4.2/255.255.255.0
I need all traffic for subnets 192.168.4.0/24 192.168.3.0/24 192.168.2.0/24 to go through eth1 and all the rest to go through eth0.
Which is the best way to do this?
route command?
Cheers for the help.

A:

Just set routes to your desired Networks over eth1:
route add -net 192.168.4.0 netmask 255.255.255.0 dev eth1
route add -net .........

And then set your default gateway to whatever you need:
route add default dev eth0

(Nevertheless a route using an interface looks a bit strange to me - usually you should address the gateways using the correct router(s):
route add -net 192.168.3.0 netmask 255.255.255.0 gw <your routers IP>


Q:

How to draw a dotted line in Firemonkey?

I want to draw a dotted grid on a TPaintbox canvas in a Firemonkey project, the outcome should be exactly like this:

To start with I thought I would draw the vertical dotted lines and then the horizontal dotted lines, so with that in mind I attempted to draw a single line first in attempt to get the appearance just right, this is what I tried:
Canvas.Stroke.Color := TAlphaColorRec.Black;
Canvas.Stroke.Dash := TStrokeDash.Dot;
Canvas.Stroke.Kind := TBrushKind.Solid;
Canvas.Stroke.Thickness := 1;
Canvas.DrawLine(PointF(0, 0), PointF(0, 150), 1);

The result is not what I had hoped, in fact the TLine shape can do a dotted line how I want it to:

But I need to do this drawing myself on the canvas and not use additional controls. For the record TLine simply needs the Stroke.Dash property changing to Dot.
So, using the canvas in a Firemonkey project how may I draw a dotted line the same as TLine does so that I can draw a grid like the first sample image?

A:

Without going into the 'why it works' you can achieve 1 pixel dotted line (like in TLine) by adding (or subtracting) half the line width to the coordinates. I got the idea when tracing through what TLine does; during rendering it uses
InflateRect(Result, -(FStroke.Thickness / 2), -(FStroke.Thickness / 2));

Applying the 0.5 modification to the line coordinates, gives the same result.
procedure TForm24.PaintBox1Paint(Sender: TObject; Canvas: TCanvas);
var
  a: integer;
begin
  Canvas.BeginScene;
  try
    Canvas.Stroke.Dash := TStrokeDash.Dot;

    for a := 0 to 10 do
      Canvas.DrawLine(PointF(a * 20 + 0.5, 0.5), PointF(a * 20 + 0.5, 200.5), 1);

    for a := 0 to 10 do
      Canvas.DrawLine(PointF(0.5, a * 20 + 0.5), PointF(200.5, a * 20 + 0.5), 1);

    Canvas.DrawLine(PointF(0.5, 0.5), PointF(200.5, 200.5), 1);
    Canvas.DrawEllipse(RectF(5.0, 5.0, 195.5, 195.5), 1);
  finally
    Canvas.EndScene;
  end;
end;

produces this result:

Magnifier view is 500%
Edit 2018.02.23:
An alternative way, worth to test, is to change the forms Quality property to HighPerformance


Q:

Why no CSRF cookie is generated for my request?

I'm trying to activate the CSRF cookies in Spring. So I have the following class:
SecurityAdapter.java
@Configuration
@EnableWebSecurity
public class SecurityAdapter extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http)
            throws Exception
    {
        http
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }
}

Since I'm trying to implement a REST web service (no HTML or anything), I believe the first request to the server should be a GET one because other request types will require XSRF-TOKEN and we don't have that yet.
So when I send a GET request, I expect to receive some cookies in response (I've been a good boy after all!). But I don't get any.
Here's the rest of the project files:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

DemoApplication.java
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication
{
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Controller.Java
package com.example;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Controller
{
    @RequestMapping(value = "/first", method = RequestMethod.GET)
    public ResponseEntity get()
    {
        return ResponseEntity.ok("first");
    }

    @RequestMapping(value = "/second", method = RequestMethod.POST)
    public ResponseEntity post()
    {
        return ResponseEntity.ok("second");
    }
}

When I call the second method (of course in POST method), I get:
{
  "timestamp": 1481500256460,
  "status": 403,
  "error": "Forbidden",
  "message": "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.",
  "path": "/second"
}

But when I get the first method in GET while it is called, I don't get any cookies to use and call the second method!
What am I missing something here?

A:

I tested your code and I am getting csrf token in cookie. I verified the GET method in Chrome browser and checked the cookies tab. There is XSRF-TOKEN present which is returned by service. In order to print the csrf token returned by service, I modified your first method in Controller like below. Please test it.
@RequestMapping(value = "/first", method = RequestMethod.GET)
public ResponseEntity get(HttpServletRequest request)
{
    CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
    System.out.println(token.getHeaderName()+" = "+token.getToken());
    return ResponseEntity.ok("first");
}

One more thing. As you are using Spring Boot you should use spring-boot-starter-security, instead of individual Spring Security dependencies. Dependencies in your pom.xml should be like below.
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>


Q:

Transforming into Map using Java 8 and lambdas

I have
List<Gift> gifts = new ArrayList<>();
gifts .add(new Gift().withType(INF, CHD));
gifts .add(new Gift().withType(ADT, CHD));
gifts .add(new Gift().withType(INF, ADT));

Gift has a method List<Type> getTypes();
and now I'd like to transform gifts list into something like
Map<Type,List<Gift>>.
I'd like to do it with Java 8 and lambdas in one line. Is it possible?
public class Gift {

    public List<Type> getTypes() {
        return types;
    }

    public Gift withType(Type... types) {
        this.types = Arrays.asList(types);
        return this;
    }

    List<Type> types = new ArrayList<>();
}

public enum Type {
    ADT,
    CHD,
    INF;
}

Previous old code (it looks awfully). That's all what I have.
Map<Type, List<Gift>> byTypes = new HashMap<>();

for (Gift gift : gifts) {
    for (Type type : gift.getTypes()) {
        List<Gift> giftList = byTypes.get(type);
        if (giftList == null) {
            giftList = new ArrayList<>();
        }
        giftList.add(gift);
        byTypes.put(type,giftList);
    }
}

A:

Using Guava's Multimap:
ListMultimap<Type, Gift> multimap = ArrayListMultimap.create();

gifts.forEach(g -> g.getTypes().forEach(t -> multimap.put(t, g)));

Map<Type, Collection<Gift>> map = multimap.asMap();


Q:

Find position in array of strings in Word VBA

I have an array of strings "alpha", "beta"... and I'd like to test another string string2 against this to return 1, if string2 = "alpha", 2 if it equals "beta" etc.
I could do this if it were Excel using application.match, but this doesn't exist in Word.
The end goal is to return the unicode value for the appropriate Greek letter from the name of the letter, so if there's a better way of doing it, I'm open to suggestions. Maybe I've been writing too much python, and lists seem like the easy way.

A:

You need to loop through the array and test each value against the searched value.
Here's some pseudo code to get you started.
Dim greek() As String
Dim x As Integer
Dim searchString As String
Dim match As Integer

For x = LBound(greek) To UBound(greek)
    If greek(x) = searchString Then
        match = x
        Exit For
    End If
Next x


Q:

split dvb url address into separate values

Let assume we have such URL:
dvb://1.3f3.255c.15

my question is how to parse this address in following way:
val1 = 1
val2 = 3f3
val3 = 255c
val4 = 15

First idea is to use strchr() from standard C library, but maybe done it before. I would like to make it as simple as possible. When I will succeed I will put my solution.
Best Regards

A:

You could use strtok
char dvb_url[] = "dvb://1.3f3.255c.15";

//Begin stripping the scheme (dvb:/)
char *tokenized = strtok(dvb_url, "/");
//Finish stripping scheme
tokenized = strtok(NULL, "/.");

while(tokenized != NULL)
{
    //Store in variable here
    printf("%s\n", tokenized);
    tokenized = strtok(NULL, ".");
}


Q:

Getting SyntaxError with pd.DataFrame(ticker: data.c)

def load_tickers(ticker):
     fname = ( '%s.csv' % ticker.lower())
     data = pd.read_csv( fname, header = None, parse_dates = ['Date'],
                  names =['Date','Open','High','Low','c','Adj Close','Volume'])
     data = data.set_index('Date')
     x = pd.DataFrame(ticker: data.c)
     print(x)

load_tickers('AAPL')

I tried running my code but for some reason it's raising a SyntaxError:
How can I fix this ?

A:

Seems like you want to pass a dictionary and forgot curly brackets. Try this one:
x = pd.DataFrame({ticker: data.c})


Q:

Getting error : WebSphere MQ reason code 2538?

I have WebSphere MQ and WebSphere Message Broker installed on Linux and when I execute mqsicreateexecutiongroup I get an error saying:

BIP1046E: Unable to connect with the queue manager (Could not connect to queue manager 'NSPZPAI1' (MQ reason code 2538)).

When I search for this reason code I understand that it is a host not available error.
Can somebody please tell me how to resolve this error?
When I run a runmqlsr command I always end up in a hang. Can somebody tell me how to start a listener?

A:

Don't start the listener by hand or script.  If you have a modern queue manager, define a listener object like so:
DEF LISTENER(LISTENER.1414)  TRPTYPE(TCP) +
    CONTROL(QMGR)            PORT(1414) +
    REPLACE

START LISTENER(LISTENER.1414)

The attribute CONTROL(QMGR) tells the QMgr to start the listener automatically when the QMgr is started and to kill the listener when the QMgr is shut down.  This ensures that the listener will always be started when the QMgr comes up, even if the QMgr is started manually instead of from the usual boot script.  Because the listener is a child process of the QMgr it will always come down with the QMgr so you don't need to worry about orphaned listeners preventing connections after a QMgr restart.
Once the listener is defined, you can also use START LISTENER or STOP LISTENER MQSC commands to manually start and stop it independently of the QMgr.  In the example above, I've manually started the listener rather than reboot the QMgr.  Either would work but the START command is less intrusive.


Q:

Galaxy S3 graphics issue, how to resolve?

My Galaxy S3 has developed a graphics fault (see image) and I don't know the cause or the cure.  It has not been exposed to humidity or any thing magnetic and to the best of my knowledge it has not been dropped.  Im not sure whether its a hardware or an Android OS issue.
The fault is a purplish blemish that seems to be getting darker and bigger with time.  Has any body got any idea of the cause but more importantly the cure (if any).  Many Thanks

A:

Your phone officially needs a trip back to a Samsung Service center
That is in No Way caused by any android glitch, as the issue is progressive (getting darker, bigger in time). It might be caused by some shock that made the lcd inside crack and bleed.


Q:

Shortest path algorithm in 0-1-unoriented graph

I have an unoriented graph with n vertices and m edges, 1 <= n, m <= 100000. All edges have 0 or 1 weights (two vertices are connected even if the corresponding edge has 0 weight). Vertices indexing starts with 1. I need to find length of the shortest path from vertex A to vertex B.
Input data example:
4 5 1 3
1 2 1
2 3 0
3 4 1
4 1 1
1 3 0

From the first line I get: n = 4, m = 5, A = 1, B = 3. Then I get the elements of the adjacency list. The first number in each line is from-vertex, the second - to-vertex, and the last is the weight of current edge. 0 or 1.
In the output I must receive the length of the shortest path or -1 if the path doesn't exist.
Here is my solution using Dijkstra's algorithm:
#include <iostream>
...

using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::pair;
using std::string;
using std::map;

size_t INF = 200000;

int main() {
    size_t nVert,
        mEdges,
        start,
        end;
    cin >> nVert >> mEdges >> start >> end;
    vector<vector<pair<size_t, size_t>>> ajList(mEdges);
    size_t edStart, edEnd, weight;
    for (size_t vert = 0; vert < mEdges; ++vert) {
        cin >> edStart >> edEnd >> weight;
        ajList.at(edStart - 1).push_back(pair<size_t, size_t>(edEnd, weight));
    }

    vector<size_t> minLen(nVert, INF),
        pred(nVert);
    minLen[start - 1] = 0;
    vector<char> used(nVert);
    for (size_t vert = 0; vert < nVert; ++vert) {
        size_t currentVert = -1;
        for (size_t j = 0; j < nVert; ++j) {
            if (!used[j] && (currentVert == -1 || minLen[j] < minLen[currentVert]))
                currentVert = j;
        }
        if (minLen[currentVert] == INF)
            break;
        used[currentVert] = true;

        for (size_t j = 0; j < ajList[currentVert].size(); ++j) {
            int to = ajList[currentVert][j].first - 1,
                len = ajList[currentVert][j].second;
            if (minLen[currentVert] + len < minLen[to]) {
                minLen[to] = minLen[currentVert] + len;
                pred[to] = currentVert;
            }
        }
    }

    if (minLen[end - 1] == INF)
        cout << -1;
    else
        cout << minLen[end - 1];
    return 0;
}

I know that Dijkstra is the fastest algorithm for searching the shortest path from one vertex to all other vertices, but in my case it takes too long.

How can I optimize this code to make it working faster (this is the main problem)?
If you see some bugs in this snippet, please, let me know.

A:

You should extract reading the data and the Dijkstra to their own method. It helps debugging. You don't have enough information to make a meaningful heuristic for A* anyway.
When filling the adjacency matrix you do it as if it is directional while your post says it's not:
for (size_t vert = 0; vert < mEdges; ++vert) {
    cin >> edStart >> edEnd >> weight;
    ajList.at(edStart - 1).push_back(pair<size_t, size_t>(edEnd, weight));
    ajList.at(edEnd - 1).push_back(pair<size_t, size_t>(edStart, weight));
}

I suggest you use a priority queue of some sort; it lets you remove the current node in \$O(\log n)\$ instead of \$O(n)\$ (the first inner for loop in your code).

A:

How long is too long? How many vertices and edges does your sample test have? Did you measure the performance? How?
Also, in the initial phase of loading the edges in the ajList vector, for every edge from v -> w, you save them as (v - 1) -> w, not (v - 1) -> (w - 1). In others words, you changed the start vertex to a zero index system, but you didn't apply the same rule for the end vertex. You should apply the same rule for every vertex, i.e., manage all vertices in a X index way (being consistent is the key).
I recommend you to transform all vertices to a \$0\$ to \$N-1\$ range at the initial phase. Don't forget to apply this to the start and end vertices (given in the first line).


Q:

What does it mean: Create Regular Grammar which is generated by this Context Free Grammar?

I am not asking for the solution, it's an assignment, but I didn't see any question like that, I am asking for what's does it means:
The question:

Create a Regular Grammar that generates the same language which is
  generated by the following Context Free Grammar:
G = {{S,X,Y}, {a,b,c}, S, P} Where P is:
S ----> aaS
S ----> bX
X ----> cYb

X ----> cb
Y ----> bbY
Y ----> bb

Does it means to generate the language? I am confused about creating RG from CFG.

A:

Good question and this topic is worth knowing.  I would seek help from a TA or something of that nature.   The study of finite automaton is vital to a successful career in computer science in my opinion.
The languages that can be represented by CFGs and RLs are very different and the question is designed to help you understand that.
I don't really like the use of the word "generate", "accept" is more appropriate.  Find the RL that accepts the same strings as CFG given below is how I would write the question.
Keep in mind that a regular language is equivalent to a finite state machine, so you can work in this by drawing one that accepts the stings accepted by the given CFG.
Find the answer to your question, but doing so here is kind of the wrong place to do so.
now to do this problem for fun...


Q:

JDA send notification to private channels

I want to have an ability to send notification to private channels of all users in my group
This is my code
public static void main(String[] args) throws LoginException {
    final JDA bot =
                new JDABuilder(AccountType.BOT)
                        .setToken("secret")
                        .addEventListener(new DemoApplication())
                        .build();
}

@Override
public void onPrivateMessageReceived(final PrivateMessageReceivedEvent event) {
    if (event.getAuthor().isBot()) {
        return;
    }
    event.getJDA().getGuilds().get(0).getMembers().forEach(user->user.getUser().openPrivateChannel().queue());
    event.getJDA().getPrivateChannels().forEach(privateChannel -> privateChannel.sendMessage("ZDAROVA").queue());
}

But only sender of this private message receive a message . What did i miss ?
I use JDA with version 3.8.3_462

A:

Your code makes use of async operations. An async task is one that is started on another thread and possibly happens at a later time.
Discord has rate-limits which have to be respected by the operating client. For this reason and the reason that HTTP requests take some time, the requests happen in the background. The method you're using which is called queue() simply puts the request on a queue that is drained by a worker thread.
openPrivateChannel() returns RestAction<PrivateChannel> which means it will receive a private channel instance as a response. This response can be interacted with by using the callback parameter of queue(Consumer<PrivateChannel> callback).
static void sendMessage(User user, String content) {
    user.openPrivateChannel().queue(channel -> { // this is a lambda expression
        // the channel is the successful response
        channel.sendMessage(content).queue();
    });
}

guild.getMembers().stream()
    .map(Member::getUser)
    .forEach(user -> sendMessage(user, "ZDAROVA"));

More information on RestAction is available in the JDA Wiki and Documentation.


Q:

Different signatures

I was working out the christoffel symbols, once where the metric that I am using has (+---) signature and another time where it has (-+++) signature because two books had different signatures and I had to check for any inconsistencies. I had the christoffel symbols the same for both but the curvatures $(R_{\mu\nu})$ has opposite signs. Why is that?

A:

If you stick to one convention out of many other conventions, you should have same results regardless of signature of metric. Here I follow Carroll's conventions: http://amzn.com/0805387323 or http://arxiv.org/abs/gr-qc/9712019.
For Christoffel symbol, we have
\begin{equation}
\Gamma^\lambda_{\mu\nu}=\frac{1}{2}g^{\lambda\rho}(\partial_\mu g_{\nu\rho}+\partial_\nu g_{\rho\mu}-\partial_\rho g_{\mu\nu})\,.
\end{equation}
So if you change signature of the metric $g_{\mu\nu}\to -g_{\mu\nu}$, you have same Christoffel symbol. As a same argument, the definition of Ricci curvature is
$$
R_{\mu\nu}=R^\lambda_{\phantom{a}\mu\lambda\nu}
$$
where Riemann curvature only depends on Christoffel symbol and its derivative. Therefore we have same Ricci curvature, even if we change the signature of metric.


Q:

Have Google maps center around geo-locs and zoom in appropriately

I would like to pass an x amount of geo-locations to the Google Maps API and have it centered around these locations and set the appropriate zoom level so all locations are visible on the map. I.e. show all the markers that are currently on the map.
Is this possible with what the Google Maps API offers by default or do I need to resolve to build this myself?

A:

I used fitBounds (API V3) for each point:

Declare the variable.
var bounds = new google.maps.LatLngBounds();

Go through each marker with FOR loop
for (i = 0; i < markers.length; i++) {
    var latlng = new google.maps.LatLng(markers[i].lat, markers[i].lng);
    bounds.extend(latlng);
}

Finally call
map.fitBounds(bounds);

A:

There are a number of ways of doing this but it is pretty easy if you are using the V2 API. See this post for an example, this group post or this post.


Q:

RecyclerView item touch to highlight

I am using a RecyclerView and I am not able to see any feedback when I touch on the item of the RecyclerView. How do I achieve it?
I am trying to show a feedback to the user when they are touching the row of RecyclerView. Something like a ripple effect.
I want to know how to achieve it in a specific row of the RecyclerView.
This is the recycler view's custom row layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/drawer_row"
    android:background="?android:attr/selectableItemBackground"
    android:clickable="true">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_toEndOf="@+id/navigation_image"
        android:layout_toRightOf="@+id/navigation_image"
        android:textSize="17sp" />

    <ImageView
        android:id="@+id/navigation_image"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp" />

    <TextView
        android:id="@+id/horizontal_line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_alignParentBottom="true"
        android:background="#F1F1F1" />

</RelativeLayout>

This is the layout of the Activity having the RecyclerView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/windowBackground">

    <RelativeLayout
        android:id="@+id/nav_header_container"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentTop="true"
        android:background="@drawable/ic_drawer_header">

        <ImageView
            android:id="@+id/circle_imageview"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/profile_pic"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="John Doe"
            android:textSize="20sp"
            android:textColor="#ffffff"
            android:layout_below="@+id/circle_imageview"
            android:layout_alignLeft="@+id/circle_imageview"
            android:layout_alignStart="@+id/circle_imageview"
            android:layout_marginTop="5dp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Transaction Technologies"
            android:layout_below="@+id/textView"
            android:layout_alignLeft="@+id/textView"
            android:layout_alignStart="@+id/textView"
            android:textColor="#ffffff"
            android:layout_marginTop="5dp" />

    </RelativeLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/drawerList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/nav_header_container" />

</RelativeLayout>

I just need to highlight/give feedback of the row which is being touched by the user. How do I achieve it?
Thanks in advance.

A:

You need to add android:focusable="true" in your custom row item for RecyclerView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/drawer_row"
    android:background="?android:selectableItemBackground"
    android:focusable="true"
    android:clickable="true" >
</RelativeLayout>


Q:

jQuery: Center fancybox in viewport

I am currently using fancybox version 2 to display my images when a thumbnail is clicked but I can't seem to get the fancybox to sit in the middle of the viewport, vertically speaking, since horizontally it's fine.
I've tried quite a few things and this is the latest:
CSS
.fancybox-wrap {
    position: fixed !important;
    top: 50px !important;
}

jQuery
jQuery(document).ready(function() {
    $(".fancybox-wrap").css("position", "absolute");

    // fancybox initialisation etc

});

$(window).scroll(function() {
    $('.fancybox-wrap').css('top', $(this).scrollTop() + "50px");
});

Does anyone have any ideas?

A:

The only thing you need to do is add to website css
html, body {height: 100%;}

And fancybox will position image at the screen center instead of page center.

A:

$(window).bind('resize', function() {
    var top = ($(window).height() / 2) - ($(".fancybox-wrap").outerHeight() / 2);
    var left = ($(window).width() / 2) - ($(".fancybox-wrap").outerWidth() / 2);
    $(".fancybox-wrap").css({ top: top, left: left});
}).trigger('resize');

http://jsfiddle.net/aGhxK/23/