text:
Q: Editing Magento header I need to edit Magento header by adding an icon and small image telling visitors that we offer Cash-on-Delivery. It should be somewhere around the search bar in the header.

A: You need to edit your theme's header template.
This can be found at app/design/$package_name/$theme_name/template/page/html/header.phtml
$package_name is the name of the package - e.g. rwd, base
$theme_name is the name of the theme (usually default) e.g. default, modern
These values can be found in the admin under System -> Configuration -> General -> Design.

Please note that depending on where you need to add the icon you may need to edit another template file as it might be a child block of the header template.


text:
Q: Firefox lingering images on page reload I'm using Firefox 24.0. The problem (see title) does not seem to be a caching issue. The image actually reloads; however, the previous image is displayed until the new one is available. Which in my case, produces a page full of images that refresh at different times and it's hard to see what is new and what is old content. Neither IE nor Chrome have this problem, as the image is not shown until the new one is ready.
The only solutions that have occurred to me are to add a time-stamp or randon number to the image URL, or to hide the image using javascript until the image is loaded, then show it. However, I would like a cleaner solution, on the server side if possible, like specifying some header that would make Firefox forget the old image.
Here is the code showing the annoying effect. Variant 1 does not work well in Firefox:
<html>
<head></head>
<script type="text/javascript">
    function AddImage() {
        var imgElem = document.createElement('img');

        // Variant 1
        imgElem.setAttribute('src', 'http://localhost/ImageServer.asmx/GetImage');

        // Variant 2
        //imgElem.setAttribute('src', 'http://localhost/ImageServer.asmx/GetImage?r=' + Math.random());

        // Variant 3
        //imgElem.setAttribute('src', 'http://localhost/ImageServer.asmx/GetImage');
        //imgElem.style.display = 'none';
        //imgElem.setAttribute('onload', 'this.style.display = "block"');

        document.body.appendChild(imgElem);
    }
</script>
<body onload="AddImage()">
</body>
</html>

For completeness here is the server side code, which is an old fashion web service that alternates between two images and adds a delay to show the lingering effect.
static int imgNumber = 2;

[WebMethod]
public void GetImage()
{
     Thread.Sleep(2000); // Delay to see the effect of the lingering image

     HttpContext.Current.Response.AppendHeader("Cache-Control", "private, max-age=0, s-maxage=0, no-cache, must-revalidate, proxy-revalidate");

     imgNumber = imgNumber % 2 + 1;
     string strPathPrefix = @"A:\Path\";
     HttpContext.Current.Response.WriteFile(strPathPrefix + imgNumber + ".png");
}

A: Your "variant 2" method, wherein you generate a unique URL by appending a randomly generated number to the end is completely valid and is a widely used method of preventing caching.
I would highly recommend going with this rather than trying to fix the problem with cache control headers as they can be unreliable. Some CDN's even ignore caching headers in attempt to save bandwidth and such.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift 2: check for type of touch in touchesBegan In Swift 2 I have the touchesBegan method with Set<UITouch>. Now, in the method I would like to check whether it was a tap/touch, a 3D touch..
I tried using .phase on the first UITouch, but that resulted in nothing. How would I check what kind of touch the user did?

A: You cannot check that by looking at touchesBegan alone. That method is only called when the user first touches the screen. The system cannot know what will happen after that (if the user lifts the finger again, or if he moves it, or if he presses with force etc.).
You also have to have a look at touchesMoved and touchesEnded and check what is happening there.
For example:
1) The touch was a Tap if the touches locationInView property is more or less the same in touchesBegan and touchesEnded. The won't be exactly the same because even if the user just taps the screen the finger moves a tiny bit.
2) The touch was a Pan or Swipe if the touches locationInView property is different in touchesBegan and touchesEnded.
3) The touch was a ForceTouch if the touches 'force' property is larger than a certain amount. This is only visible in touchesMoved. In touchesBegan the force property will always be 0. Of course force will only be available on devices that offer that feature.
If you want to detect a ForceTouch yourself you can do it like this:
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    guard let touch = touches.first else { return }
    if traitCollection.forceTouchCapability == .Available {
        if touch.force == touch.maximumPossibleForce {
            print("This is a force touch")
        }
    }
}

Just be aware that this is called continuously as long as the user presses the screen. If you want to execute some code once when you detect a force touch you have take care that you only execute the code once until touchesEnded has been called.


text:
Q: is there any way to control font for yadcf / select2 choices When I create an external filter for a yadcf column, which uses select2 as the selection method, the font in the selections does not follow the .body font specified in the wrapper

Is there any way to control this?
See http://codepen.io/louking/pen/rxKeob click in Match field. You can see the font has serif but .body font is Arial, Helvetica, sans-serif.
Note I am using yadcf 0.8.8+ (through commit https://github.com/vedmack/yadcf/commit/4b778d7747c5c1cd4f362e6a6154c172f4a88ad3)
html shown below

  Match:

        col0
        col1
        col2

        text-obvious
        b0
        c0

        more-text
        b1
        c1

js shown below
options = {
  dom: '<"H"lBpfr>t<"F"i>',
  jQueryUI: true,
  paging: false,
  scrollY: true,
  scrollCollapse: true,
  scrollX: true,
};

var yadcffilters = [{
  column_number: 0,
  filter_container_id: "select",
  column_data_type: "text",
  filter_match_mode: "exact",
  filter_type: "multi_select",
  select_type: 'select2',
  select_type_options: {
    width: '20em',
  },
  filter_reset_button_text: 'all',
}];

var table = $('#tbl').dataTable(options)
  .yadcf(yadcffilters);


text:
Q: Event 4104, MSDTC Client 2 I am using Idera SQL Diagnostic Manager to monitor a Windows Server Failover Cluster with two SQL Server 2008 R2 clusters configured to run with one SQL Server cluster on each node. It just started reporting that one of the instances does not have DTC or SQL Server Agent installed.
I've RDP'd to the cluster, and both nodes. In the cluster manager I see the DTC node running and is owned by the "A" node. On the "A" node, there are two services called "Distributed Transaction Coordinator." On the "B" node (which is the node on which the instance throwing the error on SQL Diagnostic Manager) there is only one service (in services.msc) called "Distributed Transaction Coordinator."  There is an error in the event log that says:

Failed trying to get the state of the cluster node: SERVER-DTC.The
  error code returned: 0x80070005

This cluster node is on the "A" node along with a SQL Server instance. The "B" node has this error. I can list and enumerate jobs in SSMS in the instance that is on the "B" node, but the SQL Server Agent does not have the little green triangle in it (just the empty circle).
So, I don't know exactly what to do. It seems like things are working OK, but this message from Idera SQL Diagnostic Manager has me perplexed since it is new (the error).
Running:
EXEC master..xp_servicecontrol N'QUERYSTATE', 'MSDTC'

on both nodes results in "Running".

A: Typically, 0x80070005 is an Access Denied error.  Perhaps the account Idera SQL Diagnostic Manager is using no longer has access to the Service Control Manager on the Windows nodes where the errors are occurring.


text:
Q: When I access the value of longitude and Latitude, it shows null I used this .getFusedLocationProviderClient to get user coordinates but when I try to access the value of longitude and latitude outside the function block of requestLocationUpdate(), I get null values.

 LocationServices.getFusedLocationProviderClient(mContext).
                requestLocationUpdates(locationRequest, new LocationCallback() {
                    @Override
                    public void onLocationResult(@NonNull LocationResult locationResult) {
                        super.onLocationResult(locationResult);
                        LocationServices.getFusedLocationProviderClient(mContext)
                                .removeLocationUpdates(this);
                        if(locationResult != null && locationResult.getLocations().size()>0) {
                            int latestLocationIndex = locationResult.getLocations().size() -1;
                            latitude =
                                    locationResult.getLocations().get(latestLocationIndex).getLatitude();
                            longitude =
                                    locationResult.getLocations().get(latestLocationIndex).getLongitude();
                        }
                    }
                }, Looper.getMainLooper());


text:
Q: the code is not entering the completion handler of the data task The completion handler code is not getting executed. while i debug the code its coming till the session.datatask and after that its not getting into the completion handler. we are actually migrating this project from objectivec to swift. i am not sure if the request generated is hitting the django or not. how to debug further. after the datatask the control exits the if request loop and there is smooth execution without any error. but the data is not fetched from DB.
func makeRequest(_ url: String?, path: String?, httpMethod: String?, httpBody httpBoday: Data?, completion: @escaping (_ result: [AnyHashable : Any]?, _ error: Error?) -> Void) {
        let headers = [
            "cache-control": "no-cache",
            "Authorization": "Token f491fbe3ec54034d51e141e28aaee87d47bb7e74"
        ]
        var request: URLRequest? = nil
        if let url = URL(string: "\(url ?? "")\(path ?? "")") {
            request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
        }
        request?.httpMethod = httpMethod ?? ""
        request?.allHTTPHeaderFields = headers
        let configuration = URLSessionConfiguration.default
        configuration.httpCookieStorage = nil
        configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
        if #available(iOS 11.0, *) {
            configuration.waitsForConnectivity = false
        }
        let session = URLSession(configuration: configuration)
        //        let session = URLSession.shared
        var task: URLSessionDataTask? = nil
        print ("Request =======>",request)
        if let request = request {
            task = session.dataTask(with: request , completionHandler: { data, response, error in
                            //.dataTask(with: request, completionHandler: { data, response, error in
               print ("testing******************")
                var result: Any? = nil
                if error != nil {
                    if let error = error {
                        print("\(error)")
                    }
                    if completion != nil {
                        completion(nil, error)
                    }
                } else
                {
                    var string: String? = nil
                    if let data = data {
                        string = String(data: data, encoding: .utf8)
                    }
                    string = self.string(byRemovingControlCharacters: string)

                    do {
                        if let data = string?.data(using: .utf8) {
                            result = try JSONSerialization.jsonObject(with: data, options: []) as!  [AnyHashable : Any]
                             print ("Result ===============>",result)
                        }
                    } catch {
                        print("Error while getting the data from json object")
                    }
                    DispatchQueue.main.async() {
                        if completion != nil {
                            completion(result as! [AnyHashable : Any], error)
                        }
                    }
                }
            })
        }
        else
        {
            print("Inside the else block of request")
        }
        task?.resume()
    }

A: This line is your problem:
if let url = URL(string: "\(url ?? "")\(path ?? "")") {
   request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
}

It needs to be like this:
guard let urlString = url else { return }
guard let path = path else { return }
if let requestURL = URL(string: "\(urlString)\(path)" {
   request = URLRequest(url: requestURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
}

Also, shouldn't make a difference, but you have 2 different cachePolicies.
Also, you're not using the httpBody anywhere. I suppose your request doesn't need it, but thought I would remind you to take a look.


text:
Q: Sorting data with array of pointers to a structure using strcmp In my program, I create an array of pointers to a struct (typedef'd as Person) and sort information in ascending order by zip code.
Here is the function that is supposed to sort my data:
void sortdata(Person * arr[], int noElements) {
    /* temporary pointer to Person data type to aid with swapping */
    Person * tempptr = (Person * ) malloc(sizeof(Person));

    int i, j, compare;

    for (i = 0; i <= (noElements - 1); i++); {
        for (j = (i + 1); j <= noElements; j++) {
            compare = strcmp(arr[i] - > zip, arr[j] - > zip);
            if (compare > 0) {
                printf("attempted sort %d times.\n", j);
                /* stores value in index i for array inside of temporary pointer  */
                strcpy(tempptr - > name, arr[i] - > name);
                strcpy(tempptr - > address, arr[i]);
                strcpy(tempptr - > citystate, arr[i] - > address);
                strcpy(tempptr - > zip, arr[i] - > zip);

                /* swaps values */
                strcpy(arr[i] - > name, arr[j] - > name);
                strcpy(arr[i] - > address, arr[j] - > address);
                strcpy(arr[i] - > citystate, arr[j] - > citystate);
                strcpy(arr[i] - > zip, arr[j] - > zip);

                strcpy(arr[j] - > name, tempptr - > name);
                strcpy(arr[j] - > address, tempptr - > address);
                strcpy(arr[j] - > citystate, tempptr - > citystate);
                strcpy(arr[j] - > zip, tempptr - > zip);
            }

        }
    }
}

I've included the printf statement to tell me how many times my program actually enters the loop. I am setting a variable equal to the value returned by strcmp, which would be positive if the zip code at index [i] was greater than the one in index [j] of the array. If this was the case, I would enter my sort and swap the values in the two indices, but my program never enters the loop. What am I doing wrong here?
Structure definition:
typedef struct person{
char name[50];
char address[50];
char citystate[30];
char zip[10];
}Person;

Function that allocates memory:
int takedata(Person *arr[])
{
/* counter variable */
int i = 0;
char teststring[25];

while ((gets(teststring)) != NULL && i < 50)
{
    /* dynamically allocates memory for each index of the array */
    arr[i] = (Person *)malloc(sizeof(Person));

    /* takes in data from user/ input file */

    strcpy(arr[i]->name, teststring);
    gets(arr[i]->address);
    gets(arr[i]->citystate);
    gets(arr[i]->zip);

    i++;
}

    printf("Processed %d sets of data.\n\n", i);

    return (i-1);
}

sample data:
A1, A2
20294 Lorenzana Dr
Woodland Hills, CA
91364
B1, B2
19831 Henshaw St
Culver City, CA
94023
C1, C2
5142 Dumont Pl
Azusa, CA
91112
D1, D2
20636 De Forest St
Woodland Hills, CA
91364
A1, A2
20294 Lorenzana Dr
Woodland Hills, CA
91364
E1, E2
4851 Poe Ave
Woodland Hills, CA
91364
F1, F2
20225 Lorenzana Dr
Los Angeles, CA
91111
G1, G2
20253 Lorenzana Dr
Los Angeles, CA
90005
H1, H2
5241 Del Moreno Dr
Los Angeles, CA
91110
I1, I2
5332 Felice Pl
Stevenson Ranch, CA
94135
J1, J2
5135 Quakertown Ave
Thousand Oaks, CA
91362
K1, K2
720 Eucalyptus Ave 105
Inglewood, CA
89030
L1, L2
5021 Dumont Pl
Woodland Hills, CA
91364
M1, M2
4819 Quedo Pl
Westlake Village, CA
91362
I1, I2
5332 Felice Pl
Stevenson Ranch, CA
94135
I1, I2
5332 Felice Pl
Stevenson Ranch, CA
94135
N1, N2
20044 Wells Dr
Beverly Hills, CA
90210
O1, O2
7659 Mckinley Ave
Los Angeles, CA
90001

A: The main problem in your code is that you have a ; in the wrong place, I am sure by oversight.
for (i = 0; i <= (noElements - 1); i++); {
                                       ^^ Remove the ;

It ends the first for loop. That is messing up your logic.
Regarding the comment by @DavidHoelzer:
You can replace the lines:
strcpy(tempptr - > name, arr[i] - > name);
strcpy(tempptr - > address, arr[i]);
strcpy(tempptr - > citystate, arr[i] - > address);
strcpy(tempptr - > zip, arr[i] - > zip);

/* swaps values */
strcpy(arr[i] - > name, arr[j] - > name);
strcpy(arr[i] - > address, arr[j] - > address);
strcpy(arr[i] - > citystate, arr[j] - > citystate);
strcpy(arr[i] - > zip, arr[j] - > zip);

strcpy(arr[j] - > name, tempptr - > name);
strcpy(arr[j] - > address, tempptr - > address);
strcpy(arr[j] - > citystate, tempptr - > citystate);
strcpy(arr[j] - > zip, tempptr - > zip);

by
tempptr = arr[i];
arr[i] = arr[j];
arr[j] = tempptr;

where tempPtr is declared simply as:
Person * tempptr = NULL;

Caution
Use of gets is strongly discouraged.
Read Why is the gets function so dangerous that it should not be used?.


text:
Q: Converting JSON Dictionary to Dataframe I am relatively new to JSON and after going through several tutorials I have decided to reach out here for additional advice. I am trying to convert the following JSON dictionary  via Jupyternotebook/Pandas into a dataframe and later into a csv file (data is extracted from a public API).
Example JSON dictionary without indentation:
json_search_result =
{'inactive_count': 0, 'links': {'self': '/company/08892216/officers'}, 'etag': '1ccc4c74454bc359a9b9ef686d11e70cc03b6cb8', 'kind': 'officer-list', 'resigned_count': 0, 'total_results': 1, 'active_count': 1, 'items_per_page': 35, 'items': [{'date_of_birth': {'year': 1964, 'month': 2}, 'links': {'self': '/company/08892216/appointments/Ao1-pIsFQHy0FVSv26y6ep4Qhyw', 'officer': {'appointments': '/officers/JpJgO2pKVmGq5VHD7j7lluLW-jo/appointments'}}, 'officer_role': 'director', 'address': {'premises': '19', 'locality': 'London', 'country': 'United Kingdom', 'address_line_1': 'Norcott Road', 'postal_code': 'N16 7EJ'}, 'appointed_on': '2014-02-12', 'nationality': 'Irish', 'country_of_residence': 'England', 'name': 'FLOOD, Eileen', 'occupation': 'Company Director'}], 'start_index': 0}

With indentation for better visibility:
json_search_result =
{'inactive_count': 0, 'links': {'self': '/company/08892216/officers'},
 'etag': '1ccc4c74454bc359a9b9ef686d11e70cc03b6cb8', 'kind': 'officer-list',
'resigned_count': 0, 'total_results': 1, 'active_count': 1, 'items_per_page': 35, 'items':
[{'date_of_birth': {'year': 1964, 'month': 2}, 'links': {'self': '/company/08892216/appointments/Ao1-pIsFQHy0FVSv26y6ep4Qhyw', 'officer': {'appointments':
'/officers/JpJgO2pKVmGq5VHD7j7lluLW-jo/appointments'}}, 'officer_role': 'director', 'address': {'premises': '19', 'locality': 'London', 'country': 'United Kingdom',
'address_line_1': 'Norcott Road', 'postal_code': 'N16 7EJ'},
 'appointed_on': '2014-02-12', 'nationality': 'Irish', 'country_of_residence': 'England',
'name': 'FLOOD, Eileen', 'occupation': 'Company Director'}], 'start_index': 0}

I have tried among others json_normalize but I either get errors given this is a dictionary:
df2 =  pd.json_normalize(json_search_result)

Thank you for any advice on this issues!

A: I assume that you will also want to flatten your dataframe since it contains additional nested information. So start by transforming you json string to a dataframe:
json_search_result = {'inactive_count': 0, 'links': {'self': '/company/08892216/officers'}, 'etag': '1ccc4c74454bc359a9b9ef686d11e70cc03b6cb8', 'kind': 'officer-list', 'resigned_count': 0, 'total_results': 1, 'active_count': 1, 'items_per_page': 35, 'items': [{'date_of_birth': {'year': 1964, 'month': 2}, 'links': {'self': '/company/08892216/appointments/Ao1-pIsFQHy0FVSv26y6ep4Qhyw', 'officer': {'appointments': '/officers/JpJgO2pKVmGq5VHD7j7lluLW-jo/appointments'}}, 'officer_role': 'director', 'address': {'premises': '19', 'locality': 'London', 'country': 'United Kingdom', 'address_line_1': 'Norcott Road', 'postal_code': 'N16 7EJ'}, 'appointed_on': '2014-02-12', 'nationality': 'Irish', 'country_of_residence': 'England', 'name': 'FLOOD, Eileen', 'occupation': 'Company Director'}], 'start_index': 0}
A = pd.DataFrame.from_dict(json_search_result, orient='index').T

which gives:
inactive_count                                   links  \
0              0  {'self': '/company/08892216/officers'}

                                       etag          kind resigned_count  \
0  1ccc4c74454bc359a9b9ef686d11e70cc03b6cb8  officer-list              0

  total_results active_count items_per_page  \
0             1            1             35

                                               items start_index
0  [{'date_of_birth': {'year': 1964, 'month': 2},...           0

Now, this function will flatten ANY dataframe with nested json strings:

def flatten_nested_json_df(df):
    df = df.reset_index()
    s = (df.applymap(type) == list).all()
    list_columns = s[s].index.tolist()

    s = (df.applymap(type) == dict).all()
    dict_columns = s[s].index.tolist()

    while len(list_columns) > 0 or len(dict_columns) > 0:
        new_columns = []

        for col in dict_columns:
            exploded = pd.json_normalize(df[col]).add_prefix(f'{col}.')
            exploded.index = df.index
            df = pd.concat([df, exploded], axis=1).drop(columns=[col])
            new_columns.extend(exploded.columns)  # inplace

        for col in list_columns:
            # print(f"exploding: {col}")
            df = df.drop(columns=[col]).join(df[col].explode().to_frame())
            new_columns.append(col)

        s = (df[new_columns].applymap(type) == list).all()
        list_columns = s[s].index.tolist()

        s = (df[new_columns].applymap(type) == dict).all()
        dict_columns = s[s].index.tolist()
    return df

Applying it:
flatten_nested_json_df(A)

will result in:
  index inactive_count                                      etag  \
0      0              0  1ccc4c74454bc359a9b9ef686d11e70cc03b6cb8

           kind resigned_count total_results active_count items_per_page  \
0  officer-list              0             1            1             35

  start_index                  links.self  ...  items.occupation  \
0           0  /company/08892216/officers  ...  Company Director

  items.date_of_birth.year items.date_of_birth.month  \
0                     1964                         2

                                    items.links.self  \
0  /company/08892216/appointments/Ao1-pIsFQHy0FVS...

                    items.links.officer.appointments items.address.premises  \
0  /officers/JpJgO2pKVmGq5VHD7j7lluLW-jo/appointm...                     19

   items.address.locality  items.address.country items.address.address_line_1  \
0                  London         United Kingdom                 Norcott Road

  items.address.postal_code
0                   N16 7EJ

As you can see, the nested fields have been made to columns:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1 entries, 0 to 0
Data columns (total 25 columns):
 #   Column                            Non-Null Count  Dtype
---  ------                            --------------  -----
 0   index                             1 non-null      int64
 1   inactive_count                    1 non-null      object
 2   etag                              1 non-null      object
 3   kind                              1 non-null      object
 4   resigned_count                    1 non-null      object
 5   total_results                     1 non-null      object
 6   active_count                      1 non-null      object
 7   items_per_page                    1 non-null      object
 8   start_index                       1 non-null      object
 9   links.self                        1 non-null      object
 10  items.officer_role                1 non-null      object
 11  items.appointed_on                1 non-null      object
 12  items.nationality                 1 non-null      object
 13  items.country_of_residence        1 non-null      object
 14  items.name                        1 non-null      object
 15  items.occupation                  1 non-null      object
 16  items.date_of_birth.year          1 non-null      int64
 17  items.date_of_birth.month         1 non-null      int64
 18  items.links.self                  1 non-null      object
 19  items.links.officer.appointments  1 non-null      object
 20  items.address.premises            1 non-null      object
 21  items.address.locality            1 non-null      object
 22  items.address.country             1 non-null      object
 23  items.address.address_line_1      1 non-null      object
 24  items.address.postal_code         1 non-null      object
dtypes: int64(3), object(22)
memory usage: 328.0+ bytes
None

A: Please try this if this helps your problem.
Good reference for further improvements: Convert list of dictionaries to a pandas DataFrame
json_search_result = {'inactive_count': 0, 'links': {'self': '/company/08892216/officers'}, 'etag': '1ccc4c74454bc359a9b9ef686d11e70cc03b6cb8', 'kind': 'officer-list', 'resigned_count': 0, 'total_results': 1, 'active_count': 1, 'items_per_page': 35, 'items': [{'date_of_birth': {'year': 1964, 'month': 2}, 'links': {'self': '/company/08892216/appointments/Ao1-pIsFQHy0FVSv26y6ep4Qhyw', 'officer': {'appointments': '/officers/JpJgO2pKVmGq5VHD7j7lluLW-jo/appointments'}}, 'officer_role': 'director', 'address': {'premises': '19', 'locality': 'London', 'country': 'United Kingdom', 'address_line_1': 'Norcott Road', 'postal_code': 'N16 7EJ'}, 'appointed_on': '2014-02-12', 'nationality': 'Irish', 'country_of_residence': 'England', 'name': 'FLOOD, Eileen', 'occupation': 'Company Director'}], 'start_index': 0}

pprint(json_search_result)

out = pd.DataFrame.from_dict(json_search_result, orient='index').T
print(out)
print(out.columns)


text:
Q: Can't able to get the value from textbox outside the function I have a simple JS code that finds the value of textbox that is entered by the user.
 var input= document.getElementsByClassName("textbox_properties");
 var click_button=document.getElementsByClassName("button_properties");
 var animal="Platypus";
 var textbox_response=input[0].value;

 function verify_request()
  {
   alert(animal);
   alert(textbox_response);
  }

As I have made animal variable in Global scope and that is accessible inside the function but for textbox value it is saying Undefined which is strange.
In the console I am getting this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'value')
I tried putting this textbox_response variable inside the function., it is behaving normally.
I want to know why can't i find the value from textbox outside the function.


text:
Q: VB.NET if button1 caused post back then I have a situation where I need to ignore parts of page load sub inside a isPostback = true. Basically inside the isPostBack I want something like if button1 caused postback.... do this else do this...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If IsPostBack = True Then

        If TextBox1.Text <> String.Empty Then

            CheckDate()
        End If

    End If

End Sub

A: I think what you need is the reference to the control name which triggered the postback.
http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
Implement the solution which is there in the above link (Got it from here.... How to Get Source of postback)
If the control name is your button then do not do what needs to be done upon postback.
HTH

A: You should probably not have all this going on inside the Page_Load event.  Instead, you should be handling events for each control that can cause a postback.  This helps with code clarity, and ease of maintenance, not to mention better control in the first place.
Here's a nice brief blog entry I found on the subject: http://www.sitepoint.com/blogs/2007/01/21/page_load-is-evil/
Incidentally, handling events is much different in ASP.NET than in other environments,  My guess, just based on the fact that you're trying to accomplish this in the Page_Load event is that you're not yet "getting" the event-driven programming model.  (If I'm wrong, I apologize, I don't mean to be insulting).
If I'm right, however, once you get used to it, it's going to be a lot simpler for you than things were in the classic ASP days, for example, where you had to do things like try to figure out which button was clicked.  Here's another nice article to explain this further:  http://articles.sitepoint.com/article/driven-asp-net-development-c

A: It's hard to see this as a good idea.  From the short snippet you posted, it looks like what you really need is a Validation control attached to your textbox.

A: Have a look at the POSTed items. You should see some sort of reference to that button in there. IIRC, if it was clicked, you will see some sort of reference in there, and if it wasn't it wouldn't be in there.
I had this same problem a while a ago and that's how I circumvented loading some stuff.


text:
Q: An expression of non-boolean type specified; in a view I have a view in SQL Server, which contains a WHERE clause, which is the following:
WHERE andon_digitaloutput.on_when_other_lights_off

But when I run it I get the following error:

an expression of non-boolean type specified in a context where a condition is expected

VIEW:
FROM andon_device AS ad
  JOIN (SELECT
      id AS id,
      do_name AS do_name,
      color AS color,
      do_destination AS do_destination
    FROM andon_digitaloutput
    WHERE andon_digitaloutput.on_when_other_lights_off = 1 ) AS c
  LEFT JOIN andon_device_product adp
    ON ad.id=adp.device_id_id
  LEFT JOIN andon_product ap
    ON adp.product_id_id = ap.id
WHERE ad.id NOT IN (SELECT
    andon_event_active.device_id
  FROM andon_event_active);

A: This is the where clause:
WHERE andon_digitaloutput.on_when_other_lights_off

As the error message explains, SQL Server does not support boolean types.  SO you need some comparison.  Perhaps one of the following:
WHERE andon_digitaloutput.on_when_other_lights_off = 1
WHERE andon_digitaloutput.on_when_other_lights_off = 'T'
WHERE andon_digitaloutput.on_when_other_lights_off <> 0

It all depends on what the column contains and what logic you want.
Also, you should learn to use table aliases.  This will simplify your code, making it easier to write and read.  The code might then look like:
WHERE ado.on_when_other_lights_off = 1


text:
Q: How secure is BitLocker's "Encrypt Used Space Only" on a hard disk that was previously overwritten with zeros several times? I completely overwrote an older hard disk three times with zeros to completely remove data that was on it before. Now I want to use the disk with BitLocker, but I don't want to wait again until the encryption is finished. (I know that I can continue to use the hard disk during the encryption, but the performance suffers if I encrypt and write data at the same time.)
My real question is in the title of this post.

A:
How secure is BitLocker's "Encrypt Used Space Only" on a hard disk
  that was previously overwritten with zeros several times?

It depends.
What information are you looking to protect, and from who / what?
Information I can imagine you being concerned about:

*

*The data that was on the drive before

*The data that you are putting on the drive now

*Information about how much data is on the drive now

Information in category #1:
It isn't clear.  If this is a rotational drive, and if there are no bad sectors, then quite possibly this information is gone with the outside chance that the NSA or their counterparts can retrieve the media and do some hardcore analysis of the magnetic domains of the drive.  Otherwise, there is possibly some data preserved that could be recovered by less ... extreme ... adversaries.
Encrypting the whole media could help (only because overwriting with random data is likely to improve the efficacy of the overwriting with zeros), but won't hit the fundamental issues with bad sectors or portions of the SSD that are resting due to wear leveling.
Information in category #2:
This information is probably as safe as the Bitlocker keys and the least secure account password on the computer make it.
Information in category #3:
This information is exposed to anyone with access to your media.  This is really what you're exposing with the option to encrypt used space only, with the outside chance that an attacker who gets periodic access to the media can perform clever analysis on the media to determine useful metadata (e.g. how much you changed, and when) about the contents.
There is no question that encrypting the whole drive is more secure.  If you are protecting credit card numbers, you're done.  If you are protecting your diary from the NSA, you probably want to go a little farther; they are serious Nosy Nancys.


text:
Q: Extending Django PositiveIntegerField to automatically pad string representation? I'm wondering if there's a best way to extend one of my model's fields to automatically pad the string representation of a PositiveIntegerField
models.py
class User(AbstractUser):
    coupon_code = models.PositiveIntegerField(default=0, help_text='Coupon code',)

admin.py:
class CustomUserAdmin(UserAdmin):
    model = User
    list_display=['username','email','coupon_code',]
    fieldsets = UserAdmin.fieldsets + ( ('Coupon Code', {'fields': ['coupon_code',]} ), )

Currently the field displays as an integer would. For example, 42 is printed as '42'. However I would like if the field would pad with zeros whenever printed across the site, especially for built-in pages like admin, so 42 displayed would always be displayed as '0000000042', while keeping the underlying Integer representation in the database.
Can this be done?

A: zfill is your best bet, you could use a representation property or something on the class.
https://docs.python.org/3.7/library/stdtypes.html?highlight=zfill#str.zfill
class User(AbstractUser):
    coupon_code = models.PositiveIntegerField(default=0, help_text='Coupon code',)

    @property
    def coupon_code_display(self):
        return self.coupon_code.zfill(10)


text:
Q: A property of a prime divisor of a number consisting of 1s
For $n>0$ let $A(n) = \underbrace{111 \ldots 11}_{n}$. Prove that if $A(n)$ is divisible by a prime number $p>3$, then $\gcd(n, p-1) > 1$.

It is no huge discovery that if $n$ is even, then $2$ is a common divisor of $n$ and $p-1$, thus the implication holds. I don't know how to justify the general case though, so I would appreciate some hints.

A: If $10^n\equiv 1 \pmod p,(n,p-1)=1,(p,10)=1$,then there exist integer $x,y$, satisfies $xn+y(p-1)=1,$ hence
$$10^1=10^{xn+y(p-1)}=(10^n)^x\cdot(10^{p-1})^y\equiv1^x\cdot  1^y=1 \pmod p$$
We get $p=3.$

A: If $p(>3)$ divides $\underbrace{111 \ldots 11}_n, p$ divides $\underbrace{999\ldots 99}_n\implies p$ divides $(10^n-1)$
$\implies 10^n\equiv1\pmod p\implies ord_p{10}$ divides $n$
Again, using Fermat's Little Theorem, $10^{p-1}\equiv1\pmod p\implies ord_p{10}$ divides $p-1$
$\implies ord_p{10}$ divides $(n,p-1)$
If $(n,p-1)=1,ord_p{10}$ divides  $1\implies ord_p{10}=1\implies 10^1\equiv1\pmod p\implies p$ divides $9$ which is impossible as $p>3$


text:
Q: Thread Interrupted sometimes works and sometimes not Please help me with my problem. I have 2 JMenuItems, if I Click on Start it shall start and do stuff. If I click on Stop it shall stop :)
After i clicked on Start, I click on Stop and sometimes it stops and sometimes not. But I want that it always stops.
What have I done wrong? :/
class DiashowListener implements ActionListener {
Thread td;
boolean ok = false;

        public void actionPerformed(ActionEvent e) {

            if (e.getActionCommand().equals("Start")) {

                td = new Thread(new Runnable() {
                    public void run() {
                        if (bimg != null) {
                                while (!ok) {
                                    try {
                                        ...

                                     } catch (Exception e2) {
                                    }
                                    frame.repaint();
                                }
                        }
                    }
                });

                td.start();

            } else if (e.getActionCommand().equals("Stop")) {
                if (td != null){
                    ok = true;
                }
            }
        }
}

EDIT: ok I changed something, its working now, but: If I click on Stop it shall stop immediately.

A: First of all, you are interrupting the wrong thread (should be td). Second, the contents of the try clause that you omitted is actually important (some operations are uninterruptible). Finally, Thread.isInterrupted is likely not what you want to use, as the flag may get cleared by some unrelated code. Depending on what exactly you are interrupting, it may (or may not) be a good idea to just catch InterruptedException, and terminate in case it is thrown. A better approach is to add your own flag, that the thread will check instead of isInterrupted, and the event handler will set instead of (or in addition to) interrupting the worker thread.


text:
Q: Hadoop Java MapReduce parsing JSON with Jackson issues I am using Jackson JSON parser (1.9.5) in Hadoop Java M/R program (0.20.205).  Given the JSON example below:
{"id":23423423, "name":"abc", "location":{"displayName":"Florida, Rosario","objectType":"place"}, "price":1234.55}

Now, let say I just want to parse out id, location.displayName, and price so I created the following Java object and I am omitting unwanted fields.
@JsonIgnoreProperties(ignoreUnknown = true)
public class Transaction {
  private long id;
  private Location location;
  private double price;

  private static final ObjectMapper mapper = new ObjectMapper();

  ..setter/getter method would be here for id, Location, price

  @JsonIgnoreProperties(ignoreUnknown = true)
  public static class Location {
     private String displayName;

     public String getDisplayName { return displayName; }
     public void setDisplayName(String displayName) { this.displayName = displayName; }
  }

  public static final Transaction fromJsonDoc(String jsonDoc) throws IOException {
     JsonNode rootNode = mapper.readTree(jsonDoc);
     return mapper.treeToValue(rootNode, Transaction.class);
  }
}

When I run this program in standalone mode (not in Hadoop distributed mode).  All the fields that I want parse out correctly. However, as soon as I try to parse out the data in Hadoop map only job, I only get the id field and not the location.displayName and price (they are not deserialized and are null). It seems that the @JsonIgnoreProperties(ignoreUnknown = true) annotation is somehow not working property when running in MapReduce and the fields that I want don't get deserialized (everything after id is null).  If I add all the fields and getters and setter to to my Transaction object and remove @JsonIgnoreProperties, then everything works fine.
Does anyone have a suggestion why this is happening? I just gave a simple example but in reality my JSON document is very complex and I don't want to deserialize all the fields out of it. Am I doing something wrong here?
This is how I am using Jackson in main method and Java/Map reduce program.
Transaction tran = Transaction.fromJsonDoc(jsonRec);
System.out.println("id: " + tran.getId());  //works in both
System.out.println("location: " + tran.getLocation().getDisplayName());  //works only in standalone execution but not in Map/Reduce

A: This might be due to class loading problems: old version of jackson core or so.
The tricky part wrt class loading and annotations is that VM is apparently allowed to just drop annotations it does not recognize. I don't know if this could be causing problem you have, but it may be worth checking. Hadoop used to bundle rather old version of Jackson (1.1?), and since @JsonIgnoreProperties was added in 1.4, this might explain the problem.
How could this occur? You must be compiling using a more recent version (to see the annotation), but perhaps runtime environment is using old (1.1) version. Because you do not actively use annotation class from your code (it is "only" associated with the class), class loader would then drop this annotation as it can not find it from jar.


text:
Q: Get the adjacent indexes from the linear indexing in matlab Given a set of linear indexes of a matrix, how can I get only the adjacent indexes from it ?.  By adjacent I meant the indexes which are either on the left, right, top, bottom or diagonal position of an index.
For example, given a 4*5 matrix
B = [1 0 0 0 0;
     1 1 0 1 1;
     0 0 1 0 1;
     1 0 1 0 0;]

and the linear indices of B [1, 2, 4, 6, 11, 12, 14, 18, 19] (it corresponds to the indexes of non-zero entreies), how can I select only the one which have at least one neighbour ?  In this case, my input is
[1, 2, 4, 6, 11, 12, 14, 18, 19]

I want the output to be
[1, 2, 6, 11, 12, 14, 18, 19]

as except 4, all others have neighbours in the index set.

A: You can use 2D-convolution to compute the number of non-zero neighbours of each entry, and use that as a logical mask:
result = find(B & conv2(B~=0, [1 1 1; 1 0 1; 1 1 1], 'same'));

A: The bwconncomp function from the Image Processing Toolbox returns connected components in binary images. As your matrix is a binary image, i.e. a 2-D matrix containing zeros and ones, we can use this.
Calling the function
>> CC = bwconncomp(B);

returns a struct containing (among other fields) PixelIdxList, which is a cell array, where each element is an array of pixel indices corresponding to a specific connected component. In your case, this is:
>> CC.PixelIdxList

ans =

  1×2 cell array

    {8×1 double}    {[4]}

So you have two connected components: one consisting of 8 pixels, with indices given by CC.PixelIdxList{1}, and a second one containing 1 pixel with index 4.
As you want to remove all pixels that have no neighbors, you can check all elements of CC.PixelIdxList for their number of elements and remove all with only one elements:
>> numPixels = cellfun(@numel,CC.PixelIdxList);
>> toRemove = (numPixels == 1);

This gives us an array toRemove containing a 0 for each connected component we want to keep, and a 1 for each connected component we want to remove. Finally, you can concatenate all connected components you want to keep into a single array with
>> allIdx = CC.PixelIdxList(~tooSmall);
>> allIdx = allIdx{:};

which leaves us with the desired result
>> allIdx

allIdx =

     1
     2
     6
    11
    12
    14
    18
    19


text:
Q: Azure Sql managed instance database mail to external emails blocked due to "Relay Access Denied" We have moved from ono-premise to Azure SQL Managed Instances for our database servers and cannot seem to get database mail to sent to external email addresses however it works correctly for internal (our domain) email addresses. The specific error thrown is as follows:

Message: Cannot send mails to mail server. (Mailbox unavailable. The
server response was: 5.7.64 TenantAttribution; Relay Access Denied
[PU1APC01FT013.eop-APC01.prod.protection.outlook.com])

We have followed Microsoft guidelines in enabling and configuring database for managed instances in Azure and have used the following resources to assist in troubleshooting:
https://techcommunity.microsoft.com/t5/azure-sql/sending-emails-in-azure-sql-managed-instance/ba-p/386235
https://techcommunity.microsoft.com/t5/azure-sql/troubleshooting-database-mail-issues-in-azure-sql-managed/ba-p/583018
We have named the mail profile correctly as described and set up the mail account correctly as described using basic authentication with a valid Exchange mailbox user over SSL/TLS on port 25. Azure nsg (firewalls) have been configured to allow TCP port 25 etc. etc.
I have looked a the Office365 exchange config as well but am unable to set up a connector as our Azure SQL Managed instances do not have a public IP address but we shouldn't need a connector anyway as we are authenticating when trying to send mail from the SQL Server.
Has anyone had success in getting this to work?

A: After lots more research, trial and error and hours on the phone with both the SQL and Exchange MS support teams we have managed to get this working. Essentially we made a change to the SQL DB Mail account to get it working after reading this article here.
We achieved this by moving from the connection Option 3 mentioned in the article to connection Option 1. Specifically we used smtp.office365.com on port 25 (as opposed to port 587) and ticked the secure connection box in conjunction with Basic Authentication.


text:
Q: Hibernate @Email validation allows email with quote in domain part I am using hibernate-validator 4.1.0 and its email validator @Email allows emails containing quote symbol in domain part.
For example, test@my.com' is valid according to hibernate @Email validation.
In email specification such symbol is not allowed in domain part. Therefore, I have concerns that mail server can not send email which is valid according to hibernate validation.
Is it possible to configure hibernate validation to reject such emails?

A: It's not valid.
If it was t'est@my.com then it will be valid, email is divided into a local and domain part. The domain part can't contain '
You can read RFC 952 and 1123 concerning the domain part of the email.
You're just doing syntax validation, but you can also take a bit further, where you can test to see if the domain actually exists. Then if it exists you can to do a SMTP Transaction to see if the email is really valid.
A good Email Hygiene Tool will do validations from basic syntax checking all the way to SMTP Validations.


text:
Q: null pointer exception-parsing json with gson android Hi i am trying to parse Json using gson library.My Json String is this
{
"data": [
    {
        "atb_atestwebservice_cities": [
            {
                "id": "3",
                "cities": "Ajmer",
                "date": "2012-03-01 19:30:32"
            }
        ]
    },
    {
        "atb_atestwebservice_states": [
            {
                "id": "2",
                "states": "goa",
                "date": "2012-02-28 12:53:51"
            }
        ]
    }
]

}
With following classes
public class Cities {

@SerializedName("id")
private String id;

@SerializedName("cities")
private String cities;

@SerializedName("date")
private String date;

public Cities(String id,String city,String date)
{
    this.id=id;
    this.date=date;
    this.cities=city;

}
public String getId()
{
    return id;
}
public String getCity()
{
    return cities;
}
public String getDate()
{
    return date;
}

}
 and
public class States {
@SerializedName("id")
private String id;

@SerializedName("states")
private String states;

@SerializedName("date")
private String date;

 public States(String id,String states,String date)
{
    this.id=id;
    this.date=date;
    this.states=states;

}
public String getId()
{
    return id;
}
public String getCity()
{
    return states;
}
public String getDate()
{
    return date;
}

}
and a data class
public class Data {

 private List<Cities> atb_atestwebservice_cities;

 private List<States> atb_atestwebservice_states;

 public Data(List<Cities> cityList,List<States>stateList)
 {
     this.atb_atestwebservice_cities=cityList;
     this.atb_atestwebservice_states=stateList;
 }

 public List<Cities> getCityList()
 {
     return atb_atestwebservice_cities;
 }

 public void setCityList(List<Cities> cityList)
 {
     this.atb_atestwebservice_cities=cityList;
 }

 public List<States> getSateList()
 {
     return atb_atestwebservice_states;
 }

 public void setDatList(List<States> stateList)
 {
     this.atb_atestwebservice_states=stateList;
 }

}
 and code to deserialize the json string
Gson gson = new Gson();
Data data = gson.fromJson(jsonString,Data.class);

The problem is i am getting null pointer exception.i have referred this link for parsing.I am not sure what is the problem.Are my POJO classes proper or do i need to modify or add some more class ?
EDIT:here is my log cat
  03-14 14:59:31.694: ERROR/AndroidRuntime(323): java.lang.NullPointerException
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at com.jimesh.ShowData$LongOperation.onPostExecute(ShowData.java:88)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at com.jimesh.ShowData$LongOperation.onPostExecute(ShowData.java:1)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at android.os.AsyncTask.finish(AsyncTask.java:417)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at android.os.Looper.loop(Looper.java:123)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at android.app.ActivityThread.main(ActivityThread.java:4627)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at java.lang.reflect.Method.invokeNative(Native Method)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at java.lang.reflect.Method.invoke(Method.java:521)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-14 14:59:31.694: ERROR/AndroidRuntime(323):     at dalvik.system.NativeStart.main(Native Method)

A: your Data.class is not properly write to get your json data parse in proper way  .you need following structure for to get your all response.
you need to use following classes for get Result Data.
Gson gson = new Gson();
Data data = gson.fromJson(jsonString,Data.class);

Here is your Data class
 public class Data {

 @SerializedName("data")
 public List<ResultData> mResultData;
}

  public class ResultData {

    @SerializedName("atb_atestwebservice_cities")
    public List<City> mCityList;

    @SerializedName("atb_atestwebservice_states")
    public List<State> mStateList;

  }

public class City {

/*"id": "3",
"cities": "Ajmer",
"date": "2012-03-01 19:30:32"*/

    @SerializedName("id")
    public String id;

    @SerializedName("cities")
    public String mCitie;

    @SerializedName("date")
    public String mData;

}

  public class State {

/*"id": "2",
"states": "goa",
"date": "2012-02-28 12:53:51"*/

@SerializedName("id")
public String id;

@SerializedName("states")
public String mState;

@SerializedName("date")
public String mDate;

 }

All these class you need to add in your package.


text:
Q: Linear Algebra Challenge Question involving Vector Spaces. Problem:
Let $V$ be the space of continuously differentiable maps $f:\mathbb{R}\to\mathbb{R}$ and let $W$ be the subspace of those maps $f$ for which $f(0)=f^\prime(0)= 0.$ Let $Z$ be the subspace of $V$ consisting of maps $x\to ax+b$, with $a,b \in \mathbb{R}$. Prove that $V=W\oplus Z.$
In order to solve the problem, we have to show that for all $v\in V$ $$v=w+z,$$ where $w\in W$ and $z\in Z.$ I don't know why this must be true, however I can show that $W\cap Z=\{0\}$ since if $z(x)=ax+b$ and $z\in W$ then $z(0)=z^\prime(0)=0$ implies that $a=b=0.$ and so the intersection of the two subspaces must be the zero function denoted by $0.$
How do I proceed to show that every function can be represented as the sum of the functions $w\in W$ and $z\in Z$?

A: The first step is to figure out the values of $a$ and $b$ depending on $v$. Without knowing these values ahead of time, you're going to struggle.
So, let's suppose for the moment that we do indeed have $v(x) = ax + b + w(x)$ for some $w \in W$. We know that these are equal for all $x$. How can we extract the values of $a$ and $b$?
Hint: try subbing in numbers, and/or using differentiation!
Once you get these values, it shouldn't be too hard to prove.

A: Hint Suppose there is a decomposition $V = W \oplus Z$, so that for any $v(x) \in C^1(\Bbb R)$ we have
$$v(x) = w(x) + z(x)$$
for $w(x) \in W, z(x) \in Z$.
Now, we want to express $w(x)$ and $z(x)$ in terms of $v(x)$, and the only information available is the definitions of $W, Z$. Since $W$ is characterized by the evaluation of functions (and their derivatives) at $x = 0$, this suggests evaluating our above expression at $x = 0$, giving
$$v(0) = w(0) + z(0) .$$
Now, what does the definition of $W$ tell us about $w(0)$?


text:
Q: Finding all the eigenvalues and eigenfunctions for a BVP with an inequality condition I am trying to find all the eigenvalues and eigenfunctions for the following boundary value problem
\begin{eqnarray}
\phi''(z) + \phi'(z) + \lambda \phi(z) &=& 0\\
\phi (0)&=& 0 \\
|\phi (\infty)| &<& \infty. \\
\end{eqnarray}
The characteristic polynomial equation is $r^2 + r + \lambda$. The roots are easily obtained as $r_{1,2}=\dfrac{-1 \pm \sqrt{1 - 4\lambda}}{2}$.
Case $\lambda < \frac{1}{4}$ ($r_1$ and $r_2$ are distinct real roots)
Then the general solution to the differential equation is then,
$$\phi(z) = c_1\exp\left[\left(\frac{-1 + \sqrt{1 - 4\lambda}}{2}\right)z\right] + c_2\exp\left[\left(\frac{-1 - \sqrt{1 - 4\lambda}}{2}\right)z\right].$$
Applying the first boundary condition gives us,
$$\phi \left(0\right) = c_1 + c_2.$$
Case $\lambda = 0$ ($r_1 = r_2$)
Then the general solution to the differential equation is then,
$$\phi(z) = c_1\exp\left[\frac{-z}{2}\right] + c_2 z\exp\left[\frac{-z}{2}\right].$$
Applying the first boundary condition gives us,
$$\phi \left(0\right) = c_1.$$
Case $\lambda > \frac{1}{4}$ ($r_1$ and $r_2$ are complex roots)
$$\phi(z) = c_1\exp\left[\frac{-z}{2}\right] \cos (z\frac{\sqrt{4\lambda -1}}{2}) + c_2 \exp\left[\frac{-z}{2}\right]\sin (z\frac{\sqrt{4\lambda -1}}{2}).  $$
Applying the first boundary condition gives us,
$$\phi \left(0\right) = c_1.$$
As suggested by others, in the comments the cases of interest are

*

*$\lambda < -\frac{1}{4}$ (distinct real roots case).

*$\lambda = -\frac{1}{4}$ (distinct real roots case).

*$-\frac{1}{4} < \lambda < 0$ (distinct real roots case).

*$\lambda = 0$ (distinct real roots case).

*$0 < \lambda < \frac{1}{4}$ (distinct real roots case).

*$\lambda = \frac{1}{4}$ (same real roots case).

*$\lambda > \frac{1}{4}$ (complex roots case).

I am not sure how to use the second boundary condition.
Any help will be greatly appreciated.
Thank you.

A: Case 1: $\lambda<0$. Then one of the independent solutions blows up at infinity. Thus its coefficient must be zero in order for the right boundary condition to be satisfied. But then the other must also be zero by the left condition. So there are no eigenfunctions.
Case 2: $\lambda>0$. The forms of the (real) solutions change as $\lambda$ passes through $1/4$, but despite this, both of the independent solutions go to zero at infinity. So the right boundary condition is automatically satisfied, and only the left boundary condition constrains the possible solution. Noting that it doesn't happen that both independent solutions are zero (so the left boundary condition is never trivial), there is a 1D subspace of eigenfunctions.
Case 2a: $0<\lambda<1/4$. In this case we can choose a solution basis given by two both real exponentials $e^{r_1 x},e^{r_2 x}$, and their coefficients must sum to zero by the left BC. So the eigenfunctions are $C(e^{r_1 x}-e^{r_2 x})$
Case 2b: $\lambda=1/4$. In this case we can choose a solution basis consisting of an exponential $e^{rx}$ and $xe^{rx}$ (where $r=r_1=r_2$). The first one does not vanish at zero while the second does, so the eigenfunctions are multiples of the second one, i.e. $Cxe^{rx}$.
Case 2c: $\lambda>1/4$. In this case we can choose a solution basis where one solution has a cosine and the other has a sine (neither with a phase shift). The one with a sine in it vanishes at zero, and the one with a cosine doesn't, so the eigenfunctions are multiples of the sine solution, i.e. $Ce^{Re(r_1)x}\sin(Im(r_1)x)$ (or $r_2$, it doesn't matter).
I'll leave $\lambda=0$ to you.


text:
Q: .htc-файлы не срабатывают в ие Для скругления уголков блока в ие7,8 подключаю файл ie-css3.htc
article #news-box{
        background: url(/images/news-backg.png) no-repeat center top;
        position: relative;
        width: 267px;
        margin: 3px 20px 0 0;
        padding-bottom: 12px;
        border: 1px solid #d7d7d7;
        border-top: 2px solid #d7d7d7;
        border-left: 2px solid #a8a8a8;
        border-radius: 10px;
        -moz-border-radius: 10px; /* Для Firefox 3 */
        -webkit-border-radius: 10px; /* Для Safari 4 и Chrome */
        -khtml-border-radius: 10px;
        behavior: url(css/ie-css3.htc); /*Для IE*/
    }

но он не срабатывает. Подскажите, как можно это исправить либо какой-нибудь альтернативный способ решения этой задачи.
A: Адрес картинки для фона задан от корня, а .htc файла - относительный.


text:
Q: how to set local notification for every two weeks How to trigger local notification for every two weeks?
What i did was:
UILocalNotification *localNotification = UILocalNotification.new;
localNotification.repeatInterval = 14;
localNotification.fireDate = [NSDate dateWithTimeInterval:10 sinceDate:notificationDate];
localNotification.alertBody = notificationMessage;
localNotification.alertAction = @"Open";
localNotification.category = @"default_category";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

A: Try below code:
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.userInfo = @{@"notification_identifier":@"After14Days"};
notification.fireDate = [[NSDate date] dateByAddingTimeInterval:(60*60*24*14)];
notification.alertBody = @"Text to display";
notification.repeatInterval = NSCalendarUnitDay;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];

A: Set repeatInterval of UILocalNotification to NSCalendarUnitDay.


text:
Q: Modifying "pg_hba.conf" file to listen a dynamic address this is the sequel of "Modifying "pg_hba.conf" file to listen local TCP/IP conection"
I manage to modify pg_hba.conf to listen other PCs and allow them through the firewall, but my problem now is that the addresses are dynamic, so the configuration work for one day, but in the next day the router assigns the addresses randomly and we are in trouble again. When I use mySQL I use to work it around using the machine name as the server, but if I use it in the pg_hba it doesn't work. I show you:
what works:
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# IPv4 local connections:
  host    all             all             192.168.1.18/32         md5

what doesn't:
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# IPv4 local connections:
  host    all             all             the_mch_name/32         md5

Is there any solution besides static IP?

A: Your only option other than static IPs is to open it up to listen to any IPs:
host    all             all             all                       md5

Going this method I would recommend you change the connection to require SSL connections by replacing host with hostssl like this:
hostssl    all             all          all                     md5

Be warned, I have found a couple commercial products that will not connect to PostgreSQL using SSL Required.  MapBox Studio is one of such projects unfortunately.

A: The solution to access the database from any machine inside the local network is to set the address to the whole subnet range (as @LR1234567 said):
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# IPv4 local connections:
host    all             all             192.168.1.0/24          md5

or
host    all             all             all                     md5

as @RustProof said.
depending on the net restriction we need.


text:
Q: Parse Comments / Annotations From PDF Using .NET Version of PDFBox: PDFBox.NET-1.8.9 I am using the following code to parse text from a PDF using the .NET version of PDFBox.
Imports org.apache.pdfbox.pdmodel
Imports org.apache.pdfbox.util

Private Shared Function parseUsingPDFBox(ByVal input As String) As String
      Dim doc As PDDocument = Nothing

      Try
        doc = PDDocument.load(input)
        Dim stripper As New PDFTextStripper()
        Return stripper.getText(doc)
      Finally
        If doc IsNot Nothing Then
          doc.close()
        End If
      End Try
    End Function

http://www.squarepdf.net/how-to-convert-pdf-to-text-in-net-vb
The code is extracting the plain visible text, but is not extracting the comments.
I have tried using FDFAnnotation.ToString() But it warns that ToString() is ambiguous...
doc = PDDocument.load(strFilename)
Dim stripper As New FDFAnnotationText
Return stripper.tostring(doc)

I have tried iTextSharp and with this I can extract them using PdfName.ANNOTS class, but wish to stick with PDFBox.
My preferred language is VB, but I am happy to accept answers in C# too.

A: I assume by "comments" you mean text annotations with Name value Comment. The following code outputs the Contents of all text annotations. If you mean a different annotation kind, you might have to adapt it:
Dim doc As PDDocument = PDDocument.loadNonSeq(New java.io.File("..."), Nothing)
Dim pages As java.util.List = doc.getDocumentCatalog().getAllPages()
For i = 0 To pages.size() - 1
    Dim page As PDPage = pages.get(i)
    Dim annotations As java.util.List = page.getAnnotations()
    For j = 0 To annotations.size() - 1
        Dim annotation As PDAnnotation = annotations.get(j)
        If annotation.getSubtype() = "Text" Then
            Console.WriteLine("{0}-{1} : {2}", i, j, annotation.getContents())
        End If
    Next
Next

doc.close()


text:
Q: fixed floating point calculations in Java In Java I need some hint to declare floating point variable that in all virtual machine run uniquely and show number unique float number in all machine ( mobile machine and PC )

A: You can use strictfp keyword for class declaration or variables :
public strictfp class MyFPclass {
    // ... contents of class here ...
}

The Java package java.lang.Math class contains these strictfp methods:
 public static strictfp double abs(double);
 public static strictfp int max(int, int);
 public static strictfp long max(long, long);
 public static strictfp float max(float, float);
 public static strictfp double max(double, double);
 public static strictfp int min(int, int);

A: I can suggest 2 classes for this purpose you can think of

*

*Math.random()

*java.util.Random class

The methods of the Random class often produce random numbers in a more convenient form, but requires creating an object, which sometimes is inconvenient. In constrast, the Math.random() method produces a double value which must sometimes be translated and cast into the form you need it. It's a tradeoff between the globalness of Math.random more directly useful numbers from the Random class.


text:
Q: Place div in a single line on opposite side I'm trying to place two classes on the same line on opposite sides of a div.
I want the two buttons: Login & Register to be on extreme sides of the #home-button and on the same line.
Here is the HTML code:

        Hello

Login

Register

My CSS:
.login-button{
    background:#4578bc;
    color:#fff;
    padding:15px 20px;
    text-align:center;
}

#home-button{
    width:100px;
    margin:100px 0 0 0;
}

.lfloat{float:left}
.rfloat{float:right}

However, no matter what I try, the two buttons: Login & Register end up being on the same side on different lines.

A: The reason Login and Register are on different lines is because they are both block-level elements. You have to float one or both of them to put them on the same line, or make them inline.
Here is an example:
http://jsfiddle.net/K2Rtr/

Login

Register

#right { float: right; width: 100px;}
#right-left {float: left; }
#right-right {float: right;}

In this example, Login and Register are on opposites sides of a div that is 100px wide and floated right.

A: Try following style,
.login-button {
    background:#4578bc;
    color:#fff;
    padding:15px 20px;
    text-align:center;
    display:inline-block;
}
#home-button {
    margin:100px 0 0 0;
}

http://jsfiddle.net/YvUER/

A: You can try this :
Edit :
.login-button {
background: #4578BC;
color: white;
padding: 15px 20px;
text-align: center;
width: 100px;
float: left;
}

#home-button {
width: 282px;
margin: 100px 0 0 0;
float: right;
}

A: If you use float:right; means it will create problems in bigger size monitor and high resolutions, so you can use left: 35%; position: absolute; for div2 to solve resolution issues.
happy coding...


text:
Q: Controlling bounding boxes of a \rotatebox I tried defining a nicer \emptyset using the following:
\documentclass{article}

\usepackage{amsmath, amssymb}
\usepackage{mathtools}
\usepackage{graphics}

\renewcommand{\emptyset}{
    \makebox[1em][c]{
        \scalebox{1.1}{
            \rotatebox[origin=c]{21}{$\varnothing$}
        }
    }
}

\begin{document}

    \[
        X\neq\emptyset\neq Y
    \]

\end{document}

This produces nice-looking results, but when I use a text selecting tool in the pdf, I get a rotated bounding box like this:

Is there a way to edit this meta information in the macro?


text:
Q: Dynamic names for LinkedList Java I have a LinkedList of some type <Structure>. While looping through directories, i have some folders that i read it. I dynamically want to create the these LinkedList with the name of the read directory.
i.e. If directory read is Kitchen or Lobby. I want:
LinkedList<Structure> Kitchen = new LinkedList<Structure>();
LinkedList<Strucutre> Lobby = new LinkedList<Strucure>();

Structure object has (String, ImageIcon, ImageIcon, ImageIcon)
The question here is to name the LinkedList based on the names received by reading directories.
URL url = getClass().getResource("/path/to/directory/");
File file = new File(url.getPath() + "/");
File[] directories = file.listFiles();
for (int i = 0; i < directories.length; i++) {
     if (directories[i].isDirectory()) {
         // if directory then create LinkedList with that name
     }
}

A: It sounds to me like you want a new class, e.g.
class Room {
    private final String name;
    private final LinkedList<Structure> elements;

    ...
}

Alternatively, you could have a Map<String, LinkedList<Structure>> and just populate the map as you load different files.
Then when you load each room, you can supply the name for the object. It's very important that you distinguish between variables (which have names) and objects (which don't, unless you add a field to represent that name, as I have above). Variable names are usually only relevant in code - so the idea of a "dynamically generated variable name" is pointless.

A: You could solve this by use a Map<String, LinkedList<Structure>> where the String key to the Map is the directory name. Then you can access the related LinkedList easily via the directory String.

A: You cannot do this. The names of variables are just symbols you use for programming. At runtime all of this is reduced to references to some space in memory. Also there is no way you or anybody else would be able to actually see the names of those variables, so there's no point here anyway.

A: Java variables names are not variable in themselves but you could go with MultiMap<String, LinkedList<Structure>>. This would help deal with duplicate name entries.


text:
Q: Outlook 2013 creating bogus x500 records when sending email I have this very strange problem that I've spent the last 6 weeks googling and researching and trying different things to fix to no avail.  Any help would be greatly appreciated.
Our Environment:
We run a single Exchange 2010 server - Latest service pack/fully patched.  All clients are Outlook 2013 some running in cache mode, some not.  We're in the middle of a swing migration to exchange 2013.  We completed the upgrade from 2003 to 2010 and will upgrade to 2013 sometime early next year.  We have a sister company - separate email server, domain, namespace, network, etc.  However, we have a 2-way transitive trust setup between our two domains. As far as exchange is concerned though it's just another foreign recipient.  Each night we run a 3rd party program called GALSync that emails certain user information from us to them and they in turn email us some of their user information.  This information is imported into our GAL as mail contacts.  This is a hold-over from the 2003 era and i'm not sure there isn't a better way to do this now but for now it is in place and functioning.
The Problem.
Randomly a user will send an email to someone in our sister company and get a 5.1.1 NDR for an x500 address that is completely wrong.  It actually replaces the domain portion of the email with our internal domain name. This address does not, nor has ever, existed in our domain.
Example:
User JaneDoe@internalname.com emails JoeSmith@sistercompany.com
The NDR shows IMCEAEX-_O=!!OURCOMANY!!_OU=EXCHANGE+20ADMINISTRATIVE+20GROUP+20+28FYDIBOHF23SPDLT+29_CN=RECIPIENTS_CN=JoeSmith1@internalname.com
Notice the "1" after the name and the end and how the @ was changed to our internal name.
JoeSmith@internalname.com, or any variation with a 1 or any other number, has never existed in our company.  A powershell search of all mailboxes' and contacts' LegacyExchangeDNS shows it does not exit anywhere in AD.
I reviewed the logs on exchange and the incoming mail from the user has already had the address converted to this non-existent address so I know the conversion is happening before the new mail makes it to the email server.
The user had successfully sent a message to the same recipient a few days earlier and once I cleared the entry out of their auto-complete cache they were able to successfully send again.
This is happening to single users once every couple of days but it keeps happening more and more and happens to senior executives a lot since they are the ones that email our sister company the most.
The issue does not happen with any other address.
Thank you for your time.


text:
Q: How to bind a C# DataSet with info from SQL Server query to a Telerik Radmap VisualizationLayer I have a DataSet with information from a SQL Server query
SELECT TOP (1000) [Id]
,[Name]
,[placemark]
FROM [testmap].[dbo].[table1]

with the following result:
Result query (click to see image)
SQL Management Studio also can show Spatial Results
Vector geography
I need to bind that map vector to a Telerik RadMap VisualizationLayer and show it above the plain satelite map. In their documentation shows a way to load it one by one with the latitude and longitude but I need to load it with the info in the database. Any ideas?
Thanks in advance.


text:
Q: TYPO3: Add custom set functions in extension controller I'm creating an extension for visitors to sign up to the page.
When signing up, it should create a FE user in the backend which is disabled (and will be manually enabled by an admin). So I'll need to set the disable field to 1 when creating the FE user.
This is the function inside my controller:
/**
 * action create
 *
 * @param \Vendor\FeReg\Domain\Model\Dummy $newDummy
 * @return void
 */
public function createAction(\Vendor\FeReg\Domain\Model\Dummy $newDummy)
{
    // vars
    $title = $newDummy->getTitle();
    $atitle = $newDummy->getAtitle();
    $fname = $newDummy->getFname();
    $lname = $newDummy->getLname();
    $street = $newDummy->getStreet();
    $city = $newDummy->getCity();
    $post = $newDummy->getPost();
    $phone = $newDummy->getPhone();
    $fax = $newDummy->getFax();
    $email = $newDummy->getEmail();
    $org = $newDummy->getOrg();
    $cat = $newDummy->getCat();
    $field = $newDummy->getField();
    $uname = $newDummy->getUname();
    $ppass = $newDummy->getPpass();
    $cpass = $newDummy->getCpass();
    $fulltitle = ($atitle ? $title." ".$atitle : $title);

    $frontendUser = new FrontendUser();

    $frontendUser->setUsername($uname);
    $frontendUser->setPassword($ppass);
    $frontendUser->setFirstname($fname);
    $frontendUser->setLastname($lname);
    $frontendUser->setAddress($street);
    $frontendUser->setTelephone($phone);
    $frontendUser->setFax($fax);
    $frontendUser->setEmail($email);
    $frontendUser->setTitle($fulltitle);
    $frontendUser->setZip($post);
    $frontendUser->setCity($city);
    $frontendUser->setCompany($org);

    $this->frontendUserRepository->add($frontendUser);

    // $this->dummyRepository->add($newDummy);
    // $this->addFlashMessage($title, '', \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR);

    $this->redirect('new');
}

To make this work I'm also loading the $frontendUserRepository.
I need something like $frontendUser->setDisable(1).
Environment: TYPO3 7.6.8 / PHP 5.6.24 / mysqlnd 5.0.11

A: Disabling a user is not default enabled on the standard user object. I've tackled this issue myself by creating a model extending the FrontendUser from TYPO3 and adding a property disable.
class FrontendUser extends \TYPO3\CMS\Extbase\Domain\Model\FrontendUser {
    /**
     * @var boolean
     */
    protected $disable;

    /**
     * Gets the Disable
     *
     * @return boolean
     */
    public function getDisable() {
        return (bool)$this->disable;
    }

    /**
     * Sets the Disable
     *
     * @param boolean $disable
     * @return void
     */
    public function setDisable($disable) {
        $this->disable = (bool)$disable;
    }
}

You might need a bit of typoscript to map it to the proper property
config.tx_extbase {
    persistence{
        classes {
            VendorName\ExtensionName\Domain\Model\FrontendUser {
                mapping {
                    tableName = fe_users
                    columns {
                        disable.mapOnProperty = disable
                    }
                }
            }
        }
    }
}

You'll need the FrontendUserRepository as well
/**
* A Frontend User repository
*/
class FrontendUserRepository extends \TYPO3\CMS\Extbase\Domain\Repository\FrontendUserRepository {
}

After this you can use the newly created FrontendUser model as your model for the FrontendUser, inject it, and happily use
$userModel->setDisable(1);
// and
$userModel->getDisable();

(All namespaces are fully written, this is not necessary obviously, but simply done for ease of reading)


text:
Q: Casting error in VB 4.5 when turning Option Strict On The following code works great with Option Strict off.  However flipping the switch to On gives me the following error - *Value of type DSreprint_ship.companyRow cannot be converted to DSholding.companyRow*.  on Me.DSreprint_ship.company
Dim row As DSholding.companyRow
    For Each row In Me.DSreprint_ship.company
        If row.PLANT = Me.DSreprint_ship.shipmaster.Item(0).plant Then
            If row.IsCITYNull Then
                From_city = "null"
            Else
                From_city = row.CITY
            End If
            If row.IsSTATENull Then
                From_state = "null"
            Else
                From_state = row.STATE
            End If

        End If
    Next

I've researched this until I'm blue in the face and can't seem to see the issue.  Any help is appreciated.

A: The problem here is that you are using two different row types.  They DSreprent_ship.companyRow is different than DSHolding.companyRow` type.  Change the declaration of row to the following
Dim row As DSreprint_ship.companyRow


text:
Q: How to find an element in selenium whose locator value changes on mouse hover? I have a drop down list where each element of the list is a search method, not a select tag. The list has a generic locator value. On select of specific search method, the locator value changes with respect to selected search method. I have to enter the search string, choose the search method and click search icon.
Now, I want to select the 3rd element, for example, search method of the list whose locator value changes on selecting it, and search the search string.

A: Use xpath: http://www.w3schools.com/xml/xpath_intro.asp
With this you can say things like "Find me all the elements that are inside a div with a given id" Or even "find me the third element inside a given div". Which is pretty much what you need.
See examples here: http://www.webperformance.com/load-testing/blog/real-browser-manual/building-a-testcase/how-locate-element-the-page/xpath-locator-examples/


text:
Q: Trying to take a screenshot with selenium (while selecting the url from a text file) So, i started trying to use selenium today and i have a txt file with a lot of urls
The goal here is to select one line of this txt, open the browser and take a picture, after that, save with the name of the url (i want to see what i have on those txts without open one by one, i know it's really lazy)
The problem here is, idk if it works and what i am missing (for sure i am missing something here)
from selenium import webdriver
from time import sleep

myfile = open("links.txt", "r")

url = myfile.readline()
while url:
    url = myfile.readline()

    driver = webdriver.Firefox()
    driver.get(url)
    sleep(1)

    driver.get_screenshot_as_file(url + ".png")
    driver.quit()
    print("printed!")

myfile.close()

That's the error that i get:
selenium.common.exceptions.InvalidArgumentException: Message: Malformed URL: URL constructor:  is not a valid URL.
Stacktrace:
RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8
WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:182:5
InvalidArgumentError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:311:5
GeckoDriver.prototype.navigateTo@chrome://remote/content/marionette/driver.sys.mjs:823:11


text:
Q: Getting error "Object (NaN, NaN) has no method 'extend'" when extenting bounds for Google Map v3 I am getting an error "Object (NaN, NaN) has no method 'extend'", when I try to extend the bounds for each of my markers on google map.
Here is some code:
First I declare the bounds globally:
var bounds = new google.maps.LatLngBounds();

Then I set each markeer using the following code
function displayMarker(appID, title, image, imageType, address, markerType, lat, lng, markersCount) {
    var listingLatLng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
        position: listingLatLng,
        map: map,
        icon: markerType ? imgBluePin : imgGreenPin,
        title: title + address
    });

    bounds.extend(listingLatLng);
    map.fitBounds(bounds);

    var infowindow = new google.maps.InfoWindow(
        { content: GetContent(title, image, imageType, address),
            size: new google.maps.Size(50, 50)
        });

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });

Them, when I load the page I get the error mentioned above when the code tries to extend the bounds,e.g. on line
bounds.extend(listingLatLng);

Why am I getting that error?
Thanks.

A: I found the reason for the bug. Except declaring bounds as
var bounds = new google.maps.LatLngBounds();

it was declared as
var bounds = new google.maps.LatLng();

which was wrong.


text:
Q: [self.tableview reloadData]; causes flickering The problem is the UI appears and then gets updated : giving a flickering affect.
I want the UI to be updated only once when user enters app, thus i've put reload in ViewDidLoad.. Here is the code .. Any help how can remove this flickering ... Some code example would help.
- (void)viewDidLoad {

[super viewDidLoad];

self.myTableView.dataSource = self;
self.myTableView.delegate = self;

PFQuery * getCollectionInfo = [PFQuery queryWithClassName:@"Collection"];   // make query

[getCollectionInfo orderByDescending:@"updatedAt"];
[getCollectionInfo setCachePolicy:kPFCachePolicyCacheThenNetwork];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    [getCollectionInfo findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            CollectionQueryResult = (NSMutableArray *)objects;
                [self.tableView reloadData];

            // whenevr get result
        }
        else{
            //no errors
        }

    }];
});

A: Why don't you simply call reloadSections method instead of [self.tableView reloadData];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];

A: Refer cellForRowAtIndexPath delegate method. You might be doing some operation that might cause a flick. In my case, I was setting an image of an image view with animation. So whenever I reload the table, it was flickering due to that animation.
I removed that animation and worked for me..

A: Hope the below lines can help you in delaying and flickering issues
dispatch_async(dispatch_get_main_queue()
                   , ^{
 [self.tableView reloadData];

 });

A: Your download is asynchronous, so it won't complete before the view is shown. So, whatever you have in CollectionQueryResult will get displayed.
You could either:

*

*Clear CollectionQueryResult so the table isn't populated till you get an update

*Compare CollectionQueryResult and objects, then update only the visible cells where the data has changed (before setting CollectionQueryResult)

Note that for option 2 you will also need to compare the count of CollectionQueryResult and objects and then insert / delete rows from the table view as appropriate. The whole point of option 2 is to not call reloadData, so you need to do a lot more work...
You can also avoid calling reloadRowsAtIndexPaths if you get the visible cells and update them directly (which avoids any animation from happening). See cellForRowAtIndexPath:.


text:
Q: Topological indices for systems that lack translational invariance I have a 1D discrete, finite system that lacks translational invariance. It appears to have edge states, in much the same way as an SSH model has edge states. In the SSH model we can study the infinite version of the finite chain to calculate a topological index, the Zak phase. I am trying to think if I can define (or there already exists) some kind of topological index that captures the presence of these edge states. However my system lacks translational invariance. Any suggestions on how to approach this? I have found the Bott index, but it appears to only be defined for 2D systems.

A: The Bott index is essentially limited to finite, 2D systems with periodic boundary conditions.  There may be some applications of the Bott index to a 1D system that will be found someday.  I assume you have a new system and you want an established index to compute.
What you are looking for are real-space formulas for the index/K-theory.  There are formulas for open boundary conditions and different formulas for periodic boundary conditions.  For an index you compute based on periodic boundary conditions, see the work of Emil Prodan and coauthors.  Some of his papers numerical studies invoving 1D systems in class AIII.
Since you are seeing boundary states, I assume you are fine working with open boundaries.  I wrote out formulas for all five relevant symmetry classes for 1D systems in section 4 of my paper "K-theory and pseudospectra for topological insulators" but I did not publish a study of 1D systems.
A numerical study, in class BDI and in 1D, using the pseudospectral index, was published recently:  Liu, Dillon T., Javad Shabani, and Aditi Mitra. "Long-range Kitaev chains via planar Josephson junctions." Physical Review B 97.23 (2018): 235114.
A word of warning.  The formulas involves the operator $\kappa X + iH$  where $X$ is position (here assumeing that the system is centered at position zero and the spectral gap also around zero).  The small positive consant $\kappa$ is a necessary tuning parameter.  Roughly speaking, one requires is to be chosen so that $\kappa X$ has norm roughly equal to the gap in the corresponding infinite system.  One must experiment.
Assuming you are working in class AIII, the formula involves the grading operator $\Gamma$ which in $+1$ on the even basis vectors and -1 on the odd basis sites.  In physics this is often denoted $S$.  The index is the integer
$$\frac{1}{2} \mbox{sig}(\kappa X + iH)\Gamma .$$
The signature can be computed without finding all the eigenvalues quickly, and is just the number of positive eigenvalues minus the number of even eigenvalues.

A: The index for spectrally gapped, one-dimensional chiral systems (i.e. the disordered version of the SSH model) was already defined for both bulk (infinite) or edge (half-infinite) systems in the work of Schulz-Baldes and Prodan (see their Springer textbook from a few years ago for an introduction). This essentially extends the ground-breaking work of Bellissard, van Elst and Schulz-Baldes to the chiral case in all dimensions.
Allow me to summarize the results succinctly: when you have chiral symmetry (being implemented by some operator $\Pi=\begin{bmatrix}Id&0\\0&-Id\end{bmatrix}$), your Hamiltonian (which obeys $\{H,\Pi\}=0$) is necessarily written in block form as $H=\begin{bmatrix}0&S^\ast\\S&0\end{bmatrix}$ for some operator $S$ (not necessarily self-adjoint). If you consider the half-infinite system, the index is simply the Fredholm index of $S$ (the spectral gap condition combined with the locality of Hamiltonians guarantee that $S$ is indeed a Fredholm operator). This index counts the signed (by chirality) number of zero modes of the edge Hamiltonian.
Conversely if you consider the infinite system, if $P$ is your Fermi projection (for chiral systems one must put the Fermi energy at zero) then your index is $2 tr(\Pi P [X,P])$ where $tr$ is the trace-per-unit-length and $X$ is the position operator.
Prodan and Schulz-Baldes also prove the bulk-edge duality for spectrally gapped systems in their text book, showing that these two indices are equal if you take an infinite system and cut it in the middle.

A: Case Study
Let's see if I've understood some things. Consider the (simplified) Hamiltonian from this paper
$$H=\sum_{n=1}^N \Omega_1 a_n^\dagger b_n + \sum_{n=1}^{N-1} \Omega_2 a_{n+1}^\dagger b_n + \text{H.c.}$$
which describes interactions between nearest neighbours on a dimerised chain with basis particles $A$ and $B$. Here, $\Omega_m = (1/2)(a/d_m)^3$, $d_1=d(1+\epsilon)/2$, $d_2=d(1-\epsilon)/2$, $d=d_1+d_2$ and $\epsilon \in \mathbb{R}$ controls the dimerisation. We choose $a=d/6$.

Infinite system (periodic boundary conditions)
For $\epsilon<0$ the system has a Zak phase of zero and no-edge states. For $\epsilon>0$ the system has a Zak phase of $\pi$ and does have (two) zero-energy edge states. Of course these topological indices have been calculated from the momentum space representation which requires periodic boundary conditions. In addition we can analytically calculate the band-gap between the upper and lower band as $\Delta=2|\Omega_1-\Omega_2|$(see image below, concentrate on just the blue curves for example).

Finite system
Let's try to calculate a topological index for the finite system with open boundary conditions (where the edge states actually manifest). The Hamiltonian can be rewritten as
$$H=\Psi^\dagger \mathbf{H} \Psi,$$
where $\Psi^\dagger=(a^\dagger,b^\dagger)$, $a^\dagger = (a_1^\dagger, a_2^\dagger, \dots, a_N^\dagger)$ (and similarly for $b^\dagger$) and
$$\mathbf{H} = \begin{pmatrix}
0 & \mathbf{\Omega}\\
\mathbf{\Omega}^\dagger & 0
\end{pmatrix}.
$$
Here
$$\mathbf{\Omega} = \begin{pmatrix}
\Omega_1 & \Omega_2 & 0 & 0 &\dots \\
0 & \Omega_1 & \Omega_2 & 0 & \dots \\
\vdots & \vdots & \ddots & \ddots & \dots
\end{pmatrix}.
$$
is a band-diagonal matrix with $\Omega_1$ along the diagonal and $\Omega_2$ along the 1-diagonal.
This system is in the class BDI (I get the same result if I use the measure for the AIII class), therefore we can use the index developed in Loring's paper (here)
$$Z=(1/2)\text{sig}(\kappa \mathbf{X} \mathbf{\Gamma} + \mathbf{H}).$$
Here $\text{sig}(M)$ is literally just the number of positive eigenvalues of $M$ minus the negative ones.
We choose the tuning parameter to be $\kappa=\Delta$ which is the band-gap in the infinite system.
Following this paper, we choose $\mathbf{X}$ to be a diagonal matrix with the diagonal elements the literal physical positions of the particles, but in units of the chain length $L=Nd$ and centred around zero, i.e.
$$\text{diagonal}(\mathbf{X})=(1/L)(-L/2,-L/2+d_1,-L/2+d,-L/2+d+d_1,\dots,L/2)$$
Finally we have $\mathbf{\Gamma}=\sigma_3 \otimes \mathbb{1}_N$, where $\sigma_3$ is a Pauli matrix.
Below I plot the Zak phase (in units of $2\pi$, in red dashed line) and the finite index $Z$ (in black dotted line). We see that they more-or-less agree. Although the finite index remains 'topologically trivial' $Z=0$ for values of $\epsilon$ slightly above zero. Perhaps this makes sense, because here the spectrum has a small band-gap.

Ok, so I seem to have arrived at something sensible. Although the whole thing feels like a black box to me. I just can't digest what the motivation is for the measure. A 'tuning' parameter $\kappa$ also makes me very uncomfortable, because if I get the 'wrong' answer this just allows me to tune it to the 'right' answer. What if I don't know what the right answer is? What if I can't calculate the band-gap of the infinite system (because it doesn't have any sort of translational invariance for example). How can I be confident in my result? I'm also not sure if I interpreted what $\mathbf{X}$ should be correctly. Is it correct? Can I also choose it to be something slightly different?
For example, what if I choose $\kappa=2\Delta$ then I get this incorrect result


text:
Q: Inline VF page is showing in record edit mode in Lightning experience I have added inline visualforce page in account page layout. It is working properly in classic experience.
In Lightning experience, I have updated the account record page using app builder. I am using " Record Detail" standard component in record page. When I create a new account record, the page does not show any inline VF page. However, when I edit existing account record, it shows me inline VF page in the edit page.
How can I avoid showing this inline VF page in edit page in Lightning Experience?


text:
Q: Where is Aria T'Loak in Mass Effect 3? My quick question is, where is she Aria T'loak? If I'm not mistaken, she's suppose to be in the club at the number 3 location (on the map), but I don't see her.

A:
She's listed at the number 2 location, and will always be there.  She's sitting on the corner couch.

A: After entering the club, go up the first set of stairs and take a right, she will be sitting on the red couch.

A: In the Purgatory at the VIP lounge


text:
Q: getting weird issue with redis on laravel i am trying to make larvel use redis in unix socket mode , but when i run php artisan cache:clear
i get the following error msg, what am i doing wrong here, i followed the .env correctly
   Exception

  When setting a value in the cache, you must pass an array of key / value pairs.

  at vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:246
    242|             return app('cache')->get(...$arguments);
    243|         }
    244|
    245|         if (! is_array($arguments[0])) {
  > 246|             throw new Exception(
    247|                 'When setting a value in the cache, you must pass an array of key / value pairs.'
    248|             );
    249|         }
    250|

      +28 vendor frames
  29  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

i also noticed
RedisException

  php_network_getaddresses: getaddrinfo failed: Name or service not known

  at vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php:137
    133|                 $parameters[] = $context;
    134|             }
    135|         }
    136|
  > 137|         $client->{($persistent ? 'pconnect' : 'connect')}(...$parameters);
    138|     }
    139|
    140|     /**
    141|      * Create a new redis cluster instance.

      +25 vendor frames
  26  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()


text:
Q: Ruby Unable to map values to array of hash, searching for alternative I have an array of hashes:
data1 = [{:first => 1, :second => 'whatever'},{:first => 2, :second => 'something'}]

test_merge = {'whatever' => {:third => 1, :fourth => 1}, 'something' => {:third => 2, :fourth => 2}}

I want this output:
[{:first=>"MODIFIED", :second=>"whatever", :test_field=>"added", :third=>1, :fourth=>1, "sdsds"=>"sdsds", "2x4"=>8}, {:first=>"MODIFIED", :second=>"something", :test_field=>"added", :third=>2, :fourth=>2, "sdsds"=>"sdsds", "2x4"=>8}]

I did map and merge:
data2 = data1.map do |d|
    d[:test_field] = 'added'
    d[:first] = 'MODIFIED'
    d2 = test_merge[d[:second]]
    d = d.merge(d2)
    d['sdsds'] = 'sdsds'
    d['2x4'] = 2*4
  end

I got:
data1 #=> [{:first=>"MODIFIED", :second=>"whatever", :test_field=>"added"}, {:first=>"MODIFIED", :second=>"something", :test_field=>"added"}]
data2 #=> [8, 8]

This can be fixed if I do
data2 = data1.map do |d|
        d[:test_field] = 'added'
        d[:first] = 'MODIFIED'
        d2 = {:test_field_two => 'notadded'}
        d = d.merge(d2)
        d['sdsds'] = 'sdsds'
        d['2x4'] = 2*4
        d #or d=d
end

But why do I have to insert that d in the end (d or d=d)? It looks ugly to write d in the end. Isn't there an alternative way to do it, I want the exact output as mentioned above?
Edit: 3 Jan 2017 (Don't read this edit if you are reading the question for first time, everything is mentioned above)
I have to necessarily use merge inside the .map, because I have got another hash as follows:
test_merge = {'whatever' => {:third => 1, :fourth => 1}, 'something' => {:third => 2, :fourth => 2}}

which needs to be merged like this inside the .each (merge doesn't work in .each unfortunately so I have to use map) or .map
d = d.merge(test_merge[d[:second]])

Also '2x4' , :first and other keys are important which needs to be set/modified.
And if I need to modify d[:first] , it should get modified.
I tried .each as mentioned by steve,
data1 = [{:first => 1, :second => 'whatever'},{:first => 2, :second => 'something'}]

    test_merge = {'whatever' => {:third => 1, :fourth => 1}, 'something' => {:third => 2, :fourth => 2}}
      data1.each do |d|
        d[:test_field] = 'added'
        d[:first] = 'MODIFIED'
        d2 = test_merge[d[:second]]
        d = d.merge(d2)
        d['sdsds'] = 'sdsds'
        d['2x4'] = 2*4
      end

And this is the result I got:
[{:first=>"MODIFIED", :second=>"whatever", :test_field=>"added"}, {:first=>"MODIFIED", :second=>"something", :test_field=>"added"}]

That is not my expected output. Is there any hack to this?

A: When doing a map with a block the last executed line of the block is what's returned in the new array.
So if the last line is...
d['2x4'] = 2*4

Then it's 2*4 (8) that's returned.
Setting the last line of the block to...
d

...means that the value of the d variable (the entire hash) is returned.
You don't need to use map if you just want to change the hashes and don't need an array returned.  Use each instead. (Edited to take into account Eric's observation about shallow duplication).
data2 = data1.map{|d| d.dup}
data2.each do |d|
  d[:test_field] = 'added'
  d[:test_field_two] = 'notadded'
  d['sdsds'] = 'sdsds'
  d['2x4'] = 2*4
end

A: Hash#merge returns a merged Hash without changing the original one, so you can add new |key,value| pairs and return the desired hash directly :
data2 = data1.map do |h1|
  h1.merge(:test_field     => 'added',
           :test_field_two => 'not_added',
           'sdsds'         => 'sdsds',
           '2x4'           => 2 * 4)
end

data2 is now :
[{:first=>1,
  :second=>"whatever",
  :test_field=>"added",
  :test_field_two=>"not_added",
  "sdsds"=>"sdsds",
  "2x4"=>8},
 {:first=>2,
  :second=>"something",
  :test_field=>"added",
  :test_field_two=>"not_added",
  "sdsds"=>"sdsds",
  "2x4"=>8}]

while data1 still is :
[{:first=>1, :second=>"whatever"}, {:first=>2, :second=>"something"}]

A: I think this might be better! Though I am not really sure if i understood the question correctly. Hope this helps.
data1 = [{:first => 1, :second => 'whatever'},{:first => 2, :second => 'something'}]

d2 = {:test_field_two => 'notadded', "sdsds"=>"sdsds", "2x4"=>2*4}

data2 = data1.map do |d| d.merge(d2) end

#=> [{:first=>1, :second=>"whatever", :test_field_two=>"notadded", "sdsds"=>"sdsds", "2x4"=>8}, {:first=>2, :second=>"something", :test_field_two=>"notadded", "sdsds"=>"sdsds", "2x4"=>8}]