text:
Q: How can i get content between dates using java regular expressions Below code did not get me the content between dates.can you please help me.
String res="05/22/2014 03:22:39.288 ffff gggg kkkkkk lllllll ssss 05/22/2014 03:22:39.288 oooooo ppppp qqqq rrrrrr sss 05/22/2014 03:22:39.378 mmmmmm nnn oooo ";

String regEx="((0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d).*([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9].[\\d]*)(.*?)((0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d).*([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9].[\\d]*)?";

Matcher matcher = Pattern.compile(regEx).matcher(res);

while(matcher.find())
{
  String group = matcher.group();
  System.out.println(group);
}

Even i tried below using string split with regular expression in java  but it gives only one result:
String regEx="((0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d).*([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9].([\\d][^\\s]+)?)";
        String[] split = res.split(regEx);

A: You can use this regex to capture your text:
(?<=\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}\.\d{3} )(.*?)(?=(?: \d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}\.\d{3}|$))

And grab your text in group #1 i.e.
matcher.group(1);

Working Demo

A: The reason you only get one result in the split is that the * operator is greedy in a regex. Take a read of this, it's good stuff: http://www.regular-expressions.info/repeat.html


text:
Q: Different ways to Launch MAC OSX objective C opplication from command line I have a MAC OSX objective C application say first.app ,in which i use NSAppleScript with admin privileges to run a shell script.This script is indented to launch another Objective C application say second.app.
When you use open command Ex: "open second.app" in shell script it works fine .
But if you launch the second.app by calling its binary Ex: "/second.app/Contents/MacOS/second "  in shell script ,then the control don't come back to first.app until second.app closes . when we close the second.app then first.app resumes .
What is the difference in launching the application from open command and calling  the applications binary directly as mentioned ?

A: Calling
open Second.app

is the same as double-clicking the app's icon in the Finder. The application is started via LaunchServices, and the open command returns immediately.
Calling
/path/to/Second.app/Contents/MacOS/Second

starts the application directly (without LaunchServices), and returns only when the application has terminated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Test coverage for JSON.derserializeuntyped Method I have the following response for my callout from apex trigger to an external webservice.
JSON Response:
{"status":"ok","data":{"account_id":"6819"}}

Apex class method for parsing the JSON using JSON.deserializeUntyped:
  Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
    system.debug(m);
    if(m.get('status') == 'ok' || m.get('status') == 'error' ){
    map<string,object> data = (map<string,object>)m.get('data');
    system.debug('---data----'+data);
    if(m.get('status') == 'ok'){
     opp.Account_Id__c=String.ValueOf(data.get('account_id'));
     }
    else if(m.get('status') == 'error'){
    opp.Sync__c=String.valueOf(data.get('message'));
    }
    SUPPRESS_OPP_UPDATE_CALLOUT = true;
    update opp;
    }

I was not able to cover the above lines in my test class of updating my opp fields with the response.


text:
Q: 'Cannot set property "innerHTML" of undefined' - but it is defined Curious problem, when using '.innerHTML' on a JS element object I am seeing the error 'Cannot set property "innerHTML" of undefined', yet it isn't undefined as I can print it to console with console.log(myElement) on the line before. This error appears when using Chrome and Firefox.
Furthermore, 'myElement.innerHTML("text")' is working, even with this error, so my code is working (functionally), but I wonder if it could create some unforeseen issues, or if this is just a bug.
The code that creates the issue/bug is:
var errorList = event.target.getElementsByClassName("errorList")[0];
  console.log(errorList);    // successfully displays my intended element
  errorList.innerHTML = "";  // successfully clears the

A: Even if you use events, switch to document while invoking getElementClassByName.
event.target is not always what you believe, try to log it to catch the issue.
Working example

document.getElementsByClassName("errorList")[0].addEventListener("click",
function(event){
var errorList = document.getElementsByClassName("errorList")[0];
  console.log(errorList);    // successfully displays my intended element
  errorList.innerHTML = "";  })

test

Event example (return undefined on log)

document.getElementsByClassName("errorList")[0].addEventListener("click",
function(event){
var errorList = event.getElementsByClassName("errorList")[0];
  console.log(errorList);    // successfully displays my intended element
  errorList.innerHTML = "";  })

test

A: Your code may be running multiple times, perhaps at startup or page load.  If this happens, and at one of the times that it runs, the "errorList" element does not exist, the error could be thrown at that time - even if it successfully runs later.
To check for this, I recommend adding something like
console.log("TEST!");

before the
var errorList = event.target.getElementsByClassName("errorList")[0];

If the "TEST!" shows up multiple times in the console, you'll know it's running more than once.

A: You need to add load event in order to get the element when DOM is ready.

function init(){
 var el = document.getElementById("btn");
 el.addEventListener('click',function(){ alert("Button clicked"); });
}

addEventListener('load',init);
<button id="btn">Click</button>


text:
Q: use text-align smartly (if english dir=ltr if arabic dir=rtl) I have a community web site and I want that users write

*

*English posts with direction LTR / text-align: left) and

*Arabic posts with direction RTL / text-align: right.

E.g. Google+ and twitter provides such an POST solution.
I want add automatically direction  attribute to post when i read it from data base post load in rtl or ltr ! but i don't know how ?!

A: you can specify dir="rtl" in your html tags for the correct presentation  with php
in your CMS or if you aren't using one, when storing the context to the DB you can have a option to store a variable with the direction of text the author used.
So, when fetching the post, you can also fetch the option the author marked.
otherwise, like the fellow programmers have suggested, parse the content and see if its arabic characters or latin characters.
example
<body dir="<?php se_11787707_get_post_language(); ?>">

without more information on how you are publishing your posts, i can't detail much more.
please provide how you are storing your posts and how you are fetching them.
I've built a site using this tecnique and i deal with arabic rtl content everyday. it's very simple:
a working example of dir="rtl"
jsfiddle.net
reference: w3.org

A: You'll need to create a function that has all the letters you know are RTL and check when loading. To display RTL you need the CSS attributes, direction, text-align, and unicode-bidi.
Demo:
Script
function checkRtl( character ) {
    var RTL = ['ا','ب','پ','ت','س','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];
    return RTL.indexOf( character ) > -1;
};

var divs = document.getElementsByTagName( 'div' );

for ( var index = 0; index < divs.length; index++ ) {
    if( checkRtl( divs[index].textContent[0] ) ) {
        divs[index].className = 'rtl';
    } else {
        divs[index].className = 'ltr';
    };
};

CSS
.rtl {
    direction: rtl;
    text-align: right;
    unicode-bidi: bidi-override;
}

.ltr {
    direction: ltr;
    text-align: left;
    unicode-bidi: bidi-override;
}

HTML

hello

ظ

A: There is a CSS-only solution:
div {
    text-align: start;
    unicode-bidi: plaintext;
}

jsFiddle
Unfortunately this solution doesn't work with Microsoft Edge.

A: it's very easy. You can use dir='auto' Attribiute in Html Element. So if your text is Arabic or Persian Text use RTL and if your text is English automatic text use LTR.

Hello

سلام

A: Actually the Arabic alphabet letters are these
var RTL = ['ا','ء','ب','ت','ث','ج','ح','خ','د','ذ','ر','ز','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','ل','م','ن','و','ه','ی'];

and Persian (Farsi) alphabet letters are these
var RTL = ['ا','ب','پ','ت','ث','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];

and it can be useful if check the first and second letter because sometimes it can starts by a bullet or something like that.
for ( var index = 0; index < divs.length; index++ ) {
    if( checkRtl( divs[index].textContent[0] ) || checkRtl( divs[index].textContent[1] ) ) {
        divs[index].className = 'rtl';
    } else {
        divs[index].className = 'ltr';
    };
};


text:
Q: List of Horizontal List view to scroll together Flutter I want to create a vertical list of a horizontal list view. I have achieved it using this. But my issue is that each item is scrolling separately horizontally and I don't want that. I need that complete recycler view scrolls horizontally together. This is the code I'm using.
ListView.builder(
                itemCount: memberItemArray.length,
                shrinkWrap: true,
                itemBuilder: (BuildContext context, int index) {
                  return SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: <Widget>[
                        scrollItem(
                            75,
                            const Color(0x00FFFFFF),
                            const Color(0x50000000),
                            memberItemArray[index].sID),
                        scrollItem(
                            200,
                            const Color(0x00FFFFFF),
                            const Color(0x50000000),
                            memberItemArray[index].sName),
                        scrollItem(
                            150,
                            const Color(0x00FFFFFF),
                            const Color(0x50000000),
                            memberItemArray[index].sMobile),
                        scrollItem(
                            150,
                            const Color(0x00FFFFFF),
                            const Color(0x50000000),
                            memberItemArray[index].sPlan != null &&
                                memberItemArray[index].sPlan !=
                                    'null' &&
                                memberItemArray[index].sPlan != ''
                                ? memberItemArray[index].sPlan
                                : '-'),
                        scrollItem(
                            150,
                            const Color(0x00FFFFFF),
                            const Color(0x50000000),
                            memberItemArray[index].sExpDate != null &&
                                memberItemArray[index].sExpDate !=
                                    'null' &&
                                memberItemArray[index].sExpDate !=
                                    ''
                                ? memberItemArray[index].sExpDate
                                : '-'),
                        scrollItem(
                            100,
                            const Color(0x00FFFFFF),
                            const Color(0x50000000),
                            memberItemArray[index].sAmount != null &&
                                memberItemArray[index]
                                    .sAmount
                                    .toString() !=
                                    'null' &&
                                memberItemArray[index]
                                    .sAmount
                                    .toString() !=
                                    ''
                                ? memberItemArray[index]
                                .sAmount
                                .toString()
                                : '-'),
                        scrollItem(
                            100,
                            const Color(0x00FFFFFF),
                            const Color(0x50000000),
                            memberItemArray[index].sDue != null &&
                                memberItemArray[index]
                                    .sDue
                                    .toString() !=
                                    'null' &&
                                memberItemArray[index]
                                    .sDue
                                    .toString() !=
                                    ''
                                ? memberItemArray[index]
                                .sDue
                                .toString()
                                : '-'),
                      ],
                    ),
                  );
                })

Any Help or suggestions are welcomed

A: After 2 days of research, I finally got the answer to this. Simply use  SingleChildScrollView as a parent giving scroll direction as horizontal and its child will be a sized box whose width will be static as I already know the width of the list view, and inside this sized box, we can directly use the ListView.Builder and child of this ListView.Builder will be simple Row
SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Container(
                      margin: EdgeInsets.only(left: 5, right: 5),
                      child: SizedBox(
                        width: 975,
                        child: ListView.builder(
                            itemCount: memberItemArray.length,
                            shrinkWrap: true,
                            itemBuilder: (BuildContext context, int index) {
                              return Row(
                                children: <Widget>[
                                  scrollItem(
                                      75,
                                      const Color(0x00FFFFFF),
                                      const Color(0x50000000),
                                      memberItemArray[index].sID),
                                  scrollItem(
                                      200,
                                      const Color(0x00FFFFFF),
                                      const Color(0x50000000),
                                      memberItemArray[index].sName),
                                  scrollItem(
                                      150,
                                      const Color(0x00FFFFFF),
                                      const Color(0x50000000),
                                      memberItemArray[index].sMobile),
                                  scrollItem(
                                      150,
                                      const Color(0x00FFFFFF),
                                      const Color(0x50000000),
                                      memberItemArray[index].sPlan != null &&
                                              memberItemArray[index].sPlan !=
                                                  'null' &&
                                              memberItemArray[index].sPlan != ''
                                          ? memberItemArray[index].sPlan
                                          : '-'),
                                  scrollItem(
                                      150,
                                      const Color(0x00FFFFFF),
                                      const Color(0x50000000),
                                      memberItemArray[index].sExpDate != null &&
                                              memberItemArray[index].sExpDate !=
                                                  'null' &&
                                              memberItemArray[index].sExpDate !=
                                                  ''
                                          ? memberItemArray[index].sExpDate
                                          : '-'),
                                  scrollItem(
                                      100,
                                      const Color(0x00FFFFFF),
                                      const Color(0x50000000),
                                      memberItemArray[index].sAmount != null &&
                                              memberItemArray[index]
                                                      .sAmount
                                                      .toString() !=
                                                  'null' &&
                                              memberItemArray[index]
                                                      .sAmount
                                                      .toString() !=
                                                  ''
                                          ? memberItemArray[index]
                                              .sAmount
                                              .toString()
                                          : '-'),
                                  scrollItem(
                                      100,
                                      const Color(0x00FFFFFF),
                                      const Color(0x50000000),
                                      memberItemArray[index].sDue != null &&
                                              memberItemArray[index]
                                                      .sDue
                                                      .toString() !=
                                                  'null' &&
                                              memberItemArray[index]
                                                      .sDue
                                                      .toString() !=
                                                  ''
                                          ? memberItemArray[index]
                                              .sDue
                                              .toString()
                                          : '-'),
                                ],
                              );
                            }),
                      ),
                    ),
                  )


text:
Q: Selenium not finding custom attribute 'data-target-section-id' I'm trying to scrape some profiles of people in linkedin from a specific job. To do this I was trying to find the people button and click it to specifically look at the relevant people.
The path is as follows:
From signed out Linkedin home -> I sign in and go to LinkedIn home -> I write in the search bar "hr" and hit enter.
In the result page of hr, on the left side of the page, there is a navigation list that says "On this page". One of the options includes "People" and that is what I want to target.
The link to the page is: https://www.linkedin.com/search/results/all/?keywords=hr&origin=GLOBAL_SEARCH_HEADER&sid=Xj2
The HTML of the button for 'People' in the navigation list is:

   <button aria-current="false" class="search-navigation-panel_button" data-target-section-id="PTFmMNSPSz2LQRzwynhRBQ==" role="link" type="button"> People

I have tried to find this button through By.Link_text and found the keyword People but did not work. I have also tried to do By.XPATH "//button[@data-target-section-id='RIK0XK7NRnS21bVSiNaicw==']")"" but it also does not find it.
How can I make selenium find this custom attribute so I can find this button through data-target-section-id="PTFmMNSPSz2LQRzwynhRBQ=="?
Another issue that I am having is that I can target all the relevant people on the page and loop through them but I cannot extract the link of each of the profiles. It only takes the first link of the first person and never updates the variable again through the loop.
For example, if the first person is Ian, and the second is Brian, it gives me the link for Ian's profile even if 'users' is Brian.
Debugging the loop I can see the correct list of people in all_users but it only gets the href of the first person in the list and never updates.
Here is the code of that:
all_users = driver.find_elements(By.XPATH, "//*[contains(@class, 'entity-result__title-line entity-result__title-line--2-lines')]")

for users in all_users:
    print(users)
    get_links = users.find_element(By.XPATH, "//*[contains(@href, 'miniProfileUrn')]")
    print(get_links.get_attribute('href'))

A: If you want to locate several elements with the same attribute replace find_element with find_elements. See if that works to find not just the first element matching your search, but all elements with that attribute.
Review the Selenium: Locating Elements documentation and see if you can try each and every option they have for locating elements.
Something else to try:
button_element = driver.find_element(By.XPATH, "//button[@data-target-section-id='RIK0XK7NRnS21bVSiNaicw==']")
list_element.find_element(By.TAG_NAME, "button").click()

A:
I have also tried to do By.XPATH
"//button[@data-target-section-id='RIK0XK7NRnS21bVSiNaicw==']")"" but
it also does not find it.

The data-target-section-id that you mention is not the same as the one that the button has (PTFmMNSPSz2LQRzwynhRBQ==). Check that this is not dynamic before targeting it.
Your xPath is not bad but as I told you, fix the target-id:
driver.findElement(By.xpath("//button[@data-target-section-id='PTFmMNSPSz2LQRzwynhRBQ==']")).click()

Where "driver" is your WebDriver instance.

A: Given the HTML:

   <button aria-current="false" class="search-navigation-panel_button" data-target-section-id="PTFmMNSPSz2LQRzwynhRBQ==" role="link" type="button"> People </button>

The data-target-section-id attribute values like PTFmMNSPSz2LQRzwynhRBQ== are dynamically generated and is bound to chage sooner/later. They may change next time you access the application afresh or even while next application startup. So can't be used in locators.

Solution
The desired element being a dynamic element to click on the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

*

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.search-navigation-panel_button[data-target-section-id]"))).click()

*Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='search-navigation-panel_button' and @data-target-section-id][contains(., 'People')]"))).click()

*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

A: It looks like the reason your People button locator isn't working is because the data-target-section-id is dynamic. Mine is showing as hopW8RkwTN2R9dPgL6Fm/w==. We can get around that by using an XPath to locate the element based on the text contained, "People", e.g.
//button[text()='People']

Turns out that matches two elements on the page because many of the left nav links are repeated as rounded buttons on the top of the page so we can further refine our locator to
//button[text()='People'][@data-target-section-id]

Having said that, that link only scrolls the page so you don't really need to click that.
From there, you want to get the links to each person listed under the People heading. We first need the DIV that contains the People section. It's kinda messy because the IDs on those elements are also dynamic so we need to find the H2 that contains "People" and then work our way back up the DOM to the DIV that contains only that section. We can get that using the XPath below
//div[@class='search-results-container']/div[.//h2[text()='People']]

From there, we want all of the A tags that uniquely link to a person... and there's a lot of A tags in that section but most are not ones we want so we need to do more filtering. I found that the below XPath locates each unique URL in that section.
//a[contains(@href,'miniProfileUrn')][contains(@class,'scale-down')]

Combining the two XPaths, we get
//div[@class='search-results-container']/div[.//h2[text()='People']]//a[contains(@href,'miniProfileUrn')][contains(@class,'scale-down')]

which locates all unique URLs belonging to a person in the People section of the page.
Using this, your code would look like
all_users = driver.find_elements(By.XPATH, "//div[@class='search-results-container']/div[.//h2[text()='People']]//a[contains(@href,'miniProfileUrn')][contains(@class,'scale-down')]")

for user in all_users:
    print(user.get_attribute('href'))

NOTE: The reason your code was only returning the first href repeatedly is because you are searching from an existing element with an XPath so you need to add a "." at the start of the XPath to indicate to start searching from the referenced element.
get_links = users.find_element(By.XPATH, ".//*[contains(@href, 'miniProfileUrn')]")
                                          ^ add period here

I've eliminated that step in my code so you won't need it there.


text:
Q: How to create structure destruction like Fortnite in Unity? I'm trying to make a fan remake of Fortnite. I already made a construction system and editing, but I don't know how destruction can be done. https://www.youtube.com/watch?v=hwuvoOXL2vw
This how it looks in Fortnite - https://youtu.be/EGXYWceVUPU
Do you have any ideas how to do this? I tried through checking neighboring cells, but this is not optimized or I did something wrong.
I will be glad to any advice!

A: Using raycasts, you can send out a raycast whenever the player wants to hit something, then if the object has the script that means it can take damage (maybe just use a tag for this), then it will take damage from the object. You could use Brackeys' FPS Shooting tutorial, and adapt that to suit your needs.


text:
Q: conflict versions android studio I have the following issue and can not build my app
Found play-services:12.0.1, but version 11.4.2 is needed for the google-services plugin.
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':lib_baselibs:processDebugGoogleServices'.

Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 11.4.2.

these are the versions that I am using
ext.kotlin_version = '1.2.41'
ext.support_version = '27.1.1'
ext.google_version = '12.0.1'
ext.firebase_version = '12.0.1'

A: Avoid same version number and update to the latest version, use google play services:
classpath 'com.google.gms:google-services:4.0.1'

And update firebase based on this link to the latest version like below (pick what you need):
    implementation 'com.google.firebase:firebase-core:16.0.0'
    implementation 'com.google.firebase:firebase-ads:15.0.1'
    implementation 'com.google.firebase:firebase-analytics:16.0.0'
    implementation 'com.google.firebase:firebase-appindexing:15.0.1'
    implementation 'com.google.firebase:firebase-auth:16.0.1'
    implementation 'com.google.firebase:firebase-firestore:17.0.1'
    implementation 'com.google.firebase:firebase-functions:16.0.1'
    implementation 'com.google.firebase:firebase-messaging:17.0.0'
    implementation 'com.google.firebase:firebase-storage:16.0.1'
    implementation 'com.google.firebase:firebase-crash:16.0.0'
    implementation 'com.google.firebase:firebase-invites:16.0.0'
    implementation 'com.google.firebase:firebase-perf:16.0.0'
    implementation 'com.google.firebase:firebase-database:16.0.1'
    implementation 'com.google.firebase:firebase-config:16.0.0'

And also make sure that you are using latest version of com.google.android.gms:play-services like (example) based on this link:
    implementation 'com.google.android.gms:play-services-location:15.0.1'
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    implementation 'com.google.android.gms:play-services-places:15.0.1'
    implementation 'com.google.android.gms:play-services-gcm:15.0.1'


text:
Q: How do I resume large file downloads, and obtain download progress using the ServiceStack client? I have a ServiceStack client that calls a service which returns an large data file of between 100MB to 10GB. Currently this client works perfectly over the LAN using the Stream.CopyTo method to save to file.
When the client is being run over a WAN (in addition to over a LAN) the ability to resume a download if it is stopped or loses a connection, as well as see the progress, has become important.
The service supports sending partial files but I am unclear on how to support this in the ServiceStack client or even if it is built in and I do not realise it.
Also the CopyTo method on the stream to copy to another stream does not report its progress so for a large file it can take hours and you can't tell its progress.  I have seen posts about a CopyFrom method that reports progress but I can't find that anywhere on the classes I am using.
My environment is the latest version of ServiceStack and latest version of Mono on Mac OS X and .NET 4.5 on Windows.
Being able to do concurrent downloads on a file for different segments would be ideal but just been able to resume downloads would be a huge help.
Can someone point out the best way to do this in the ServiceStack client? Most examples I found are just for the normal web client and are very old so wanted to see what the best way is with the later version of dotnet and mono as well as with ServiceStack.
If possible a basic example would be perfect.

A: ServiceStack supports Partial Content Responses for services that return:
A Physical File
return new HttpResult(new FileInfo(filePath), request.MimeType);

A Memory Stream
return new HttpResult(ms, "audio/mpeg");

Raw Text
return new HttpResult(customText, "text/plain");

Static files served through ServiceStack
Partial Content is also available in static file downloads served directly through ServiceStack which lets you stream mp3 downloads or should you ever want to your static .html, .css, .js, etc.
Http Utils
See PartialContentResultTests.cs for examples of how to request partial downloads using ServiceStack's built-in HTTP Utils.


text:
Q: Please explain the proof of if $d$ is $\gcd(a,b)$, then $d=sa+tb$ for some integers $s$ and $t$. I am learning Discrete Mathematics myself by reading book titled "Discrete Mathematical Structures" by Kolman, Busby and Ross.
In this book, on Chapter 1, the following theorem is mentioned.
if $d$ is $\gcd(a,b)$, then
(i) $d=sa+tb$ for some integers $s$ and $t$. (These are not necessarily positive)
(ii) if $c$ is any other common divisor of $a$ and $b$, then $c \mid d$
The proof is given as follows.
Let $x$ be the smallest positive that can be written as $sa+tb$ for some integers $s$ and $t$, and let $c$ be a common divisor of $a$ and $b$. Since $c\mid a$ and $c\mid b$, it follows from the Theorem 2 that $c\mid x$, so $c \leq x$. if we can show that $x$ is a common divisor of $a$ and $b$, it will then be the greatest common divisor of $a$ and $b$ and both parts of the theorem will have been proved. By Theorem 1, $a=qx+r$ with $0 \leq r \le x$. Solving for $r,$ we have
$$r=a-qx=a-q(sa+tb)=a-qsa-qtb=(1-qs)a+(-qt)b.$$
If $r$ is not zero, then since $r \leq x$ and $r$ is the sum of a multiple of $a$ and a multiple of $b$, we will have a contradiction to the fact that $x$ is the smallest positive number that is a sum of multiples $a$ and $b$. Thus $r$ must be $0$ and $x\mid a$. In the same way we can show that $x\mid b$, and this completes the proof.
I only understand up to "follows from the Theorem 2 that $c\mid x$, so $c \leq x$." in the theorem. then I understand how $r$ is calculated using Theorem 1. Other than that I can't understand this proof.
How it will prove both the part of the theorem if we show $x$ is a common divisor of $a$ and $b$, it will then be the greatest common divisor of $a$ and $b$ ?
Can somebody please explain this elaborately?
Edit:
Theorem 1: if $n$ and $m$ are integers and $n \gt 0$, we can write $m = qn + r$ for integers $q$ and $r$ with $0 \leq r \lt n$.
Theorem 2: If $a\mid b$ and $a\mid c$, then $a\mid(mb+nc)$, for any integers $m$ and $n$.

A: The global strategy of the proof is this: if $x$ is the smallest positive that can be written as $sa+tb$ for some integers $s$ and $t$, then $x=\gcd(a,b)$; in particular, $\gcd(a,b)$ can be written as a linear combination of $a$ and $b$ with integer coefficients. And it follows from the fact that $x$ can be written as $sa+tb$ for some integers $s$ and $t$ that if $c\mid a$ and $c\mid b$, then $c\mid x(=sa+tb)$.
In order to prove that $x=\gcd(a,b)$, the authors first prove that every common divisor of $a$ and $b$ is smaller than or equal to $x$. So, if it turns out that $x$ itself is also a common divisor of $a$ and $b$, it will follow that it is the greatest common divisor.
In order to prove that $x\mid a$, the authors note that, if $a=qx+r$ with $0\leqslant r<x$, then$$r=(1−qs)a+(−qt)b.$$So, if $r>0$, $r$ would be a positive number that could be written as a linear combination of $a$ and $b$ with integer coefficients. But $r<x$ and $x$ is the smallest such positive number. So, $r=0$; in other words, $a=qx$ and, in particular, $x\mid a$. By the same argument, $x\mid b$.


text:
Q: Generalized log likelihood ratio test for non-nested models I understand that if I have two models A and B and A is nested in B then, given some data, I can fit the parameters of A and B using MLE and apply the generalized log likelihood ratio test.  In particular, the distribution of the test should be $\chi^2$ with $n$ degrees of freedom where $n$ is the difference in the number of parameters that $A$ and $B$ have.
However, what happens if $A$ and $B$ have the same number of parameters but the models are not nested? That is they are simply different models.  Is there any way to apply a likelihood ratio test or can one do something else?

A: The paper Vuong, Q. H. (1989). Likelihood ratio tests for model selection and non-nested hypotheses. Econometrica, 307-333. has the full theoretical treatment and test procedures. It distinguishes between three situations, "Strictly Non-nested Models", "Overlapping Models", "Nested Models", and also examines cases of misspecification. It is therefore no-accident that it finds that for some cases, the test statistic is distributed as a linear combination of chi-squares.
The paper is not light, neither it proposes an "off-the-shelf" testing procedure. But, for once, its (close to) 3,000 citations speak of its merits, being an inspired combination of classical testing framework and the information-theoretic approach.

A: The Generalised likelihood ratio test DOES NOT work the way you are saying. See for example the following lecture notes:
http://www.maths.manchester.ac.uk/~peterf/MATH38062/MATH38062%20GLRT.pdf
http://www.maths.qmul.ac.uk/~bb/MS_Lectures_12b.pdf
The GLRT is defined for hypothesis of the type:
$$H_0: \theta\in\Theta_0 \,\,\, vs. \,\,\, H_1: \theta\in\Theta_1,$$
where $\Theta_0\cap\Theta_1=\emptyset$ and $\Theta_0\cup\Theta_1=\Theta$.
For the framework you describe, you can compare the models using other tools such as AIC and BIC. Also Bayes factors, if you are willing to go full Bayesian.


text:
Q: Rails - merge two tables with identical structure In my model I've got two tables with identical structure:
League1
id  other_columns  match_starts_at  main_page
----------------------------------------------
1   xxxxxxxxxxxxx  24/06/2018       1
2   xxxxxxxxxxxxx  26/06/2018       1

and
League2
id  other_columns  match_starts_at  main_page
----------------------------------------------
1   xxxxxxxxxxxxx  23/06/2018       1
2   xxxxxxxxxxxxx  25/06/2018       1

My controller does something like this:
league1 = League1.where(main_page: 1)
leageu2 = League2.where(main_page : 1)

How can I mix (append, unite, or any other english word for that) records from both leagues into one object, so that I can later order it by match_starts_at?
Something like this:
@leagues = league1 + league2
@leagues.order(match_starts_at: :desc)

But it results in error:
undefined method 'order' for #<Array:0x007f0338c02898>
And my desired result is this (sorted by match_starts_by):
League2
id  other_columns  match_starts_at  main_page
----------------------------------------------
1   xxxxxxxxxxxxx  23/06/2018       1
1   xxxxxxxxxxxxx  24/06/2018       1
2   xxxxxxxxxxxxx  25/06/2018       1
2   xxxxxxxxxxxxx  25/06/2018       1

And then I paginate it and send it to my view.

A: I can now answer my own question.
I didn't manage to merge these two ActiveRecord::Relation objects into one, but it turned out that having Array on the output was also sufficient here.
What I did:
league1 = League1.where(main_page: 1) #ActiveRecord::Relation
leageu2 = League2.where(main_page : 1) #ActiveRecord::Relation

@leagues = league1 + league2 #which returns Array

@league = @league.sort_by { |r| r.match_starts_at }.reverse #sorting a normal array

@league = Kaminari.paginate_array(@league).page(params[:page]).per(10) # it turned out Kaminari can also paginate Array using #paginate_array


text:
Q: A linearly ordered set $P$ has a countable dense subset, then $|P|\le 2^N$ This is a question on the book, "Introduction to Set Theory", by Karel Hrbacek and Thomas Jech, 101.p.

If a linearly ordered set $P$ has a countable dense subset, then $|P|\le 2^N$

Clearly, $N \le P$, but I cannot go any further. Let $D$ the given subset, then $D$={$d_i$|$i \in N$} since D is countable. I think I need to use some theorems related to structure isomorphism, but professor doesn't cover it so I'm not sure what I should do now. Any hints or full answer would be very thankful.

A: For each $p\in P$ there exists a sequence $(d_n)_{n\in\mathbb N}$ of elements in $D$ such that $d_n\to p$. Since $D$ is countable, there are only $2^{\aleph_0}$ sequences (even ignoring convergence) - just like there are only $2^{\aleph_0}$ sequences of natural or rational numbers.

A: Hint: For each $p\in P$ let $I_p=\{i:d_i\lt p\}$. The map $p\mapsto I_p$ may not be one-to-one, but it's at most two-to-one, and so the number of points in $P$ is at most twice the number of subsets of $N$.


text:
Q: Passing hash key to controller I have this code in Rails 2.x:

    <%= t('select_a_course_batch') %>

 <%= select :fees_submission, :batch_id, @batches.map { |c| [c.full_name, c.id] },
        {:prompt => "#{t('select_a_batch')}"},
        {:onChange => "#{remote_function(:url => {:action => "update_fees_collection_dates_voucher"}, :with => "'batch_id='+value")}"}%>

for the onChange action.. I want to pass the hash key (c.fullname) to the remote update_fees_collection_dates_voucher controller instead of the hash value (c.id) .. Replacing "'batch_id='+value" with "'batch_id='+key" doesnt seem to work. Any ideas? Thanks!

A: Isn't this working?
{:onChange => "#{remote_function(:url => {:action => "update_fees_collection_dates_voucher"}, :with => "'batch_id='+ $(this).html()}"}%>


text:
Q: Fonts smoothing on Windows - how to disable ClearType but still get a smoothing For a quite some time I had had a nice font smoothing settings set on my Windows 7 Pro. I can't remember exactly how I set it, I'm sure I changed two parameters to get the effect:

*

*Control Panel -> Fonts -> "Adjust ClearType text"

*Control Panel > System > Advanced system settings > Performance Settings > Visual Effects -> "Smooth edges of screen fonts"

Fonts (I'm talking about popular fonts on websites (Chrome, Opera) - Arial, Verdana, Tahoma, etc.) had been looking nice and sharp. With those settings fonts with a smaller size (up to 16-17px) look 100% sharp (single color, no transparency/gray) and fonts with a bigger size are also nicely and sharply rendered (obviously not 100% sharp).
Yesterday I was watching a video on livestream and at one moment I lost my screen for a second, something like "Nvidia display driver has stopped responding and has recovered". After this I noticed that fonts look different, I checked the settings and in fact they were reset - ClearType and "Smooth edges of screen fonts" were enabled.
I tried to change the settings back, unfortunately I cannot get the same effect. What I can get is either default ClearType, which makes fonts look fuzzy, or no smoothing at all (no matter what is the font size, always a single color, 100% sharp).
I tried to reinstall the nvidia display driver. I tried every combination for FontSmoothing and FontSmoothingType in HKEY_CURRENT_USER\Control Panel\Desktop (via regedit). I tried a program called ClearType Switch. I also tried to get the effect on another computer (also Windows 7), still I cannot get it.


text:
Q: What does it mean creating network in docker? During reading tutorial about docker swarm I came across on follwing thing:
docker network create --opt encrypted --subnet 100.0.0.0/24 -d overlay net1

What does it do?
And how does it work internally? Maybe, does it create some network namespace?  What does it mean overlay.
Could someone explain these things?

A: Most of those options are explained in "Use overlay networks":

The overlay network driver creates a distributed network among multiple Docker daemon hosts. This network sits on top of (overlays) the host-specific networks, allowing containers connected to it (including swarm service containers) to communicate securely. Docker transparently handles routing of each packet to and from the correct Docker daemon host and the correct destination container.

Regarding the --opt encrypted option:

To encrypt application data as well, add --opt encrypted when creating the overlay network. This enables IPSEC encryption at the level of the vxlan. This encryption imposes a non-negligible performance penalty, so you should test this option before using it in production.
When you enable overlay encryption, Docker creates IPSEC tunnels between all the nodes where tasks are scheduled for services attached to the overlay network.

The command docker network create includes advanced options like subnet:

When you create a network, Engine creates a non-overlapping subnetwork for the network by default. This subnetwork is not a subdivision of an existing network. It is purely for ip-addressing purposes. You can override this default and specify subnetwork values directly using the --subnet option.


text:
Q: Winforms DataGridViewComboBox column and List<> I'm having to modify an old Winforms app to add a combo box to a DataGridView.
The data source for the grid is a normal list object with primitives which binds fine but now the object in the list has its own list of objects.
eg:
public class Person
{
 public string Name {get; set;}
 public int Age {get; set;}
 public List<Colors> ColorList {get; set;}
}

and the Colors lets say is something like:
public class Colors
{
  public string Name;
}

The list in Person is simply a list. It's not a foreign key with one colour linked to each person. The grid has to show each person and a final column with all the colors in that list in a combobox for the user to select one.
So the Grid has 3 columns. 2 DataGridViewTextBoxColumn and 1 DataGridViewComboBoxColumn
Setting the data properties in the designer and a datasource to the List of Person's shows the Name and Age values but the Combobox is empty and has no drop down.
Manually adding the columns, the rows and assigning the cell item values doesn't work either.
It seems unless I set the Columns DataPropertyName, I get an empty combobox.
As the grid is bound to the List I can only set the DataPropertyName to a property on the Person object and then the DisplayMember and ValueMember to members of the Color object but this doesn't work either..it seems to be a sort of Foreign key setup which would select 1 color matching some id from the Person object but this isn't what I need.
I just want every item from the ColorList list that has been added to the Person object to appear in the dropdown of the associated Person
What am I missing as this seems such a simple thing.
Edit:
Here is some code I've tried to manually put data into the grid.
 grd2.AutoGenerateColumns = false;

 var colors = new List<Colors>
              {
                 new Colors() { Color = "red", Id = 1 },
                 new Colors() { Color = "blue", Id = 1 }
              };

 var persons = new List<Person>
              {
                 new Person() { Name = "Bob", Age = 20, ColourList = colors },
                 new Person() { Name = "Jane", Age = 24, ColourList = colors }
              };

 foreach (var person in persons)
 {
   var row = new DataGridViewRow();
   var cell1 = new DataGridViewTextBoxCell { Value = person.Name };
   var cell2 = new DataGridViewTextBoxCell { Value = person.Age };
   var cell3 = new DataGridViewComboBoxCell { ValueType = typeof(string) };
   person.ColourList.ForEach(x => cell3.Items.Add(x.Color));
   row.Cells.AddRange(new DataGridViewCell[] {cell1, cell2});
   row.Cells.Add(cell3);
   grid.Rows.Add(row);
 }

This populates the Name and Age columns but the dropdown list doesn't even dropdown.
The grid has a 3 columns defined in the designer. 2 text and 1 combo.
Obviously in this example the colors are fixed for both Bob and Jane but this wouldn't be the case in reality..this is just an example.

A: Your person class should contains only selected color right?
then you should make the following changes
public class Person
{
 public string Name {get; set;}
 public int Age {get; set;}
 public Colors SelectedColor{get; set;}
}

by this it should work if you populate the combo correctly and the column is link to the column SelectedColor

A: I finally solved it doing the following:
foreach (var person in persons)
{
  var row = new DataGridViewRow();
  row.Cells.Add(new DataGridViewTextBoxCell());
  row.Cells.Add(new DataGridViewTextBoxCell());
  row.Cells.Add(new DataGridViewComboBoxCell());

  row.Cells[0].Value = person.Name;
  row.Cells[1].Value = Person.Age;

  var percolours = person.ColourList.Select(x => x.Color).ToList();

  ((DataGridViewComboBoxCell)row.Cells[1]).DataSource = percolours;

  dataGridView1.Rows.Add(row);
}

Credit: SO answer dealing with my issue. I thought I'd searched more thoroughly than I apparently did.


text:
Q: What should be the ViewModel members visibility? I've came across an interesting issue for which I've found no explanation yet...
Given the very simple MVVM WPF application below, why is the list bound to the combo box only if its visibility in the ViewModel is set to public ?
Changing the TestList visibility to internal raises no error or warning at compile time but leaves the combo box empty at run time.
Quoting the official documentation: internal types or members are accessible only within files in the same assembly.
And this issue is happening despite the fact that the View and the ViewModel are defined in the same assembly.
Here is how the code looks like:
Model:
class TestModel
{
    internal List<string> Musketeers { get; private set; }

    public TestModel()
    {
        Musketeers = new List<string> { "Athos", "Porthos", "Aramis" };
    }
}

View:
<Window x:Class="TestWpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <ComboBox Width="250" Height="25" ItemsSource="{Binding TestList}" />
    </Grid>
</Window>

ViewModel:
class TestViewModel : INotifyPropertyChanged
{
    TestModel myModel = new TestModel();

    public List<string> TestList
    {
        get
        {
            return myModel.Musketeers;
        }
    }

    // INotifyPropertyChanged members are below ...
}

A: ViewModel with internal access is visible for View, but is not visible to Binding class, which really makes the binding work.
{Binding TestList} is transformed into Binding class instance, which has no knowledge about internal members of your ViewModel class.

A: This is because Data Binding uses reflection and that in turn adhers to the visibility of items. Since data binding is implemented outside of your assembly - inside the WPF libraries - it cannot see non-public members.
Binding to a non-existing member will not issue a runtime error but rather a debug output with a message containing details about the missing member.


text:
Q: currentDevice.name and iOS 10.0 I'm working on an Obective-C app with XCode 8.0 (beta build 8S128d) and iOS 10.0 (beta build 14A5297c) and I stumbled upon a weird issue.
Whenever I call [[UIDevice currentDevice] name], the app crashes, the process stops in XCode, and the only log I get in the console is
[access] <private>
It doesn't work either when using an ipa compiled with XCode 7, so I guess the problem comes from iOS 10.
Did anyone else get the same behavior? Is there any solution?
Thanks!


text:
Q: Help me real analysis I have to study character of this serie
$\sum_{n=3}^{\infty} (\log(n+1)-\log(n-1))$.
I know that it diverges but I don't know how I have to show it

A: The behavior of the series is determined by the growth of the partial sums. In this case you have a telescoping series, which means that due to a large amount of cancellation the partial sums have a particularly simple expression. The partial sum up to $n$ gives
$$
(\log 4-\log 2)+(\log 5-\log 3)+(\log 6-\log 4)+\cdots +(\log (n+1)-\log (n-1)).
$$
Note the $\log 4$ cancels with the $\log 4$ coming two terms later, and similarly for $\log 5, \ldots,\log (n-1)$. Consequently the partial sum equals
$$
\log(n+1)+\log n-\log 2-\log 3.
$$
As $n\to\infty$ this grows logarithmically, so the series diverges at a relatively slow rate (comparable to the harmonic series $\sum\frac{1}{n}$).

A: $$\sum_{n=3}^{\infty} (\log(n+1)-\log(n-1)) = \sum_{n=3}^{\infty} \log{\frac{n+1}{n-1}} = \sum_{n=3}^{\infty} \log{\left(1+\frac{2}{n-1}\right)}$$
And remember that $\frac{\ln(1+x)}{x}\rightarrow 1 $ for small $x$

A: $$\sum_{n=3}^\infty (\log(n+1)-\log(n-1)) = \lim_{N \to \infty} \sum_{n=3}^N (\log(n+1)-\log(n-1)) = \lim_{N \to \infty} {({\sum_{k=4}^{N+1}\log k - \sum_{l=2}^{N-1} \log l})}$$
Can you complete the proof now?


text:
Q: Recursively expanding struct definition? How can expand a structure definition to show nested types?  For example, I would like to expand this
type Foo struct {
  x int
  y []string
  z Bar
}
type Bar struct {
  a int
  b string
}

to something like this:
type Foo struct {
  x int
  y []string
  z Bar
    struct {
      a int
      b string
    }
}

context: reverse engineering existing code.

A: You can try something along these lines to list all fields defined in a struct, recursively listing structs found in the way.
It does not produce exactly the output you asked for but it's pretty close and can probably be adapted to do so.
package main

import (
    "reflect"
    "fmt"
)

type Foo struct {
  x int
  y []string
  z Bar
}
type Bar struct {
  a int
  b string
}

func printFields(prefix string, t reflect.Type) {
    for i := 0; i < t.NumField(); i++ {
        f := t.Field(i)
        fmt.Printf("%v%v %v\n", prefix, f.Name, f.Type)
        if f.Type.Kind() == reflect.Struct {
            printFields(fmt.Sprintf("  %v", prefix), f.Type)
        }
    }
}

func printExpandedStruct(s interface{}) {
    printFields("", reflect.ValueOf(s).Type())
}

func main() {
    printExpandedStruct(Foo{})
}

I get this output as a result of the above:
x int
y []string
z main.Bar
  a int
  b string


text:
Q: Rails, send data to a facebook app and get this data on my app I know that I need to use the data like this, in order to send data to my facebook canvas app:
FB.init({appId: '#{Facebook::APP_ID}', xfbml: true, cookie: true});
FB.ui({  method: 'apprequests', message: 'Invite Friends to Blabloo...',
           data: '{\"draw_token\":\"#{@draw.token}\",\"invitation_token\":\"#{current_kid.invitation_token}\"}',
    exclude_ids: #{@draw.get_invited_ids_for current_kid}},handle_fb_callback);

and this send a Facebook invitation, that show you my registration form inside a cavas Facebook app, now on this registration form, on my new action, I need to get this draw_token and invitation_token.
How can I get this information?
NOTE: I'm using the koala gem

A: This data field that you sent is specific for that request you send to the user.
Here are the steps to follow to work with this:

*

*When the recipient clicks the requests and redirected to your application with the request_ids parameter, you should then get the data for the requests.

*To get the requests from the user, make the call-
{user-id}/apprequests

*You will get a list of the requests and the data for each one (if any).

*The requests are accumulated and of-course cannot disappear by itself, so you need to delete the request once the user has accepted. To delete a request, make the call-
/{request-id}?method=delete
You can see this example from the developers site.


text:
Q: gwt ext helloworld application I am trying to make my HelloWorld Application in GWt Ext from this tutorial
In out HTML class we have to put this line
              <script type="text/javascript" src='com.mycompany.mypackage.HelloWorld.nocache.js'></script>

can anyone please tell me whats this line is and which path i have to mention here
right now my application is running and GWT shell is opening but there's nothing in it, I see just an empty browser

A: you should copy the adress(Development Mode in Eclipse, something like:http://127.0.0.1:8888/******.html?gwt.codesvr=127.0.0.1:9997) in the brower, have a try.


text:
Q: Making periodic network calls when iOS app is in background I'm currently working on an app that should periodically (every minute)  perform a network call while the app is backgrounded or killed. This network call will send information to our API.
Is this possible on iOS? How?

A: Assuming you want a service like a Social Media app, where it will check in the background every minute for new activity, you should use background execution.
Have a look at this Background Execution tutorial and the Apple Reference for Background Execution.


text:
Q: file input not work in joomla 2.5 component I have a simple component that must upload a file to the server, but when submit form I see this error:
Notice: Undefined index: uploaded_file in D:\wamp\www\joomla2.5\components\com_print\print.php on line 13

component is in frontend and my code is:
<?php
// no direct access
defined('_JEXEC') or die;
jimport('joomla.application.component.controller');
?>
<form enctype="multipart/form-data" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
</form>
<?php
echo $_POST['uploaded_file'];
echo $_POST['MAX_FILE_SIZE'];
?>

please help.

A: The datas for an input of type "file" are in $_FILES not $_POST
var_dump($_FILES['uploaded_file']);

A: While the answer from F.C. is technically correct, you should never directly access PHP Superglobals within Joomla. You should instead use JInput (or the depreceated JRequest) instead.
You can read more about JInput here: http://docs.joomla.org/Retrieving_request_data_using_JInput


text:
Q: Entendendo o algoritmo quick sort graficamente Tenho esse código abaixo funcionando corretamente.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void quicksort (int *vetor, int inicio, int fim) {

int i, j, meio, aux;

i = inicio;
j = fim;
meio = vetor [(inicio+fim)/2];

do {

    while (vetor [i] < meio)
        i++;

    while (vetor [j] > meio)
        j--;

    if (i<= j) {
        aux = vetor[i];
        vetor[i] = vetor[j];
        vetor[j] = aux;
        i++;
        j--;
    }
} while (i <= j);

if (inicio < j)
    quicksort(vetor, inicio, j);
if (i < fim)
    quicksort(vetor, i, fim);
}

int main()
{
int vetor[8] = {25, 57, 48, 37, 12, 92, 86, 33};
int n = 8, i;

quicksort(vetor,0,n-1);

for (i=0; i<8; i++) {
    printf("%d ", vetor[i]);
}

return 0;
}

1 - Eu determino meio do vetor e esse meio vai ser o pivô, que nas minhas contas é na posição 3, conteúdo 37.
A partir daí qual o próximo passo?


text:
Q: Apex Continuation - Response Method I am using Apex Continuation to make a callout from a VF page, but the response method is not being executed and, as a result, no response is displayed on the page. Can anyone please see why this is failing? I am re-rendering the outer output panel following the button click, which SHOULD display the {!Result}, but it doesn't seem to be executing the response method. Any help would be greatly appreciated.
Controller Extension:
   public class TakePaymentControllerExtension {

    public Opportunity theOpp {get;set;}
    public Id theOppId {get;set;}
    public Booking__c booking {get;set;}

    public String requestLabel {get;set;}
    public String result {get;set;}
    public String errorMessage {get;set;}
    //State variable for rendering output panels
    public Double finalAmount {get;set;}
    public Boolean showLoading {get;set;}
    public Boolean showError {get;set;}
    public Boolean showResults {get;set;}
    public Boolean showForm {get;set;}

    //List (and Class Name) for logging exceptions/errors
    List<Error_Log__c> logs = new List<Error_Log__c>();
    String CLASS_NAME = 'TakePaymentControllerExtension';

    public TakePaymentControllerExtension(ApexPages.StandardController cont){

        //Hide loading spinner (Default)
        showLoading = false;
        //Hide Errors (Default)
        showError = false;
        //Hide Results (Default)
        showResults = false;
        //Show the form
        showForm = true;

        //Retrieve the Opportunity
        theOppId = cont.getRecord().Id;

        //Retrieve the Opp and related booking
        theOpp = [Select Id, Name, Transaction_Authorised_Amount__c, Card_Token_Id__c, (Select Id,  Account__c, Account__r.PersonEmail From Bookings__r Order by LastModifiedDate Desc LIMIT 1) From Opportunity Where Id = :theOppId];
        if(theOpp != null){
            system.debug('theOpp: '+theOpp);
            if(theOpp.Bookings__r != null && theOpp.Bookings__r.size()>0){
                booking = theOpp.Bookings__r[0];
                system.debug('booking: '+booking);
            }else{
                //Display No Booking error
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'No Booking was found for this Opportunity ('+theOpp.Name+' ['+theOpp.Id+']). Please contact your system administrator for assistance'));
                showError = true;
                return;
            }
        }else{
            //Display No Opportunity error
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'No Opportunity record was found. Please contact your system administrator for assistance'));
            showError = true;
            return;
        }

        //Check all the required information is available
        boolean verified = verifyPaymentRequestDetails();
        if(verified != null && !verified){
            //TO DO -- Display Validation (errorMessage)
            //APEX PAGES ERROR
            showError = true;
        }

        //Default finalAmount
        finalAmount = theOpp.Transaction_Authorised_Amount__c;

    }

    //This method handles the payment request to Clubhouse
    public Object processRequest(){

        //Validation to ensure the final amount does not exceed the authorised transaction amount
        if(theOpp.Transaction_Authorised_Amount__c < finalAmount){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'The payment cannot exceed the "Transaction Authorised Amount": '+theOpp.Transaction_Authorised_Amount__c ));
            showError = true;
            showForm = true;
            return null;
        }else{

            //Hide Error, Hide Form, Show Spinner
            showError = false;
            showForm = false;
            showLoading = true;

            //Build Booking Payment Request wrapper
            system.debug('Building Payment Request Wrapper');

            ... (Built wrapper: bprw)

            try{

                // Create callout request
                Http http = new Http();
                HttpRequest request = new HttpRequest();
                request.setMethod('POST');
                request.setHeader('Content-Type', 'application/json');
                request.setEndpoint('callout:APICredentials/api/Payment');
                request.setBody(JSON.serialize(bprw));
                system.debug('Request Body: '+request.getBody());

                //Get timeout value from custom setting
                Http_Timeout__c httpTimeout = Http_Timeout__c.getInstance('Take Payment');
                Integer timeOut;
                if (null != httpTimeout){
                    //We have a value, so set the timeout
                    system.debug('*** -- Setting Take Payment timeout to ' + integer.valueOf(httpTimeout.Timeout_In_Seconds__c) + ' -- ***');
                    timeOut = integer.valueOf(httpTimeout.Timeout_In_Seconds__c);
                }else{
                    //Else it will keep the default of 20 seconds
                    timeOut = 20;
                }

                system.debug('Time Out: '+timeOut);

                // Create continuation with a timeout
                Continuation con = new Continuation(timeOut);
                // Set callback method
                con.continuationMethod='processResponse';

                // Add callout request to continuation
                requestLabel = con.addHttpRequest(request);
                system.debug('Request Label: '+requestLabel);

                // Return the continuation
                return con;

            }catch(exception e){
                //DISPLAY ERROR
                system.debug('Contination Apex Error: '+e);
                return null;
            }
        }

    }

    // Callback method
    public Object processResponse() {
        system.debug('Processing Response');
        //Hide the loading spinner
        showLoading = false;
        showResults = true;
        showForm = false;

        // Get the response by using the unique label
        HttpResponse response = Continuation.getResponse(this.requestLabel);
        // Set the result variable that is displayed on the Visualforce page
        this.result = response.getBody();
        system.debug('Response Body: '+result);

        // Return null to re-render the original Visualforce page
        return null;
    }

}

VF PAGE:
  <apex:page StandardController="Opportunity" extensions="TakePaymentControllerExtension" sidebar="false" showHeader="false" lightningStylesheets="true">
    <apex:form>
        <apex:outputPanel id="theForm">

                <apex:slds />

                    <apex:outputPanel rendered="{!showError}">

                                    <apex:messages />

                    </apex:outputPanel>

                                Take Payment - {!theOpp.Name}

                    <apex:outputPanel rendered="{!showForm}">

                                        Confirm Payment Amount

                                            <apex:inputText value="{!finalAmount}" styleClass="slds-input slds-align_absolute-center" style="width:50%;"/>

                                        Transaction Authorised Amount

                                    <apex:outputText value="{0, number, currency}" styleClass="slds-align_absolute-center">
                                        <apex:param value="{!theOpp.Transaction_Authorised_Amount__c}"/>
                                    </apex:outputText>

                                <apex:commandButton styleClass="slds-button slds-button_neutral slds-p-horizontal_large slds-size_12-of-12 slds-box " action="{!processRequest}" value="Take Payment" reRender="theForm"/>

                    </apex:outputPanel>

                        <apex:outputPanel rendered="{!showLoading}">

                        </apex:outputPanel>

                            <apex:outputPanel id="Results" rendered="{!showResults}">
                                <apex:outputText value="{!result}"/>
                                RESULTS
                            </apex:outputPanel>

        </apex:outputPanel>
    </apex:form>
</apex:page>

DEBUG LOG 1 - Initial REQUEST

42.0 APEX_CODE,DEBUG;APEX_PROFILING,NONE;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,NONE;VISUALFORCE,NONE;WAVE,NONE;WORKFLOW,ERROR
  22:53:00.0 (345875)|USER_INFO|[EXTERNAL]|005b0000004IcX6|jradcliffe@example.com|Greenwich Mean Time|GMT+01:00
  22:53:00.0 (395909)|EXECUTION_STARTED
  22:53:00.0 (403790)|CODE_UNIT_STARTED|[EXTERNAL]|0667E000000G8eK|VF: /apex/TakePaymentVF
  22:53:00.0 (15338870)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (15852265)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (16124677)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (31413522)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (31614836)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (34549099)|USER_DEBUG|[104]|DEBUG|Building Payment Request Wrapper
  22:53:00.0 (47141418)|USER_DEBUG|[139]|DEBUG|Request Body: {"PaymentMethods":[{"TokenisedCardPayment":{"Surcharge":{"Value":0.0,"CurrencyIso3Code":"GBP"},"EmailAddress":"fakeClient@example.com","ClientAccountID":"0017E00000ouXRWQA2","CardName":null},"SalesforceTrackingID":"0067E00000AHgPvQAL","Amount":{"Value":12.2,"CurrencyIso3Code":"GBP"}}],"BookingSalesforceID":"a0Y7E0000032r9aUAA","BookingGolfbreaksID":23432}
  22:53:00.0 (49119613)|USER_DEBUG|[146]|DEBUG|* -- Setting Take Payment timeout to 10 -- *
  22:53:00.0 (49178518)|USER_DEBUG|[153]|DEBUG|Time Out: 10
  22:53:00.0 (50842887)|USER_DEBUG|[162]|DEBUG|Request Label: Continuation-1
  22:53:00.0 (52163973)|USER_DEBUG|[EXTERNAL]|DEBUG|Continuation Controllers State: 1807 out of 81920 bytes used (0.02%), count 2
  22:53:00.0 (128716393)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (129105529)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (129490462)|CODE_UNIT_FINISHED|VF: /apex/TakePaymentVF
  22:53:00.0 (131184285)|EXECUTION_FINISHED

DEBUG LOG 2 - Response

42.0 APEX_CODE,DEBUG;APEX_PROFILING,NONE;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,NONE;VISUALFORCE,NONE;WAVE,NONE;WORKFLOW,ERROR
  22:53:00.0 (80384)|USER_INFO|[EXTERNAL]|005b0000004IcX6|jradcliffe@example.com|Greenwich Mean Time|GMT+01:00
  22:53:00.0 (155506)|EXECUTION_STARTED
  22:53:00.0 (162964)|CODE_UNIT_STARTED|[EXTERNAL]|0667E000000G8eK|VF: /apex/TakePaymentVF
  22:53:00.0 (5561870)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (5765586)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (5906050)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (6103491)|SYSTEM_MODE_ENTER|true
  22:53:00.0 (60845798)|CODE_UNIT_FINISHED|VF: /apex/TakePaymentVF
  22:53:00.0 (62454319)|EXECUTION_FINISHED


text:
Q: Unexpected billing on AWS EC2 I am doing some checkings in billing console and there I found a c5.xlarge instance that I can't find on EC2 console. I am searching for these instances on the correct Region that is sa-east-1 in my case and the heading of the bill is Amazon Elastic Compute Cloud running Linux/UNIX.
How can I check all EC2 related instances in a region? Thanks in advance :)

A: You can find the region on your bill detail

*

*Services > Billing

*Bills > Details > Expand All

You should also check any Volumes, Elastic ips are using in your account.
Another way is go to the ec2 directly.
Change region one by one to check if any resources are in used.


text:
Q: How a group could be attached to a screen in Java The main class has following part for FXMLLoader
public void GeomStart() {
    try {
        FXMLLoader loader = new FXMLLoader (MYGUI.class.getResource (
                "Geom.fxml"));
        AnchorPane geomPage = (AnchorPane) loader.load ();
        rootLayout.setCenter (geomPage);
        primaryStage.setScene (rootScene);
        GeomController controller = loader.getController ();
        controller.setMainApp (this);
        controller.setMyStage (primaryStage);
    } catch (IOException ex) {
        System.out.println (" Problem in loading geometry set");
        Logger.getLogger (MYGUI.class.getName ()).log (Level.SEVERE, null,
                ex);
    }
}

In the GeomController I am inheriting Scene from inherited Stage of main class to a FXMLController with:
public void setMainApp(MoncGUI badGUI) {
    this.myGUI = myGUI;
}

public void setMyStage(Stage stage) {
    this.geoStage = stage;
}

I declare another function in this controller as
private void fixSetup() {
    geoStage.setTitle("Testing");
    System.out.println("fixSetup :  Height = " + geoStage.getHeight()+"  Width = "+geoStage.getWidth());
    System.out.println("Scene Height " + geoStage.getScene().getHeight()+" Width "+geoStage.getScene().getWidth());
    newScene = geoStage.getScene();

    System.out.println("Scene Height " + geoScene.getHeight()+" Width "+geoScene.getWidth());
    final Scene geoScene = new Scene(camV, drawWidth, drawHeight, true);
    geoScene.setFill(new RadialGradient(225, 0.85, centerX, centerY,
            drawWidth, false,
            CycleMethod.NO_CYCLE, new Stop[]{new Stop(0f, Color.BLUE),
                new Stop(1f, Color.LIGHTBLUE)}));
    buildCamera(geoScene);
    Context3D context = Context3D.getInstance(camV);
    lightSetting(context);
    axis = buildAxes();
    camV.add(axis);
}

The FXMLController initiates action as
@FXML
void doShapeCyl(ActionEvent event) {
    if (initialized == 0) {
        System.out.println("Processing initialized=0");
        fixSetup();
        initialized = 1;
    }
    drawCylSolid();
}

Lastly there is one function as
void complete() {
    camV.frameCam(geoStage, geoScene);
    MouseHandler mouseHandler = new MouseHandler(geoScene, camV);
    KeyHandler keyHandler = new KeyHandler(geoStage, geoScene, camV);
    geoStage.setScene(geoScene);
    geoStage.show();
}

There may be many functions like drawCylSolid() like drawSphSolid(), drawDiscSolid(), drawTube() etc. I like to associate groups like
CameraViewer camV

to the scene and define width and height such that the job is equivalent to
final Scene geoScene = new Scene(camV, drawWidth, drawHeight, true);

while I wish to avoid "new Scene" definition as it would be local to this function only and won't be available to FXML initiated functions or function complete() at the end.


text:
Q: Segmentation fault for lambda function in non-static data member initializer I am unsure about a possible GCC bug in initialization of a std::function from a lambda function capturing this in a non-static data member initializer. Is this allowed by the C++ standard or is this UB?
Given the following code:
#include <functional>
#include <iostream>

template <typename T>
struct A {
      T x = 0;
      std::function<void(T)> f = [this](T v) { x = v; };
};

int main() {
      A<int> a;
      a.f(1);
      std::cout << a.x << "\n";
}

In my understanding, it should print 1. However, when built with GCC 5.4.0 or GCC 6.2.0, a.f(1) emits a segmentation fault, because the captured this pointer is null.
The following alternatives work as I expected:

*

*Using constructor initializer list:
template <typename T>
struct B {
    B() : f([this](T v) { x = v; }) {}
    T x = 0;
    std::function<void(T)> f;
};

*Without template:
struct C {
    int x = 0;
    std::function<void(int)> f = [this](int v) { x = v; };
};

Also, when built with Clang 3.8.0, all three versions behave as I expect, which doesn't mean it is not UB.

A: You cannot do:
template <typename T>
struct A {
    T x = 0;
    std::function<void(T)> f = [this](T v) { x = v; };
};

As this does not exist when you define f. You need to initilize f in a constructor, such as:
A(){ f = [this](T v){ x=v; } }

It worked with G++4.8.

A: Your code compiles and runs on VS2015 (windows).
So this is probably a compiler error.
Also, if you will remove the template it works on http://cpp.sh/
Try this code:
#include <functional>
#include <iostream>

struct A {
      int x = 0;
      std::function<void(int)> f = [this](int v) { x = v; };
};

int main() {
      A  a;
      a.f(1);
      std::cout << a.x << "\n";
}

running original code on  cpp.sh gives:
 internal compiler error: in tsubst_copy, at cp/pt.c:12569
Please submit a full bug report

So I guess it's a bug


text:
Q: How can I inject ServletContext in Spring unit test? I need to write a jUnit test for a rather complex application which runs in a Tomcat.
I wrote a class which builds up my Spring context.
private static ApplicationContext
springContext = null;

springContext = new ClassPathXmlApplicationContext(
                     new String[] {"beans"....});

In the application there is a call:
public class myClass implements ServletContextAware {

.... final String folder = **servletContext.getRealPath**("/example"); ...
}

which breaks everything, because the ServletContext is null.
I have started to build a mock object:
static ServletConfig servletConfigMock = createMock(ServletConfig.class);
static ServletContext servletContextMock = createMock(ServletContext.class);

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        expect(servletConfigMock.getServletContext())
                 .andReturn(servletContextMock).anyTimes();

        expect(servletContextMock.getRealPath("/example"))
                 .andReturn("...fulllpath").anyTimes();
        replay(servletConfigMock);
        replay(servletContextMock);
    }

Is there a simple method to inject the ServletContext or to start the Tomcat with a deployment descriptor at the runtime of the jUnit test?
I am using: Spring, Maven, Tomcat 6 and EasyMock for the mock objects.

A: What you actually want is to test the web-layer.
There are a couple of ways to do it:

*

*use MockServletContext provided by spring. This is the best way - check the linked documentation for how to do it.

*use ServletUnit from HtmlUnit

*use the cactus framework

*use selenium to test the web layer functionally

*make a runtime mock as you did

And whenever you want to inject something in a test, use ReflectionTestUtils
The complication comes from the fact that the web-layer is not quite suitable for unit-testing. It is more a subject of functional testing.
If there are methods that seem suitable for unit-testing, they perhaps belong to the service layer. And they should not have a dependency on the ServletContext


text:
Q: How do I Integrate the Firebase cocoaPods in my custom swift framework? I want to build a iOS swift framework (ex. XYZ) which for users to login firebase with customized access token.
I finished my login method and get the access token in XYZ. Now I want to Integrate the Firebase in XYZ to pass the access token to Firebase.
So I install Firebase in XYZ with cocoaPods. and write the code and build a XYZ framework. Everything seems fine.
Than I create a swift project ABC, and import XYZ framework. Then I got error "Missing required module 'Firebase' " at the line I import XYZ.
If I also install Firebase in ABC with cocoaPods. It will run successfully but get many errors about "Class FirebaseXXX is implemented in both ABC and XYZ. One of the two will be used. Which one is undefined." And Crash soon.
Would Someone please help me to figure it out how to fix this problem?

A: Have you tried a podfile like:
platform :ios, '9.0'

target 'ABC' do
  use_frameworks!
  workspace 'ABC'
  project 'ABC'

  pod 'Firebase'
  # ...
end

target 'XYZ' do
    use_frameworks!
    workspace 'ABC'
    project 'XYZ'

    # pods for the framework
    pod 'Firebase'
    # ...
end

?


text:
Q: Bash script to execute a binary file for a time I have two binary files that I want to execute one after the other, the thing is that I want to execute both for one minute. I have the following bash code:
./file_1
./file_2

but I do not know how to only run it for a minute.

A: Here's a portable solution - run the binaries in the background, and kill them after a minute:
for file in "file_1" "file_2"; do
    "./$file" &
    file_pid=$!

    sleep 60

    kill "$file_pid"
done

The & operator starts a background job, and the special variable $! contains the PID of the last job. The loop is optional. We can use it to reduce duplicated code.

A: This is a one-liner using the timeout command
$ timeout 60 binary-1; timeout 60 binary-2

In this case, the format is:
timeout duration command

Where duration defaults to seconds, or also could be used 1m (1 minutes), from the man:
duration is a floating point number followed by an optional unit:

's' for seconds (the default)
'm' for minutes
'h' for hours
'd' for days


text:
Q: Getting length of video I am having trouble finding a simple example of how to get the video length of a file programmatically. Many people say, oh use this library/wrapper or whatever, but do not say how. I have downloaded ffmpeg, but have no clue how to actually use it and there does not seem to be any example of how to use it to get the video duration. I see how you can use it to convert videos, but I simply just want to know the duration of a video. All of the other information does not matter.
Is there any way of doing this simply, whether it be in C#, python, java, whatever, that will just return a string that indicates the length of a video file.
Please provide examples if possible. Thanks in advance!
Assume standard file formats, such as wmv, avi, mp4, mpeg. Stuff that has metadata.

A: The easist and flawless solution I found is to use MediaToolkit nuget package.
using MediaToolkit;

// a method to get Width, Height, and Duration in Ticks for video.
public static Tuple<int, int, long> GetVideoInfo(string fileName)
{
    var inputFile = new MediaToolkit.Model.MediaFile { Filename = fileName };
    using (var engine = new Engine())
    {
        engine.GetMetadata(inputFile);
    }

    // FrameSize is returned as '1280x768' string.
    var size = inputFile.Metadata.VideoData.FrameSize.Split(new[] { 'x' }).Select(o => int.Parse(o)).ToArray();

    return new Tuple<int, int, long>(size[0], size[1], inputFile.Metadata.Duration.Ticks);
}

A: The open-source tool MediaInfo provides comprehensive meta-data for media files and can be used easily from your own application in DLL form:
void* Hande=MediaInfo::OpenQuick("**FILENAME**", "**VERSION**;**APP_NAME**;**APP_VERSION**")
MediaInfo::Inform()

A: I have tried to get the video length in a bit different way :
Actually using Windows Media Player Component also, we can get the duration of the video.
Following code snippet may help you guys :
using WMPLib;
// ...
var player = new WindowsMediaPlayer();
var clip = player.newMedia(filePath);
Console.WriteLine(TimeSpan.FromSeconds(clip.duration));

and don't forget to add the reference of wmp.dll which will be
  present in System32 folder.

A: Here is an example:
using DirectShowLib;
using DirectShowLib.DES;
using System.Runtime.InteropServices;

...

var mediaDet = (IMediaDet)new MediaDet();
DsError.ThrowExceptionForHR(mediaDet.put_Filename(FileName));

// find the video stream in the file
int index;
var type = Guid.Empty;
for (index = 0; index < 1000 && type != MediaType.Video; index++)
{
    mediaDet.put_CurrentStream(index);
    mediaDet.get_StreamType(out type);
}

// retrieve some measurements from the video
double frameRate;
mediaDet.get_FrameRate(out frameRate);

var mediaType = new AMMediaType();
mediaDet.get_StreamMediaType(mediaType);
var videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));
DsUtils.FreeAMMediaType(mediaType);
var width = videoInfo.BmiHeader.Width;
var height = videoInfo.BmiHeader.Height;

double mediaLength;
mediaDet.get_StreamLength(out mediaLength);
var frameCount = (int)(frameRate * mediaLength);
var duration = frameCount / frameRate;

A: you can get all sorts of information about many types of video formats including their duration with ffmpeg by using the -i flag:
ffmpeg -i videofile.whatever

If you want a nice library that can wrap ffmpef for you in C# then you can use MediaHandlerPro

A: ffprobe is companian tool from the ffmpeg project. Besides provinding information from a wide range of file formats, it can also ouput in a JSON format to ease the parsing.
Check this answer for an example of a JSON output.

A: I recently found a solution to a similar problem I had, with ColdFusion and FFMpeg's little cousin, FFProbe...
Is there a way to obtain the duration of a video file using ColdFusion?
FFProbe has a show_streams argument that pushes out a considerable amount of information in the initial stream within the returned output; including the width, height and duration of a video...
Not sure about C#'s syntax for running the equivalent of "ffprobe.exe -show_streams testFile" but I'm sure once you've figured that out, you can parse out the information you need from the output you receive.

A: You can use Emgu.CV to get a lot of video data if using a VideoCapture object:
using Emgu.CV;
using (var video = new VideoCapture(path))
{
   double fc = (int)Math.Floor(video.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.FrameCount));
   // frame count
   double fps = video.GetCaptureProperty(Emgu.CV.CvEnum.CapProp.Fps);
   // fps
   double length = fc / fps;
   // length in seconds
}

Responding here because I stumbled across this post looking for the same thing - adding it just in case it helps anyone.

A: Namaskaram,
One of the simplest ways is to use OpenCvSharp. It is allowed for commercial usage as well.
using OpenCvSharp;

void GetVideoDuration()
{
   VideoCapture vidCapture = new VideoCapture(videoClipPath);

   var totalFrameCount = vidCapture.Get(VideoCaptureProperties.FrameCount);

   var framesPerSecond = vidCapture.Get(VideoCaptureProperties.Fps);

   var videoDurationInSeconds = totalFrameCount/framesPerSecond ;
}


text:
Q: LiveCharts: Show chart title in windows form I want to show Title of the chart using LiveCharts in Windows Forms.
I am unable to find Title property on the chart control, I have also gone through the documentation and found WPF related example only. So, I tried setting Text property of the chart itself but could not find it working.
Any idea, how can I set chart title?


text:
Q: How to Compare two Arrays are Equal using Javascript? I want position of the array is to be also same and value also same.
var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

I tried like this
var array3 = array1 === array2   // returns false

A: You could try this simple approach

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

console.log(array1.join('|'));
console.log(array2.join('|'));

if (array1.join('|') === array2.join('|')) {
 console.log('The arrays are equal.');
} else {
 console.log('The arrays are NOT equal.');
}

array1 = [[1,2],[3,4],[5,6],[7,8]];
array2 = [[1,2],[3,4],[5,6],[7,8]];

console.log(array1.join('|'));
console.log(array2.join('|'));

if (array1.join('|') === array2.join('|')) {
 console.log('The arrays are equal.');
} else {
 console.log('The arrays are NOT equal.');
}

If the position of the values are not important you could sort the arrays first.
if (array1.sort().join('|') === array2.sort().join('|')) {
    console.log('The arrays are equal.');
} else {
    console.log('The arrays are NOT equal.');
}

A: A less robust approach, but it works.
a = [2, 4, 5].toString();
b = [2, 4, 5].toString();

console.log(a===b);

A: If you comparing 2 arrays but values not in same index, then try this
var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)

A: Use lodash.
In ES6 syntax:
import isEqual from 'lodash/isEqual';
let equal = isEqual([1,2], [1,2]);  // true

Or previous js versions:
var isEqual = require('lodash/isEqual');
var equal = isEqual([1,2], [1,2]);  // true

A: You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)
var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index];
});

THE WORKING DEMO.

A: var array3 = array1 === array2

That will compare whether array1 and array2 are the same array object in memory, which is not what you want.
In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.
Assuming your array is filled with primitives—numbers and or strings—something like this should do
function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true;
}

A: A more modern version:
function arraysEqual(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every((el, ix) => el === b[ix]);
}

Coercing non-array arguments to empty arrays stops a.every() from exploding.
If you just want to see if the arrays have the same set of elements then you can use Array.includes():
function arraysContainSame(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every(el => b.includes(el));
}

A: Here goes the code. Which is able to compare arrays by any position.
var array1 = [4,8,10,9];

var array2 = [10,8,9,4];

var is_same = array1.length == array2.length && array1.every(function(element, index) {
    //return element === array2[index];
  if(array2.indexOf(element)>-1){
    return element = array2[array2.indexOf(element)];
  }
});
console.log(is_same);

A: function isEqual(a) {
if (arrayData.length > 0) {
    for (var i in arrayData) {
        if (JSON.stringify(arrayData[i]) === JSON.stringify(a)) {
            alert("Ya existe un registro con esta informacion");
            return false;
        }
    }
}
}

A: Try doing like this:    array1.compare(array2)=true
Array.prototype.compare = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].compare(array[i]))
                return false;
        }
        else if (this[i] != array[i]) {
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;
        }
    }
    return true;
}


text:
Q: Atmega328p FT232RL invalid device identifier I have this little guy

and I want to read it's code, edit it and rewrite

This guy fortunately ready and as far as I found out equipped with
Atmega328p

and FT232RL

I have: Centos 8, Arduino IDE, avrdude 6.3-20171130 (compiled today)
I did
avrdude -p m328p -P ft0 -c uncompatino -vvv -U flash:w:flash.hex with different -c (ft232r, arduino-ft232r, diecimila, uncompatino) and -P (ft0, ttyUSB0) all gave the same result
avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/opt/avrdude/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : ft0
         Using Programmer              : uncompatino
avrdude: <unknown>: Pin is ok.
avrdude: VCC: Pin is ok.
avrdude: BUFF: Pin is ok.
avrdude: RESET: Pin is ok.
avrdude: SCK: Pin is ok.
avrdude: MOSI: Pin is ok.
avrdude: MISO: Pin is ok.
avrdude: ERRLED: Pin is ok.
avrdude: RDYLED: Pin is ok.
avrdude: PGMLED: Pin is ok.
avrdude: VFYLED: Pin is ok.
avrdude: ft245r_open(): invalid device identifier '        '

avrdude done.  Thank you.

Also tried to add some stuff to my avrdude.conf that I got from the internet
programmer
  id    = "APU-2";
  desc  = "FT232RL with 74hc125";
  type  = "ftdi_syncbb";
  connection_type = usb;
  miso  = 4;  # выв. 2 ft232rl
  sck   = 2;  # выв. 3 ft232rl
  mosi  = 6;  # выв. 10 ft232rl
  reset = 5;  # выв. 9 ft232rl
  buff  = ~3; # выв. 11 ft232rl
;

$ dmesg | tail
[ 2909.002278] ata4.00: configured for UDMA/133
[ 6750.283200] usb 1-13: new full-speed USB device number 5 using xhci_hcd
[ 6750.415079] usb 1-13: New USB device found, idVendor=0403, idProduct=6001, bcdDevice= 6.00
[ 6750.415080] usb 1-13: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 6750.415080] usb 1-13: Product: FT232R USB UART
[ 6750.415081] usb 1-13: Manufacturer: FTDI
[ 6750.415081] usb 1-13: SerialNumber: ********
[ 6750.418234] ftdi_sio 1-13:1.0: FTDI USB Serial Device converter detected
[ 6750.418253] usb 1-13: Detected FT232RL
[ 6750.418479] usb 1-13: FTDI USB Serial Device converter now attached to ttyUSB0

EDIT 1:
Fixed -P to usb:<SerialNumber> or usb:ft0 and now I get this:
avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/opt/avrdude/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb:ft0
         Using Programmer              : ft232r
avrdude: <unknown>: Pin is ok.
avrdude: VCC: Pin is ok.
avrdude: BUFF: Pin is ok.
avrdude: RESET: Pin is ok.
avrdude: SCK: Pin is ok.
avrdude: MOSI: Pin is ok.
avrdude: MISO: Pin is ok.
avrdude: ERRLED: Pin is ok.
avrdude: RDYLED: Pin is ok.
avrdude: PGMLED: Pin is ok.
avrdude: VFYLED: Pin is ok.
avrdude: ft245r_open(): device number parsed as: 0
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : ftdi_syncbb
         Description     : FT232R Synchronous BitBang
         Pin assignment  : 0..7 = DBUS0..7
           VCC     =  (not used)
           BUFF    =  (not used)
           RESET   =  4
           SCK     =  0
           MOSI    =  2
           MISO    =  1
           ERR LED =  (not used)
           RDY LED =  (not used)
           PGM LED =  (not used)
           VFY LED =  (not used)

avrdude: Device is not responding to program enable. Check connection.
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

What am I missing?


text:
Q: encrypting a file during upload or after upload I have a .net web application, using C#, which will allow users to upload a file, we need to encrypt that file to be more secure, rather than leaving the file as is on the server, so will also need a way to decrypt the file so users can view it from the web application.  can someone recommend a way to do this?  The files types may vary, but for now they only want .pdf files to by uploaded, if that matters.
Thank you.

A: Follow the following steps:

*

*Use AES encryption

*Generate and store AES keys and IVs as varbinary in the database

*Encrypt the file stream that comes when someone uploads a file

*Add a general handler *.ashx and, in it, query the database to get the AES keys and IVs

*Write to the response stream the decrypted bytes


text:
Q: Styles not working after gulp watch task because of mime-type text/html I have a gulp watch task, which compiles and concats all scss files to one css file. In my index I link the css file like this:
<link rel="stylesheet" type="text/css" href="./css/styles.css">

This is my gulp watch task:
gulp.task('watch', ['browserSync', 'sass'], function () {
    gulp.watch('app/scss/**/*.scss', ['sass']);
    // Reloads the browser whenever HTML or JS files change
    gulp.watch('app/*.html', browserSync.reload);
    gulp.watch('app/js/**/*.js', browserSync.reload);
});

And this is my gulp file with the sass task:
gulp.task('sass', function () {
    return gulp.src('app/scss/**/*.scss') // Gets all files ending with .scss in app/scss
        .pipe(sass())
        .pipe(concat('styles.css'))
        .pipe(gulp.dest('app/css/'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

After I start the gulp watch task, my browser opens my site but the style is wrong. I got this error: Refused to apply style from 'http://localhost:3000/css/styles.css/' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Here's the whole gulpfile.js:
//My Gulpfile
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var dev = require('gulp-dev');

gulp.task('sass', function () {
return gulp.src('app/scss/**/*.scss') // Gets all files ending with .scss in
app/scss
    .pipe(sass())
    .pipe(concat('styles.css'))
    .pipe(gulp.dest('app/css/'))
    .pipe(browserSync.reload({
        stream: true
    }))
});

gulp.task('watch', ['browserSync', 'sass'], function () {
gulp.watch('app/**/*.scss', ['sass']);
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', browserSync.reload);
});

gulp.task('browserSync', function () {
browserSync.init({
    server: {
        baseDir: 'app'
    },
   })
 });

 gulp.task('dev', function() {
  gulp.src('index.html')
    .pipe(dev(true))
    .pipe(gulp.dest('index.html'));
 });

I don't know why this happens, I'm using the type="text/css" attribute in my link like described in this solution: "The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"
After starting the gulp watch task I have to make a change in one of my scss files and than the whole style is correct? Any ideas what I'm doint wrong?

A: You need to use this:
<link rel="stylesheet" type="text/css" href="./app/css/styles.css">

I change href="./css/styles.css" to href="./app/css/styles.css". You can also change type="text/css" to type="text/html" - however this solution in low satisfyable
UPDATE
In your gulp-file you have line
.pipe(gulp.dest('app/css/'))

This mean that processed files are stored in ./app/css directory, so probably your webserwer dont see it (maybe this files must by stored do different directory like ./public/css - it depends of your project.


text:
Q: Is there a way to change the skills so that right mouse is not always secondary
Possible Duplicate:
Marked For Death - Can you assign them as 1-2-3-4 keyboard skill?

In diablo iii I saw a build where people are using offensive or defensive skills on 2 numbers.
Sample is
http://us.battle.net/d3/en/calculator/wizard#aYk

A: Yes!
Go into the options menu and then the Gameplay tab and there is an option called Elective Mode.
This coupled with Advanced Tooltips will improve your play experience.
While elective mode is on, you can drag and drop spells on your hotbar, or you can even select more than one of any category of spell by using the left and right arrows in the spell select screen.
For example, I can use all 3 focus spells, by having the focus spells take up the defensive and secondary slots as well if I like.