text:
Q: Cyrillic text is not displayed under \paragraph (with KOMA-Script) I'v got problems with KOMA-Script and cyrillic (I guess).
Commands \paragraph (as well as \section, \subsection, etc.) don't display russian text. Is this a known issue?
I am using SublimeText, LatexTools, MikTeX and Sumatra
\documentclass[fontsize=5,parskip=never]{scrartcl}

\usepackage[paper=a5paper,landscape, left=1mm, top=4mm]{geometry}

\usepackage{multicol}

\usepackage{setspace}
\singlespacing% одинарный интервал

\usepackage{enumitem}
\setlist{nosep} % or \setlist{noitemsep} to leave space around whole list

\usepackage{fontspec}
\setmainfont{Arial}

\usepackage{cmap}                   % поиск в PDF
\usepackage[T2A]{fontenc}           % кодировка
\usepackage[utf8]{inputenc}         % кодировка исходного текста
\usepackage[russian]{babel} % локализация и переносы
%\usepackage{fontspec}              % otf шрифты
\usepackage{textpos}                % текстовые блоки
%\usepackage[export]{adjustpage}        % положение картинок
\usepackage{xcolor}                 % цвет

\begin{document}

\begin{multicols*}{5}

\Large \textbf{Flush Shutter DC} \normalsize

\large \textbf{Электробезопасность} \normalsize     %% I SEE THIS (TEXTBF WORKS WELL)
\paragraph{ПАРАГРАФ}                                %% I DONT SEE THIS
\paragraph{PARAGRAPH}                               %% I SEE THIS

text

\end{multicols*}
\end{document}

A: The document is using latin modern bold sans serif for titles and that font does not have Cyrillic.
The log warns
Missing character: There is no П in font [lmsans10-bold]:+tlig;!

You could select a different font using the classes heading setup features or generally avoid the problem with the egregdoesnotlikesansseriftitles option.
In this case you still get sans titles as you have specified Arial as the main document font.

\documentclass[
  fontsize=5,
  parskip=never,
  egregdoesnotlikesansseriftitles
]{scrartcl}

\usepackage[paper=a5paper,landscape, left=1mm, top=4mm]{geometry}

\usepackage{multicol}

\usepackage{setspace}
\singlespacing% одинарный интервал

\usepackage{enumitem}
\setlist{nosep} % or \setlist{noitemsep} to leave space around whole list

\usepackage[russian]{babel} % локализация и переносы
\usepackage{fontspec}
\setmainfont{Arial}

%\usepackage{fontspec}              % otf шрифты
\usepackage{textpos}                % текстовые блоки
%\usepackage[export]{adjustpage}        % положение картинок
\usepackage{xcolor}                 % цвет

\begin{document}

\begin{multicols*}{5}

\subsection*{Flush Shutter DC}

\subsection*{Электробезопасность}    %% I SEE THIS (TEXTBF WORKS WELL)
\paragraph{ПАРАГРАФ}                                %% I DONT SEE THIS
\paragraph{PARAGRAPH}                               %% I SEE THIS

text

\end{multicols*}
\end{document}

A: You are just forgetting to set the sans serif font:
\documentclass{scrartcl}

\usepackage{fontspec}
\usepackage[russian]{babel} % локализация и переносы

% settings
\setmainfont{Arial}
\setsansfont{Arial}

\begin{document}

\textbf{Flush Shutter DC}

\textbf{Электробезопасность}

\paragraph{ПАРАГРАФ}

\paragraph{PARAGRAPH}

text

\end{document}


text:
Q: Dropdownlist changing the selected value when control is out of focus I have several comboboxes with the same properties.
Dropdownstyle : Dropdownlist
AutoCompleteMode: SuggestAppend
AutoCompleteSource: ListItems

For example, I have a dropdownlist cboxStates that has 50 states of United States of America in Items Collection entered manually. When I type in WI, it is highlighted among WA,WV,WI,WY but if I tab over/press enter/mouse click on another control, WA is selected instead of WI which is highlighted. This is total random and it happens to comboboxes that are binded dynamically. And also, they do not have any events.

A: This seems to be an issue that has been submitted to Connect. There's a workaround there which extends the default ComboBox control and fixes the issue. The extended ComboBox code is horribly formatted on the Connect site, so here's the nicer version :)
public class BetterComboBox : ComboBox
{
    private int _windows7CorrectedSelectedIndex = -1;
    private int? _selectedIndexWhenDroppedDown = null;

    protected override void OnDropDown(EventArgs e)
    {
        _selectedIndexWhenDroppedDown = SelectedIndex;
        base.OnDropDown(e);
    }

    private bool _onDropDownClosedProcessing = false;

    protected override void OnDropDownClosed(EventArgs e)
    {
        if (_selectedIndexWhenDroppedDown != null && _selectedIndexWhenDroppedDown != SelectedIndex)
        {
            try
            {
                _onDropDownClosedProcessing = true;
                OnSelectionChangeCommitted(e);
            }
            finally
            {
                _onDropDownClosedProcessing = false;
            }
        }
        base.OnDropDownClosed(e);
        if (SelectedIndex != _windows7CorrectedSelectedIndex)
        {
            SelectedIndex = _windows7CorrectedSelectedIndex;
            OnSelectionChangeCommitted(e);
        }
    }

    protected override void OnSelectionChangeCommitted(EventArgs e)
    {
        if (!_onDropDownClosedProcessing)
            _windows7CorrectedSelectedIndex = SelectedIndex;
        _selectedIndexWhenDroppedDown = null;
        base.OnSelectionChangeCommitted(e);
    }

    protected override void OnSelectedIndexChanged(EventArgs e)
    {
        bool alreadyMatched = true;
        if (_windows7CorrectedSelectedIndex != SelectedIndex)
        {
            _windows7CorrectedSelectedIndex = SelectedIndex;
            alreadyMatched = false;
        }
        base.OnSelectedIndexChanged(e);

        //when not dropped down, the SelectionChangeCommitted event does not fire upon non-arrow keystrokes due (I suppose) to AutoComplete behavior
        //this is not acceptable for my needs, and so I have come up with the best way to determine when to raise the event, without causing duplication of the event (alreadyMatched)
        //and without causing the event to fire when programmatic changes cause SelectedIndexChanged to be raised (_processingKeyEventArgs implies user-caused)
        if (!DroppedDown && !alreadyMatched && _processingKeyEventArgs)
            OnSelectionChangeCommitted(e);
    }

    private bool _processingKeyEventArgs = false;

    protected override bool ProcessKeyEventArgs(ref Message m)
    {
        try
        {
            _processingKeyEventArgs = true;
            return base.ProcessKeyEventArgs(ref m);
        }
        finally
        {
            _processingKeyEventArgs = false;
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript "for of" value transformations do not persist in the following code snippet, a "for of" iterates over an array and adds 1 to each element in the array.
Why doesn't that transformation persist? When the second "for of" iterates over the same array, none of the elements reflect the transformation performed in the first "for of"
Thank you

let iterable = [10, 20, 30];

for (let value of iterable) {
  value += 1;
  console.log(value);
}

for (let val of iterable) {
  console.log(val);
}

A: Because you just get the copy of the value and change that copy - the actual item is not changed. If you have an array of primitive types, you need access via the index and update according to that index.
In the for of loop you can get the index and value via entries function, destruct them in the loop for more comfort, change the value and again assign it to the index-th item of the array.

let iterable = [10, 20, 30];

for (let [index, value] of iterable.entries()) {
  value += 1;
  iterable[index] = value;
}

for (let val of iterable) {
  console.log(val);
}

A: for of copies the value to the variable specified.  You then change that variable.
If you were dealing with an object, then the variable and original array would both hold a value that was a reference to the object.
… but you are not. Numbers are primitives and primitives are immutable.
You could use for in to get the property name and then change what the array holds for that property:
for (let index in iterable) {
    iterable[index] += 1
}

You could use a map to create a new array with different values:
iterable = iterable.map(value => value + 1);

A: The for of is only initializing the variable value with an element from that array, in this case with a number which is primitive and primitive are immutable.
So, what you really did was increment that variable value and nothing else.
This is what you need to do to get it work:

let iterable = [10, 20, 30];

for(let [index] of Object.entries(iterable)) iterable[index]++;
//      ^
//      |
//      +--- The function Object.entries returns an
//           two indexes array, ie [0, 10], [1, 20]
//           and so on.  This is called destructuring
//           assignment.

for (let val of iterable) console.log(val);

Or, using a for-loop:

let iterable = [10, 20, 30];

for(var index = 0; index < iterable.length; index++) iterable[index]++;

for (let val of iterable) console.log(val);


text:
Q: Difference between MKCoordinateRegion vs region.span.latitudeDelta? I have been learning a piece of code, and trying to understand the difference between MKCoordinateRegion vs region.span.latitudeDelta?
MKCoordinateRegion region = {{0.0, 0.0}, {0.0, 0.0}};
region.center.latitude = latitude;
region.center.longitude = longitude;
region.span.latitudeDelta = 0.1f;

Can someone please explain what the differences are based on the above. I feel like the first line decided the frame of the map but the rest seemed to repeat this (I defining the frame and position on map)

A: The region is a MKCoordinateRegion. So the first line initializes a local variable with the structure (using the old C89 convention):
MKCoordinateRegion region = {{0.0, 0.0}, {0.0, 0.0}};

and the subsequent lines just update that previously initialized structure with the desired values:
region.center.latitude = latitude;
region.center.longitude = longitude;
region.span.latitudeDelta = 0.1f;

For what it is worth, you could alternatively just instantiate it and set the values all in one step (again, using the C89 convention):
MKCoordinateRegion region = { { latitude, longitude }, { 0.1, 0.1 } };

Or, nowadays, one might use the C99 convention of designated initializers:
MKCoordinateRegion region = {
    .center = { .latitude = latitude, .longitude = longitude },
    .span = { .latitudeDelta = 0.1, .longitudeDelta = 0.1 }
};

Again, this initializes and populates the MKCoordinateRegion in one step (and in this case, in a less cryptic manner than the C89 pattern).
The alternative is to build CLLocationCoordinate2D, MKCoordinateSpan, and MKCoordinateRegion using the various xxxMake functions:
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(latitude, longitude);
MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1);
MKCoordinateRegion region = MKCoordinateRegionMake(center, span);

For more information about initializing C structs, I would refer you to How to initialize a struct in accordance with C programming language standards. Also, the GCC documentation talks about designated initializers, including structs.

Or, if you are trying to set a map view's region, another approach is to use MKMapCamera instead:
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(latitude, longitude);
MKMapCamera *camera = [MKMapCamera cameraLookingAtCenterCoordinate:center fromDistance:1000 pitch:0 heading:0];
[self.mapView setCamera:camera animated:true];

But, bottom line, the region is effectively the range of latitude and longitude coordinates that the map will show (as defined by the combination of the center, where the map is looking, and the span, how much of the map is visible).
All of these map coordinates and spans should not be confused with the frame of the map view, which is the visual size of the map view that will show that region.


text:
Q: WCF 4 Routing service wif Does anybody know would be the configuration of the routing service for one scenario like the one described here http://zamd.net/2011/02/08/silverlight-claim-based-security/?
Regards

A: My answer is not complete since I have not fully tested yet. However the following link seems interesting : WCF4 routing with WIF
Also this


text:
Q: regex for specific phone number arrangement i'm currently using this regex
"/^([0-9\(\)\/\+ \-]*)$/",
which is fine,but the problem is i am also using a masking script,
which produces this line automatically,
(___) ___-____

and it messes up my validation, what regex code can allow me to verify only this type of input from the use
(999) 999-9999

and also not accept a "blank" input field from user when entered. any length is fine, as long as it only accepts this inputs that i mentioned above.

A: This should work:
^\(\d{3}\)\s{0,1}\d{3}-\d{3}$
Breaking this regexp:
\(\d{3}\) matches only three numbers between brackets.
\s{0,1} matches only 0 or 1 space.
\d{3}-\d{3} matches only three numbers followed by '-' and then three other numbers.

A: Formatting and validation are two very different things. If you try to mix them, you will fail.
That being said, before performing validation you should strip all formatting characters from your string, then validate the content.
// remove everything that isn't a digit
var strippedNumber = value.replace(/\D/g, '');

if (strippedNumber.length === 10) {
    // valid phone number
}

A: First, when asking about regular expressions, you should always say which language or tool you are using because that affects what features are available and which characters need to be quoted with backslash.  I'll assume you're asking about JavaScript based on your question's tags.
You say any length is fine.  I shall take that to mean that each sequence of consecutive digits can contain any number of digits from one to infinity.  I shall assume there's exactly one space and exactly one dash.  On that basis, your RE is:
/^\(\d+\) \d+-\d+$/

If, as is more likely, you want to limit the lengths of the digit sequences, you would say something like:
/^\(\d{3,4}\) \d{3}-\d{1,10}$/

(three or four digits, exactly three digits, one to ten digits).
I have omitted any capturing parentheses (...) , which are a bit redundant if you're capturing the whole string ^(....)$ .
Here's a concise summary of JavaScript regex syntax:
http://www.regextester.com/jssyntax.html


text:
Q: How to check a particular value on basis of condition in karate Goal: Match the check value is correct for 123S and 123O response in API
First check the value on this location x.details[0].user.school.name[0].codeable.text if it is 123S then check if x.details[0].data.check value is abc
Then check if the value on this location x.details[1].user.school.name[0].codeable.text is 123O then check if x.details[1].data.check is xyz
The response in array inter changes it is not mandatory first element is 123S sometime API returns 123O as first array response.
Sample JSON.
{
    "type": "1",
    "array": 2,
    "details": [
        {
            "path": "path",
            "user": {
                "school": {
                    "name": [
                        {
                            "value": "this is school",
                            "codeable": {
                                "details": [
                                    {
                                        "hello": "yty",
                                        "condition": "check1"
                                    }
                                ],
                                "text": "123S"
                            }
                        }
                    ]
                },
                "sample": "test1",
                "id": "22222"
            },
            "data": {
                "check": "abc"
            }
        },
        {
            "path": "path",
            "user": {
                "school": {
                    "name": [
                        {
                            "value": "this is school",
                            "codeable": {
                                "details": [
                                    {
                                        "hello": "def",
                                        "condition": "check2"
                                    }
                                ],
                                "text": "123O"
                            }
                        }
                    ]
                },
                "sample": "test",
                "id": "11111"
            },
            "data": {
                "check": "xyz"
            }
        }
    ]
}

How I did in Postman but how to replicate same in Karate?
var jsonData = pm.response.json();

pm.test("Body matches string", function () {
    for(var i=0;i<jsonData.details.length;i++){
        if(jsonData.details[i].user.school.name[0].codeable.text == '123S')
        {
            pm.expect(jsonData.details[i].data.check).to.equal('abc');
        }
        if(jsonData.details[i].user.school.name[0].codeable.text == '123O')
        {
            pm.expect(jsonData.details[i].data.check).to.equal('xyz');
        }
    }
});

A: 2 lines. And this takes care of any number of combinations of lookup values :)
* def lookup = { '123S': 'abc', '123O': 'xyz' }
* match each response.details contains { data: { check: '#(lookup[_$.user.school.name[0].codeable.text])' } }


text:
Q: Inverse of a Cauchy-like matrix Consider $n\times n$ symmetric Cauchy-like matrix $M$ with elements $(M_{ij})_{i,j=1}^{n}$ given by
$$M_{ij} = \frac{1}{(n-i)!(n-j)!(2n-i-j+1)} = \displaystyle\int_{0}^{1}\frac{x^{n-i}}{(n-i)!} \frac{x^{n-j}}{(n-j)!}\:{\rm{d}}x.$$
Is there a way to compute the elements of the inverse $(M^{-1})_{ij}$ analytically?

A: I was able to figure this out by viewing $M$ as a scaled Cauchy matrix.

Theorem. $\left(M^{-1}\right)_{ij} = \dfrac{(n-i)!(n-j)!}{2n-i-j+1}\dfrac{\displaystyle\prod_{r=1}^{n}(2n-i-r+1)(2n-j-r+1)}{\left(\displaystyle\prod_{\stackrel{r=1}{r\neq i}}^{n}(r-i)\right) \left(\displaystyle\prod_{\stackrel{r=1}{r\neq j}}^{n}(r-j)\right)}$.

Proof. Define $n\times 1$ vector $\alpha$ with elements $(\alpha)_{i} = 1/(n-i)!$. Then $M = \text{diag}(\alpha) N \text{diag}(\alpha)$, where $N_{ij} := 1/(2n-i-j+1)$. Hence $\left(M^{-1}\right)_{ij} = (n-i)!(n-j)!\left(N^{-1}\right)_{ij}$.
Now, write $N$ as a Cauchy matrix: $N_{ij} = 1/(a_i + b_j)$ where $a_i := n-i$, $b_j := n-j+1$. Then using the known result [1, Sec. 1.2.3, Exercise 41] for Cauchy matrix inverse:
$$\left(N^{-1}\right)_{ij} = \dfrac{1}{2n-i-j+1}\dfrac{\displaystyle\prod_{r=1}^{n}(2n-i-r+1)(2n-j-r+1)}{\left(\displaystyle\prod_{\stackrel{r=1}{r\neq i}}^{n}(r-i)\right) \left(\displaystyle\prod_{\stackrel{r=1}{r\neq j}}^{n}(r-j)\right)},$$
the result follows.
[1] D. E. Knuth, The Art of Computer Programming. Volume 1: Fundamental Algorithms, 3rd ed. Addison- Wesley, 1997.


text:
Q: display form data in another view in Zend I am new in Zend, my problem can be simple for you. I want to make a controller that displays form input data in another view. data are an email text and a text file uploaded. I created the index view and result view.
but i get nothing. when I replace the value of $email with text it works!! I can't find what is going wrong.
The controller also should display a sorted file by firstname
Id,Firstname,Lastname
5,John,Doe
6,Adam,Ant
7,Victor,Hugo
8,Britannie,Spears

this is my controller :
public function indexAction()
    {
        // initialzing of the customized form
        $form = new Application_Form_Upload();

        $rq = $this->getRequest();

        $isForm = true; // the form has to be shown only if true

        if ($rq->isPost()) {
            if ($form->isValid($rq->getPost())) {
                // show the uploaded data instead of the form
                $isForm = false;
                $this->view->data = new Application_Model_DataViewer();
                $this->view->data->parseFromForm($form);

                $result = new Zend_View();
                $this->view->result= $result;
                $this->render('result');
            }
        }

        if ($isForm) {
            $this->view->form = $form;}
    }

this is my model :
class Application_Model_DataViewer
{
    /**
     * @var string Entered e-mail address
     */
    private $email;
    /**
     * @var array Array of extracted data from uploaded file
     */
    private $data;

    public function __construct(){
        $this->email=null;
        $this->data=array();
    }

    /**
     * Extracts the data from the form-object and saves it internally
     * @param $form Application_Form_Upload
     */
    public function parseFromForm($form){
        if(!isset($form))return;
        if(!isset($form->file)||!$form->file instanceof Zend_Form_Element_File){
            throw new Zend_Exception('The field File is empty or has wrong type');
        }

        // for validation of the IDs
        $ival = new Zend_Validate_Int();

        // reading the CSV-file (values should be separated by comma, if not - should be extended)
        if(($fp = @fopen($form->file->getFileName(), 'r')) !== false){
            while(($data = fgetcsv($fp, 500, ',')) !== false){
                if(
                    !is_array($data)
                    ||!$ival->isValid($data[0])
                    ||count($data)<3
                )continue;
                $this->data[$data[1]] = $data;
            }
        }else{return;}
        @fclose($fp);

        ksort($this->data);

        $this->email = $form->getValue('email');
    }

    /**
     * @return null|string
     */
    public function getEmail(){
        return $this->email;

    }

    /**
     * @return array
     */
    public function getData(){
        return $this->data;
    }

}

and here is my index and result views
<?php
// the form should only be rendered if form must be shown
if(isset($this->form)){
    $this->form->setAction($this->url());
    echo $this->form;
}
?>

result view:
<?php
// if the required data is submitted, it will be checked and displayed
if(isset($this->data)){
?>

Thank you <?php echo $this->escape($this->data->getEmail()); ?>.

The result of the sorting is:
<?php
    foreach($this->data->getData() as $row){
        echo '
', $this->escape($row[0]), ',',
            $this->escape($row[1]), ',',
            $this->escape($row[2]), '
';
    }
?>
<?php
}

?>

A: Use the partial helper in the view.
See: http://framework.zend.com/manual/2.2/en/modules/zend.view.helpers.partial.html
eg. your index.phtml
if ($this->data) {
    echo $this->partial("result.phtml", array("data" => $this->data->getData()));
}

you can access the variable in result.phtml by $this->data


text:
Q: SQL Server : insert multiple select results into single row I am looking for someone to point me in the right direction. Not even sure how to ask this. Everything I can find with the verbiage I am using is talking about combining results from separate tables.
I have a single table and I need multiple select result to go into another table in a single row. So I need to insert a new row from several select/as/where queries that I need as one resulting row.
In a real basic sense I need this but 10+ results into a 10+ column row with a date/time reference.
Insert into [table2].[namealias1]
    Select [number] as namealias1
    From [db].[table]
    Where [name] = 'name1'

Table1 (source)
[NAME]   [NUMBER]

Table2 (destination)
DATESTAMP  NameAlias1 NameAlias2

It has been a long time since I have done any SQL and I am looking for some advice and a push in the right direction. Even just some hints at the best way to attack this. This is on SQL Server 2012.
Thanks in advance for any help.

A: Maybe CTEs could help with your problem. You need something like this:
;WITH cte1 as
(
    select col1, col2, ... ,colN
    from table1
    where conditions_for_table1
),
cte2 as
(
    select col1, col2, ... ,colK
    from table2
    where conditions_for_table2
),
......
......

insert into destination_table( table columns here)
select c1.col1, c2.col3, c3.col5, ... , cM.colK /*choose desired columns from CTEs*/
from cte1 c1
left /*inner*/ join cte2 as c2 on c1.joining_column = c2.joining_column
left /*inner*/ join cte3 as c3 on c1.joining_column = c3.joining_column
.....
left /*inner*/ join cteM as cM on c1.joining_column = cM.joining_column

A: Brute force method:
I declared a variable for each select statement result and used the variables in the insert statement.


text:
Q: How to add a region without knowing the type and without activating it RequestNavigate(uri) is nice when you want to navigate to region using a string and immediately make it the active view. But what if you want to add a region without activating it? Is there a way to do that with a string?
I have a view model that needs to add some views to a docking control dynamically. These views should not be activated when they are added. Adding a region using Region.Add works but I have to give it a type:
RegionManager.Regions[KnownRegionNames.DockingRegion].Add(typeof(MyView));
I feel like this violates some MVVM principals of making the ViewModel completely independent from views. It's not absolutely terrible since I can probably mock out the region manager in testing, but is there another way?

A: You'll have to somehow identify the view you want to add to your region, either by type or by string.
You can use the string to resolve it from the container (basically what the region manager does) and add the resolved view to the region.


text:
Q: How can I stop the browser from closing automatically? I am using Selenium to log in to some website via EDGE.
The browser window is closing.
How can I stop the window from closing?
Sub Login_EdgeChrome2()
Dim wd As WebDriver
Set wd = New ChromeDriver

Const URL = "https://mms.fsicloud.me/Evolution/!System/Security/Login.aspx?ReturnUrl=%2fEvolution"

With wd
    .Start "Edge"
    .Get URL
    .FindElementById("ctl00_contentPlaceHolder_loginControl_UserName").SendKeys "username"
    .FindElementById("ctl00_contentPlaceHolder_loginControl_Password").SendKeys "password"

    .FindElementById("ctl00_contentPlaceHolder_loginControl_LoginButton").Click  '- this will log in with the correct credentials.

End With
wd.Wait (Now + TimeValue("00:01:30"))

End Sub

Used to do this in IE. However some features don't work well now in IE.
I tried Selenium to log in via EDGE. However, it logs automatically. So I put the time delay, but after the time lapsed, it will close again.

A: I confess I don't know much about VB - but from the looks of it, you have a subroutine that creates a localized instance of WebDriver. So when  Login_EdgeChrome2 ends, the local instance disappears. In my world (in the languages I am familiar with), I'd have to return wd as a result of that subroutine to make it "survive".


text:
Q: Spring doesn't Reject Protected Url access I have implemented spring security it was working fine but suddenly it stopped working.
Now when I try to access a protected url it doesn't reject, it allows me to open url.
when I try to login with valid user it does call loginSuccessHandler but doesn't redirect to secure/applications.html page.
Sorry it is bit lengthy detail, I am really stuck :(.
Spring Logging
20:41:04,555 DEBUG [org.springframework.security.web.util.AntPathRequestMatcher] - Checking match of request : '/j_spring_security_check'; against '/resources/**'
20:41:04,556 DEBUG [org.springframework.security.web.FilterChainProxy] - /j_spring_security_check at position 1 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
20:41:04,556 DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - No HttpSession currently exists
20:41:04,556 DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - No SecurityContext was available from the HttpSession: null. A new one will be created.
20:41:04,556 DEBUG [org.springframework.security.web.FilterChainProxy] - /j_spring_security_check at position 2 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
20:41:04,556 DEBUG [org.springframework.security.web.FilterChainProxy] - /j_spring_security_check at position 3 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
20:41:04,556 DEBUG [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] - Request is to process authentication
20:41:04,557 DEBUG [org.springframework.security.authentication.ProviderManager] - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
Hibernate: select this_.id as id1_12_1_, this_.date as date2_12_1_, this_.email as email3_12_1_, this_.firstName as firstNam4_12_1_, this_.lastName as lastName5_12_1_, this_.password as password6_12_1_, this_.phoneNumber as phoneNum7_12_1_, this_.role as role8_12_1_, registerst2_.id as id1_11_0_, registerst2_.active as active2_11_0_, registerst2_.sessionExpiry as sessionE3_11_0_, registerst2_.sessionString as sessionS4_11_0_ from User this_ left outer join RegisterStatus registerst2_ on this_.id=registerst2_.id where this_.email=?
20:41:07,736 WARN  [org.springframework.security.authentication.event.LoggerListener] - Authentication event AuthenticationSuccessEvent: yahya.arshad@gmail.com; details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null
20:41:07,737 DEBUG [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] - Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser@48f0db60: Username: yahya.arshad@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities
20:41:07,737 DEBUG [org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices] - Did not send remember-me cookie (principal did not set parameter '_spring_security_remember_me')
20:41:07,737 DEBUG [org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices] - Remember-me login not requested.
20:41:07,737 WARN  [org.springframework.security.authentication.event.LoggerListener] - Authentication event InteractiveAuthenticationSuccessEvent: yahya.arshad@gmail.com; details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null
20:41:09,038 DEBUG [org.springframework.security.web.session.HttpSessionEventPublisher] - Publishing event: org.springframework.security.web.session.HttpSessionCreatedEvent[source=org.mortbay.jetty.servlet.HashSessionManager$Session:ap7q19yq3oul@1156618876]
20:41:09,039 DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - SecurityContext stored to HttpSession: 'org.springframework.security.core.context.SecurityContextImpl@48f0accc: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser@48f0db60: Username: yahya.arshad@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities'
20:41:09,041 DEBUG [org.springframework.security.web.context.SecurityContextPersistenceFilter] - SecurityContextHolder now cleared, as request processing completed
20:41:09,047 DEBUG [org.springframework.security.web.util.AntPathRequestMatcher] - Checking match of request : '/secure/applications.html'; against '/resources/**'
20:41:09,047 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 1 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
20:41:09,047 DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@48f0accc: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser@48f0db60: Username: yahya.arshad@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities'
20:41:09,047 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 2 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 3 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 4 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 5 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 6 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 7 of 11 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter] - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser@48f0db60: Username: yahya.arshad@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.authentication.AnonymousAuthenticationFilter] - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser@48f0db60: Username: yahya.arshad@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
20:41:09,049 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Secure object: FilterInvocation: URL: /secure/applications.html; Attributes: [permitAll]
20:41:09,049 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser@48f0db60: Username: yahya.arshad@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities
20:41:09,049 DEBUG [org.springframework.security.access.vote.AffirmativeBased] - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@3aa8c31b, returned: 1
20:41:09,049 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Authorization successful
20:41:09,049 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - RunAsManager did not change Authentication object
20:41:09,049 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html reached end of additional filter chain; proceeding with original chain
20:41:09,053 DEBUG [org.springframework.security.web.access.ExceptionTranslationFilter] - Chain processed normally
20:41:09,053 DEBUG [org.springframework.security.web.context.SecurityContextPersistenceFilter] - SecurityContextHolder now cleared, as request processing completed

LoginSuccessHandler.java
public class LoginSuccessHandler implements AuthenticationSuccessHandler,
        AuthenticationFailureHandler {

    public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication auth)
            throws IOException, ServletException {
        request.getSession(true).setAttribute("user", auth.getPrincipal());
        request.setAttribute("user", auth.getPrincipal());

        **response.sendRedirect("secure/applications.html");** // it does't redirect
    }

    public void onAuthenticationFailure(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException auth)
            throws IOException, ServletException {
        // TODO Auto-generated method stub

        request.getSession(true).setAttribute("error", auth.getMessage());
        request.setAttribute("error", auth.getMessage());
        response.sendRedirect("login.html?error=true");

    }

}

security-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    <context:component-scan base-package="com.fyp.ptma" />
<beans:bean id="loggerListener"
    class="org.springframework.security.authentication.event.LoggerListener" />

<global-method-security pre-post-annotations="enabled" />

<http pattern="/resources/**" security="none" />

<http use-expressions="true" auto-config="true">
    <intercept-url pattern="/**" access="permitAll" />

    <intercept-url pattern="/secure/*" access="isAuthenticated()" />
    <intercept-url pattern="/j_spring_security_check"
        access="permitAll" />
    <intercept-url pattern="/processRegistration.html"
        access="permitAll" />
    <form-login login-page="/login.html" default-target-url="/secure/fileUpload.html"
        authentication-failure-url="/login.html?error=true"
        login-processing-url="/j_spring_security_check"
        authentication-success-handler-ref="loginSuccessHandler"
          />
    <logout />
    <remember-me user-service-ref="userDetailsService" />
    <access-denied-handler error-page="/login.html?error=true" />
</http>

<authentication-manager>
    <authentication-provider user-service-ref="userDetailsService">
        <password-encoder hash="plaintext" />
    </authentication-provider>
</authentication-manager>

<beans:bean id="userDetailsService"
    class="com.fyp.ptma.dao.service.UserDetailsServiceImpl">

</beans:bean>
<beans:bean id="loginSuccessHandler" class="com.fyp.ptma.security.LoginSuccessHandler" />

servlet-context.xml
 <?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing
        infrastructure -->

    <beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.fyp.ptma.controllers" />

</beans:beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/log4j.properties</param-value>
    </context-param>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/root-context.xml
            /WEB-INF/spring/appServlet/security-context.xml
            /WEB-INF/hibernate/hibernate-config.xml
       </param-value>
    </context-param>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>120</session-timeout>
    </session-config>
</web-app>

A: You should move
<intercept-url pattern="/**" access="permitAll" />

after
<intercept-url pattern="/secure/*" access="isAuthenticated()" />

in your security-context.xml


text:
Q: Factory pattern returning same instance Let's take an example "factory" class written in C#:
public class HasherFactory : IHasherFactory
{
    private readonly Sha1Hasher _sha1Hasher;
    private readonly Sha2Hasher _sha2Hasher;

    public HasherFactory(Sha1Hasher sha1Hasher, Sha2Hasher sha2Hasher)
    {
        _sha1Hasher = sha1Hasher;
        _sha2Hasher = sha2Hasher;
    }

    public IHasher CreateHasher(string hashAlgorithm)
    {
        switch (hashAlgorithm.ToLower())
        {
            case "sha1":
                return _sha1Hasher;
            case "sha2":
                return _sha2Hasher;
            default:
                throw new ArgumentException("Invalid hash algorithm", nameof(hashAlgorithm));
        }
    }
}

The problem I have here is the naming convention of this class. Factory suggests that each execution of CreateHasher will return a new instance, but it is not the case. What is the pattern used here called?

A: It's called a singleton pattern in the case where the same instance is always returned... This is the equivalent of two singletons--a doubleton?
I would use "Get" though (Which is the standard for singletons, as in GetInstance().  In this case it would be GetHasher("sha1")


text:
Q: read and display the content of txt file from database in index page In php how to make the index page read from a text file saved in TXT folder  and the text name is already saved in mysqli databse, am new to php and database.
here is the database table

A: Get the text file name from SQL, then use file_get_contents() to get the text file contents.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$connection= new mysqli($servername, $username, $password, $dbname);
    $query = mysqli_query($connection, "SELECT name FROM new_record");
    while ($row = mysqli_fetch_array($query)) {
        $fileName = $row['name'];
        $fileContents = file_get_contents("/TXT/$fileName");
        echo $fileContents;
    }


text:
Q: Laravel ,font-family works on Ubuntu but not on Debian I have an Problem.
I have coded an Laravel 5 Script on Ubuntu 17 and want use it now on Debian.
But the font font-family is not the same and it looks not good.
On Ubuntu i have installed on my Machine all Fonts i need and add it in my Body CSS:
body {
  font-family: "Roboto Mono", Helvetica, Arial;

Now i have installed also on Debian the Font files for the System and restart the Browser but the Laravel script dont use it, why? Or have i forget something?
Thanks

A: I would suggest loading it from Google's CDN as opposed to downloading the font files and installing them on your local machine.
You can achieve this by putting the following code at the top of your CSS file:
@import url('https://fonts.googleapis.com/css?family=Roboto+Mono');


text:
Q: Python скролл страницы с помощью pyautogui В документации к модулю pyautogui указана команда pyautogui.scroll(10) но это не работает. Может кто сталкивался?

A: Окно, к которому применяется scroll, должно быть активно (например, с помощью функции pyautogui.click()). И скроллирование страницы вниз - pyautogui.scroll(-10).


text:
Q: OleDbCommand.ExecuteNonQuery() does not save changes in ms access database I have .mdb database, and code like this:
using (OleDbConnection connection = new OleDbConnection(myConnectionString))
{
    using (OleDbCommand cmd = connection.CreateCommand())
    {
        cmd.CommandText = "UPDATE myTab SET col2 = @val1 WHERE col1 = @val2";
        cmd.Parameters.AddWithValue("@val1", 0);
        cmd.Parameters.AddWithValue("@val2", -1);
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
     }
}

I get data from db, change it in my gui programm, then save it in db. Changes saves, but not  in db (I don't know where), so when I run program, change data, close program, then again run - changes remain, but when I open db (not in programm), there are no changes saved, and again run - all changes disappear.
PS: when I commit changes, then run program several times, all changes disappear too, after (3-4 runs)

A: When we we add .mdb in project root in VS ,when change structure ,VS default delete .mdb file in debug folder and replace new file; now you can change this defult :
1- right click .mdb file and select option
2- set Copy To Output Directory to Do Not Copy

A: It is most likely the WHERE clause of your update statement isn't locating any records to update.
http://weblogs.asp.net/stevewellens/archive/2009/10/16/why-sql-updates-fail-three-reasons.aspx


text:
Q: Windows 10 paste timestamp anywhere I´d like to have a shortcut to place a timestamp at any program that I use in Windows 10.
I didn't found any native resource for that.
I wonder if I could write some macro or script or some basic function that returns a timestamp, invoked by a shortcut, regardless of the current task that I´m working.

A: You can do it with powershell.
Create a shortcut with this command line:
powershell.exe -c "Get-Date | Set-Clipboard"

Each time you start the shortcut, the clipboard will get a new timestamp.

A: So I went to my desktop, right click on it, and used the command : New >> shortcut.
After right click on this new shortcut, and selected 'Properties'.
In the 'General' tab I put "NOW CTRL + ALT + bar" in the first field (that´s the sortcut´s name).
In the 'Shortcut' tab I put the command above in the first field,
and "CTRL + Alt + /" in the third field.


text:
Q: Marketing Cloud new Transactional API - Error while activating definition My MC account just got enabled on the new transactional email API which was "released" a couple weeks ago. I'm following the documentation here. The POST to create the definition returns returns an error message "MCMS_UTM_Runtime: Error while activating definition", though I can see the definition is created when I issue a subsequent GET to /messaging/v1/email/definitions. When I then try to issue a PATCH to activate the definition ({"status": "Active"} as the PATCH body) I get the same runtime error.
Is this new API ready for primetime? Are there other people using it yet successfully?

A: I talked to support. It turns out that the content template is validated as part of the email definition creation process. My template was referencing some variables that were not in the data extension that I was trying to use for the send definition.


text:
Q: Refresh activity without open again? I have button for for install apk file download from server in specific folder and user some time delete apk file from folder but this button do not disable in same time but should exit activity and open again  ... my question is how refresh status button after delete file apk by user without open activity again
 Button install = (Button) findViewById(R.id.install_font);
        final File file_1 = new File(Environment.getExternalStorageDirectory() + "/download/app-debug.apk");
        if(file_1.exists()){
            install.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/"+"app-debug.apk")),
                            "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }

            });

        }else {
            install_font.setEnabled(false);
        }

    }

and i try add onResume but disable button all time mean if apk file exists the button is disable and apk file not exists the button is disable
 @Override
    public void onResume() {
        super.onResume();

        final File file = new File(Environment.getExternalStorageDirectory() + "/download/app-debug.apk");
        final Button install_font = (Button) findViewById(R.id.install_font);
        install_font.setEnabled(false);
    }

A: You could check if your file exist every time the user enter to the application , then set the enabled flag based on it.
Try this code:
 @Override
 public void onResume() {
    super.onResume();

    final File file = new File(Environment.getExternalStorageDirectory() + "/download/app-debug.apk");
    final Button install_font = (Button) findViewById(R.id.install_font);
    install_font.setEnabled(file.exists());
}


text:
Q: Show that the following statements are equivalent. (1) $f$ is nullhomotopic. (2) $f$ can be extended to continuous map $\tilde{f}:\Bbb D^{n+1} \to Y$.
Let $f: \Bbb S^n \to Y$ be continuous. Show that the following statements are equivalent. (1) $f$ is nullhomotopic. (2) $f$ can be extended to continuous map $\tilde{f}:\Bbb D^{n+1} \to Y$.

Suppose first that $f$ is nullhomotopic. This gives existence to $h:f \simeq c_{y_0}$ where $c_{y_0}(x)=y_0$ for all $x \in X$.
I think I can use the topological cone here somehow now. As $h$ is defined from $\Bbb S^n \times I \to Y$ and I have the quotient map $q : \Bbb S^n \times I \to C(\Bbb S^n)=(\Bbb S^n \times I)/(\Bbb S^n \times \{1\})$ I suppose I could define $$\tilde{h}:C(\Bbb S^n) \to Y, \tilde{h}(\{x\},t)=h(x,t).$$
Now if I remember correctly I have a homeomorphism between $C(\Bbb S^n)$ and $\Bbb D^{n+1}$ so I could use that here?


text:
Q: How can I make an instance return the String of a field directly in Java as I could do in Python with __radd__? In Python, if I wanted an instance to return a string of a field directly, I could do something like this:
class X:

    def __init__(self, field):
        self.field = field
        self.__repr__ = self.__str__

    def __radd__(self, other):
        return other + self.field

    def __str__(self):
        return self.field

x = X("example.")
print("This is an " + x)

In Java, I don't know how I would do it...
public class X {

    public String field;

    public X(String field) {
        this.field = field;
    }

}

public class Main {

    public static void main(String[] args) {

        X x = new X("example.");
        System.out.println("This is an " + x.field); // Just x would return the address of the object in memory.

    }

}

A: If I understand your question, you could Override toString in X with something like,
@Override
public String toString() {
    return field;
}

Then you could use
System.out.println("This is an " + x);

which would implicitly call toString (e.g. is equivalent to)
System.out.println("This is an " + x.toString());

A: You have to override the toString() method:
public class X {
    public String field;

    public X(String field) {
        this.field = field;
    }

    @Override
    public String toString() {
        return this.field;
    }
}


text:
Q: Use Bearer Token from localstorage So I'm creating a simple React Redux app using superagent to get some elements from the database and do some operations on them.
I used Symfony's Api platform as a backend and created a few of APIs. All my APIs are protected and need a bearer token to access them.
I created an Authentication API using JWT.
Now I'm trying to get the data to show in my React app. I already created a functioning login form. I can use my username and password and get a token in return.
My problem though, is after I authenticate and the app redirects me to my homepage (which contains the list of elements from the db), I get an error in my console
("{code: 401, message: "JWT Token not found"}
code: 401
message: "JWT Token not found")

which means that I'm not using the bearer token in my request.
So how do I use the token inside my POST, GET and PUT requests so I can use them.
PS: My token is stored inside my localstorage under the name jwtToken
here's my agent.js file:
import superagentPromise from 'superagent-promise';
import _superagent from 'superagent';

const superagent = superagentPromise(_superagent,global.Promise);
const API_ROOT='http://localhost:8000/api';
const responseBody = response => response.body;

let token =window.localStorage.getItem('jwtToken');;

const tokenPlugin = secured => {
    return (request) => {
        if (token && secured){
            request.set('Authorization',`Bearer ${token}`);
        }
};
};
export const requests={
    get: (url, secured = false)=>{
        return superagent.get(`${API_ROOT}${url}`).use(tokenPlugin(secured)).then(responseBody);
    },
    post: (url, body = null, secured = true) => {
        return superagent.post(`${API_ROOT}${url}`, body).use(tokenPlugin(secured)).then(responseBody);
    },
    setToken: (newJwtToken) => token = newJwtToken
    };

A: Your get accepts url and secured params and maybe you are not sending the second param and it is defaulted to false and tokenPlugin is checking for token && secured
try get(url, true) where you are using the get.


text:
Q: Long time reloading pages because weblogic 12.2.1.3.0 triggers recompiling jsp every page acces I use weblogic 12.2.1.3.0 and EVERY TIME (not only the first time) I access a web page I wait for 2 minutes for it to render cause weblogic apparently recompiles all the jsps that it contains. Every page is made up of fragments using apache tiles 3.0 using definitions like these:
<definition name="includeTemplate" template="/WEB-INF/jsp/templates/includeTemplate.jsp">
  <put-attribute name="content" value="/WEB-INF/jsp/index.jsp"/>
  <put-attribute name="headContent" value=""/>
  <put-list-attribute name="dialogs">
    <add-attribute value="messageDialogDef"/>
    <add-attribute value="validationDialogDef"/>
    <add-attribute value="detailDialogDef"/>
  </put-list-attribute>
</definition>

Weblogic throws lots of these messages in its log files:
<BEA-101360> <Recompiling JSP [ServletContext@1759767545[app:app-ear_ear module:/app path:null spec-version:3.1]], resource [/WEB-INF/jsp/templates/list/menu.jsp], because it is stale.>

I also use spring (mvc) 4.3.21
Any idea what is going on and how to avoid only the useless recompilings?

A: This is a known bug. There is a patch for WLS 12.2.1.3.0


text:
Q: finding maximum height of stack such that it is equal for all three stack we have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. we can change the height of a stack by removing and discarding its topmost cylinder any number of times.
Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of the three stacks until they are all the same height, then return the height.
example:
h1 = [3, 2, 1, 1, 1] //remove 3 , it will make height 5 i.e (1+1+1+2=5);

h2 = [4, 3, 2]       //remove [4] it will make height 5;

h3 = [1, 1, 4, 1]    //remove [1,1] it will make height 5;

It will return 5 as answer.
my approach
I counted sum1 for stack1 sum2 for stack2 and sum3 for stack 3 and then started decreasing the greatest sum value by subtracting it with the topmost element of that stack && popping it out then iteratively using while(sum1!=sum2 || sum2!=sum3 ||sum3!sum1). but my while loop executed successfully up to 2 conditional statements and after that, it kept processing without giving output, it appears it went infinite loop but I have included all conditions to terminate the loop. what goes wrong with my approach, please do help, thank you so much.
my code;
#include<iostream>
#include<stack>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
    vector<int>h1={3,2,1,1,1};
    vector<int>h2={4,3,2};
    vector<int>h3={1,1,4,1};
    int sum1=0,sum2=0,sum3=0;
    stack<int>s1,s2,s3;
    for(int i=h1.size()-1;i>=0;i--){
            s1.push(h1[i]);
            sum1+=h1[i];
        }
    for(int i=h2.size()-1;i>=0;i--){
            s2.push(h2[i]);
            sum2+=h2[i];
        }
    for(int i=h3.size()-1;i>=0;i--){
            s3.push(h3[i]);
            sum3+=h3[i];
        }
        while(sum1!=sum2 || sum2!=sum3 ||  sum3!=sum1){
        vector<int>sum;
        sum.push_back(sum1);sum.push_back(sum2);sum.push_back(sum3);
        sort(sum.begin(),sum.end(),greater<int>());
        if(sum1==sum[0] && sum2!=sum[0] && sum3!=sum[0] && !s1.empty()){
            sum1=sum1-s1.top();
            s1.pop();
            cout<<sum1<<endl;
            cout<<s1.top()<<endl;

        }
        if(sum2==sum[0] && sum3!=sum[0] && sum1!=sum[0] && !s2.empty() ){
            sum2=sum2-s2.top();
            s2.pop();
            cout<<sum2<<endl;
            cout<<s2.top()<<endl;
        }
        if (sum3==sum[0] && sum2!=sum[0] && sum3!=sum[0] && !s3.empty()){
            sum3=sum3-s3.top();
            s3.pop();
            cout<<sum3<<endl;
            cout<<s3.top();
            //h3.pop_back();
        }
        if (sum1==sum[0] && sum2==sum[0] && sum3!=sum[0] && !s1.empty() && !s2.empty()){
            sum1=sum1-s1.top();sum2=sum2-s2.top();
            s1.pop();s2.pop();
            //h1.pop_back();h2.pop_back();
        }
        if (sum1!=sum[0] && sum2==sum[0] && sum3==sum[0] && !s2.empty() && !s3.empty()){
            sum2=sum2-s2.top();sum3=sum3-s3.top();
            s2.pop();s3.pop();
            //h2.pop_back();h3.pop_back();
        }
        if (sum1==sum[0] && sum2!=sum[0] && sum3==sum[0]  && !s1.empty() && !s3.empty()){
            sum1=sum1-s1.top();sum3=sum3-s3.top();
            s1.pop();s3.pop();
            //h1.pop_back();h3.pop_back();
        }
    }
    cout<<"ans"<<sum1;
}

A: One approach is to use a max heap. If sum of top stack of the max heap is equal to the minimum of sums then its done.
Algorithm :

*

*Compute the sum of elements in each stack and track the minimum.

*Add each stack as a tuple like (index_of_the_stack, current_sum_of_the_stack) to a max heap with sum as the comparator.

*If sum of top stack of the max heap is equal to minimum sum you are done.

*Otherwise remove the max stack of the heap - by removing max stack I mean remove the tuple (index, sum)

*Then keep removing elements from the stack with that index until its sum is less than or equal to the minimum sum.

*Update the minimum sum as minimum_sum = min(minimum_sum, sum_of_updated_top_stack)

*Add the tuple ( index, updated_sum_of_the_stack ) back to the heap.

*Go to step 3.

This should handle any number of stacks.


text:
Q: Unhandled IO exception ? Playing mp3 file with a media player - Android Here's my code:
(As an example, say I put this in the OnCreate to play sound when the activity starts up.)
AssetFileDescriptor afda = getAssets().openFd("AudioFile.mp3");
MediaPlayer player;
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor());
player.prepare();
player.start();

Among other things, here's a solution I found on SO:
try {// above erroneous code here
     }
  mediaPlayer.start();
} catch (IllegalArgumentException e) {
 e.printStackTrace();
} catch (SecurityException e) {
 e.printStackTrace();
} catch (IllegalStateException e) {
 e.printStackTrace();
} catch (IOException e) {
 e.printStackTrace();
}

I tried putting every statement that gave the Unhandled IO exception error in a try catch statement. But upon doing that the app goes ANR, doesn't start up and the logcat gives something like "Could not initialize MainActivity" ....
Upon further research I found that this code worked for everyone else, maybe I'm not adding something..
What's wrong with this code ? How to correct it ?
(OR, is there a better more efficient or easier way to play a file ? I only need Play/Pause functionality.)
(I have a [scrollable tab + swipe] navigation app, I want to play a different mp3 file on every tab's screen... just putting it in the oncreate for testing..)
Here's the modified code and the logcat for the runtime error it produces. Basically, all the statements that I've put in the the try catch box gives the "Unhandled exception type IO" compile time error.
Putting these 3 erroneous statements in the try catch results in no problem when compiling, but results in the activity not being able to start(see logcat output below the code)
try {
    AssetFileDescriptor afda = getAssets().openFd("AudioFile.mp3");
} catch (IllegalArgumentException e) {
    e.printStackTrace();
} catch (SecurityException e) {
    e.printStackTrace();
} catch (IllegalStateException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
MediaPlayer player;
player = new MediaPlayer();

try {
    player.setDataSource(afd.getFileDescriptor());
} catch (IllegalArgumentException e) {
    e.printStackTrace();
} catch (SecurityException e) {
    e.printStackTrace();
} catch (IllegalStateException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

try {
    player.prepare();
} catch (IllegalArgumentException e) {
    e.printStackTrace();
} catch (SecurityException e) {
    e.printStackTrace();
} catch (IllegalStateException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

player.start();

08-13 16:00:41.869: E/AndroidRuntime(16412): FATAL EXCEPTION: main
08-13 16:00:41.869: E/AndroidRuntime(16412): java.lang.RuntimeException: Unable to start activity ComponentInfo{wn.w/wn.w.MainActivity}: java.lang.NullPointerException
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2077)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.app.ActivityThread.access$600(ActivityThread.java:134)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.os.Looper.loop(Looper.java:154)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.app.ActivityThread.main(ActivityThread.java:4624)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at java.lang.reflect.Method.invokeNative(Native Method)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at java.lang.reflect.Method.invoke(Method.java:511)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at dalvik.system.NativeStart.main(Native Method)
08-13 16:00:41.869: E/AndroidRuntime(16412): Caused by: java.lang.NullPointerException
08-13 16:00:41.869: E/AndroidRuntime(16412):    at wn.w.MainActivity.onCreate(MainActivity.java:71)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.app.Activity.performCreate(Activity.java:4479)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
08-13 16:00:41.869: E/AndroidRuntime(16412):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2041)
08-13 16:00:41.869: E/AndroidRuntime(16412):    ... 11 more

At line 71 I have :
    player.setDataSource(afd.getFileDescriptor());
(this is within the try catch(see above code))

A: Replace
AssetFileDescriptor afda = getAssets().openFd("AudioFile.mp3");
player.setDataSource(afd.getFileDescriptor());
player.prepare();
player.start();

with
    AssetFileDescriptor afda;
    try {
        afda = getAssets().openFd("AudioFile.mp3");
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (afd != null) {
        player.setDataSource(afd.getFileDescriptor());
        player.prepare();
        player.start();
    } else {
        Log.i("Check This", "AudioFile.mp3 really exist?  afd is null ");
    }


text:
Q: Get Application instance from static method Is it correct to use static method for getting instance of the Application successor in Android. I have seen this approach in a few open source projects: VLC and Shuttle
public class MyApplication extends Application {

    private static MyApplication sApplication;

    public static MyApplication getInstance() {
        return sApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        sApplication = MyApplication.this;
    }

}

A: Yes. This approach is correct. This is singleton pattern you are following. As static variable is the right way always, since its the single state you want to maintain everywhere.
Also it is safe, as long as your application never runs in multiple processes. there's a strict one to one ratio of application per process.
I am also using this in my all applications.


text:
Q: Best solution/framework to Responsive Design for IE7 For those who still don't know about Responsive Design I suggest this link
As long at it doesn't understand media querys like:
@media screen and (max-width: 1280px)   {
    h1 { font-size: 120px; padding: 10px; color:#999999 !important; }
    h2{font-size:35px;}
}

@media screen and (max-width: 1024px)   {
    h1 { font-size: 90px; padding: 1px; color:#999 !important; }
    h2{font-size:25px;}

}

@media screen and (max-width: 740px)    {
    h1 { font-size: 70px; padding: 1px; color:#999 !important; }
    h2{font-size:16px;}
    .left-col { width: 100%; }
    .sidebar { width: 100%; }
}

@media screen and (max-width: 480px) {

}

@media screen and (max-width: 478px)    {
    h1 { font-size: 50px; padding: 1px; color:#999; }
    h2 { font-size: 12px; padding: 1px; }
    body { font-size: 13px; }
}

I was considering to use adapt.js which with you can Do:
<script>
// Edit to suit your needs.
var ADAPT_CONFIG = {
  // Where is your CSS?
  path: 'assets/css/',

  // false = Only run once, when page first loads.
  // true = Change on window resize and page tilt.
  dynamic: true,

  // First range entry is the minimum.
  // Last range entry is the maximum.
  // Separate ranges by "to" keyword.
  range: [
    '0px    to 760px  = mobile.min.css',
    '760px  to 980px  = 720.min.css',
    '980px  to 1280px = 960.min.css',
    '1280px to 1600px = 1200.min.css',
    '1600px to 1940px = 1560.min.css',
    '1940px to 2540px = 1920.min.css',
    '2540px           = 2520.min.css'
  ]
};
</script>
<script src="assets/js/adapt.min.js"></script>

It's meant to be used with 960 grid But you can still use whatever you like in those .css
But the problem is that you need JavaScript enabled. I was hoping any of you know a more flexible (responsive!) solution, any?

A: I don't know of any way to make a website responsive in IE6-8 without using Javascript. It is, however, possible to just serve a desktop version of your website to these browsers and make it responsive in all other browsers. I believe this is the best approach, since IE6-8 are (almost?) exclusively used on desktops anyway.
Cascade Framework is the only CSS framework I know with a grid system that implements this technique.
See also this demo.

A: Just looking into this. I was going to use adapt.js, but I found some JS that enables media query functionality on older browsers (including IE7).
That way newer browsers without JS will still work properly, the only situation where the responsive design will fall back to the smallest version is on

Here are two of the best JS media query fallbacks I have found:

Respond
https://github.com/scottjehl/Respond
Respond is around 3kb when compressed and supports the basic media queries that you would need for simple responsive design (min/max-width)

css3-mediaqueries-js
http://code.google.com/p/css3-mediaqueries-js/
A bit bigger at <16kb minified. Supports a wider range of media queries (not tested, but it is referenced on the Respond site)

A: I didn't like the idea of some of the alternatives to make old browsers work with media queries. Loading the CSS file via AJAX and parsing it doesn't sound too efficient to me.
Another option to make responsive websites for IE7 or even IE5/6 is to use JavaScript to apply classes based on screen width, similar to media queries. This works with all browsers as long as JavaScript is enabled. You can have a default resolution which is served if JavaScript is disabled.
This is described here.
Some sample JavaScript to accomplish this:
<script type="text/javascript">
    function hasClass(el, cls) {
        return el.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    }
    function addClass(el, cls) {
        if (!this.hasClass(el, cls)) el.className += " " + cls;
    }
    function removeClass(el, cls) {
        if (hasClass(el, cls)) {
            var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
            el.className = el.className.replace(reg, ' ');
        }
    }

    var addEvent = function (elem, type, eventHandle) {
        if (elem == null || elem == undefined) return;
        if (elem.addEventListener) {
            elem.addEventListener(type, eventHandle, false);
        } else if (elem.attachEvent) {
            elem.attachEvent("on" + type, eventHandle);
        } else {
            elem["on" + type] = eventHandle;
        }
    };

    function responsive() {
        var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

        for (var i = 0; i < breakpoints.length; i++) {
            if (breakpoints[i][0] == "max-width") {
                if (w <= breakpoints[i][1]) {
                    addClass(document.getElementById(id), breakpoints[i][2]);
                }
                else {
                    removeClass(document.getElementById(id), breakpoints[i][2]);
                }
            }
            else if (breakpoints[i][0] == "min-width") {
                if (w >= breakpoints[i][1]) {
                    addClass(document.getElementById(id), breakpoints[i][2]);
                }
                else {
                    removeClass(document.getElementById(id), breakpoints[i][2]);
                }
            }
        }
    }

    var resizeTimeoutId;

    function resized() {
        window.clearTimeout(resizeTimeoutId);
        resizeTimeoutId = window.setTimeout('responsive();', 10);
    }

    var id = "body";
    var breakpoints = [["max-width", 630, "max630"], ["min-width", 1890, "min1890"]];

    addEvent(window, "resize", resized);

    responsive();
</script>


text:
Q: Using dynamic text elements from ArcMap in conjunction with text elements derived from Python I have a script that cycles through features based on attributes and makes a PDF centered around each feature.  I would like to be able to include both a dynamic text element for the date as well as a title that is derived from the python script.  I'm currently using the  arcpy.mapping.ListLayoutElements(thisMap, "TEXT_ELEMENT") command and then updating the text element for each iteration of the loop.  The problem is that not only does the title get changed but the dynamic date also gets changed to the text meant for the title.  How would I construct the code to only target a specific text element instead of all of the text elements in the map?  I have tried using the wildcard, but the problem with this is that the text gets changed from every previous iteration, so the wildcard will only identify the text from the first iteration.
with arcpy.da.SearchCursor(fc, ("SHAPE@", "UNIQUE_ID")) as searchCur:
for row in searchCur:
        myDF.extent = row[0].extent
        myDF.scale = mapScale

        for elm in arcpy.mapping.ListLayoutElements(thisMap, "TEXT_ELEMENT"):
            elm.text = str(row[1])

        arcpy.RefreshActiveView()
        arcpy.mapping.ExportToPDF(thisMap, str(pdfLoc) + "\Map_" + str(row[1]) + ".pdf", resolution=300, image_quality="Best")   #***test output location variable structure
        arcpy.AddMessage("Output --->  Map_" + str(row[1]) + ".pdf was created successfully!")
        arcpy.AddMessage(str(cycleCount) + "/" + str(recordCount))
        cycleCount += 1

A: You should name your elements in the map so that they can be referenced by the element.name property.  See the text element docs
for elm in arcpy.mapping.ListLayoutElements(thisMap, "TEXT_ELEMENT"):
    if elm.name == 'TestName'  #reference by named element here
        elm.text = str(row[1])  #do work here


text:
Q: Change ASP.Net Session ID - Call from Desktop App via AJAX I have an old VB6 application - I need to shell out to a ASP.net site via a web browser. I have the browser opening and calling the ASP site successfully. I need the VB6 app to know when the Web Browser session is closed. The VB app form (or save button) needs to be disabled when the web browser session is open. (I don't want to use the process Id of the windows process to check this.)
My thought are:

*

*Cross domain cookies perhaps? (security?)

*I have my VB6 app able to call server WebMethods

*Saving a session ID in the database which is usedbut both apps?

Some advice would be excellent. Many thanks.

A: Internal Company Applications.
Desktop App (VB6)

*

*Code to allow VB6 apps to contact Asp service. On any Asp.Net page create an extra [WebMethod] in this case a 'IsWindowOpen' method has been added to the test.aspx page (see red text beow)

*Send a JSON message to the ASP.Net service to query if a WINDOWS_STATUS Session variable is set (this tells us if a browser window is open\closed).

*When shelling out to the Asp.Net site with parameters (plan Id etc.) we'll send in an extra param for 'Session Id'.

*Randomly generate a Session Id in VB6 app [random: 24 char long, lower case, and digits between 0-5], this is replicating how the Asp.Net framework is going to generate its own Session Id for communication between the HTML and C#. We will then override the Asp.Net Session Id given to us by Asp.Net with our own random generated Session ID.
Check if ASP.Net session variable is set in VB6:
Private Sub Command1_Click()
    Dim objHTTP As Object
    Dim Json As String
    Dim result As String

    ' === Check if Browser Session is open ===
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    url = "http://dub-iisdev/SessionTest/test.aspx/IsWindowOpen"

    objHTTP.open "POST", url, False

    objHTTP.setRequestHeader("cookie") = "ASP.NET_SessionId=" + txtCookie.Text ' Required twice
    objHTTP.setRequestHeader("cookie") = "ASP.NET_SessionId=" + txtCookie.Text ' Required twice

   objHTTP.setRequestHeader "Content-type", "application/json"

   objHTTP.send (Json)

   result = objHTTP.responseText

   txtOutput.Text = result

   Set objHTTP = Nothing
End Sub

ASP.Net
We'll need a few pieces of plumbing here :
A small method for setting ASP.Net session IDs
A small closing aspx page which will run some code when we leave the browser, and
Some extra C# methods and JavaScript in our existing pages.
1. Setting Session ID:
Copy variable from old session to new location
protected void ReGenerateSessionId(string newsessionID)
{
    SessionIDManager manager = new SessionIDManager();
    string oldId = manager.GetSessionID(Context);
    string newId = manager.CreateSessionID(Context);
    bool isAdd = false, isRedir = false;
    manager.RemoveSessionID(Context);
    manager.SaveSessionID(Context, newsessionID, out isRedir, out isAdd);

    HttpApplication ctx = (HttpApplication)HttpContext.Current.ApplicationInstance;
    HttpModuleCollection mods = ctx.Modules;
    System.Web.SessionState.SessionStateModule ssm = (SessionStateModule)mods.Get("Session");
    System.Reflection.FieldInfo[] fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
    SessionStateStoreProviderBase store = null;
    System.Reflection.FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;

    SessionStateStoreData rqItem = null;
    foreach (System.Reflection.FieldInfo field in fields)
    {
        if (field.Name.Equals("_store")) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
        if (field.Name.Equals("_rqId")) rqIdField = field;
        if (field.Name.Equals("_rqLockId")) rqLockIdField = field;
        if (field.Name.Equals("_rqSessionStateNotFound")) rqStateNotFoundField = field;

        if ((field.Name.Equals("_rqItem")))
        {
            rqItem = (SessionStateStoreData)field.GetValue(ssm);
        }
    }
    object lockId = rqLockIdField.GetValue(ssm);

    if ((lockId != null) && (oldId != null))
    {
        store.RemoveItem(Context, oldId, lockId, rqItem);
    }

    rqStateNotFoundField.SetValue(ssm, true);
    rqIdField.SetValue(ssm, newsessionID);
}

Your first landing page will set the new Session ID (from VB6) param sent into the server– using out ReGenerateSessionId class above.
After this code executes out instance to Asp.Net and our instance of VB6 will have the same Session Id for HTTP communication
protected void Page_Load(object sender, EventArgs e)
{
    // Simulate Session ID coming in from VB6...
    string sessionId;
    Random rnd = new Random();
    sessionId = "asdfghjklqwertyuiop12345" [24 char - a to z (small) & 0-5]
    // Set new session variable and copy variable from old session to new location
    ReGenerateSessionId(sessionId);

    // Put something into the session
    HttpContext.Current.Session["SOME_SESSION_VARIABLE_NAME"] = "Consider it done!";
}

2. Open\Closing Browser
One of the ASP.Net pages needs to have three new WebMethods: SetOpenWindow, SetClosingWindow and IsWindowOpen
Opening the Browser:
C#. SetOpenWindow:
This will be called from your first (or any required) HTML pages via the .ready JavaScript. When the page has loaded the JavaScript will simply fire an Ajax call to the SetOpwnWindow web method. The method will set a Session variable WINDOW_STATUS to OPEN.
[WebMethod()]
[ScriptMethod(UseHttpGet = false)]
public static string SetOpenWindow()
{
    HttpContext.Current.Session["WINDOW_STATUS"] = "OPEN";
    return "Status:" + HttpContext.Current.Session["WINDOW_STATUS"];
}

ASPX. Call SetOpenWindow from Ajax once the page has loaded. This sets the WINDOW_STATUS to OPEN

Closing the Browser:
On pages where the browser window can be closed call JavaScript to catch when the browser window is closing (handy to add this to your master page instead of to each page!). This calls the ClosingSessionPage aspx page to run the SetClosingWndow webmethod:

The close JavaScript method above redirects to a closing aspx page to run some ajax and then close itself – The Ajax calls SetClosingWindow the session WINDOW_STATUS variable to CLOSED.

    <form id="form1" runat="server">

Closing browser session, please wait.

    </form>

C# SetClosingWindow
Called from Ajax JavaScript when the Browser window is closing and sets WINDOW_STATUS to CLOSED:
[WebMethod()]
[ScriptMethod(UseHttpGet = false)]
public static string SetClosingWndow()
{
    HttpContext.Current.Session["WINDOW_STATUS"] = "CLOSED";
    ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "closePage", "window.close();", true);
    return "Status:" + HttpContext.Current.Session["WINDOW_STATUS"];
}

3. Is Browser Open?
ASP.Net WebMethod called by VB6 whenever it needs to know if the Browser window is Open or Closed.
[WebMethod()]
[ScriptMethod(UseHttpGet = false)]
public static string IsWindowOpen()
{
    string isWindowOpen = HttpContext.Current.Session["WINDOW_STATUS"] != null ? HttpContext.Current.Session["WINDOW_STATUS"].ToString() : "CLOSED";

    return "IsWindowOpen:" + isWindowOpen;
}


text:
Q: Как скопировать от определенного символа несколько строк из Memo? function GetTextInPercent(aLine: string): string;
var
  i1, i2: Integer;
begin
  i1 := Pos('%', aLine) + 1;
  i2 := PosEx('%', aLine, i1);
  Result := Copy(aLine, i1, i2 - i1);
end;
procedure TForm1.Button4Click(Sender: TObject);
var
  k: integer;
begin
  for k:=0 to memo1.Lines.Count-1 do
  begin
   Que1.Lines.Text := Que1.Lines.Text + GetTextInPercent(Memo1.Lines.Strings[k]);
  end;
end;

Есть процедура, которая позволяет искать в тексте Memo символ '%' и выводить после него все, что находится после него до тех пор, пока не найдется такой же символ '%'. Но это работает только если символы на одной строке.
Как сделать, чтобы выводил по несколько строк?
Пример текста в Memo (Memo1):

% Весной снег быстро растаял, вода поднялась и затопила бобровую хатку.Бобры перетащили бобрят на сухие листья, но вода подобралась ещё выше, и пришлось бобрятам расплываться в разные стороны. (Снегирёв Г.) %

Пример результата в другом Memo (Que1):

Весной снег быстро растаял, вода поднялась и затопила бобровую хатку.Бобры перетащили бобрят на сухие листья, но вода подобралась ещё выше, и пришлось бобрятам расплываться в разные стороны. (Снегирёв Г.)

A: При таком раскладе, вам надо как-то обрабатывать весь текст:
В целом принцип такой, что берем весь текст, находим первый % при помощи PosEx('%', aText, 1), так же находим второй %, берем текст между ними при помощи Copy. А далее повторяем это в цикле, находим 3 и 4 %, потом 5 и 6 и каждый раз между ними берем текст.
Или же как-то поделить входной текст на части, чтобы в каждой было только по два знака % и передавать его в вашу функцию не по-строчно, а сразу весь (например Memo1.Text) (тогда переносы строк сохранятся)


text:
Q: UICollectionView with Custom Cell Breaking UICollectionViewDataSource Protocol I am trying to use a UICollectionView with a custom cell. My ViewController inherits from UICollectionViewDataSource as below:
import UIKit
import Parse

class DressingRoomViewController:   UIViewController,
                                    UICollectionViewDelegateFlowLayout,
                                    UICollectionViewDataSource {

That inheritance is causing me to break a protocol of UICollectionViewDataSource with my UICollectionView function that creates and returns the custom cell. This is the function:
func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath)
        -> CustomCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
                identifier,forIndexPath:indexPath) as! CustomCell
            let dressingRoomIcons: [DressingRoomIcon] =
            dataSource.dressingRoomIcons
            let dressingRoomIcon = dressingRoomIcons[indexPath.row]
            var imageView: MMImageView =
            createIconImageView(dressingRoomIcon.name!)

            cell.setImageV(imageView)
            return cell
    }

So before compilation the error is shown in the IDE. How do I get around this error? Here are the two errors I am experiencing:

Type 'DressingRoomViewController' does not conform to protocol
  'UICollectionViewDataSource'
Cannot assign a value of type 'DressingRoomViewController' to a value
  of type 'UICollectionViewDataSource?'

Here is the whole ViewController:
import UIKit
import Parse

class DressingRoomViewController:   UIViewController,
                                    UICollectionViewDelegateFlowLayout,
                                    UICollectionViewDataSource {

    @IBOutlet weak var MirrorImageView: UIImageView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    let identifier = "cellIdentifier"
    let dataSource = DataSource()
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    let cellSpacing: CGFloat = 5
    let cellsPerRow: CGFloat = 6
    let numberOfItems = 12

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
    }

    override func viewDidAppear(animated: Bool) {
        let cellSize = (collectionView.collectionViewLayout
            .collectionViewContentSize().width
            / cellsPerRow)
            - (cellSpacing)

        layout.itemSize = CGSize(width: cellSize, height: cellSize)
        layout.minimumInteritemSpacing = cellSpacing
        layout.minimumLineSpacing = cellSpacing
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView.collectionViewLayout = layout
        self.heightConstraint.constant = cellSize
        self.view.layoutIfNeeded()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func prepareForSegue(  segue: UIStoryboardSegue,
                                    sender: AnyObject?) {
        if (segue.identifier == "dressingRoom2MyOutfits") {
            let myOutfitsViewController = segue.destinationViewController
                as! MyOutfitsViewController
        } else if (segue.identifier == "dressingRoom2StickerPicker") {
            let myStickerPickerController = segue.destinationViewController
                as! StickerPickerViewController
        }
    }

    func imageTapped(sender: UITapGestureRecognizer) {
        var imageView = sender.view as! MMImageView
        println(imageView.fname)
        performSegueWithIdentifier( "dressingRoom2StickerPicker",
                                    sender: imageView)
    }
}

// MARK:- UICollectionViewDataSource Delegate
extension DressingRoomViewController : UICollectionViewDataSource {

    func numberOfSectionsInCollectionView(
        collectionView: UICollectionView) -> Int {
            return 1
    }

    func collectionView(collectionView: UICollectionView,
        numberOfItemsInSection section: Int) -> Int {
            return 12
    }

    func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath)
        -> CustomCell {
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(
                identifier,forIndexPath:indexPath) as! CustomCell
            let dressingRoomIcons: [DressingRoomIcon] =
            dataSource.dressingRoomIcons
            let dressingRoomIcon = dressingRoomIcons[indexPath.row]
            var imageView: MMImageView =
            createIconImageView(dressingRoomIcon.name!)

            cell.setImageV(imageView)
            return cell
    }

    func createIconImageView(name: String) -> MMImageView{
        var imageView :MMImageView =
            MMImageView(frame:CGRectMake(   0,
                                            0,
            (collectionView.collectionViewLayout
                .collectionViewContentSize().width / cellsPerRow)
                - (cellSpacing),
            (collectionView.collectionViewLayout
                .collectionViewContentSize().width / cellsPerRow)
                - (cellSpacing)))
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        imageView.image = UIImage(named: name)
        imageView.setName(name)
        imageView.backgroundColor = UIColor.clearColor()
        imageView.userInteractionEnabled = true
        var tapGestureRecognizer =
        UITapGestureRecognizer(target: self, action: "imageTapped:")
        tapGestureRecognizer.numberOfTapsRequired = 1
        imageView.addGestureRecognizer(tapGestureRecognizer)
        return imageView
    }
}

EDIT: Here is my CustomCell:
import Foundation
import UIKit

class CustomCell: UICollectionViewCell {
    var imageView = MMImageView()

    func setImageV(IV: MMImageView) {
        self.imageView = IV
    }
}

A: Replace this Code
func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath)
        -> UICollectionViewCell {

Instead of below this :
func collectionView(collectionView: UICollectionView,
        cellForItemAtIndexPath indexPath: NSIndexPath)
        -> CustomCell {

You can return custom cell but you can't change return type of any DataSource or Delegate method.


text:
Q: Regex to match words and acronyms in camel case string I need a regular expression to capture the word parts of a string that is camel case and might have an acronym in it. In other words, I want to split a camel case string into its words and acronyms.
For example:
SomeABCWords

... has three capture groups
Some ABC Words

So far I've found this regex:
((?:^|[A-Z])[a-z]+)

But that won't handle the acronyms and would just match 'Some' and 'Words'.

A: One way to solve it is to capture abbreviations with added negative lookahead.
[A-Z][a-z]+|[A-Z]+(?![a-z])

Sample

A: This regex should work, at least for the case you posted :
[A-Z][a-z]+|[A-Z]*(?![a-z])


text:
Q: Confused w/ syntactic assignment of classes in html So, I'm having trouble understanding the difference between commas to separate classes and the absence of them. Also, I am using 'Skeleton' style sheets for the grid system. Here's an example:

  <button type="button">Github</button>

And for 'header_buttons':
.header_buttons {
  margin-left: 180px;
}

With the commas, I get my intended result:
But without them, I get this instead:

I know the basis of having multiple classes is to not use commas. But in my case, if I take them out, why do I not get my intended result?

A: Skeleton adds .column:first-child { margin-left: 0; }, so that rule will have higher specificity than .header_buttons { margin-left: 180px; }.
Without the comma in your markup, .column:first-child { margin-left: 0; } is applied via skeleton and overwrites .header_buttons { margin-left: 180px; }
When you add the comma there, that breaks skeleton's .column class so that rule no longer applies, and the rule you specified for .header_buttons applies.
You can see it here

.header_buttons {
  margin-left: 180px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>

  <button type="button">Github</button>

  <button type="button">Github</button>


text:
Q: Building fine-uploader without the UI Fine uploader is 400kb of javascript code and 140kb minified. Since I am not using the UI and only using the API, I would like to build the library without the integrated interface (and hopefully get a smaller lib consequently). Is this possible?
Could not find this in the downloads section.
I've also setup the build environment and built the package myself, but all the files in the _dist dir seem to be bundled with the UI.

A: Fine Uploader is only 40 kB gzipped, which is compression that pretty much every web server already utilizes. The build is not currently setup to create a bundle without the UI. If you'd like to create such a build, the modules.js file will need to be modified. One place to start would be with a copy of the fuTraditional module sans the @fuSrcUi module. Then, a corresponding entry would need to be added to the concat.js build file. This doesn't seem worth it to save a few kB in my humble opinion, but it's all very possible.
If you're interested in a much more modular upload library where almost every feature is represented as an optional standalone module, take a look at Modern Uploader, which I am slowly developing as time allows. Feel free to open up issues in the repo if you have any questions regarding the future of that product.


text:
Q: BouncyCastle Provider Jar causes Java Heap Space Error Has Anyone run into this problem?
I am trying to use BouncyCastle to Create Certificate in Android but as soon as I have added BouncyCastle Provider Jar, I get Java Heap Space problem, Eclipse crashes with OutOfMemory error.
All I am doing is following, which is similar to Example code in bouncy castle,
public static X509Certificate createMasterCert(
    PublicKey pubKey,
    PrivateKey privKey)
    throws Exception
{
    //
    // signers name
    //
    String issuer = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate";

    //
    // subjects name - the same as we are self signed.
    //
    String subject = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate";

    //
    // create the certificate - version 1
    //
    X509v1CertificateBuilder v1CertBuilder = new JcaX509v1CertificateBuilder(
        new X500Name(issuer),
        BigInteger.valueOf(1),
        new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
        new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
        new X500Name(subject),
        pubKey);

    X509CertificateHolder cert = v1CertBuilder.build(new JcaContentSignerBuilder("SHA1withRSA").setProvider(BC).build(privKey));

    return new JcaX509CertificateConverter().setProvider(BC).getCertificate(cert);
}

A: To increase the heap space follow these steps:

*

*Right Click on your project in Package Explorer and go to Run As and click Run Configuration and find the name of your class.

*In the Arguments tab(next to Main tab) inside the box labeled VM arguments write -mx256m

A: I suspect something is wrong with the program e.g. long loop, high memory need or so..Not aware of the jar so unable to comment.
If you want to run eclipse with increased heap, run the command below to start the eclipse:
    eclipse [normal arguments] -vmargs -Xmx512M

set the size as per your need.
Alternatively, you can open eclipse.ini under your eclipse root directory and update the vmargs param:
  .......
  -vmargs
  -Xms40m
  -Xmx512m <---Update this value

Once done, restart the eclipse.

A: Modify
--launcher.XXMaxPermSize
256m

to
--launcher.XXMaxPermSize
512m

A: If this code is being executed in Android, increasing Eclipse's heap size will do nothing for you, because it simply has nothing to do with it. The heap size of Android applications is fixed and you cannot increase it (not before Honeycomb anyway). What version of Android are you using? Additionally, the BouncyCastle libraries are part of Android, so even if you add them to your project, it will use the system ones, which are slightly different and this can lead to subtle (and not so subtle) errors. IF you want to use BC on pre-Honeycomb (3.0) platforms you need to change the package name or include Spongy Castle which already does this for you.