Q: Regex help: My regex pattern will match invalid Dictionary I hope you guys can help me out.
I'm using C# .Net 4.0
I want validate file structure like

const string dataFileScr = @"
Start 0
{
    Next = 1
    Author = rk
    Date = 2011-03-10
/*  Description = simple */
}

PZ 11
{
IA_return()
}

GDC 7
{
    Message = 6
    Message = 7
        Message = 8
        Message = 8
    RepeatCount = 2
    ErrorMessage = 10
    ErrorMessage = 11
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}
";

So far I managed to build this regex pattern

const string patternFileScr = @"
^
((?:\[|\s)*

     (?<Section>[^\]\r\n]*)
 (?:\])*
 (?:[\r\n]{0,}|\Z))
(
    (?:\{)                  ### !! improve for .ini file, dont take {
    (?:[\r\n]{0,}|\Z)
        (                          # Begin capture groups (Key Value Pairs)
        (?!\}|\[)                    # Stop capture groups if a } is found; new section

          (?:\s)*                     # Line with space
          (?<Key>[^=]*?)            # Any text before the =, matched few as possible
          (?:[\s]*=[\s]*)                     # Get the = now
          (?<Value>[^\r\n]*)        # Get everything that is not an Line Changes

         (?:[\r\n]{0,})
         )*                        # End Capture groups
    (?:[\r\n]{0,})
    (?:\})?
    (?:[\r\n\s]{0,}|\Z)
)*

                ";

and c#

  Dictionary <string, Dictionary<string, string>> DictDataFileScr
            = (from Match m in Regex.Matches(dataFileScr,
                                            patternFileScr,
                                            RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline)
               select new
               {
                   Section = m.Groups["Section"].Value,

                   kvps = (from cpKey in m.Groups["Key"].Captures.Cast().Select((a, i) => new { a.Value, i })
                           join cpValue in m.Groups["Value"].Captures.Cast().Select((b, i) => new { b.Value, i }) on cpKey.i equals cpValue.i
                           select new KeyValuePair(cpKey.Value, cpValue.Value)).OrderBy(_ => _.Key)
                           .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)

               }).ToDictionary(itm => itm.Section, itm => itm.kvps);

It works for

const string dataFileScr = @"
Start 0
{
    Next = 1
    Author = rk
    Date = 2011-03-10
/*  Description = simple */
}

GDC 7
{
    Message = 6
    RepeatCount = 2
    ErrorMessage = 10
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}
";

in other words

Section1
{
key1=value1
key2=value2
}

Section2
{
key1=value1
key2=value2
}

, but

*1. not for multiple keyname,  i want group by key and output

DictDataFileScr["GDC 7"]["Message"] = "6|7|8|8"
DictDataFileScr["GDC 7"]["ErrorMessage"] = "10|11"

*2. not work for .ini file like

....
[Section1]
key1 = value1
key2 = value2

[Section2]
key1 = value1
key2 = value2
...

*3. dont see next section after

....
PZ 11
{
IA_return()
}
.....

A: Do yourself and your sanity a favor and learn how to use GPLex and GPPG.  They are the closest thing that C# has to Lex and Yacc (or Flex and Bison, if you prefer) which are the proper tools for this job.
Regular expressions are great tools for performing robust string matching, but when you want to match structures of strings that's when you need a "grammar".  This is what a parser is for.  GPLex takes a bunch of regular expressions and generates a super-fast lexer.  GPPG takes the grammar you write and generates a super-fast parser.
Trust me, learn how to use these tools ... or any other tools like them.  You'll be glad you did.

A: Here is a complete rework of the regex in C#.
Assumptions : (tell me if one of them is false or all are false)

*

*An INI file section can only have key/value pair lines in its body

*In an non INI file section, function calls can't have any parameters

Regex flags :
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.Singleline

Input test:

const string dataFileScr = @"
Start 0
{
    Next = 1
    Author = rk
    Date = 2011-03-10
/*  Description = simple */
}

PZ 11
{
IA_return()
}

GDC 7
{
    Message = 6
    Message = 7
        Message = 8
        Message = 8
    RepeatCount = 2
    ErrorMessage = 10
    ErrorMessage = 11
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}

[Section1]
key1 = value1
key2 = value2

[Section2]
key1 = value1
key2 = value2
";

Reworked regex:

const string patternFileScr = @"
(?<Section>                                                              (?# Start of a non ini file section)
  (?<SectionName>[\w ]+)\s*                                              (?# Capture section name)
     {                                                                   (?# Match but don't capture beginning of section)
        (?<SectionBody>                                                  (?# Capture section body. Section body can be empty)
         (?<SectionLine>\s*                                              (?# Capture zero or more line(s) in the section body)
         (?:                                                             (?# A line can be either a key/value pair, a comment or a function call)
            (?<KeyValuePair>(?<Key>[\w\[\]]+)\s*=\s*(?<Value>[\w-]*))    (?# Capture key/value pair. Key and value are sub-captured separately)
            |
            (?<Comment>/\*.+?\*/)                                        (?# Capture comment)
            |
            (?<FunctionCall>[\w]+\(\))                                   (?# Capture function call. A function can't have parameters though)
         )\s*                                                            (?# Match but don't capture white characters)
         )*                                                              (?# Zero or more line(s), previously mentionned in comments)
        )
     }                                                                   (?# Match but don't capture beginning of section)
)
|
(?<Section>                                                              (?# Start of an ini file section)
  \[(?<SectionName>[\w ]+)\]                                             (?# Capture section name)
  (?<SectionBody>                                                        (?# Capture section body. Section body can be empty)
     (?<SectionLine>                                                     (?# Capture zero or more line(s) in the section body. Only key/value pair allowed.)
        \s*(?<KeyValuePair>(?<Key>[\w\[\]]+)\s*=\s*(?<Value>[\w-]+))\s*  (?# Capture key/value pair. Key and value are sub-captured separately)
     )*                                                                  (?# Zero or more line(s), previously mentionned in comments)
  )
)
";

Discussion
The regex is build to match either non INI file sections (1) or INI file section  (2).
(1) Non-INI file sections These sections are composed by a section name followed by a body enclosed by { and }.
The section name con contain either letters, digits or spaces.
The section body is composed by zero or more lines. A line can be either a key/value pair (key = value), a comment (/* Here is a comment */) or a function call with no parameters (my_function()).
(2) INI file sections
These sections are composed by a section name enclosed by [ and ] followed by zero or more key/value pairs. Each pair is on one line.

A: # 2. not work for .ini file like
Won't work because as stated by your regular expression, an { is required after [Section].
Your regex will match if you have something like this :

[Section]
{
key = value
}

A: Here is a sample in Perl. Perl doesen't have named capture arrays. Probably because of backtracking.
Maybe you can pick something out of the regex though. This assumes there is no nesting of {} bracktes.
Edit Never content to leave well enough alone, a revised version is below.
use strict;
use warnings;

my $str = '
Start 0
{
    Next = 1
    Author = rk
    Date = 2011-03-10
 /*  Description = simple
 */
}

asdfasdf

PZ 11
{
IA_return()
}

[ section 5 ]
  this = that
[ section 6 ]
  this_ = _that{hello() hhh = bbb}

TOC{}

GDC 7
{
    Message = 6
    Message = 7
        Message = 8
        Message = 8
    RepeatCount = 2
    ErrorMessage = 10
    ErrorMessage = 11
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}
';

use re 'eval';

my $rx = qr/

\s*
( \[ [^\S\n]* )?                     # Grp 1  optional ini section delimeter '['
(?<Section> \w+ (?:[^\S\n]+ \w+)* )  # Grp 2  'Section'
(?(1) [^\S\n]* \] |)                 # Condition, if we matched '[' then look for ']'
\s*

(?<Body>                   # Grp 3 'Body' (for display only)
   (?(1)| \{ )                   # Condition, if we're not a ini section then look for '{'

   (?{ print "Section: '$+{Section}'\n" })  # SECTION debug print, remove in production

   (?:                           # _grp_
       \s*                           # whitespace
       (?:                              # _grp_
            \/\* .*? \*\/                    # some comments
          |                               # OR ..
                                             # Grp 4 'Key'  (tested with print, Perl doesen't have named capture arrays)
            (?<Key> \w[\w\[\]]* (?:[^\S\n]+ [\w\[\]]+)* )
            [^\S\n]* = [^\S\n]*              # =
            (?<Value> [^\n]* )               # Grp 5 'Value' (tested with print)

            (?{ print "  k\/v: '$+{Key}' = '$+{Value}'\n" })  # KEY,VALUE debug print, remove in production
          |                               # OR ..
            (?(1)| [^{}\n]* )                # any chars except newline and [{}] on the condition we're not a ini section
        )                               # _grpend_
        \s*                          # whitespace
    )*                           # _grpend_  do 0 or more times
   (?(1)| \} )                   # Condition, if we're not a ini section then look for '}'
)
/x;

while ($str =~ /$rx/xsg)
{
    print "\n";
    print "Body:\n'$+{Body}'\n";
    print "=========================================\n";
}

__END__

Output
Section: 'Start 0'
  k/v: 'Next' = '1'
  k/v: 'Author' = 'rk'
  k/v: 'Date' = '2011-03-10'

Body:
'{
    Next = 1
    Author = rk
    Date = 2011-03-10
 /*  Description = simple
 */
}'
=========================================
Section: 'PZ 11'

Body:
'{
IA_return()
}'
=========================================
Section: 'section 5'
  k/v: 'this' = 'that'

Body:
'this = that
'
=========================================
Section: 'section 6'
  k/v: 'this_' = '_that{hello() hhh = bbb}'

Body:
'this_ = _that{hello() hhh = bbb}

'
=========================================
Section: 'TOC'

Body:
'{}'
=========================================
Section: 'GDC 7'
  k/v: 'Message' = '6'
  k/v: 'Message' = '7'
  k/v: 'Message' = '8'
  k/v: 'Message' = '8'
  k/v: 'RepeatCount' = '2'
  k/v: 'ErrorMessage' = '10'
  k/v: 'ErrorMessage' = '11'
  k/v: 'onKey[5]' = '6'
  k/v: 'onKey[6]' = '4'
  k/v: 'onKey[9]' = '11'

Body:
'{
    Message = 6
    Message = 7
        Message = 8
        Message = 8
    RepeatCount = 2
    ErrorMessage = 10
    ErrorMessage = 11
    onKey[5] = 6
    onKey[6] = 4
    onKey[9] = 11
}'
=========================================


Q: How to update element at the arraylist on Android I had used arraylist to recycleview like this :
product.add(new InfoProduct(R.drawable.cloth, Product_title, "0", Product_data2, lunch));

I want to overwrite R.drawable.cloth when I click it , how can I do ?!

A: productList.get(0).setDrawableId(R.drawable.new_cloth_id); Type any position what you want instead of '0'. And then notify adapter.

A: Please make model(get/set) class of InfoProduct and in onClick of item you'll get the position. On that position you can set drawable to different drawable.


Q: I'm simply trying to create a file in python3, but the standard answers are not working Simple task with answers all over the web. I just can't get any of them to work. When I run the code below on macOS, I get the following error messages:
open error: [Errno 1] Operation not permitted: 'test_60'
Path error: [Errno 1] Operation not permitted: 'test_60'
mknod error: [Errno 1] Operation not permitted
The complete test program follows. What stupid thing am I doing wrong?
#!/usr/local/bin/python3
from pathlib import Path
import os

db_file = "test_60"
#
try:
    open(db_file, 'a').close()
except OSError as e:
    print('open error:', e)
try:
    Path(db_file).touch()
except OSError as e1:
    print('Path error:', e1)

try:
    os.mknod(db_file)
except OSError as e2:
    print('mknod error:', e2)


Q: ngInfiniteScroll handler not firing with specific CSS & div structure I've purchased an Angular template to build a web app and I'm struggling to get the scroll event handler to fire using ngInfiniteScroll v1.2.0 (NOTE: the handler does fire once if I set infinte-scoll-immediate-check to true) . I've reproduced the issue by building the same div structure and CSS that came with the template using jsFiddle:
jsFiddle link
This is the structure that I have to work within because of the template:

And this is the CSS that is being used by each of the divs:
.padding {
    padding: 32px 32px;
}
.box .box-inner {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
.box .box-row .box-cell {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: auto;
    -webkit-overflow-scrolling: touch;
}
.box .box-row {
    display: table-row;
    height: 100%;
}
.box {
    display: table;
    width: 100%;
    height: 100%;
    border-spacing: 0;
    table-layout: fixed;
}
.app-content {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 100%;
    overflow-y: auto;
}

If I comment out the five surrounding divs, everything works fine. I'm not a CSS guy so this "table structure" that is being used is causing me some problems. Any help would be appreciated!


Q: Make a DIV cover entire page, but WITHOUT using CSS position I want to make a div with a background-color of red to cover my entire page, but I do not want to use CSS position: absolute. Here is my example with CSS position:

CSS position works for the most part, but then I am unable to create more than one of these divs (they overlap or cancel each other out because of top: 0 and left: 0). When you scroll down, I want you to see additional divs.
It would really help if there was a pure CSS solution, but JavaScript and HTML are open to me as well. JUST NO JQUERY.

A: What about using viewport height and viewport width?
I've created an example in this JSFiddle.

body, html {
    margin: 0;
    padding: 0;
}

div {
    width: 100vw;
    height: 100vh;
}

.one {
    background-color: blue;
}

.two {
    background-color: green;
}

.three {
    background-color: yellow;
}

A: If you want to make div to occupy entire space use vw and vh
because making div alone height:100% and width:100% would not do it
without using viewport units
check this snippet

div{
 width: 100%;
  height:100%;
  background:red;

}

html,body{
  height:100%;
   width:100%;
  }

but making html and body to have height and width is a bad idea
so to skip it use view port units
check this with viewport unist

div {
  width: 100vw;
  height: 100vh;
  background: red;
}

Hope it helps

A: Older browsers such as IE7 and 8 could be supported without using visual height and width units by using a single absolutely positioned container with inner divs inheriting height and width property values.
CSS
body {
   margin: 0px;  /* optional */
}
#box {
   position:absolute;
   height: 100%;
   min-width: 100%;
}
.page {
   padding: 5px; /* optional */
   height: inherit;
}

HTML

25em

2

3

Update: the width property of the container has been replaced by a min-width property, introduced in IE7, to fix an ugly horizontal scrolling issue. Supplying width for inner div elements was removed as being unnecessary.

A: Simply change the top: value for each one. The first one would be 0, the second 100%, the third 200%, and so on. Here's a working example:


Q: Error: error MSB8020: The builds tools for v120 (Platform Toolset = 'v120') cannot be found I have both VS 2012 and 2013 installed in my computer and for some projects need 2012 version. using msbulid in shell command I have the following error:
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Microsoft.Cpp.Platform.targets(44,5): error MSB8020: The builds tools for v120 (Platform Toolset = 'v120') cannot be found

Would you please let me know how could I change msbuild option to use VS 2013?
Please Do not ask me to uninstall the VS 2012 version, because it is crucial for some other projects.


Q: Workaround for piping to an if-statement in powershell? I wanted to pipe an object to a PowerShell if-statement, but it doesn't work:
for($i = 1; $i -le 70; $i++) {
    Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101" | if ($_.ProvisioningState -eq 'Succeeded') {
    Remove-AzureRmRedisCache $_ -Force
}}

"The term 'if' is not recognized as the name of a cmdlet, function, script file, or operable program". So what should I do instead?

A: you need to do something like this:
Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101" | where { $_.ProvisioningState -eq 'Succeeded' } |
    Remove-AzureRmRedisCache -Force

You filter with Where-Object.
Alternatively you can do:
$cache = Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101"
if ( $cache.ProvisioningState -eq 'Succeeded' ) { do stuff }

or this (UGLY):
if ( (Get-AzureRmRedisCache -Name "isi$i" -ResourceGroupName "iaas101").ProvisioningState -eq 'Succeeded' ) { do stuff }


Q: Jest: How to test get descriptor of Object I'm trying to test object and return his descriptors using jest. In my case the object contains get function. I believe my syntax is wrong here:
get: function number() {
    return this.x;
},

Any ideas how to fix it?
Here the example:
let obj = {
    x: 10,
    get number() {
        return this.x;
    },
};

test('Return property descriptors of obj', () => {
    expect(Object.getOwnPropertyDescriptors(obj)).toMatchObject({
        x: {
            value: 10,
            writable: true,
            enumerable: true,
            configurable: true
        },
        number: {
            get: function number() {
                return this.x;
            },
            set: undefined,
            enumerable: true,
            configurable: true
        }
    });
});

And result:

A: The assertion fails because get: function number() {...} isn't the same function as in the descriptor, function number() {} !== function number() {}.
It should be asserted to be any function with:
    ...
    number: {
        get: expect.any(Function),
        set: undefined,
        enumerable: true,
        configurable: true
    }
    ...


Q: Undefined class OneSignal I use Laravel 5.2 and want to use berkayk/laravel-onesignal package, and I installed this package step by step according to Guide on github.
But when I want to use this package I get "Undefined class OneSignal", also I run this artisan command in the terminal:
php artisan config:clear
php artisan config:cache

I try this code in controller
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use OneSignal;
use App\Http\Requests;

class SignalController extends Controller
{

    public function index()
    {
        OneSignal::sendNotificationToAll("Some Message");
    }
}

I get this error

A: You should use full namespace for the facade:
\OneSignal::sendNotificationToAll("Some Message");

Or add this to the top of your class:
use OneSignal;

A: You should write use OneSignal top of the class underneath the namespace.
Hope this work for you!


Q: Not receiving emails, but Mailgun shows 100% delivery rate I'm using a CMS to send emails when a form is submitted. Its configured to use smtp.mailgun.org:587 with the username postmaster@domain.com. I'm using Google Apps for my email, so in this case the email account I'm receiving emails at is support@domain.com. Customers fill out a form and enter their email address is used as the "from" address and the "to" address is support@domain.com. I don't see anything in my Junk folder in Gmail. Mailgun is getting all the emails and marking them as sent/received, but I simply am not getting the emails in Gmail, thus not getting support emails from my customers. What gives?

A: Issue was I had mxa.mailgun.org and mxb.mailgun.org added in my MX Records on my host (Linode). Removing those records fixed the issue.


Q: How can I read another program's STDOUT from a Ruby program line by line? I have a small test Ruby program called "count", which counts 1..50.
#!/usr/bin/ruby
#count
for i in 1..50 do
 STDOUT.puts i
 sleep 1
end

I want to call it from another program, and read the outputted numbers line by line, and output them from the other program, line by line.
However my construction doesn't work:
IO.popen("count","r+") {|f| puts f.readline}

What should I do to make it work? Maybe some modification in the test program "count"?

A: If you have some patience (about 50s worth), you'll see that you do get one line of output and that line will be "1\n". You have two problems:

*

*count is using buffered output. This means that nothing will show up in your stdin until count's output buffer is full; given the small number of bytes that you're printing, the buffer won't be flushed until count finishes.

*Your popen block is only looking for one line.

You can solve the first one by using STDOUT.sync = true to turn off the output buffering in count:
STDOUT.sync = true
for i in 1..50 do
  STDOUT.puts i
  sleep 1
end

Then in your popen, you can iterate over the lines using each:
IO.popen("count","r+") { |fp| fp.each { |line| puts line } }

Then you should one line of output showing up each second.


Q: How to modify selectWithKeyChar()'s function in JComboBox.java? I have a combo box that contains items that start with special characters (ie. À).
Currently, when using the combo box, if you press a key (ie. "a"), it selects an item that starts with the same first letter - but it wouldn't select the one that starts with the special character..
Is there a way to modify the method selectWithKeyChar() in JComboBox.java to ignore the special characters and and treat it like a regular character?
Solutions I have thought of but don't know how to implement:
1) Passing in a temporary combo box model to selectWithKeyChar() that doesn't include the accents. If this is possible, how do you pass in the model to selectWithKeyChar()?
2) Overriding the selectWithKeyChar() method?
3) Making a custom method. In this case, how would you make it run instead of the one that already exists in JComboBox.java?
Here is a minimal example of my setup:

*

*create a new project

*create a new file that has a JPanel form file type

*add a combo box with the following items: "Àpplebee", "Test", "Able"

*call the JPanel in the main:

   SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run(){
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.getContentPane().add(new B());
            frame.pack();
            frame.setVisible(true);
        }
    });

A:
1) Passing in a temporary combo box model to selectWithKeyChar() that
  doesn't include the accents. If this is possible, how do you pass in
  the model to selectWithKeyChar()?
2) Overriding the selectWithKeyChar() method?
3) Making a custom method. In this case, how would you make it run
  instead of the one that already exists in JComboBox.java?

All of this are possible, You can create a temp ComoBoxModel and you extends JComboBox to override selectWithKeyCharacter on your CustomComboBox. Here is the sample of a code:
CustomComboBox.java
public class CustomComboBox extends JComboBox<String>{

private static final long serialVersionUID = 1L;

public CustomComboBox(String[] items) {
    super(items);
}

@Override
public boolean selectWithKeyChar(char keyChar) {
    int index;

    ComboBoxModel<String> tempModel = getModel(); // Put the model on temp variable for saving it for later use.

    String[] itemsArr = new String[getModel().getSize()];
    for(int i = 0; i < getModel().getSize(); i++) {
        // This will normalizes the Strings
        String normalize = Normalizer.normalize(getModel().getElementAt(i), Normalizer.Form.NFD);
        normalize = normalize.replaceAll("\\p{M}", "");
        itemsArr[i] = normalize;
    }

    if ( keySelectionManager == null )
        keySelectionManager = createDefaultKeySelectionManager();

    setModel(new DefaultComboBoxModel<String>(itemsArr)); // Set the Temporary items to be checked.
    index = keySelectionManager.selectionForKey(keyChar,getModel());
    setModel(tempModel); // Set back the original items.

    System.out.println(index);
    if ( index != -1 ) {
        setSelectedIndex(index);
        return true;
    }
    else
        return false;
}
}

If you will test it, even if you enter a normal char 'a', it will select the element in JComboBox with accent or with non-accent.
TestMain.java
public class TestMain {
public static void main(String[] args) {
    String[] lists = {"ápa","Zabra","Prime"};
    CustomComboBox combo = new CustomComboBox(lists);
    System.out.println(combo.selectWithKeyChar('A'));

    JFrame frame = new JFrame("Sample");
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(null);
    frame.setVisible(true);
    combo.setSize(70, 30);
    combo.setLocation(100, 100);
    frame.add(combo);
}
}


Q: Ruby gem mechanize throwing an error : undefined method `<=>' I am using the Ruby gem mechanize to scrape some html... When I load my page and display the necessary results, the page laods fine. After a reload, I get this error when doing "search_results = @agent.submit(search_form)":
undefined method `<=>' for {emptyelem <input name="hl" value="en" type="hidden">}:Hpricot::Elem

Before I post any code, just does this ring any bells?
Thanks.
Code:
    start = Time.now

    # initial set up
    @agent = Mechanize.new
    Mechanize.html_parser = Hpricot
    page = @agent.get("http://www.google.com/")
    search_form = page.forms.first

    # conduct initial search
    @search_term = search_form.q = params[:search].to_s
    search_results = @agent.submit(search_form)

    # helper variables
    search_qs = ""; @page_number = 1; i = 0; @flag = false;

    # get the query string structure
    search_results.links.each { |li| search_qs = li.href if li.href.match(/.*search\?q=.*start=.*/) }

    # search through all paginated pages
    while (i < 500)
      search_qs = search_qs.gsub(/start=\d+/,"start=#{i}")
      @search_url = "http://google.com#{search_qs}"
      search_results = @agent.get(@search_url)
      search_results.links.each { |li| @flag = true if li.text.match("All Bout Texas Tailgating") }
      break if @flag
      i+=10; @page_number+=1
    end

@execution_time = Time.now-start

render :layout => false

VIEW:

Query results for "<%= @search_term %>" on Google

<% if @flag %>

What page is this keyword found: <%= @page_number %>

<%= link_to  "Click to see page", "#{@search_url}", {:target => "_blank"} %>

How long did this query take to run?: <%= @execution_time %> seconds

<% else %>

Keyword not found in Google search reults

<% end %>

STACK TRACE:
 NoMethodError (undefined method `<=>' for {emptyelem <input name="hl" value="en" type="hidden">}:Hpricot::Elem):
  mechanize (1.0.0) lib/mechanize/form/field.rb:30:in `<=>'
  mechanize (1.0.0) lib/mechanize/form.rb:171:in `sort'
  mechanize (1.0.0) lib/mechanize/form.rb:171:in `build_query'
  mechanize (1.0.0) lib/mechanize.rb:373:in `submit'
  app/controllers/admin/importer_controller.rb:24:in `check_page_rank'
  /opt/local/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
  /opt/local/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
  /opt/local/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
  /opt/local/lib/ruby/1.8/webrick/server.rb:162:in `start'
  /opt/local/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
  /opt/local/lib/ruby/1.8/webrick/server.rb:95:in `start'
  /opt/local/lib/ruby/1.8/webrick/server.rb:92:in `each'
  /opt/local/lib/ruby/1.8/webrick/server.rb:92:in `start'
  /opt/local/lib/ruby/1.8/webrick/server.rb:23:in `start'
  /opt/local/lib/ruby/1.8/webrick/server.rb:82:in `start'

Rendered rescues/_trace (98.4ms)
Rendered rescues/_request_and_response (1.2ms)
Rendering rescues/layout (internal_server_error)

A: So if you look through the source for mechanize in form.rb - form submitting is calling a function called build_query which sorts the fields on the form.  Since sort uses the <=> operator, and it's undefined on Hpricot elements, you are getting an exception.
It seems as if mechanize was built to use Nokogiri - it may have unfixed bugs with other parsing implementations.  I did not get too deep into mechanize's source and don't want to blame anyone, but you may want to try switching to Nokogiri for this project (if possible).  It doesn't seem from this snippet as if you're relying heavily on Hpricot.  It seems strange to me that mechanize is throwing an exception on a hidden form field from Hpricot, but the stack trace is pretty clear in this regard.
Your other major option is to hop into the mechanize source and see if you can fix it yourself (or file a bug on the mechanize github and hope somebody gets to it).
Good luck.


Q: How do I assign 2 different variable to the return values from a function that return 2 values? Sorry for the very messy title. What I have is a function that returns 2 different values:
def func(name):

return value1, value2

Now I would like to assign these 2 values to variables in one line. This is what I have tried:
x,y = func(name)[0] , [1]

The x variable is assigned correctly, but the y variable is assigned just assigned as [1].
If it relevant: The [0] is an array and the [1] is a DataFrame form a .csv file.

A: You are close. It's even simpler than you think, you can extract without reference to indices:
def func(name):
    # do something
    return value1, value2

x, y = func(var)

func returns a tuple (note parentheses are not required). You can then unpack via sequence unpacking. I would advise you choose variable names that are informative.


Q: Calling a URL in jQuery I would like to call a URL. Currently I am using a hidden iFrame to call this URL:
var data = {File: file,NAME: 'file.txt'};
<iframe src="requestFile?'+ $.param(data) + '" style="display: none;" ></iframe>

Now I would like to use AJAX to call the file. The file just has to be called.
I tried it with a GET request:
$.ajax({
    'url' : 'requestFile?'+ decodeURIComponent($.param(data)),
    'type' : 'GET',
    'success' : function(data) {
      if (data == "success") {
        alert('request sent!');
      }
    }
  });

Unfortunately this does not work. May there be a problem with the length of the URL? The file string is quite long. I do not get an error message.

A: Rather than use the decodeURIComponent($.param(data)), simply use the encode method .param as $.param(data),
decodeURIComponent does just what it says, decodes it and you want to use the encoded which $.param should do for you:  http://api.jquery.com/jquery.param/
NOTE: on that page they use the decodeURIComponent in an example so you can see the original decoded value/put it in a variable.
Reworked code (my assumption is that you DO return "success" string and not the actual file here?):
var myparam = var data = {File: file,NAME: 'file.txt'};
$.ajax({
    url: 'requestFile?' + $.param(myparam),
    type: 'GET'
}).done(function (data) {
    if (data == "success") {
        alert('request sent!');
    }
});

NOTE: You did not show how file was defined so I can only make the assumption that it is a JavaScript object somewhere.


Q: Can't build apk with the last android studio when the sdk version is changed to 4.4 I am creating a project that can run on android 4.4.
When pressing 'F4'  ( open module setting ), I see that the 'Compile sdk version is on API 23: Android 6.0 (Marshmallow)
But my cellPhone is with version 4.4.2, so I move the version back as I define when I create the project => to  API 19: Android 4.4 (KitKat)
Now, nothing works ... the IDE can't find the 'R' anywhere ... and I can't compile it.
I try to clear and rebuild the project
I try to click on the 'sync'
when i leave compile SDK at 23 and set your TARGET SDK to 19 .. the debug is not run on my cellphone.
but nothing .. not working.
Any help please ...
10x

A: Leave your compile SDK at 23, set your TARGET SDK to 19.


Q: Auto It Script Debugging I have a simple script that works on my PC but not on three others. I am running the script directly from SciTE on all the machines, including my own. Anyway, is there something I can turn on to see what's happening?
Script:
While True
WinSetOnTop("[TITLE:Production Floor Display]","", 1)
Sleep(20000)
WinSetOnTop("[TITLE:Production Floor Display]","", 0)
WinSetOnTop("[TITLE:Preview Image]","", 1)
Sleep(5000)
WinSetOnTop("[TITLE:Preview Image]","", 0)
Wend

A: No, at least not natively.
What are you trying to achieve?
Try compiling the program before doing anything else.
If that is what it looks like (something to do with an industrial camera feed), then you're better off just using Javascript, PHP, NGINX and HTML. That would also be uncomparable to your approach in terms of reliability.


Q: Knockout foreach binding inside a binding (array within an array) i have two classes; users and readings. this relates to healthcare to each user has an array of readings:
/*
 * Reading class
 * containts health readings
 */
function Reading(date,weight,glucose)
{
    var self = this;

    self.date=ko.observable(date);
    self.weight=ko.observable(weight);
    self.glucose=ko.observable(glucose);

      self.formattedWeight = ko.computed(function(){
        var formatted = self.weight();

        return formatted+" lb"
    });
}

/*
 * User class
 * contains a user name, date, and an array or readings
 */
function User(name,date,readings) {
    var self = this;

    self.name = name;
    self.date = date;
    self.readingsArray = ko.observableArray([
        new Reading(99,99)
    ]);
}

i know how to use a foreach binding to display the information for a reading or a user. but im not sure how to show the readings inside of a user?
is there a way to use a nested foreach binding or a with binding? here is my html:

Users ()

        User name	Date

        <input data-bind="value: name" />
        <input data-bind="value: date" />

        Remove

<button data-bind="click: addUser">Add User</button>

Readings ()

       Date	Weight	Glucose

and here is my model if anyone is interested. any help would be greatly appreciated! Thanks in advance!
// Overall viewmodel for this screen, along with initial state
function userHealthModel() {
    var self = this;
    self.inputWeight = ko.observable();
    self.inputDate = ko.observable();
    self.inputId = ko.observable();
    self.inputGlucose = ko.observable();

    // Operations
    self.addUser = function(){
        self.users.push(new User("",0,0,(new Reading(0,0))));
    }
    //adds a readings to the edittable array of readings (not yet the reading array in a user)
    self.addReading = function(){
        var date = self.inputDate();
        var weight = self.inputWeight();
        var glucose = self.inputGlucose();
        if((weight&&date)||(glucose&&date))
        {
            self.readings.push(new Reading(date,weight,glucose));
        }
        else{
            alert("Please complete the form!")
        }
    }

    self.removeUser = function(userName){self.users.remove(userName)}

    //editable data
     self.readings = ko.observableArray([
        new Reading(12,99,3),new Reading(22,33,2),
        new Reading(44,55,3)
    ]);

      self.users = ko.observableArray([
        new User("George",2012),
        new User("Bindu",2012)
    ]);

}

ko.applyBindings(new userHealthModel());

A: I'm not sure how you want the Readings rendered, but here is an example:
http://jsfiddle.net/jearles/aZnzg/
You can simply use another foreach to start a new binding context, and then render the properties as you wish.


Q: How To Enter Words Into This Program? He told me to put any words into this program and I can see one transform to the other, but I have no idea where to insert the words I want. I downloaded CodeBlocks because it looked like the best C++ runner according to Google but when I click run it just says I need two strings. Guessing that means words.
Can anyone look at this and tell me how to insert 2 words?
The Program:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

#define MIN(X,Y) ((X <= Y) ? X:Y)
#define MIN3(A,B,C) ((A <= MIN(B,C)) ? A : MIN(B,C))

class EDIST {
private:
  string _s1, _s2;
  int _edit_distance;

  enum backtrace_pointer { L, D, U };
  // L==left, D==diagonal, U==up.

  vector<vector<int> > dp_table;
  vector<vector<int> > backtrace;

public:
  EDIST(const char *a, const char *b) {
    _s1 = a;
    _s2 = b;
    _edit_distance = 0;
  }

  void run();

private:
  int edit_distance() const { return _edit_distance; }
  void dp_edit_distance();
  void print_dp_tables();
  void init_dp_tables();
  void print_solution();
};

void EDIST :: print_dp_tables()
{
  cout << "\nPrinting dynamic programming table\n";

  cout << "\t_";
  for ( int i=0; i < _s2.size(); i++ )
    cout << "\t" << _s2[i];
  cout << endl;

  for ( int i=0; i <= _s1.size(); i++ ) {
    if ( i ) cout << _s1[i-1];
    else cout << "_";

    for ( int j=0; j <= _s2.size(); j++ )
      cout << "\t" << dp_table[i][j];
    cout << endl;
  }

  cout << "\nPrinting backtrace table\n";

  cout << "\t_";
  for ( int i=0; i < _s2.size(); i++ )
    cout << "\t" << _s2[i];
  cout << endl;

  for ( int i=0; i <= _s1.size(); i++ ) {
    if ( i ) cout << _s1[i-1];
    else cout << "_";

    for ( int j=0; j <= _s2.size(); j++ ) {
      cout << "\t";
      if ( backtrace[i][j] == L ) cout << "L";
      else if ( backtrace[i][j] == D ) cout << "D";
      else cout << "U";
    }
    cout << endl;
  }
}

void EDIST :: init_dp_tables()
{
  for ( int i=0; i <= _s1.size(); i++ ) {
    vector <int> v;
    vector<int> b;

    for ( int j=0; j <= _s2.size(); j++ ) {
      int n=0, op=0;;

      if ( !i ) { n=j; op=L; }
      else if ( !j ) { n=i; op=U; }
      else { n=0; op=D; }

      v.push_back(n);
      b.push_back(op);
    }

    dp_table.push_back(v);
    backtrace.push_back(b);
  }

  for ( int i=0; i <= _s1.size(); i++ )
    dp_table[i][0] = i;

  for ( int j=0; j <= _s2.size(); j++ )
    dp_table[0][j] = j;
}

void EDIST :: dp_edit_distance()
{
  for ( int j=1; j <= _s2.size(); j++ ) {

    for ( int i=1; i <= _s1.size(); i++ ) {

      int a = dp_table[i-1][j]+1;
      int b = dp_table[i-1][j-1];
      int c = dp_table[i][j-1]+1;

      if ( _s1[i-1] != _s2[j-1] )
    b++;

      dp_table[i][j] = MIN3(a,b,c);

      if ( a == dp_table[i][j] ) backtrace[i][j] = U;
      else if ( b == dp_table[i][j] ) backtrace[i][j] = D;
      else backtrace[i][j] = L;
    }
  }
}

void EDIST :: print_solution()
{
  vector<string> string_sequence;
  string_sequence.push_back(_s2);

  int i = _s1.size();
  int j = _s2.size();

  while ( i || j ) {

    string s = string_sequence[string_sequence.size()-1];

    bool add_string=true;
    int new_i=i, new_j=j;

    if ( backtrace[i][j] == L ) {//LEFT :: insert
      new_j--;
      s.erase(j-1,1);
    }
    else if ( backtrace[i][j] == U ) {//UP : delete
      new_i--;
      string sub1 = (j >= 1 ? s.substr(0,j) : "");
      string sub2 = (j < s.size() ? s.substr(j) : "");
      s = sub1 + _s1[i-1] + sub2;
    }
    else {//DIAGONAL : replace OR no-operation
      new_i--;
      new_j--;
      if ( i && j && dp_table[i][j] != dp_table[new_i][new_j] )
    s.replace(j-1,1,_s1.substr(i-1,1));
      else
    add_string = false;
    }

    if ( add_string ) {
      string_sequence.push_back(s);
      _edit_distance++;
    }

    i = new_i;
    j = new_j;
  }

  cout << "\nEdit distance : " << edit_distance() << endl;

  if ( string_sequence.size() )
    cout << "\nPrinting mutations : \n";

  for ( int i=string_sequence.size()-1; i >= 0; i-- )
    cout << "\t" << string_sequence[i] << endl;

}

void EDIST :: run()
{
  cout << "\nFinding edit-distance between strings `";
  cout << _s1 << "' and `" << _s2 << "'" << endl;

  init_dp_tables();
  dp_edit_distance();
  print_dp_tables();
  print_solution();
}

int main(int argc, char *argv[])
{
  if ( argc != 3 ) {
    cerr << "Need 2 strings as input!\n" << endl;
    exit(1);
  }

  EDIST e(argv[1], argv[2]);
  e.run();

  return 0;
}

A: When you downloaded the program you probably got a .exe file, you need to execute this program with two command line arguments like so:
programname.exe word1 word2

If your friend didn't give you a executable file you need to compile the source into an executable. CodeBlocks provides this functionality and automatically runs the compiled result. Unfortunately it doesn't pass any arguments to the result which is why the program is telling you that it needs two words. (CodeBlocks is just executing programname.exe)
One solution to this problem is to configure code blocks to provide the arguments. As danben pointed out you can use the "Set program arguments" option in the "Project" menu to configure it to provide arguments. If you set your program arguments as word1 word2 then CodeBlocks will execute programname.exe word1 word2 which is what you want.
If you want to run this program elsewhere you need to compile it. Luckily whenever you click "run" in CodeBlocks it actually does compile an executable somewhere, typically in the project folder under bin\debug or bin\release you'll find a exectuable file. You can use this file as outlined above.

A: This is a question about CodeBlocks rather than about C++, but a quick Google search reveals that you need to select the "Set program arguments" option under the "Project" menu.


Q: EC2 Instance not available in ECS I have created an EC2 instance via Terraform with the following configuration:

*

*EC2 instance is using the latest Amazon ECS-Optimized Amazon Linux 2 AMI.

*Instance is sitting in a private subnet, with a route to a NAT GW. Tested internet connectivity fine.

*SG rules are configured correctly.

*EC2 Instance profile is using AmazonEC2ContainerServiceforEC2Role

*EC2 user-data is configured (with my cluster name) with:
echo ECS_CLUSTER=my-cluster-name >> /etc/ecs/ecs.config
When I go to my ecs-cluster, no instances show in the EC2 Instance section of the console.
Is there anything else I'm missing as to why this cluster can't register with the EC2 instance?


Q: Simfony2-Twig: Render only a single part of a template I have a homepage wich dynamically loads a bunch of "posts" (similar to facebook wall).
There is the option to follow a post, but when someone clicks on the follow button, which has a counter on following people, I need to reload all the homepage to update this value. How can I update just the part corresponding to the post? Actually the post is in an extern hmtl.twig file which I render from the homepage code:

         {% for sueno in suenos %}
            {% if loop.index0 is even %}
                {{ render(controller('SuenoBundle:Default:suenoFrontend', { 'sueno': sueno } )) }}
            {% endif %}
         {% endfor %}

This is the controller:
public function suenoFrontendAction($sueno)
{
        return $this->render('SuenoBundle:Default:suenoFrontend.html.twig', array(
        'sueno' => $sueno));
}

This the post html file:

{{ sueno.usuario.nombre ~ ' ' ~ sueno.usuario.apellido }}

                  {% if sueno.necesitaAyuda == 1 %}

                  {% endif %}
                  {% if sueno.rol == 'foto' %}

                  {% elseif sueno.rol == 'video' %}

                  {% endif %}

{{ sueno.titulo }}

{{ sueno.quePido }}

{{ sueno.texto }}

                            {% set size = sueno.usuariosColaboradores | length %}
                            {% set size2 = sueno.usuariosSeguidores | length %}

                             {{ size }}

                             {{ size2 }}

Here you can see the action correpsonding to follow a post(its in the previous code, I remark the line):
 {{ size2 }}

size2 value is the one to update. the controller called when clicking here is this(and where I suppose the failure is):
    public function seguirAction($suenoid)
{

    $em = $this->getDoctrine()->getManager();

    $usuario = $this->getUser();

    $sueno = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array('id' => $suenoid));

    $usuario->getSuenosSigue()->add($sueno);
    $em->persist($usuario);
    $em->flush();

  // $suenos = $em->getRepository('SuenoBundle:Sueno')->findBy(array('usuario' => $usuario->getId()));

    //esto hay que cambiarlo entero para conseguir los sueños apropiados
        //return $this->render('EstructuraBundle:Home:home.html.twig', array('suenos'=> $suenos , 'usuario' => $usuario));
                return $this->render('SuenoBundle:Default:suenoFrontend.html.twig', array(
        'sueno' => $sueno));
}

The thing is that when this render happens, the post fills the full page.
What I want is just to re-render this post in the homepage


Q: How to validate the Content-MD5 header (from the actual content) in a RequestInterceptor (WCF REST Starter Kit) - REST web service I'm implementing REST web services by means of the WCF REST Starter Kit.
I get the request in a System.ServiceModel.Channels.RequestContext.
Specifically: the interceptor starts this way: Public Overrides Sub ProcessRequest(ByRef requestContext As RequestContext)
If the request includes the Content-MD5 header, I must validate the provided hash against the actual content body, right? Because this does not happen 'automatically'. Nobody (IIS, or whoever) is verifying this for me, as I first thought it would happen.
I thought doing this content verification would be easy. I just have to get the request body as a string and compare the result of my GenerateChecksumForContent() with the hash included in the header.
How to compute the MD5 from the content:
Public Shared Function GenerateChecksumForContent(ByVal content As String) As String
    ' Convert the input string to a byte array and compute the hash.
    Dim hashed As Byte() = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(content))
    ' Convert the hash to a Base64 Encoded string and return it
    Return Convert.ToBase64String(hashed)
End Function

How to get the Content-MD5 request Header value:
Dim message As Message = requestContext.RequestMessage
Dim reqProp As HttpRequestMessageProperty = DirectCast(message.Properties(HttpRequestMessageProperty.Name), HttpRequestMessageProperty)
Dim contentMD5HeaderValue As String = reqProp.Headers("Content-MD5")

My problem is that I don't know how to do something so apparently simple as compute the Content-MD5 of the request's body.
I could not find any built-in property telling me this information (the content's MD5 current hash value).
I've tried this, but it does not work:
Dim content As String = requestContext.RequestMessage.GetBody(Of String)()
Dim computedMD5 As String = GenerateChecksumForContent(content)

In addition, what would happen after the RequestInterceptor run and the 'real' method process the content? The content would be lost because it was already read?
Should I in addition do something like ".CreateBufferedCopy()" to keep the request body available for the post-RequestInterceptor processing?
I cannot understand why this is so complicated! It should be something trivial, but as you can see, I'm completely lost.
Please someone, help me...
Many thanks,
Horacio.-

A: Here are two MSDN pages that give an answer to your question:

*

*http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx

*http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx
Hopefully one of them will be sufficient.


Q: In a json embedded YAML file - replace only json values using Python I have a YAML file as follows:
api: v1
hostname: abc
metadata:
  name: test
  annotations: {
    "ip" : "1.1.1.1",
    "login" : "fad-login",
    "vip" : "1.1.1.1",
    "interface" : "port1",
    "port" : "443"
  }

I am trying to read this data from a file, only replace the values of ip and vip and write it back to the file.
What I tried is:
open ("test.yaml", w) as f:
    yaml.dump(object, f) #this does not help me since it converts the entire file to YAML

also json.dump() does not work too as it converts entire file to JSON. It needs to be the same format but the values need to be updated. How can I do so?

A: What you have is not YAML with embedded JSON, it is YAML with some the value for annotations being
in YAML flow style (which is a superset of JSON and thus closely resembles it).
This would be
YAML with embedded JSON:
api: v1
hostname: abc
metadata:
  name: test
  annotations: |
    {
      "ip" : "1.1.1.1",
      "login" : "fad-login",
      "vip" : "1.1.1.1",
      "interface" : "port1",
      "port" : "443"
    }

Here the value for annotations is a string that you can hand to a JSON parser.
You can just load the file, modify it and dump. This will change the layout
of the flow-style part, but that will not influence any following parsers:
import sys
import ruamel.yaml

file_in = Path('input.yaml')

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.width = 1024
data = yaml.load(file_in)
annotations = data['metadata']['annotations']
annotations['ip'] = type(annotations['ip'])('4.3.2.1')
annotations['vip'] = type(annotations['vip'])('1.2.3.4')
yaml.dump(data, sys.stdout)

which gives:
api: v1
hostname: abc
metadata:
  name: test
  annotations: {"ip": "4.3.2.1", "login": "fad-login", "vip": "1.2.3.4", "interface": "port1", "port": "443"}

The type(annotations['vip'])() establishes that the replacement string in the output has the same
quotes as the original.
ruamel.yaml currently doesn't preserve newlines in a flow style mapping/sequence.
If this has to go back into some repository with minimal chances, you can do:
import sys
import ruamel.yaml

file_in = Path('input.yaml')

def rewrite_closing_curly_brace(s):
    res = []
    for line in s.splitlines():
        if line and line[-1] == '}':
            res.append(line[:-1])
            idx = 0
            while line[idx] == ' ':
                idx += 1
            res.append(' ' * (idx - 2) + '}')
            continue
        res.append(line)
    return '\n'.join(res) + '\n'

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.width = 15
data = yaml.load(file_in)
annotations = data['metadata']['annotations']
annotations['ip'] = type(annotations['ip'])('4.3.2.1')
annotations['vip'] = type(annotations['vip'])('1.2.3.4')
yaml.dump(data, sys.stdout, transform=rewrite_closing_curly_brace)

which gives:
api: v1
hostname: abc
metadata:
  name: test
  annotations: {
    "ip": "4.3.2.1",
    "login": "fad-login",
    "vip": "1.2.3.4",
    "interface": "port1",
    "port": "443"
  }

Here the 15 for width is of course highly dependent on your file and might influence other lines if they
were longer. In that case you could leave that out, and make the wrapping
that rewrite_closing_curly_brace() does split and indent the whole flow style part.
Please note that your original, and the transformed output are, invalid YAML,
that is accepted by ruamel.yaml for backward compatibility. According to the YAML
specification the closing curly brace should be indented more than the start of annotation


Q: issue with fx scene builder Hey I got this error when trying to start my fx application. I'm using icons which I believe are part of an external jar (com.gluonhq.charm.glisten.control). So I downloaded the jar and put it in referenced libraries, nothing happened. Then added it as an external annotation to the fx library. Didn't solve the problem. Any idea's?

javafx.fxml.LoadException:  /C:/Users/Gebruiker/eclipse-workspace/Pyxus/bin/application/Layout.fxml

at
  javafx.fxml/javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2863)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2707)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2676)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2542)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)    at
  application.Main.start(Main.java:18)  at
  javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:919)
    at
  javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$11(PlatformImpl.java:449)
    at
  javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$9(PlatformImpl.java:418)
    at java.base/java.security.AccessController.doPrivileged(Native
  Method)   at
  javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:417)
    at
  javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at
  javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native
  Method)   at
  javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
    at java.base/java.lang.Thread.run(Thread.java:844) Caused by:
  java.lang.ClassNotFoundException:
  com.gluonhq.charm.glisten.control.Icon    at
  java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at
  java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2931)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2920)
    at
  javafx.fxml/javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2861)
    ... 15 more


Q: Force couchdb to reference attachments instead of duplicate in new revision I have a problem with attachments in couchdb.
Let's say I have a document with a big attachment (100 MB). It means that each time you're modifying the document (not the attachment, just one field of the document), it will duplicate the 100 MB attachment.
Is it possible to force couchdb to create references of attachments when they are not modified (couchdb can easily verify if the attachment has been modified with the MD5)?
Edit:
According to this it should be able to do it but how? Mine (personal install) doesn't do it by default!

A: Normally, what you expect to find is the default behaviour of CouchDB. I think it could depend on how the API is used however. For example, following sample scenario works fine (on CouchDB 1.5)
All commands are given in bash syntax, so you can reproduce easily (just make sure to use correct document id and revision numbers).
Create 10M sample file for upload
dd if=/dev/urandom of=attach.dat bs=1024 count=10240
Create test DB
curl -X PUT http://127.0.0.1:5984/attachtest
Database expected data_size is about few bytes at this point. You can query it as follows, and look for data_size attribute.
curl -X GET http://127.0.0.1:5984/attachtest
which gives in my test:
{"db_name":"attachtest","doc_count":1,"doc_del_count":0,"update_seq":2,"purge_seq":0,"compact_running":false,"disk_size":8287,"data_size":407,"instance_start_time":"1413447977100793","disk_format_version":6,"committed_update_seq":2}
Create sample document
curl -X POST -d '{"hello": "world"}' -H "Content-Type: application/json" http://127.0.0.1:5984/attachtest
This command gives an output with document id and revision, which are then should be used hereafter
Now, attach sample file to the document; command should use id and revision as logged in the output of the previous one:
curl -X PUT --data-binary @attach.dat -H "Content-Type: application/octet-stream" http://127.0.0.1:5984/attachtest/DOCUMENT-ID/attachment\?rev\=DOCUMENT-REVISION-1
Last command output denotes that revision 2 have been created, so the document was updated indeed. One can check the database size now, which should be around 10000000 (10M). Again, looking for data_size in the following command's output:
curl -X GET http://127.0.0.1:5984/attachtest
Now, geting the document back from DB. It will be used then to update it. Important to have in it:

*

*the _rev in the document, to be able to update it

*attachment stub, to denote that attachment should not be deleted, but kept intact

curl -o document.json -X GET http://127.0.0.1:5984/attachtest/DOCUMENT-ID
Update document content, not changing the attachment itself (keeping the stub there). Here this will simply change one attribute value.
sed -i 's/world/there/' document.json
and update document in the DB
curl -X PUT -d @document.json -H "Content-Type: application/json" http://127.0.0.1:5984/attachtest/DOCUMENT-ID
Last command output denotes that revision 3 have been created, so we now that the document is updated indeed.
Finally, now we can verify the database size! Expected data_size is still around 10000000 (10M), not 20M:
curl -X GET http://127.0.0.1:5984/attachtest
And this should work fine. For example, on my machine it gives:
{"db_name":"attachtest","doc_count":1,"doc_del_count":0,"update_seq":8,"purge_seq":0,"compact_running":false,"disk_size":10535013,"data_size":10493008,"instance_start_time":"1413447977100793","disk_format_version":6,"committed_update_seq":8}
So, still 10M.

A:
It means that each time you're modifying the document (not the
  attachment, just one field of the document), it will duplicate the 100
  MB attachment.

In my testing I found the opposite - the same attachment is linked through multiple revisions of the same document with no loss of space.
Please can you retest to be certain of this behaviour?


Q: Copying Conditional Formatting without adding to the data set I have an inventory and ordering management Sheet where I use color coding via Sheets Conditional Formatting to make some cells quickly visible as having outstanding orders.  In my particular case, I am using conditional formatting based on a neighboring cell.
The sheet I built utilizes several columns for ordering cycles with our suppliers.  When I am ready to move on to the next ordering cycle, I copy and paste a set of columns to create the new cycle.
The problem that I encounter is this: the new column's Conditional Formatting gets added to the old, both in terms of adding a new column to format, but also referencing the cell from which the copied columns use to decide whether to format.
Original Order Block
In this second image, I have pasted a new order block from Columns AD-AL to Columns AM -AU.
Pasted Order Block
There are two things that I am trying to solve:

*

*I would expect the custom formula to update to =$AR5<>"", but it holds on to the Original Order Block's formula, thus applying the formatting from cells that are in the Original Order Block.

*I would expect the range to update to only the new range of AQ5:AQ397, rather than add the additional range to the original order block range.
Each order block needs the conditional formatting to be independent from the one which it was copied.
Thanks in advance.

A: In this case, you can just remove the "$" from your custom formula and it will move just fine
Your ranges are going to be together as you shown, but will look at the cell at its right


Q: Python Binary Search Tree with key and value I need to implement a Binary Search Tree class as homework but I struggle making the insert function. I have looked through Google a lot to find some solutions or possibilities on how to do it but none of them has used a key and value (mostly just value) or if they used a key aswell, they had tons of seperate functions which I am not allowed to do I think.
So the pre-built is simply that:
class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.left = self.right = None

class BinarySearchTree:
    def __init__(self):
        self.root = None
        self.size = 0

    def __len__(self):
        return self.size

    def insert(self, key, value):
        pass

    def remove(self, key):
        pass

    def find(self, key):
        pass

Now the thing is, if I want to check for example whether the value is smaller or bigger than a current Node to put it either right or left, I get Errors such as "root is not defined" or "root.right" has no such attribute etc...
And I guess that makes sense because self.root is declared as None.
But how do I actually fix it now to make the insert function work?
I am a little confused by this task as it uses key + value, so I need to insert the value bound to the specific key and in case the key already existed, overwrite its value.

A: its 5 in the morning so this might be all wrong, but here goes:
the key is what we are sorting by, the values aren't interesting
your insert function should probably look something like this:
def insert(self, key, value):
        if self.root = None:
            self.root = Node(key,value)
            return
        #regular binary tree traversal (comparing the key) to find where to insert, lets assume we need to insert on the left
        parent.left = Node(key,value)

can you figure it out from here or would you like more direction

A: You didn't specify, but I'm guessing the point of the keys is to determine if a particular key is already in the tree, and if so, replace the related node's value in O(1) runtime complexity.
So when you're inserting a node, you will first check the dictionary for the key (you will initialize an empty dictionary yourself in __init__). If it already is there, then you simply just need to replace the value of the node for that particular key. Otherwise, you add the new node the same way that you would in any BST, and also remember to update your dictionary to map the key to it's node.


Q: Three.js wrong texture on ShaderMaterial I'm trying to use a shaderMaterial to adjust the brightness and contrast on one object (the sphere for VR video)
Here is how I implement the ShaderMaterial
var geometry = new THREE.SphereGeometry( 500, 60, 40 );

var panoTexture = new THREE.VideoTexture( video );
panoTexture.minFilter = THREE.LinearFilter;
panoTexture.magFilter = THREE.LinearFilter;
panoTexture.format = THREE.RGBFormat;

// var material   = new THREE.MeshLambertMaterial( { map : texture } );

var shader = THREE.BrightnessContrastShader;
shader.uniforms[ "contrast" ].value = 0.0;
shader.uniforms[ "brightness" ].value = 0.0;
shader.uniforms[ "texture" ].texture = panoTexture;

var panoMaterial   = new THREE.ShaderMaterial(shader);

panoVideoMesh = new THREE.Mesh( geometry, panoMaterial );

And here is the code I'm using for the shader
THREE.BrightnessContrastShader = {

    uniforms: {

        "tDiffuse":   { type: "t", value: null },
        "brightness": { type: "f", value: 0 },
        "contrast":   { type: "f", value: 0 },
        "texture":   { type: "t", value: 0 }

    },

    vertexShader: [

        "varying vec2 vUv;",

        "void main() {",

            "vUv = uv;",

            "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

        "}"

    ].join("\n"),

    fragmentShader: [

        "uniform sampler2D tDiffuse;",
        "uniform float brightness;",
        "uniform float contrast;",

        "varying vec2 vUv;",

        "void main() {",

            "gl_FragColor = texture2D( tDiffuse, vUv );",

            "gl_FragColor.rgb += brightness;",

            "if (contrast > 0.0) {",
                "gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - contrast) + 0.5;",
            "} else {",
                "gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + contrast) + 0.5;",
            "}",

        "}"

    ].join("\n")

};

When the sphere is rendered it's using another more recently generated texture that is for another part of the scene.
How do I keep the video texture on the panoTexture, is this possible and and am I going about this the right way?

A: This worked
shader.uniforms[ "tDiffuse" ].value = panoTexture;


Q: What if any, programming fundamentals are better learned in C as opposed to C++? As a person who wanted to increase his fundamental programming skills, I chose to learn C++ instead of C.  Which leads me to ask:  Is there any fundamental skills that I leave in C that might not be obtained by learning C++?
Related question: Should I learn C before learning C++?

A: I don't think there are any skills that you can learn in C but not C++, but I would definitely suggest learning C first still. Nobody can fit C++ in their head; it may be the most complex non-esoteric language ever created. C, on the other hand, is quite simple. It is relatively easy to fit C in your head. C will definitely help you get used to things like pointers and manual memory management much quicker than C++. C++ will help you understand OO.
Also, when I say learn C, it's okay to use a C++ compiler and possibly use things like iostreams if you want, just try to restrict yourself to mostly C features at first. If you go all out and learn all the weird C++ features like templates, RAII, exceptions, references, etc., you will be thoroughly confused.

A: Compare the following code examples (apologies, my C++ is a little rusty).
C++:
int x;

std::cin >> x;

C:
int x;

scanf("%d", &x);

So, what do you see above?  In C++, a value is plugged into a variable.  That's cool, but what does it teach us?  In C, we notice a few things. The x has a funny & in front of it, which means it's address is being passed.  That must mean that the scanf function actually needs to know where in memory x is.  Not only that, but it needs a format string, so it must not really hvae any idea of what address you're giving it and what format it's getting information in?
C lets you discover all these wonderful things about how the Computer and the Operating System actually work, if you will put effort towards it.  I think that's pretty cool.

A: There is certainly one thing: memory management. Take following code for example:
struct foo {
   int bar;
   char **box;
};

struct foo * fooTab = (struct foo *) malloc( sizeof(foo) * 100 );
for(int i = 0; i<100; i++) {
   fooTab[i].bar = i;
   fooTab[i].box = (char **) malloc( sizeof(char *) * 10 );
   for(int j = 0; j<10; j++) {
      fooTab[i].box[j] = (char *) malloc( sizeof(char) * 10 );
      memset(fooTab[i].box[j], 'x', 10);
   }
}

Using C++ you simply do not deal with memory allocation in such way. As a result, such skills may be left untrained. This will certainly result in e.g. lower debugging skills. Another drawback may be: lower optimizing skills.
C++ code would look like:
struct foo {
    int bar;
    static int idx;
    vector< vector<char> > box;
    foo() : bar(idx), box(10) {
       idx++;
       for ( auto it = box.begin(); it != box.end(); it++) {
           it->resize(10,'x');
       }
    }
};

int foo::idx = 0;
foo fooTab[100];

As you can see there is simply no way to learn raw memory management with C++-style code.
EDIT: by "C++-style code" I mean: RAII constructors/destructors, STL containers. Anyway I had probably exaggerated, it would be better to say: It is far more difficult to learn raw memory management with C++-style code.

A: I find it's better to learn memory management in C before attempting to dive into C++.
In C, you just have malloc() and free().  You can typecast things around as pointers.  It's pretty straightfoward:  multiply the sizeof() by the # items needed, typecast appropriately, and use pointer arithmetic to jump all over the place.
In C++, you have your various reinterpret_cast<> (vs. dynamic_cast, etc) kind of things, which are important, but only make sense when you're realizing that the various castings are meant to trap pitfalls in multiple inheritance and other such lovely C++-isms.  It's kind of a pain to understand (learn) why you need to put the word "virtual" on a destructor on objects that do memory management, etc.
That reason alone is why you should learn C.  I also think it's easier to (at first) understand printf() vs. the potentially overloaded "<<" operator, etc, but to me the main reason is memory management.

A: I wouldn't say you missed anything fundamental.  Check out Compatibility of C and C++ for a few non-fundamental examples, though.

Several additions of C99 are not supported in C++ or conflict with C++ features, such as variadic macros, compound literals, variable-length arrays, and native complex-number types. The long long int datatype and restrict qualifier defined in C99 are not included in the current C++ standard, but some compilers such as the GNU Compiler Collection[3] provide them as an extension. The long long datatype along with variadic templates, with which some functionality of variadic macros can be achieved, will be in the next C++ standard, C++0x. On the other hand, C99 has reduced some other incompatibilities by incorporating C++ features such as // comments and mixed declarations and code.

A: The simplicity of C focuses the mind wonderfully.
With fewer things to learn in C, there is a reasonable chance that the student will learn those things better.  If one starts with C++ there is the danger of coming out the other end knowing nothing about everything.

A: If all you've ever used is object-oriented programming languages like C++ then it would be worthwhile to practice a little C. I find that many OO programmers tend to use objects like a crutch and don't know what to do once you take them away. C will give you the clarity to understand why OO programming emerged in the first place and help you to understand when its useful versus when its just overkill.
In the same vein, you'll learn what it's like to not rely on libraries to do things for you. By noting what features C++ developers turned into libraries, you get a better sense of how to abstract your own code when the time comes. It would be bad to just feel like you need to abstract everything in every situation.
That said, you don't have to learn C. If you know C++ you can drag yourself through most projects. However, by looking at the lower-level languages, you will improve your programming style, even in the higher-level ones.

A: It really depends on which subset of C++ you learned. For example, you could get by in C++ using only the iostreams libraries; that would leave you without experience in the C stdio library. I'm not sure I would call stdio a fundamental skill, but it's certainly an area of experience one should be familiar with.
Or perhaps manually dealing with C-style null-terminated strings and the str*() set of functions might be considered a fundamental skill. Practice avoiding buffer overflows in the face of dangerous API functions is definitely worth something.

A: This is just a shot in the dark, but perhaps you use function pointers more in C than in C++, and perhaps utilizing function pointers as a skill might be boosted by starting to learn C. Of course all of these goodies are in C++ as well, but once you get your hands on classes it might be easy to just keep focusing on them and miss out on other basic stuff.
You could for example construct your own inheritance and polymorphism "system" in pure C, by using simple structs and function pointers. This needs a more inventive thinking and I think builds up a greater understanding of what is happening "in the box".
If you start with C++ there is a chance that you miss out on these little details that are there in C++ but you never see them, since the compiler does it for you.
Just a few thoughts.

A: Depends on how you approach C++.  I would normally recommend starting at a high level, with STL containers and smart pointers, and that won't make you learn the low-level details.  If you want to learn those, you probably should just jump into C.

A: Playing devil's advocate, because I think C is a good starting point...
Personally, I started learning with C, algorithms, data structures, memory allocation, file manipulation, graphics routines... I would call these the elementary particles of programming.
I next learned C++. To over-simplify, C++ adds the layer of object-oriented programming - you have the same objectives as you do regardless of language, but the approach and constructs you build to achieve them are different: classes, overloading, polymorphism, encapsulation, etc...
It wasn't any educated decision on my part, this is simply how my programming course was structured, and it worked out to be a good curriculum.
Another simplification... C is basically a subset of C++. You can "do C" with C++, by avoiding to use the language features of C++. From the perspective of language features. Libraries are different matter. I don't think you will get past more than just programming 101 without beginning to use and build libraries, and there is enough out there to keep you busy for a lifetime.
If your goal is to learn C++ ultimately, then beginning with "C" could be a logical start, the language is "smaller" - but there is so much in "C" that you would probably want to narrow your focus. You are tackling a bigger beast, but if you get guidance, I see no compelling reason not to, despite the path I took.

A: Most C code can be compiled as C++ code with a few minimal changes. For examples of a very few things that can't be changed see Why artificially limit your code to C?. I don't think any of these could be classed as fundamental though.

A: C is essentially a subset of C++. There are differences as highligted by some of the other answers, but essentially most C compiles as C++ with only a little modification.
The benefits of learning C is that it's a much more compact language and learning it is therefore quicker. C also requires you to work on a relatively low abstraction level which is good for understanding how the computer actually works. I personally grew up with assembly and moved to C from there, which I now see as a definitive advantage in understanding how compilers actually map high abstraction level contstructs to actual machine code.
In C++ you can find yourself quickly entrenched in higher levels of abstraction. It's good for productivity but not necessarily so for understanding.
So my advice is: study C++ if you have the motivation, but first concentrate on the core low level constructs that are common with C. Only then move to the higher level things such as object orientation, templates, extensive class libraries and so on.

A: optimization theory
primarily because the asm output of a C compiler is generally mush more predictable and usually well correlated to the C.  This lets you teach/learn why its better to structure code a certain way by showing the actual instructions generated.

A: You should learn data structures in C.  First, it will force you to really understand pointers, which will help you to deal with leaky abstractions in higher level languages.  Second it will make obvious the benefits of OO.

A: Coding Sytle
By coding style I don't mean {} and whitespace, I mean how you organizing data, classes, files, etc.
I started off learning c++, which usually favors creating classes and organizing things a certain way.  I could write c code just fine when needed, but it was never like the c style code that others wrote who started off with c.
One of my OS classes required us to write a file system in C. My partner was originally a C guy and I was amazed at the difference in the code we wrote.  Mine was obviously trying to use c++ style coding in c.
It's kindof like when you first learn perl or ruby or something and you are just trying to write the same c# code except translated into that new language rather than using that languages features.
While C is a subset of C++, C programs and C++ programs are so different as to not really be comparable.

A: Yes, simple structured programming.
With OOP everywhere, it is easy to forget that you can build sound system just by using modules and functions. C's module system is pretty weak, but still...
This is also one of the advantages of functional programming, in my book. Many functional programming languages have a strong module system. When you need more genericity than simple functions can offer, there are always higher order functions.

A: if you want to learn new skills and you have good fundamentals of structured programing(SP) you should go for C++. learn to think a given problem in an object oriented(OOP) way (define objects, methods, Inheritance, etc) its sometimes the most difficult part. I was in the same situation as you a few years ago, and i choose C++, because learning a new paradigm, a new way of thinking and design software, sometimes its more difficult that the code itself, and if you don't like C++ or OOP you can go back to C and SP, but at least you will have some OOP skills.

A: I would choose C to learn low-level primitives of programming.
For OOP, there are so many other languages to learn before C++ that are much easier to learn. This isn't 1990 when the only OOP languages were Smalltalk and C++, and only C++ was used outside of academia. Almost every new programming language invented since has objects, and almost all are less complex than C++.


Q: Magento 2 wrong product price in cart after removal of category discount In Magento 2 I have created a custom module category discount. When active its working fine for product list, details and cart view page.
But when I remove this discount it shows the original price for list and details page which is correct but mini cart view shows me the discounted price which shouldn't be the case. However if I update the quantity then it's fine.
I don't want to click the update button in the mini cart view for the original price. I want to do this using an observer.


Q: Best practice for handling state change during screen rotation I've got a very simple program with a spinner and toggleButton.
When the button is toggled on I disable the spinner, and enable when I toggle off.
I've come across an issue that means the spinner is re-enabled during screen rotation.
I understand this is due to the activity state changing and onCreate being called again, but I haven't come across a definitive answer on best practice for view states in instances like this.
NOTE: The most relevant SO questions relating to this that I've found are below. All 3 have discussions on how to handle state changes (onPause/OnResume versus overriding onSaveInstanceState), but none seem to clarify which is preferred option for something as simple as this.
Losing data when rotate screen
Saving Android Activity state using Save Instance State
Android CheckBox -- Restoring State After Screen Rotation

A: The accepted answer at Saving Android Activity state using Save Instance State is the way to go.
Use onSaveInstanceState to save a boolean flag indicating whether the spinner is disabled, then read the flag in onCreate (or onRestoreInstanceState) and disable the spinner as necessary.
If you give your views an android:id in the XML layout and don't explicitly set android:saveEnabled to false, their "state" will be saved and restored automatically. For example, for text views, this includes the text currently in the view and the position of the cursor. It appears the enabled/disabled status is not part of this "state", however.

A: How does System retains ListView scroll posion automatically?
You may have noticed that some data does not get affected during rotation even if you have not handled it onSaveInstanceState method. For example

*

*Scrollposition Text in EditText

*Text in EditText etc.

What happens when the screen rotates?
When the screen rotates System kills the instance of the activity and recreates a new instance. System does so that most suitable resource is provided to activity for different configuration. Same thing happens when a full activity goes in multipane Screen.
How does system recreates a new Instance?
System creates a new instance using old state of the Activity instance called as "instance state". Instance State is a collection of key-value pair stored in Bundle Object.

By default System saves the View objects in the Bundle for example.
  eg Scroll position EditText etc.

So if you want to save additional data which should survive orientation change you should override onSaveInstanceState(Bundle saveInstanceState) method.
Be careful while overriding onSaveInstance method!!!
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
     // Save the user's current game state
     savedInstanceState.putInt(STATE_SCORE, mCurrentScore);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

Always call the super.onSaveInstanceState(savedInstanceState) ekse the default behavior will not work. ie EditText value will not persist during orientation. Dont beleive me ? Go and check this code.
Which method to use while restoring data?

*

*onCreate(Bundle savedInstanceState)
OR

*

*onRestoreInstanceState(Bundle savedInstanceState)
Both methods get same Bundle object so it does not really matter where you write your restoring logic. The only difference is that in onCreate(Bundle savedInstanceState) method you will have to give a null check while it is not needed in the latter case.
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mTextView = (TextView) findViewById(R.id.main);
        if (savedInstanceState != null) {
              CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
              mTextView.setText(savedText);
        }
}

OR
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);

    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
}

Always call super.onRestoreInstanceState(savedInstanceState) so that
  System restore the View hierarchy by default.

A:  <activity
        android:name="com.rax.photox.searchx.MainActivity"

        android:configChanges="keyboardHidden|orientation|screenSize"

It worked for me perfectly


Q: change and initialise variables in a function I was wondering if it's possible to change and initialize variables in a function without passing arguments to the function. Here is what I want to achieve:
$foo = 'Lorem';
$array = array();
foobar($foo);
function foobar(){
    if (strlen($foo)== 1)
        $bar = 'Ipsum';
    else
        $array[] = 'error';
}

fubar();
function fubar(){
    if (empty($fouten))
        echo $bar;
}

A: $foo is a local (uninitialized) variable inside a function. It is different from the global variable $foo ($GLOBALS['foo']).
You have two ways:
$foo;
$bar;
$array = array();

function foobar(){
    global $foo, $array, $bar;
    if (strlen($foo)== 1)
        $bar = 'Ipsum';
    else
        $array[] = 'error';
}

or by using the $GLOBAL array …
This is not really good practice though and will become a maintenance nightmare with all those side effects

A: Functions in php can be given arguments that have default values.  The code you posted as written will give you notices for undefined variables.  Instead, you could write:
function foobar($foo = null) {
    if($foo) { // a value was passed in for $foo
    }
    else { // foo is null, no value provided
    }
}

Using this function, neither of the below lines will produce a notice
foobar();
foobar('test');


Q: data exchange between boost::generic_image_library and external class I know how external class data can be transformed into generic image library class, such as the following codes show:
    unsigned char *dst_pixels;
    dst_pixels = new unsigned char [200*500];
    for(int i=0; i<500; i++)
    {
        for(int j=0; j<200; j++)
            dst_pixels[i*200+j]= j;
    }
    gray8c_view_t my_view = interleaved_view(200,500,(const  gray8_pixel_t*)dst_pixels,src_row_bytes);

However, I cannot find a easy way to obtain the image data pointer in the image view class of generic image library, which can be used to communicate with external classes as the following codes show:
unsigend char *p_memory;
p_memory = my_view.get_pointers_to_the_image_data;
functin_work_on_p_memory;

Any ideas will be appreciated.


Q: Get app version from UWP (Windows 10) app A simple question : How to get app version from C# code?
I want to send email from my UWP app and add into it app version to know which version user is using.
App version is stored on Package.appxmanifest, but i didn't want to make a xml reader to get it and i hope there is an esay way to do it.


Q: remove text where regex pattern has trailing backslash doublequote at end of string I have a string from which I need to remove some characters that end in backslash doublequote.  There are multiple matches.  I have it to where it ALMOST works, except I can't get rid of the last backslash double quote (\") in each place that the namespace occurs.
I went to regexpal.com and came up with this regex string that does what I want.
xmlns=*.+be/\\"

But when I put it in C# the two backslashes make it grab way too much.  This code repeats my issue and shows my progress:
var str = "<Request>  <sender xmlns=\"http://stuff.otherstuff.be/\">    <name>Sender name</name>    </sender>  <addressee xmlns=\"http://some.stuff.be/\"> </addressee>  <networkType xmlns=\"http://yet.more.stuff.be/\">11</networkType></Request>";

str = Regex.Replace(str, @"xmlns=.*?\.be/", "", RegexOptions.IgnoreCase);

I wind up with a string that looks like this.  I need to modify the regex a bit to also catch the backslash and double quote
<Request>
    <sender \">
         <name>Sender name</name>
    </sender>
    <addressee \">
    </addressee>
    <networkType \">11</networkType>
</Request>

I've tried various combinations of multiple backslashes and multiple double quotes but am not getting it.
I have looked at a lot of answers here and elsewhere, and haven't figured it out, so a "has duplicate" isn't really going to help me.
EDIT: At this point in the code all I have is a string that came from a serialized class.  I don't really want to load the string into and XMLDocument and do recursive calls like in the possible answer shown.  A quick regex replace should get me what I need in 1 statement.
EDIT:  The answer with adding two doublequotes does not help me because it ignores the final backslash that I'm trying to get rid of.

A: You need to add the trailing quote like this (if using the @ syntax you must use "" to match a one quote):
str = Regex.Replace(str, @"xmlns=.*?\.be/""", "", RegexOptions.IgnoreCase);

Add a space at the beginning if you want <sender> instead of <sender >:
str = Regex.Replace(str, @" xmlns=.*?\.be/""", "", RegexOptions.IgnoreCase);

A: Note that to remove XML namespaces, you can use regular C# code described at How to remove all namespaces from XML with C#?, but since you say that does not help, here is a solution for your special case.
In order to remove any slashes you may use a character class [/\\] - just in case you have both \ and /. Note that a literal backslash must be doubled in a verbatim string literal.
The regex will look like
\s*xmlns=[^<]*?\.be[/\\]"

Here is a regex demo
And in C#:
var rx = new Regex(@"\s*xmlns=[^<]*?\.be[/\\]""");

The \s* will "trim" the whitespace in the resulted replacement.
Results after replacing with string.Empty:


Q: SiteMinder SSO not protecting ASP.NET MVC 5 site This problem may be related to the UrlRoutingModule handling all the routing and bypassing SiteMinder. Any ideas on how may I be able to make SiteMinder's webagent handle the HTTP request before MVC's default request handler?
<system.webServer>
    <!-- SM Server Config -->
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="wa-handler" path="*" verb="*" type="" modules="IsapiModule" scriptProcessor="%NETE_WA_PATH%\ISAPI6WebAgent.dll"
           resourceType="Unspecified" requireAccess="None" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />
    </handlers>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
</system.webServer>

A: Issue Resolved: Apparently, for SiteMinder to protect ASP.NET MVC Apps, it must be upgraded to version R12.5 / WebAgent 7 or higher. Just update SiteMinder on your IIS server and it should start working.


Q: PHP gzipping JSON, saving to memcache... Node.js serving - proper headers? In PHP I am doing something like:
$gzdata = gzencode(json_encode($data), 9);
$mc->set("latest", $gzdata);

So I pull my associative array from the DB, I turn it to JSON, Gzip it and store to memcache
In my Node.js I read the memcached entry and serve it (where client is memcache client)
client.get('latest', function(err, response) {
            if (err) { console.log("GET", err.type ); }
            else{
                result.writeHead(200,{
                    "Content-Type": "application/json",
                    "content-encoding":"gzip"
                });

                result.end(response['latest']);
            }
        });

I am getting

Content Encoding Error

on the page

The page you are trying to view cannot be shown because it uses an
  invalid or unsupported form of compression.

I cannot even check the headers in FB... any ideas what am I doing wrong?

A: Did you know that the Memcache client can already do compression for you?
$memcache_obj = new Memcache;
$memcache_obj->addServer('memcache_host', 11211);
$memcache_obj->setCompressThreshold(20000, 0.2);

This would compress values when larger than 20k with a minimum compression of 20%.
See also: Memcache::setCompressThreshold


Q: How to change color of a container border using radio buttons using JS? I have an issue, I need to create a settings dropdown menu when you can select different themes. The themes have to change the background color and border color, I have the background color working, however I'm struggling to make the border change color.

function changeTheme() {
  if (document.getElementById("theme1").checked = true) {
    document.container.style.backgroundColor = "lightgray";
    document.container.style.borderColor = "red";
  }
}

function bgcolor(color, border) {
  document.body.style.background = color;
  document.body.style.borderColor = border;

}

  <input type="radio" id="theme1" name="theme" value="1" onclick="bgcolor('lightgray', 'red');" onchange="showFeedback('You changed the theme!')">Light

So the container is a square in the middle of the page with a border. When I select one of the themes the background color of the whole page should change and the border color of the container in the middle should change as well.
I tried onclick="changeTheme()but it doesn't work

A: To set a border, you must specify the thickness and style.
Also, don't use inline styles or inline event handlers. Just set a pre-existing class upon the event. And instead of checking to see if the radio button is selected, just use the click event of the button. If you've clicked it, it's selected.
Lastly, if you are using a form field, but only as a UI element and not to actually submit data anywhere, you don't need the name attribute.

document.getElementById("theme1").addEventListener("click", function() {
  document.body.classList.add("lightTheme");
});
.lightTheme { border:1px solid red; background-color:lightgrey; }

  <input type="radio" id="theme1" value="1">Light

A: As @Tyblitz remarked: your "border" needs to be set properly:

function changeTheme() {
  if (document.getElementById("theme1").checked = true) {
    document.container.style.backgroundColor = "lightgray";
    document.container.style.borderColor = "red";
  }
}

function bgcolor(color, border) {
  document.body.style.background = color;
  document.body.style.border = border;

}

  <input type="radio" id="theme1"
   name="theme" value="1"
   onclick="bgcolor('lightgray', '6px solid red');"
   onchange="console.log('You changed the theme!')">Light

A: 2nd Edit :
(Thanks to Scott Marcus answer and Mike 'Pomax' Kamermans comment)

Here is a pen for it.
I create classes for each theme with the naming pattern : prefix "colorTheme" followed by the input value attribute's value.
function themeChange() {
    /* theme class naming pattern : prefix "colorTheme"
     followed by the input "value attribute" 's value */
    var themeCheckedClassValue = "colorTheme" + this.value;

    /* don't do anything if we click on the same input/label */
    if (themeCheckedClassValue != document.body.dataset.currentThemeClass) {

      document.body.classList.remove(document.body.dataset.currentThemeClass);
      document.body.classList.add(themeCheckedClassValue);
      /* new current theme value stored in data-current-theme-class custom
         attribut of body */
      document.body.dataset.currentThemeClass = themeCheckedClassValue;
    }
}

document.addEventListener('DOMContentLoaded', function () {
    /* querySelector and if statement only needed at DOMContentLoaded
       So I did a seperate function for this event */
    var themeChecked = document.querySelector('input[id^="theme"]:checked');
    if (themeChecked) {
        var themeCheckedClassValue = "colorTheme" + themeChecked.value;
        document.body.classList.add(themeCheckedClassValue);
        document.body.dataset.currentThemeClass = themeCheckedClassValue;
    }
    else {
        /* if there is no input with the attribute "checked"
        the custom attribut data-current-theme-class takes the value "null" */
        document.body.dataset.currentThemeClass = null;
    }
});

/* input[id^="theme] mean every input with an id starting with "theme" */
var themeInputs = document.querySelectorAll('input[id^="theme"]');

for (let i = 0; i < themeInputs.length; i++) {
    themeInputs[i].addEventListener("click", themeChange);
}

This way you can simply add new themes by following the same naming pattern.

function themeChange() {
  /* theme class naming pattern : prefix "colorTheme"
     followed by the input "value attribute" 's value */
  var themeCheckedClassValue = "colorTheme" + this.value;

  /* don't do anything if we click on the same input/label */
  if (themeCheckedClassValue != document.body.dataset.currentThemeClass) {

    document.body.classList.remove(document.body.dataset.currentThemeClass);
    document.body.classList.add(themeCheckedClassValue);
    /* new current theme value stored in data-current-theme-class custom
       attribut of body */
    document.body.dataset.currentThemeClass = themeCheckedClassValue;
  }
}

document.addEventListener('DOMContentLoaded', function() {
  /* querySelector and if statement only needed at DOMContentLoaded
     So I did a seperate function for this event */
  var themeChecked = document.querySelector('input[id^="theme"]:checked');
  if (themeChecked) {
    var themeCheckedClassValue = "colorTheme" + themeChecked.value;
    document.body.classList.add(themeCheckedClassValue);
    document.body.dataset.currentThemeClass = themeCheckedClassValue;
  } else {
    /* if there is no input with the attribute checked
    the custom attribut data-current-theme-class takes the value "null" */
    document.body.dataset.currentThemeClass = null;
  }
});

/* input[id^="theme] mean every input with an id starting with "theme" */
var themeInputs = document.querySelectorAll('input[id^="theme"]');

for (let i = 0; i < themeInputs.length; i++) {
  themeInputs[i].addEventListener("click", themeChange);
}
html {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  font-size: 16px;
}

*,
*::after,
*::before {
  -webkit-box-sizing: inherit;
  box-sizing: inherit;
}

body {
  margin: 0;
  padding: 0;
  min-height: 100vh;
  width: 100vw;
  border: 10px solid;
  border-color: transparent;
  -webkit-transition: all .4s;
  transition: all .4s;
}

ul {
  list-style: none;
  margin: 0;
  padding: 10px;
  font-size: 20px;
}

li {
  padding: 2px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

input,
label {
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  outline: none;
}

.colorTheme1 {
  color: rgb(36, 36, 33);
  font-weight: 400;
  background-color: rgb(248, 236, 220);
  border-color: rgb(60, 75, 124);
}

.colorTheme2 {
  background-color: rgb(39, 34, 28);
  border-color: rgb(102, 102, 153);
  color: rgb(248, 236, 220);
  font-weight: 700;
}

.colorTheme3 {
  background-color: rgb(255, 0, 0);
  border-color: rgb(0, 255, 255);
  color: rgb(255, 255, 0);
  font-weight: 700;
}

<input type="radio" id="theme1" name="theme" value="1" checked>Light

      <input type="radio" id="theme2" name="theme" value="2">Dark

      <input type="radio" id="theme3" name="theme" value="3">Flashy