text:
Q: Wicket: double login required due to extended browser info I have a Wicket 8.6 application. Currently, when logging in to the application, mostly (does not always happen) the user has to login twice. After the first login (after entering the credentials and clicking the submit button) a white page appears saying "If you see this, it means that both javascript and meta-refresh are not support by your browser configuration. Please click this link to continue to the original destination." This is the BrowserInfoPage. After a few seconds the user is redirected to the login page again where he/she has to enter his/her credentials again and press the login button. This time, the user logs in successfully. My question is, how do I prevent that the user hast to enter his/her credentials twice.
From my research I know that it has something to do with the collection of extended browser info. In the init method of my WicketApplication class, I had the following code:
getRequestCycleSettings().setGatherExtendedBrowserInfo(true);

However, I already commented out this code several month ago. For some reason, the described effect occurs for every new deploy now. Maybe a newly added package in the application is the reason for it. I don't know. Is there a possibility to prevent this second login maybe by creating a customized bowser info page which forwards the login? Please point me in the right direction. Thanks.

A: After some research, I came up with a work around. It is probably not very efficient but it works for me so far. In my custom Session class which inherits from AuthenticatedWebSession, I added the following code.
    @Override
    protected WebPage newBrowserInfoPage() {
        final Request request = RequestCycle.get().getRequest();
        if(request.getUrl().toString().contains("LoginPage")) {
            if(!isSignedIn()) {
                signIn(username, password);
            }
            PageParametersEncoder encoder = new PageParametersEncoder();
            PageParameters parameters = encoder.decodePageParameters(request.getUrl());
            String url = parameters != null && parameters.get("originUrl") !=null && !parameters.get("originUrl").isNull() && !parameters.get("originUrl").isEmpty()?
                    parameters.get("originUrl").toString("pages/home"):"pages/home";
            String finalUrl=url.startsWith("pages/")?url.substring("pages/".length()):url;
            throw new RedirectToUrlException(finalUrl);
        }
        return super.newBrowserInfoPage();
    }

Some explanation to the code. As mentioned in the question, I want to prevent the user from logging in multiple times. Thus, I check if the request comes from the LoginPage and perform my work around only in that case.
During my implementation, I realized, that the method newBrowserInfoPage is called in the process when I call session.signIn(username,password); on my LoginPage. In this signIn process the authenticate method of my custom Session is called but the signedIn flag in the AuthenticatedWebSession is not changed (keeps false on successfull authentication). Is this a bug? Thus, I have to login again to set the flag to true.
Finally, I read the URL of the LoginPage where I have stored the target URL and forward the user to the target URL.
I am aware this is probably not the best approach but it is the only solution I came up with. If someone has a better idea, I am happy to hear it.


text:
Q: Hashtag within string breaks JavaScript I am trying to save a string to an external file using JavaScript. Below is what I am executing.
var mytext = "1111#1111"
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html";
a.href = "data:text/html," + mytext;
a.click();

This code works perfectly using Chrome. However with Firefox, it stops just prior to the "#". When I look at the resulting output file I see the following:
Results in Chrome look like this
1111#1111
Results in Firefox look like this
1111
It looks to me like the hashtag is breaking something. Can anyone help me understand why the "#" in a string is causing grief in Firefox but not Chrome? I have tried wrapping the string in double quotes as well as single quotes, but it does not appear to have any effect.
Any ideas?

A: You need to add URL Encoding to your string before you submit it.
var mytext = encodeURIComponent( "1111#1111" );
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html";
a.href = "data:text/html," + mytext;
a.click();

More information can be found here: encodeURIComponent
EDIT: And, this is just me btw, but why would you even do data:text/html?   Just seems unnecessary.
You could just as easily submit this via Ajax (or use jQuery's $.ajax if you have that library available).  If you happen to use jQuery, then all of this might be a little easier.  Either way, hope that helps.

A: If I use this in firefox it comes out fine
var mytext = encodeURIComponent("1111#1111");
var a = document.body.appendChild(document.createElement("a"));
a.download = "My_output.html";
a.href = "data:text/html," + mytext;
a.click();

The trick is as always to encode uri components. And what you are passing along is in essense an uri component.
This way all special characters like ? # and + and % will be parsed correctly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: check if dynamically added class is present in order to resize the elements on window.resize in a function i trigger based on the html response from an api a two or one column lay-out and add corresponding classes (one-col or two-col):
if ($('element > table').length) {
    widget.fadeIn().slideDown(time);
    if ($windowWidth < 480){
       $content_main.animate({width: "90%"});
       //class handling
       content_main.removeClass('two-col');
       content_main.addClass('one-col');
       $sidebar_container.animate({width: "90%"});
    }
    if ($windowWidth >= 480 && $windowWidth < 1024 ) {
       $content_main.animate({width: "100%"});
       //class handling
       content_main.removeClass('two-col');
       content_main.addClass('one-col');
       $sidebar_container.animate({width: "100%"});
    }
    if ($windowWidth >= 1024) {
       $content_main.animate({width: "65%"});
       //class handling
       content_main.removeClass('one-col');
       content_main.addClass('two-col');
       $sidebar_container.animate({width: "33%"});
    }
       $('element').slideDown(1000);
    } else {
       if ($windowWidth < 480){
       //class handling
       $content_main.removeClass('two-col');
       $content_main.addClass('one-col');
       $content_main.animate({width: "90%"});
       $sidebar_container.animate({width: "90%"});
    }
       if ($windowWidth >= 480 ) {
       //class handling
       $content_main.removeClass('two-col');
       $content_main.addClass('one-col');
       $content_main.animate({width: "100%"});
       $sidebar_container.animate({width: "0"});
    }

      widget.css({'display':'none'});

   }

this works.
But then i tried to make this work with a resize function:
function resize65(){
  //this if statement is not recognized
  if ($content_main.hasClass("two-col")) {
    if ($windowWidth < 480){
       $content_main.animate({width: "90%"});
      $sidebar_container.animate({width: "90%"});
    }
    if ($windowWidth >= 480 && $windowWidth < 1024 ) {
       $content_main.animate({width: "100%"});
       $sidebar_container.animate({width: "100%"});
    }
    if ($windowWidth >= 1024) {
       $content_main.animate({width: "65%"});
       $sidebar_container.animate({width: "33%"});
     }
  }
}//end function

//call function on resize
$window.on("resize", function () {
      console.log('resized');
      resize65();
  }).resize();

The dynamically added class is not recognized.
I tried various ways (not worth mentioning and spoiling space) to get this to work, but finally i seek help from stackoverflow.


text:
Q: If any potential issues using xpath find/update xml tag text I wrote a script, based on some of the existing StackOverflow questions, but no one perfectly fit my issues.
The user use xpath to find a XML tag from a given XML file, and update the tag text based on user inputs.
Below is my script using Python 3 (The most difficult part for me is around the namespaces):
import xml.etree.ElementTree as ET
import sys

# user inputs and variables
filename = 'actors.xml'
xpath = 'actor/name'
value = 'test name'
temp_namespace = 'temp_namespace'

# get all namespaces
all_namespaces = dict([node for _, node in ET.iterparse(filename, events=['start-ns'])])

# register namespace
for key in all_namespaces.keys():
    ET.register_namespace(key, all_namespaces[key])

# remove all namespace from elements first
# and temp save it to tag attribute
# The below logic is copied from other Stackoverflow answers
# From **Python 3.8**, we can add the parser to insert comments
it = ET.iterparse(filename, parser=ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)))
for _, el in it:
    prefix, has_namespace, postfix = el.tag.partition('}')
    if has_namespace:
        el.tag = postfix
        el.set(temp_namespace, prefix + has_namespace)

# find and update
root = it.root
for el in root.findall(xpath):
    el.text = str(value)

# get xml comments before root level
doc_comments = []
with open(filename, 'r') as f:
    lines = f.readlines()
    for line in lines:
        if line.startswith('<?xml'):
            continue
        if line.startswith('<' + root.tag):
            break
        else:
            doc_comments.append(line)

def add_tag_namespace(el):
    for sub_el in el:
        if temp_namespace in sub_el.attrib.keys():
            sub_el.tag = sub_el.attrib[temp_namespace] + sub_el.tag
            del sub_el.attrib[temp_namespace]
        add_tag_namespace(sub_el)
    if temp_namespace in el.attrib.keys():
        el.tag = el.attrib[temp_namespace] + el.tag
        del el.attrib[temp_namespace]

# add all namespace back
# and delete the temp namespace attribute
add_tag_namespace(root)

# write back to xml file
tree = ET.ElementTree(root)
tree.write(filename, encoding='unicode', xml_declaration=True)

if len(doc_comments) == 0:
    sys.exit()

# write xml comments before root back
lines = []
# first read all lines
with open(filename, 'r') as f:
    lines = f.readlines()
# second, insert xml comments back into memory
for i, line in enumerate(lines):
    if line.startswith('<?xml'):
        insert_at = i + 1
        for comment in doc_comments:
            lines.insert(insert_at, comment)
            insert_at += 1
        break
# finally, write all contents to file
with open(filename, 'w') as f:
    for line in lines:
        f.write(line)

actors.xml:
<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
    </actor>
</actors>


text:
Q: expansion taylor series; mistake? The Taylor series at $x=0$ for $\frac{1}{x-1} = -1 - x - x^2 - x^3 - \cdots$
The Taylor series at $x=0$ for $\frac{1}{e^x-1}=\frac{1}{x}-\frac{1}{2}+\frac{x}{12}-\frac{x^3}{720}+\cdots$
However, when substituting the Taylor series at $x=0$ for $e^x=1+x+\frac{x^2}{2!}+\cdots$ in the first result, there clearly doesn't appear any $\frac{1}{x}$.
Where is the mistake, as I think it's perfectly fine to substitute $e^x$ as the expansion is done around $0.$

A: The issue is basically as follows:

You substitute the Taylor series for $e^x$ (around $0$) to $x$. That would be totally fine... if you indeed had $e^x \to 0$ when $x\to 0$.

But this is not the case. You are basically replacing the approximation of $e^x$ around $x=0$ (which goes to $1$) into something that is asking for a quantity going to $0$.


text:
Q: Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it I am using axios to access the backend when a user registers, it takes their name, email, and password and dispatches REGISTER_SUCCESS when they are successful. When a user fails to register, it dispatches. for dispatch am using redux thunk as middleware so i can write dispatch in arrow function REGISTER_FAILURE, but instead gets the error below. This is stated in the webpack documentation.

topLevelAwait: Support the Top Level Await Stage 3 proposal, it makes
the module an async module when await is used on the top-level. And it
is enabled by default when experiments.futureDefaults is set to true.

But I don't know how to implement this code. I have tried react-scripts webpack.config.js file, but I get another error. Can you please help?
ERROR IN CONSOLE
ERROR in ./src/action/auth.js
    [1] Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
    [1] File was processed with these loaders:
    [1]  * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
    [1]  * ./node_modules/babel-loader/lib/index.js
    [1]  * ./node_modules/source-map-loader/dist/cjs.js
    [1] You may need an additional loader to handle the result of these loaders.
    [1] Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
    [1]     at C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\webpack\lib\dependencies\HarmonyDetectionParserPlugin.js:54:11
    [1]     at Hook.eval [as call] (eval at create (C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:7:16)
    [1]     at Hook.CALL_DELEGATE [as _call] (C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\tapable\lib\Hook.js:14:14)
    [1]     at JavascriptParser.walkAwaitExpression (C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\webpack\lib\javascript\JavascriptParser.js:2337:29)
    [1]     at JavascriptParser.walkExpression (C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\webpack\lib\javascript\JavascriptParser.js:2267:10)
    [1]     at JavascriptParser.walkVariableDeclaration (C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\webpack\lib\javascript\JavascriptParser.js:2121:33)
    [1]     at JavascriptParser.walkStatement (C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\webpack\lib\javascript\JavascriptParser.js:1615:10)
    [1]     at JavascriptParser.walkStatements (C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\webpack\lib\javascript\JavascriptParser.js:1476:9)
    [1]     at C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\webpack\lib\javascript\JavascriptParser.js:1650:9
    [1]     at JavascriptParser.inBlockScope (C:\Users\krish\OneDrive\Desktop\udemy learning 2\dev-connector\client\node_modules\webpack\lib\javascript\JavascriptParser.js:3108:3)
    [1]
    [1] ERROR in [eslint]
    [1] src\action\auth.js
    [1]   Line 14:31:  Unexpected use of 'name'   no-restricted-globals
    [1]   Line 14:37:  'email' is not defined     no-undef
    [1]   Line 14:44:  'password' is not defined  no-undef
    [1]   Line 17:52:  'config' is not defined    no-undef
    [1]   Line 18:3:   'dispatch' is not defined  no-undef
    [1]   Line 26:29:  'dispatch' is not defined  no-undef
    [1]   Line 28:3:   'dispatch' is not defined  no-undef
      },

AUTH.JS FILE
import axios from 'axios';
import { SET_ALERT } from './types';
import { REGISTER_FAILURE, REGISTER_SUCCESS } from './types';

// Register
export const register =
  ({ name, email, password }) =>
  async dispatch => {
    const config = {
      'Content-Type': 'application/json',
    };
  };

const body = JSON.stringify({ name, email, password });

try {
  const res = await axios.post('/api/users', body, config);
  dispatch({
    type: REGISTER_SUCCESS,
    payload: res.data,
  });
} catch (err) {
  const errors = err.response.data.errors;

  if (errors) {
    errors.forEach(error => dispatch(SET_ALERT(error.msg, 'danger')));
  }
  dispatch({
    type: REGISTER_FAILURE,
  });
}

A: The problem was with the axios because  we don't need a config object for axios as the default headers in axios are already Content-Type: application/json also axios stringifies and parses JSON for you, so no need for JSON.stringify or JSON.parse
there is no need to write config file default headers in axios are already Content-Type: application/json
export const register =
  ({ name, email, password }) =>
  async dispatch => {
    const config = {
      'Content-Type': 'application/json',
    };
  };

const body = JSON.stringify({ name, email, password });

change my code to this here formdata contains email,name and password
export const register = (formData) => async dispatch => {
 try {
   const res = await axios.post('/api/users',formData);
   dispatch({
     type: REGISTER_SUCCESS,
     payload: res.data,
   });
 } catch (err) {
   const errors = err.response.data.errors;

   if (errors) {
     errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
   }
   dispatch({
     type: REGISTER_FAILURE,
   });
 }
}


text:
Q: How do I get the current week start date and end date in ksh I want to get the current week start date and end date in shell scripting.
example:
for the current week
start date is 041015
end date is 101015

A: If you have Gnu or recent versions of date, this works.
date -dlast-sunday +%d%m%y

date -dnext-saturday +%d%m%y

Use Perl on Solaris because date command does not support this.
perl -MPOSIX -e '@DateComponents = localtime; print strftime "%d%m%y", localtime time - 86400*(($DateComponents[6]))'

perl -MPOSIX -e '@DateComponents = localtime; print strftime "%d%m%y", localtime time + 86400*(6-($DateComponents[6]))'


text:
Q: Array of objects - Removing an object from the array I have been assigned the task of creating the infamous "UNO" game. I am running into trouble with one of the methods, which is supposed to "delete" one of the card objects in the players hand if they choose to play it. I suppose you have to have played UNO to understand. Anyways, here is the description of what the method should be:

Create a method named removeCardFromHand that takes an integer index as a parameter and both removes and returns the Card at that position of the player's hand. If the specified index does not correspond to one of the cards in the hand, the method should throw an IndexOutOfBoundsException.
  After the card has been removed, the remaining cards should be rearranged as needed so that they occupy the leftmost positions of the array. One way to do this is to move the rightmost card into the position of the card that is being removed. For example, if the hand is currently the four cards {blue 3, red 2, yellow 7, green 1} and you are removing the card at position 1 (the red 2), you could replace it with the last card (the green 1), and thus the resulting hand would be: {blue 3, green 1, yellow 7}.

I am unfortunately not allowed to use an Array List or Vectors, just simple old arrays
Here is my code so far:
public Card removeCardFromHand(int n)
{
    Card c = cards[n];
    for(int i = n; i < cards.length; i--)
    {
        cards[n] = cards[n + 1];
    }
    c = cards[cards.length - 1];
    return c;
}

Obviously this isn't right, but I'm just not sure what to do.

A: You pretty much got it, except that you are moving all cards in the array one position to the left, so you are dropping the leftmost card, and you leave the "removed" card in the array, unless it happens to be the left most one.
You want to be doing the moving only starting at the card to the right (higher index) of the removed card. Since I think this is homework, I'll let you figure out the one expression you need to change ;-)

A: Assuming the array is created with a static size. You would not be able to change the array size by reassigning the length of the array. Probably giving you errors about trying to do that.
In the Class
Add a new variable in the Class, ie. int numberOfCardsInHand.

In the method removeCardFromHand
Make a copy of the card to discard, i.e. discardCard.

Iterate from i = n to i < numberOfCardsInHand
  Left shift the remaining cards to the right of the discarded card.

Decrement numberOfCardsInHand by 1.

Return discardCard


text:
Q: How to fix PHP Warning: file_get_contents? I'm getting following warning:
Warning: file_get_contents(C:\xampp\htdocs\test/wp-content/themes/test\images) [function.file-get-contents]: failed to open stream: Permission denied in ..\plugins\theme-check\main.php on line 29

The line 29 of main.php reads as:
$other[$filename] = file_get_contents( $filename );

Here is code related to $files:
$files = listdir( $theme );

$files = array_merge( listdir( $parent ), $files );

if ( $files ) {
        foreach( $files as $key => $filename ) {
            if ( substr( $filename, -4 ) == '.php' ) {
                $php[$filename] = php_strip_whitespace( $filename );
            }
            else if ( substr( $filename, -4 ) == '.css' ) {
                $css[$filename] = file_get_contents( $filename );
            }
            else {
                $other[$filename] = file_get_contents( $filename );
            }
        }

        // run the checks
        $failed = !run_themechecks($php, $css, $other);

As far I have understood, its the permission error. As the file can't seem to access that folder. I'm using XAMPP on Windows 7. I dont know how can i change the folder permissions on windows.
PS. Please notice the folder path in the warning, it has \ and also /.
I don't want to turn off the Warning etc., instead want to fix the warning.

A: Marc B hit it on the head. You need to add a test to check if the filename is a directory with php function is_dir($filename)
   if ( $files ) {
    foreach( $files as $key => $filename ) {
        if ( substr( $filename, -4 ) == '.php' ) {
            $php[$filename] = php_strip_whitespace( $filename );
        }
        else if ( substr( $filename, -4 ) == '.css' ) {
            $css[$filename] = file_get_contents( $filename );
        }
        else {
            if(!is_dir($filename)) $other[$filename] = file_get_contents( $filename );
        }
    }

Edit
If you are doing something like a directory view online. You could go further and include the directories in a seperate array and sort them and list them out first. and then list the files. I have created something like this for a dynamic gallery.

A: Try using this PHP function to replace the windows path: getcwd().
You will need to concatenate the file names.


text:
Q: I want to use google API (Voice commands) on my PC I want to use google API (Voice commands) on my PC but now I don't know, how to i begin that,Please someone to guide me about this and post some project for example

A: It is true that Google speech recognition is one of the best and that it is now available offline but in my experience,  is much more oriented to Android applications and web rather than Desktop ones. If what you want is to integrate speech recognition to a website, you could find some examples in the Web Speech API.
Now, if what you need is to incorporate speech recognition to desktop applications I would recommend Microsoft's speech recogntition, Nuance or Sphynx.
Please also see this useful answer


text:
Q: Python - Using function in parent from child

I am trying to make a module that when imported can be used to easily define commands for an interactive 'console'. However this requires me to be able to run a function from the parent file, which when I do so I get this: <function Test at 0x027234B0> instead of the function being run.
I am somewhat new to using classes and modules in python so I am not sure what I am meant to be doing.
Here is the module for the Menu (Menu.py): (Not complete, just trying to get this working)

I have just an imbecile and forgot to put the thing in quotes
class Menu:
    def __init__(self):
        self.temp=0
        self.menuobj = dict()

    def add(self, command, function):
        self.menuobj[command] = function
        print(command)
        return 0

    def debug(self):
        print(self.menuobj)

    def lookup(self, command):
        return self.menuobj[command]

    def mainloop(self):
        while 1:
            x = input("> ")
            try:
                self.menuobj[x]()

            except KeyError:
                print("Not Found")

if __name__ == "__main__":
    print("This module is meant to be imported")

And the module that calls it:
import Menu
def Men():
    a = Menu.Menu()
    a.add("1",Test)
    a.mainloop()

def Test():
    print(Test)

Men()

A: The issue is in your Test() function, not that its not getting called -
def Test():
    print(Test)

You are printing the reference to Test itself, hence it prints what you get - <function Test at 0x027234B0> .
Example to show this -
>>> def a():
...     print(a)
...
>>> a()
<function a at 0x0018B198>

You should print something meaningful.


text:
Q: How do I close the CMD when I enter a certain value in perl? I am currently making a program that will eventually be able to auto start when I sign onto my computer and will allow me to select from a variety of programs to start. I currently have two (just started it). Anyway, I was wondering, because it is being run thru CMD, how can I have the program close CMD when I enter a certain value. My code:
print "What would you like to run? (1 for Chrome and 2 for Calculator \"e\" for exit)  \n";
my $prog_run = <STDIN>;

if ($prog_run == 1){
#Chrome Function
system('"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"');
}elsif ($prog_run == 2){
#Calculator Function
system('"C:\Windows\System32\calc.exe"');
}elsif ($prog_run == "e"){
  #Exit Fucntion
  print "Exiting........";
}

A: }elsif ($prog_run == "e"){

== is the numeric comparison operator; it only works correctly on numbers. Since "e" is a string, you will need to use the string comparison operator, eq, to compare something with it:
} elsif ($prog_run eq "e") {

However, the line you read from standard input will have a newline on it by default. You can either include this in your string ("e\n"), or chomp $prog_run; beforehand to strip off the newline.
Anyways.
If you're in a loop, you can use last to exit out of it. Alternatively, you can use exit to make the whole Perl process… well, exit.


text:
Q: Replacing string with Regex with start and end tags with Java replace function I have a mathematical formulas string like this.
(##type## * 2) + 5 + ##component## + ##param##

After replacing, I want to get like this.
((value.type) * 2) + 5 + (value.component) + (value.param)

I will always add the "value." string to the begining of the parameters and add both side (). How can i do this?

A: String test = "(##type## * 2) + 5 + ##component## + ##param##";
System.out.println(test.replaceAll("##(.*?)##", "(value.$1)"));

A: You can do it by chaining replaceAll methods, e.g.:
class Value {
    String type;
    String component;
    String param;
    //Getters and setters
}

public static void main(String[] args) {
    String s = "(##type## * 2) + 5 + ##component## + ##param##";
    Value value = new Value();
    value.type = "a";
    value.component = "b";
    value.param = "c";
    s = s.replace("##type##", value.type).replaceAll("##component##", value.component).replaceAll("##param##",
            value.param);
    System.out.println(s);
}


text:
Q: How do I make a python turtle program wait a bit? So I'm making a game where the two turtles race each other, but I want them to wait a bit before they start (to display a 3,2,1) screen. But I can't figure it out! I used time.sleep, and turtle.delay, but both did not work. What can I do? Here is the code :)
import turtle
import random
import time

turt = turtle.Turtle()
turt2 = turtle.Turtle()
turtle.Screen() .bgcolor("green")

turt.speed(10)
turt.penup()
turt.goto(200,100)
turt.pendown()
turt.right(90)
turt.width(10)
turt.forward(450)
turt.right(180)
turt.forward(800)

#position 1
turt.penup()
turt.goto(-400,200)
turt.pendown()
turt.right(90)
turt.forward(100)

#position 2
turt2.width(10)
turt2.penup()
turt2.goto(-400,-200)
turt2.pendown()
turt2.forward(100)

A: Contrary to the advice so far, I'd avoid sleep() in my turtle program and use ontimer() instead to countdown the start of the race:
from turtle import Screen, Turtle
from random import choice

FONT = ('Arial', 36, 'bold')

def race():
    while turtle_1.xcor() < 200 > turtle_2.xcor():
        choice([turtle_1, turtle_2]).forward(10)

def countdown(seconds=3):
    pen.clear()

    if seconds < 1:
        screen.ontimer(race)
    else:
        pen.write(seconds, align='center', font=FONT)
        screen.ontimer(lambda: countdown(seconds - 1), 1000)

screen = Screen()
screen.bgcolor('green')

marker = Turtle()
marker.hideturtle()
marker.speed('fastest')
marker.color('white')
marker.width(5)

marker.penup()
marker.goto(200, 300)
marker.pendown()

marker.right(90)
marker.forward(600)

pen = Turtle()
pen.hideturtle()

turtle_1 = Turtle()
turtle_1.shape('turtle')
turtle_1.color('red')
turtle_1.penup()
turtle_1.goto(-400, 200)

turtle_2 = turtle_1.clone()
turtle_1.color('blue')
turtle_2.goto(-400, -200)

countdown()

screen.exitonclick()


text:
Q: Mailchimp tag API silently failing I'm calling the Node.js Mailchimp API like so:
const mailchimp = require('@mailchimp/mailchimp_marketing');
const md5 = require('md5');

// ...

const resp = await mailchimp.lists.updateListMemberTags(
  mailchimpListId,
  md5('my@email.com'),
  { tags: [{ name: 'Tag Name', status: 'active' }] }
);

(resp === null) // true

*

*The subscriber exists

*The md5 library is providing the valid md5 hash (confirmed by calling getListMemberTags successfully)

*No error is being generated

But the response is null, and the tag is not being added to the subscriber.
Any ideas as to why it might be silently failing, and if so, how I can debug it?
(If relevant, this is all being run within an Auth0 Custom Action.)

A: Thanks to Buck at Mailchimp, I found the solution. Unlike most API calls in the library, updateListMemberTags needs a body wrapper like so:
const resp = await mailchimp.lists.updateListMemberTags(
  mailchimpListId,
  md5('my@email.com'),
  { body: { tags: [{ name: 'Tag Name', status: 'active' }] } }
);


text:
Q: Mysql gem causes MysqlCompat::MysqlRes error with Passenger only I have a problem similar to the one outlined at uninitialized constant MysqlCompat::MysqlRes (using mms2r gem)
Trying to run a Rails 2.3.14 application under passenger 3.0.9 with the mysql 2.8.1 gem on Snow Leopard I get an error:
uninitialized constant MysqlCompat::MysqlRes
However, this ONLY happens under passenger, I can interact with mysql through ActiveRecord through all other means: i.e. I can create models in script/console, rake db:migrate, tests and so on. The mysql gem has been built with with the correct ARCHFLAGS. Both ruby and mysql have been built 64 bit.
Other information: I'm using RVM, REE and bundler.

A: Turns out that this was caused by using the DYLD_LIBRARY_PATH environment variable to overcome the problem in the mysql 2.8.1 gem. This wasn't part of the apache environment, but was part of any user process spawned from the shell, hence it not working under apache.


text:
Q: How to pass value from AJAX to codebehind in mvc? string values are null came $(document).ready(function () {
    $("#btn").click(function () {
        var data = {
            "Username": $("#name").val(),
            "Password":$("#pswd").val()
        }
        $.ajax({
            url: "/loginform/logdetail",
            data: JSON.stringify(data),
            type: "post",
            ContentType: "application/json;charset=utf-8",
            datatype: "json",
            success: function (response) {
                event.preventDefault();
                var result = JSON.parse(response.d);
                if (result.status == "success") {
                    window.location = "https://www.google.co.in";
                    return false;
                }
            },
            error: function (result) {
                alert("errormessage");
            }
        })
    });
});

In the logdetail() method, the string value is null. How do I get string value?
public JsonResult logdetail(string Username, string Password)
{
    return Json(dbform.checkuser(Username,Password),JsonRequestBehavior.AllowGet);
}

A: Please have a look following solution, First better to put preventDefault(); outside of success function, And create Class in server side same as JSON object
public class User {
 public string Username { get; seet; }
 public string Password{ get; seet; }
}

change action to
public JsonResult logdetail(User user) {..}

A: There are few mistakes in your code :
Especially these 2 lines
contentType: "application/json; charset=utf-8", data: JSON.stringify({ userdataObj: data })
Your ajax code will become :
$(document).ready(function () {
    $("#btn").click(function () {
        var data = {
            "Username": $("#name").val(),
            "Password":$("#pswd").val()
        }
        $.ajax({
            url: "/loginform/logdetail",
            data: JSON.stringify({ userdataObj: data }),
            type: "post",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            success: function (response) {
                event.preventDefault();
                var result = JSON.parse(response.d);
                if (result.status == "success") {
                    window.location = "https://www.google.co.in";
                    return false;
                }
            },
            error: function (result) {
                alert("errormessage");
            }
        })
    });
});

Now create a User data class with below details
public class User
{
    public string Username { get; set; }
    public string Password{ get; set; }
}

And change controller to below code :
[HttpPost]
public JsonResult logdetail(User userdataObj)
{
    return Json(dbform.checkuser(userdataObj.Username,userdataObj.Password),JsonRequestBehavior.AllowGet);
}

A: You can do two things to solve this issue.
1) Create User class with two properties (Username, Password), modify your logdetail function like this logdetail(User user) and use your version of javascript ajax call.
2) If you want to use same version of controller (logdetail(string Username, string Password)), then you have to modify your javascript ajax call.
$(document).ready(function () {
    $("#btn").click(function () {
        var username = $("#name").val();
        var password = $("#pswd").val();
        $.ajax({
            url: "/loginform/logdetail",
            data: { Username: username, Password: password }
            type: "post",
            ContentType: "application/json;charset=utf-8",
            datatype: "json",
            success: function (response) {
                event.preventDefault();
                var result = JSON.parse(response.d);
                if (result.status == "success") {
                    window.location = "https://www.google.co.in";
                    return false;
                }
            },
            error: function (result) {
                alert("errormessage");
            }
        })
    });
});


text:
Q: Arquivo css não atualiza no django O problema é que ao iniciar o site, ele carrega o arquivo css na primeira vez. Mas se eu edito esse arquivo o django não reconhece e continua do mesmo jeito. Já tentei da um reload no server local(python manage.py runserver) aq do notebook e da F5 na pag mas ainda assim não funciona.
settings.py:
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g!c%%3ut6lu)%=a&si^!&soq74tz(rvp8=rro(e1n&09x&@81@'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    #my_apps
    'pokedex',
    'scrapy',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'pokedexdjango.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'pokedexdjango.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

urls.py:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('pokedex/', include('pokedex.urls')),
    path('scrapy/', include('scrapy.urls')),
    path('admin/', admin.site.urls),
]

Não entendo porque isso acontece.

A: Tente utilizar o CTRL+F5 para atualizar a pagina forçando o recarregamento de todos os objetos, mesmo aqueles que já estão no cache do navegador.
Apertar somente F5 não obriga o navegador a baixar a nova versão dos arquivos css ou JavaScript... então ele acaba reutilizando o que já está no cache. O ctrl+F5 obriga o navegador a baixar tudo independente de já ter no cache.


text:
Q: CUICatalog: Invalid asset name supplied: '(null)' when playing video I am generate list of thumbails of videos on iOS:
 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // get a reference to our storyboard cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath)
    cell.backgroundColor = UIColor.red

    // Use the outlet in our custom class to get a reference to the UILabel in the cell
    let imageView = UIImageView(frame: CGRect(x:0, y:0, width:cell.frame.size.width, height:cell.frame.size.height))
    let image = uiImageArray[indexPath.row]
    imageView.image = image
    imageView.contentMode = UIViewContentMode.scaleAspectFit

    cell.addSubview(imageView)
    return cell
}

When user clicks image i want to play video :
  override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    print("You selected cell #\(indexPath.item)!")
    self.assetToNav = indexPath.item
    let data = self.assestArray[self.assetToNav]

    self.playVideo(view: self, videoAsset: data)
}
  func playVideo (view: UIViewController, videoAsset: PHAsset) {

        guard (videoAsset.mediaType == .video) else {
            print("Not a valid video media type")
            return
        }

        PHCachingImageManager().requestAVAsset(forVideo: videoAsset, options: nil) { (asset, audioMix, args) in
            let asset = asset as! AVURLAsset

            DispatchQueue.main.async {
                let player = AVPlayer(url: asset.url)
                let playerViewController = VideoPlayerViewController()
                playerViewController.player = player
                view.present(playerViewController, animated: true) {
                    playerViewController.player!.play()
                }
            }
        }
    }

When videos start to playing i see in console error:
[framework] CUICatalog: Invalid asset name supplied: '(null)'
I am beginner wth swift programming , please help


text:
Q: POST request not working in form I'm trying to submit some form using POST method. Here is par of form:
<form action="interlopers.php" mehod="post"  id = "interlopersForm" name="interlopersForm" onsubmit="return validateInterlopersForm()">

                           Ast. num
                          <input type="text" name="ast_num" id = "ast_num"
                                     value="<?php if(isset($_REQUEST['ast_num'])) { echo htmlentities ($_REQUEST['ast_num']); } ?>"
                                                  size="6">

                       Cut-off
                      <input type="text" name="cut_off"  id="cut_off" size="6" >

                       Data
                      <input type ="checkbox" name="data" id = "dataSDSS" value="SDSS" checked> SDSS

                       <input type ="checkbox" name="data" id="dataWISE" value="WISE" checked > WISE

                       <input type ="checkbox" name="data" id = "dataSp" value="Sp" checked> Taxonomy

                        Just interlopers?
                       <input type = "checkbox" name="isFinalStep" id = "isFinalStep">

 <input type="hidden" name="submitted" value="1">

                           <input  type="submit" value="Calculate" >

            </form>

But, instead of getting POST request im getting GET request. I'm using apache server and php5 on Ubuntu. I tried this on local-server and on remote host, but still GET instead of POST.

A: Change mehod="post" to method="post".
You wrote wrong.


text:
Q: Консольная графика c++ независимая от платформы Подскажите пожалуйста библиотеку для работы с консолью для c++, типа ncurses.h или windows.h только независимую от платформы (может быть на основе предыдущих).

A: Ну так ncurses как раз и кроссплатформенен, его и используйте.


text:
Q: Equally divide contents of a directory between disks - rounded up to the nearest top level directory I have a Music directory, and an MP3 player with two SD card slots. The contents of the directory is too big for one card, so I'd like to split it over two.
I like to have stuff in alphabetical order. If I filled up SD1 and left SD2 partly empty, whenever I add new music I'd either have to break the alphabetical order by putting new stuff on SD2, or re-jig everything around.
The other thing is that my directories are grouped by Artist, so if I got a new album by an artist on SD1 it wouldn't fit.
In short, I want the two cards filled up roughly equally.
Right now my solution is actually OK:

*

*List the directories and output the list to a file

*Open the file and find the halfway point (I'm sure there's a clever way to do this but it's quick to do manually in vim)

*Cut the bottom half of the list and paste it to a second file

*Run rsync --files-from= using one file on SD1 and the next on SD2. Job done!

This got me thinking though, is there a more accurate way to do this so that the two SD cards get filled more evenly? How would you go about this?
I guess I would have to maybe

*

*Run du on the Music dir to find the totalSize.

*Then loop through every Artist dir to get their sizes and keep a running total.

*Once that total surpasses the totalSize * 0.5, output a list of all the dirs you just counted to get the first half and put the rest in a second file to get the other half?

*Do the same rsync from-file

Anyone got any better ideas?

A: So, somewhat ironically, this would be really easy to do if those two SD cards where two separate computers on the same network, as there are all kinds of cluster storage solutions that do exactly what you're asking.
Given that that's not a very realistic option however (using a clustered filesystem is overkill for this), your best bet is probably a program called mhddfs.  The official homepage is in Russian, but there's a decent post here about it, and it's packaged a number of different distributions.  In essence, it does file-level RAID.  The big advantage here is that once you get the mhddfs mount set up, you can literally just call rsync once.  Each file will end up entirely on exactly one filesystem, and it will intelligently manage distribution across the filesystems.  Additionally, it stores no state on the underlying devices (it just looks at the data distribution across the devices to figure out where to put  any newly created files, and properly checks all of them for existing files), so it won't waste any space either.


text:
Q: How do templates work when using them as array dimensions? I tried to use tempaltes as array dimension value. I was puzzled when tried to specify wrong dimension as tempate argument. For example code:
#include <iostream>

using namespace std;

template <int X, int Y>
void f(int a[X][Y]) {
    for (int i = 0; i < X; ++i) {
        for (int j = 0; j < Y; ++j) {
            cout << a[i][j] << " ";
        }
        cout << '\n';
    }
}

int main() {
    int a[2][2] = {{1, 2}, {3, 4}};
    f<2, 2>(a); // compilation succeeded
    f<10, 2>(a); // compilation succeeded
    f<2, 10>(a); // compilation FAILED
}

Why in the last case compilation fails, but in case <10, 2> it does not?
error: no matching function for call to 'f'
note: candidate function template not viable: no known conversion from 'int [2][2]' to 'int (*)[10]' for 1st argument

A: You get this result because f(int a[X][Y]) is a lie.
Arrays are not first-class citizens in C++. You cannot pass an array as a function parameter by value. So when you write such parameter, it is silently adjusted to a pointer (the first level only). Thus the type of a is really int (*)[Y].
Since there is no X in the type of a, absolutely any X will work.
If you want to enforce both X and Y, try passing the array by reference:
void f(int (&a)[X][Y])

or use std::array.


text:
Q: Tkinter Time Button Not Outputting I am trying to record the time between button presses and then append that time to a list however when I press the stop_time_forward button I don't get it printing anything. Any help on this would be amazing.
My Code:
import time
from tkinter import *

initial = 0
top = Tk()
command_time_list = []

#start forward
def start_time_forward():
   global initial
   print("Timer Start")
   initial = time.time()
   return initial

def stop_time_forward():
   final = time.time()
   time_elapsed = final - initial
   command_time_list.append('a')
   command_time_list.append(time_elapsed)
   return command_time_list

forward_output = stop_time_forward()
print(forward_output)

forward_end = Button(top, text ="Forward Time Stop", command = stop_time_forward)
forward_start = Button(top, text ="Forward Time Start", command = start_time_forward)

forward_end.pack()
forward_start.pack()
top.mainloop()

A: all what you need to add is print function in stop_time_forward that is called when button forward_end is called
import time
from tkinter import *

initial = 0
top = Tk()
command_time_list = []

#start forward
def start_time_forward():
   global initial
   print("Timer Start")
   initial = time.time()
   return initial

def stop_time_forward():
   final = time.time()
   time_elapsed = final - initial
   command_time_list.append('a')
   command_time_list.append(time_elapsed)
   print(command_time_list) # here is the fix
   return command_time_list

forward_output = stop_time_forward()
print(forward_output)

forward_end = Button(top, text ="Forward Time Stop", command = stop_time_forward)
forward_start = Button(top, text ="Forward Time Start", command = start_time_forward)

forward_end.pack()
forward_start.pack()
top.mainloop()


text:
Q: Browser prompting download of JSON response, ASP.NET MVC2 I've encountered this problem all of a sudden doing a simple ajax submit of a form. The JSON comes back formatted correctly but the browser prompts to download it. Fiddler shows the content-type as correct:
application/json; charset: utf-8

Here's my javascript:
 $("#submitbutton").click(function(e) {
 $.post('FormTest', function(o) {
  FormCallback(o);
  });
});

Here is the server side:
public JsonResult FormTest(string test) {
        return Json("This worked!");
    }

Again, I get back an object from the server fine, but it either prompts me to download (Firefox) or simply shows the object in a new tab in the browser (Chrome).
I found one other question like this but the author didn't explain what was wrong. This is crazy! Any ideas?
Edit: The correct code is below, beside the e.preventDefault, I also needed to tell it which form data to use:
  $("#submit-button").click(function(e) {
    $.post('address', $("#form").serialize(), function(o) {
        FormCallback(o);
    });
   e.preventDefault();
});

A: You want to cancel the default action, I expect:
 $("#submitbutton").click(function(e) {
 $.post('FormTest', function(o) {
  FormCallback(o);
  });
  return false; // <<=====
});

You can also try:
e.preventDefault();

if that doesn't work by itself

A: In addition to @Marc's answer I would like to add that:
return Json("This worked!");

in fact doesn't work as it doesn't return a valid JSON object. It simply returns "This worked!" to the client. You need to construct the object:
return Json(new { Message = "This worked!" });

A: MVC 2 returns JSON mimetype by default. If you want to receive JSON data in plain HTML you should pass your JSON data as following:
return Json(model, "text/html", JsonRequestBehavior.AllowGet);

Another point, you can mark your Action with [ChildActionOnly] and call your action in your view this way
var json = <%= Html.Action("YourActionMethod", "YourControllerName") %>


text:
Q: How to resize jpg file by PHP? It's now 925*1139,I want to change it to 90*110.

A: try the imagecopyresampled PHP function or the imagecopyresized function from the GD library.

A: Basically using GD is pretty easy once you know what to do.
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width, $height) = getimagesize($uploadedfile);

$tmp = imagecreatetruecolor(800, 600);

$filename = '/path/to/images/' . $_FILES['file']['name'];

imagecopyresampled($tmp, $src, 0, 0, 0, 0, 800, 600, $width, $height);
imagejpeg($tmp, $filename, 100);

Again check the blog for details.

A: here's a resizing class called SimpleImage that you can use. Or take a look at the source and see how they tackle the problem:
SimpleImage Code

A: I haven't done PHP in a while (why am I even in this tag?) but you should check out GDLib. iirc, its better integrated than imagemagick.
http://php.net/manual/en/book.image.php


text:
Q: How can I difference id (number) and email (string) in Javascript? I have API and some of them return to only email and some return only id. For example:
user1
value: example@example.com
user2
value: 1212391361783212
I need that if I have input and wanna give value if the value is email. If the value is id, the input value must be null
<input value={???}/>

A: You can check if a string is a valid number using isNaN. So
if(isNaN(value)) {
    // value is email
 } else {
    // value is id
 }

A: Your code sample is incomplete but what you're trying to do should look something like this. Rather than assuming any non-numerical response is a valid email, which can break in the future as the API changes, be explicit about what you're looking for as below.
// Assume you're comfortable using a relatively loose pattern to match an email i.e. no overly strict formatting rules
const mailPattern = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
// Assume response is in scope and contains the API response with the email or id deserialized from the body
const value = mailPattern.test(response) ? value : null

A: You can use Regular expression /^\d+$/ combined with RegExp.prototype.test():
if (/^\d+$/.test(value)) {
  // It's number
}


text:
Q: STS-Secured Service EndorsingSupportingTokens support in java/metro I have created a .NET WCF service described by a hand-written platform-agnostic WSDL file. The service is secured by an STS and this is expressed in the WSDL by an EndorsingSupportingTokens security policy element. I need to create a Java example client (preferably in NetBeans) for my service and it's a lot harder than I expected.
I've just tried working through the entire section 12.9.7 "STS Issued Token" of https://metro.java.net/2.3/guide/user-guide.pdf in hopes that I could get this working in a pure Java environment and then incrementally change it to work with my situation, but it doesn't work for me. I find that by fiddling with various settings I can get a variety of different error messages, but it never quite works.
So I can work out for sure that this is supported, is there any example of the following in NetBeans+Metro that I can just download and use? I've followed a number of step-by-step guides but something always goes wrong^.

*

*Client authenticates with STS using an X509 certificate

*STS sends client an encrypted SAML Assertion

*Client sends request to Service, with SAML Assertion in headers

^ I'm happy to get a tentative "No" answer, so I can begin the process of raising specific questions about all the things that have gone wrong.


text:
Q: Redirect port without opening it I have the following iptables configuration
iptables -P INPUT DROP
iptables -A INPUT -i eth0 -p TCP --dport 443 -j ACCEPT
iptables -A INPUT -i eth0 -p TCP --dport 10001 -j ACCEPT
iptables -A PREROUTING -t nat -p tcp -m tcp --dport 443 -j REDIRECT --to-port 10001

But I don't want to have port 10001 opened, that's the reason why I'm doing the redirect (and that I don't want to run my server as root), right?
But if I remove the third line, the forwarding stops working.
So any idea how to redirect the port without opening it to the world?

A: From your question, I understand that eth0 is your public interface and that you don't wish your SSL web server to be visible to the public.
I think you should rather restrict who can connect to the port instead of trying to hide it.
One solution without using routing would be to set your web server (apache2?) to only bind to your loopback device (lo, 127.0.0.1) for SSL. This assumes you connect to your web server only from the computer where the webserver is running.
Another method would be to add to your iptables the ability to accept anything on lo, and refuse if port 443 on eth0 (via default policy)
iptables -P INPUT DROP
iptables -A INPUT -i lo -p TCP -j ACCEPT

If you need to connect remotely to the web server, and you have static IP address, you can always only accept incoming connections to 443 from only that IP.
Another method I can think of to hide your port 443 from the exterior would be using port knocking.
Other methods do exist (within apache2) to prevent/accept connections to the server from specific IPs.


text:
Q: Convert string with spaces to html url in python 3.3 I'm trying to convert a YQL string with spaces to html code.
Here's the YQL string I'm using:
select * from yahoo.finance.historicaldata where symbol in ("MSFT", "AAPL") and startDate = "2010-10-01" and endDate = "2010-10-05"

Here's the url code that needs to come out:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20in%20(%22MSFT%22%2C%20%22AAPL%22)%20and%20startDate%20%3D%20%222010-10-01%22%20and%20endDate%20%3D%20%222010-10-05%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=

I've been trying to do this with urllib.parse.urlencode but have not had any luck.
I can get up to "http://query.yahooapis.com/v1/public/yql?" but afterwards it starts to break down. Is there a pythonesque way to do this that I'm just missing?
Thank you!

A: import urllib

url_start = "http://query.yahooapis.com/v1/public/yql?q="
url_end = "&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="

you can encode the string as a dict like this:
d = {'select * from yahoo.finance.historicaldata where symbol in ("MSFT", "AAPL") and startDate':'"2010-10-01"', 'and endDate':'"2010-10-05"'}

encode_url = urllib.urlencode(d)

#output is:
'select+%2A+from+yahoo.finance.historicaldata+where+symbol+in+%28%22MSFT%22%2C+%22AAPL%22%29+and+startDate=%222010-10-01%22&and+endDate=%222010-10-05%22'

url = url_start + encode_url + url_end

A: >>> import urllib
>>> urllib.quote('http://www.example.com/déjà-vu/example two.html')
'http%3A//www.example.com/d%C3%A9j%C3%A0-vu/example%20two.html'


text:
Q: in openfoam, paraview cannot connect to X server My background in ubuntu and OpenFOAM: I started to learn to simulate in OpenFoam this week. I have windows 10 on my laptop and downloaded ubuntu 18.04 from the app store. In ubuntu OpenFOAM and paraview are installed by a guy from the ICT-helpdesk (paraview has already worked). Also, the Xming X server is installed.
My question: During the first tutorial (cavity) you must visualize the data with paraview. So after the guy installed everything, I could use paraview. Now I closed ubuntu and started again. If I now call paraFoam into action I get the following lines:
    Created temporary 'cavity.foam'
    paraview: cannot connect to X server
Does anybody know what to do with this? I checked this forum and I checked google, but could not find anybody with this specific problem.
Sincerely,
Me

A: Make sure that xming is running then run the following on your ubuntu terminal:
export DISPLAY=localhost:0

Now you can run paraview:
paraview


text:
Q: How can I change the PHP version used by phpmyadmin? I have phpmyadmin installed on my ubuntu server, that runs several versions of PHP depending on the website used.
The default version is 7.4, but phpmyadmin use 7.2 for unknown reason.
Simple question : where do I change that ?
Cannot find it in any forum or documentation...
I tried to put in phpmyadmin/apache.conf what I use in my virtual hosts sites :
<FilesMatch \.php$>
    SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost/"
</FilesMatch>

but it doesn't work and I still have 7.2
Thanks a lot !

A: Solution found !
As my Phpmyadmin installation doesn't use the virtual host file system, the file to modify is /etc/phpmyadmin/apache.conf
I put a code, but outside the Directory tags, and you have to put it inside to make it work :
<Directory /usr/share/phpmyadmin>
    <FilesMatch \.php$>
    SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost/"
    </FilesMatch>
</Directory>

And then, restart Apache change the PHP version of phpmyadmin page.
Thanks !

A: Here's how I do it:
Go to phpMyAdmin config
cd /etc/apache2/sites-available

Open config file
sudo nano phpmyadmin.conf

Put the following line inside the  tags to serve 7.4:
include /etc/apache2/conf-available/php7.4-fpm.conf

Restart apache:
sudo systemctl restart apache2

Note that my setup is mostly from this tutorial.

A: Add the below code inside  /etc/phpmyadmin/apache.conf
<Directory /usr/share/phpmyadmin>
    <FilesMatch \.php$>
    SetHandler "proxy:unix:/var/run/php/php8.1-fpm.sock|fcgi://localhost/"
    </FilesMatch>
</Directory>

After that restart Apache
sudo systemctl restart apache2


text:
Q: How to download file response using Angular JS that is sent via c# web api? I am using c# to create a pdf file and then the file is sent via response. The file seems to be created totally fine because the swagger shows the download link. Below is the controller code where a pdf file is created and then returned:
[HttpGet("generatepdf")]
    public async Task<IActionResult> GeneratePDF(string AccountId, [FromQuery] InvoiceRequestDto model)
    {
        var document = new PdfDocument();
        var rv = await service.GetAccountInvoices(model);

        string htmloutput = string.Empty;
        htmloutput = "
";

        htmloutput += "

Invoice Id	Invoice Date	Invoice Due Date	Fee Type	Fee	Amount Outstanding	Status

";
        htmloutput += "
";
        foreach (var item in rv.Items)
        {
            htmloutput += "
" + item.Id + "	" + item.Date + "	" + item.PaymentDueDate + "	" + item.AmountOutstanding + "	" + item.StatusName + "	";
        }
        htmloutput += "

";

        string HtmlContent = htmloutput;
        PdfGenerator.AddPdfPages(document, HtmlContent, PageSize.A4);
        byte[]? response = null;
        using (MemoryStream ms = new MemoryStream())
        {
            document.Save(ms);
            response = ms.ToArray();
        }
        string Filename = "Invoice.pdf";
        return File(response, "application/pdf", Filename);
    }

And here is the service code at the angular end:
async getPdfList(params: any) {
    return await this.ws.get(`${this.billingApiUrl}/invoice/generatepdf`,params).toPromise();
  }

However, I am unable to download the pdf file from the angular js. It is throwing an error as follow:

And here is the response that I get in the network:

Any help would be more than appreciated.


text:
Q: Unrealised/unrealisable - synonyms A person's potential, given their strengths was unrealised - attributable to their character.
"Unrealised" reminds me of utility, both sounding cold and business-oriented.
Are there more personal, less formal words like unrealised that also carry more a more implicit worth - so for example, the person above is not devalued? (Even if mention of the character seemed to)

A: Unrealized/unrealisable are two different uses of unrealized. If one has not accomplished their goals then their goals are still unrealized. The goals that cannot be reached no matter who by or how long they are sought are unrealisable.
I don't know of Unrealized goals reflecting on or being attributable to ones character except in novels. In your experience it may sound cold and business-oriented but it is merely accurate. One's subjective experience comes into play here.
Other characterizations of goals that have not or perhaps cannot be reached are Lofty as in a loft, the higher spaces in a barn or building. They could be Over Ambitious or even Unrealistic. Worthy ambitions might be undreamt of goals, those they would not even dream of reaching.


text:
Q: Typo3 v10 image metadata translation issue I'm developing a multi language website with Typo3 v10.4.32.
Everything works fine. Except image metadata translation feature.
I uploaded an image, and I added translation for metadata (German is default)

After then I added page translation. In backend I see that images have default language metadata in both languages

If I click the image element to edit I see the correct behaviour: Typo3 is aware that the image has translation of metadata

In frontend unfortunately I see the problem: the default language metadata is shown

Typoscript template is simple:
config {
    linkVars = L
    sys_language_mode = content_fallback
    sys_language_overlay = 1
    sys_language_softExclude = tt_content:image
    sys_language_softMergeIfNotBlank = tt_content:image
    sys_language_uid = 0
}

# Default PAGE object:
page = PAGE
page.10 = TEXT
page.10.value = HELLO WORLD!

page.20 = CONTENT
page.20.table = tt_content
page.20.select {
    orderBy = sorting
    where = {#colPos} = 0
}
[siteLanguage("languageId") == 1]
    config.sys_language_uid = 1
    config.htmlTag_langKey = en
    config.language = en
    config.locale_all = en_US
[end]

Is the code below necessary ? since it is configured in yaml file
config.sys_language_uid = 1
config.htmlTag_langKey = en
config.language = en
config.locale_all = en_US

I could add translation in content elements, but images are supposed to be used in many places, so it becomes annoying to add the same text
I tried to search a solution, but I found very old similar issue with Typo3 v7 and the issue was supposed to be fixed in the next version Typo3 v8.
I suppose that the problem does not connect to NGINX ?
Maybe I need to add some code in LocalConfiguration ?


text:
Q: Sorting answers, given overvotes and undervotes At many question-and-answer sites, like StackExchange, people can upvote or downvote each answer.  These sites also typically try to use the votes to sort answers, so the answers that are most likely to be helpful or accurate tend to appear nearest the top.  Given the number of upvotes and downvotes for each answer, how should one sort the answers?

Examples. To illustrate why I think this question might have some non-trivial statistical content, let me survey a handful of methods one might consider and some shortcomings of them.  In each method, we compute a score for each answer from its upvotes and downvotes, and then sort the answers by score, so the only question is what method to use to compute the score.

*

*Upvotes minus downvotes. The additive difference is simple to compute.  Limitations. Is an answer with 121 upvotes and 100 downvotes really better than an answer with 20 upvotes and 0 downvotes?

*Upvotes divided by total number of votes. This estimates the fraction of voters who held a positive opinion of the answer, which is arguably natural and meaningful in its own right. Limitations. Is an answer with 1 upvote and 0 downvotes really better than an answer with 8 upvotes and 1 downvotes?

*Compute a confidence interval. I suppose we could compute, for each answer, a confidence interval for the true fraction of people who would vote positively if they voted.  But it is not clear how to extend this to a complete sorting scheme; what do we do when two answers have overlapping confidence intervals?

*Laplace smoothing. We could apply Laplace smoothing (additive smoothing) to the counts of upvotes and downvotes, then estimate the fraction of votes that are positive.  If we have $u$ upvotes and $d$ downvotes for an answer, its score will be $(u+1)/(u+d+2)$.  (For instance, this would declare that an answer with 3 upvotes and 1 downvote is equivalent an answer with 1 upvote and 0 downvotes.  Does that seem reasonable?  Hard to say.)

A: I recently learned about Bayesian rating.  Bayesian rating computes a weighted average of the naive uncorrected rating for this answer and the average rating for all answers.  The fewer the votes for this answer, the more we weight things towards the average rating.  The intuition is that if we have no votes on this answer, then the average rating (across all answers) is our best guess at the rating of this answer; as we gain more votes on this answer, they start to move our estimate away from the average rating.
The scheme apparently works like this.  The naive uncorrected rating for an answer is $r = u/n$, where $u$ is the number of upvotes and $n$ the total number of votes for that answer (i.e., $n=u+d$, where $d$ is the number of downvotes).  Let $r^*$ denote the average uncorrected rating, averaged over all answers, i.e., the average of $r$ over all answers.  Also, let $n^*$ the average number of votes per answer, over all answers, i.e., the average value of $n$.
With these definitions, the Bayesian rating for an answer is $r'$, defined as follows:
$$ r' = \frac{n}{n+n^*} r + \frac{n^*}{n+n^*} r^*. $$
Notice how if we have no votes on this answer, then $r'=r^*$ (the Bayesian rating is the average rating across all answers); whereas as $n \to \infty$, we have $r' \to r$ (the Bayesian rating for an answer converges to the naive uncorrected rating, as the number of votes on the answer becomes large).  These seem like appealing properties.
For a generalization that can be used if items can be rated from 1-5 stars, instead of upvoted/downvoted, see the answers to How to find confidence intervals for ratings?, the essay Bayesian sorting by rank (which appears to use a slightly different formula), and Bayesian Ratings: Your Salvation for User-Generated Content.

A: I found an essay (How Not To Sort By Average Rating) which argues that you should compute a 95% confidence interval for the true fraction of people who would vote positively, and then sort ratings by the lower end of the confidence interval.
This is an interesting approach.  It is hard for me to judge whether this is in some sense the "right" way to do it, but it seems to behave better than some of the more naive alternatives.  Worth noting: @raegtin gives a cogent criticism of this approach, in his answer to a related question.  The short version of the criticism is that using the lower limit of a confidence interval pushes items with few ratings towards a very low rating, where it's probably better to push them towards the average rating over all items (as Bayesian rating does).


text:
Q: IconFactory with `setContentRotation` change aling of the content I'm working with maps and I'm trying to do something similar as Uber does, show information near the marker (in two markers at the same time so I can't use infowindow )

As I have read I'm using IconFactory to achieve this:
    val iconFactory = IconGenerator(this)
    //iconFactory.setBackground(resources.getDrawable(R.drawable.background_iconfactory))
    iconFactory.setRotation(90)
    iconFactory.setContentRotation(-90)
    iconFactory.setContentView(view)

    val mMarkerA = mMap?.addMarker(MarkerOptions().position(LatLng(location.latitude, location.longitude)).anchor(iconFactory.anchorU, iconFactory.anchorV))
    mMarkerA?.setIcon(BitmapDescriptorFactory.fromBitmap(iconFactory.makeIcon("hello world")))

But I came up with the next problem: If I use a regular text the iconFactory is placed like I want.

But if I inflate a custom view (this is what i need), the view appeared to be displaced to the right.
Does anybody knows what I'm doing wrong?! Can anybody help me?
Thanks in advance.
Edit
I don't think the xml could be a problem, if I don't rotate the content it's ok.

Anyway I post the xml:
 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<ImageView
    android:id="@+id/backgroundMarker"
    android:layout_width="30dp"
    android:layout_height="30dp"

    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/background_marker" />

<ImageView
    android:id="@+id/image_person"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="@+id/backgroundMarker"
    app:layout_constraintEnd_toEndOf="@+id/backgroundMarker"
    app:layout_constraintStart_toStartOf="@+id/backgroundMarker"
    app:layout_constraintTop_toTopOf="@+id/backgroundMarker"
    app:srcCompat="@drawable/ic_person_white_24dp" />

<ImageView
    android:id="@+id/imageView9"
    android:layout_width="1dp"
    android:layout_height="10dp"
    app:layout_constraintEnd_toEndOf="@+id/backgroundMarker"
    app:layout_constraintStart_toStartOf="@+id/backgroundMarker"
    app:layout_constraintTop_toBottomOf="@+id/backgroundMarker"
    app:srcCompat="@android:color/black" />

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginStart="4dp"

    android:background="@android:color/white"
    android:padding="8dp"
    android:text="Calle Pepe dos aguas"
    app:layout_constraintBottom_toBottomOf="@+id/imageView9"
    app:layout_constraintStart_toEndOf="@+id/backgroundMarker"
    app:layout_constraintTop_toTopOf="@+id/backgroundMarker" />

  <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginEnd="8dp"
        android:background="@android:color/black"
        android:padding="4dp"
        android:tint="@android:color/white"
        app:layout_constraintBottom_toBottomOf="@+id/text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/text"
        app:layout_constraintTop_toTopOf="@+id/text"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@android:drawable/ic_secure" />
</android.support.constraint.ConstraintLayout>


text:
Q: Radial Basis Function Network (RBF Network) According to the link below, i didn't understand what is the "center vector for neuron i", in other words "center of the RBF units called also prototype ".
read the Network architecture in this link
Please i need your appreciated help.

A: If you read on to the Training section in your link, it explains what the centre vectors are:

Reading the above, it seems to me that you have your set of samples, the x's, and from these you choose a number of centre vectors - one for each neuron in the hidden layer . The centre vectors, broadly speaking are centres of clusters in your sample data.
As the remarks say, you can use an unsupervised clustering algorithm, such as k-means, to find n cluster centres in your data, where n is the number of neurons in the hidden layer that you are dealing with. Different layers may have more or less neurons and so will have correspondingly more or less centre vectors.
Then the RBF relates each individual sample, x, to each centre vector by some function of the Euclidean distance between them.

A: The center vector of the neuron are the centers of the RBF. RBF is just a function the distance of a point (called x in the article) to a center (called ci in the article). Each neuron has its own center.


text:
Q: how to change tls version on python I am connecting to mysql database using mysql-connector in python script. But when I checked, there are logs like below in mysql. For this reason, I want to connect with TLSv1.2.
Log:

[Warning] [MY-013745] [Server] Accepted a connection with deprecated protocol 'TLSv1' for account xxx@yyy from host yyy. Client supplied username xxx

When I try to send tls_versions parameter it can't connect. How can I proceed in this situation? I'm asking for help from friends who have faced similar problems.
conn_intadmdb = mysql.connector.connect(host=xxx,
                                             database=yyy,
                                             user=zzz,
                                             password=***,
                                             charset='utf8',
                                             tls_versions=["TLSv1.2"],
                                             use_unicode=True)

mysql-connector        2.2.9
mysql-connector-python 8.0.6


text:
Q: My iPhone won't pair to my August EP650R headphones I have had my headphones paired to my iPhone but needed to disconnect recently which wouldn't work so I had to 'forget the device'. Now my iPhone won't pair with my headphones at all. Is there a way to get them paired again?

A: Go to settings -> Bluetooth and make sure the switch is turned on:

Then make sure the headphones are in a range of up to 10 metres and in a state to be paired to the phone.
If this doesn't work try:

*

*Turning Bluetooth on and off on both the phone and the device

*Resetting the device and restarting the phone

*Contacting the device manufacturer

A: try resetting network settings first if you are reluctant to reset whole phone at once. It is settings-> general-> reset-> network reset.
also to rule out the obvious, try pairing headphones and phone both to a third working device which can be a laptop or some other speakers.


text:
Q: Trying to setup a Ghost blog with Buster I'm trying to set up a static Ghost blog with Github hosting using the Buster Static generator. I've tried various instructions including:
https://stefanscherer.github.io/setup-ghost-for-github-pages/
http://blog.sunnyg.io/2015/09/24/ghost-with-github/
But when I get to the "buster generate" command I get the following output in terminal.
It is running fine locally.
Can anyone point me in the right direction?
buster generate
--2016-03-07 23:53:11--  http://localhost:2368/
Resolving localhost... ::1, 127.0.0.1
Connecting to localhost|::1|:2368... failed: Connection refused.
Connecting to localhost|127.0.0.1|:2368... connected.
HTTP request sent, awaiting response... 200 OK
Length: 4508 (4.4K) [text/html]
Saving to: '/Users/philip/Development/Node/ghost-0.7.8/static/index.html'

fixing links in  /Users/philip/Development/Node/ghost-0.7.8/static/index.html
Traceback (most recent call last):
File "/usr/local/bin/buster", line 9, in <module>
load_entry_point('buster==0.1.3', 'console_scripts', 'buster')()
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/buster/buster.py", line 90, in main
newtext = fixLinks(filetext, parser)
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/buster/buster.py", line 64, in fixLinks
d = PyQuery(bytes(bytearray(text, encoding='utf-8')), parser=parser)
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyquery/pyquery.py", line 226, in __init__
elements = fromstring(context, self.parser)
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyquery/pyquery.py", line 90, in fromstring
result = custom_parser(context)
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/html/__init__.py", line 867, in fromstring
doc = document_fromstring(html, parser=parser, base_url=base_url, **kw)
File "/usr/local/Cellar/python/2.7.8_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lxml/html/__init__.py", line 752, in document_fromstring
value = etree.fromstring(html, parser, **kw)
File "src/lxml/lxml.etree.pyx", line 3213, in lxml.etree.fromstring (src/lxml/lxml.etree.c:82934)
File "src/lxml/parser.pxi", line 1819, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:124533)
File "src/lxml/parser.pxi", line 1707, in lxml.etree._parseDoc (src/lxml/lxml.etree.c:123074)
File "src/lxml/parser.pxi", line 1079, in lxml.etree._BaseParser._parseDoc (src/lxml/lxml.etree.c:117114)
File "src/lxml/parser.pxi", line 573, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:110510)
File "src/lxml/parser.pxi", line 683, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:112276)
File "src/lxml/parser.pxi", line 624, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:111367)lxml.etree.XMLSyntaxError: None

A: As stated in the comment, I did get in working however instead of just doing the 'Quick Install' recommended by many, I went the route of the 'Developer Install' guide here https://github.com/TryGhost/Ghost using the Stable branch.
After you run through that (with your local server running), in another terminal, run
$ buster setup
<Enter git repo>
$ buster generate --domain=localhost:2368
$ buster deploy (or as most sane people prefer, just git push)

Full instructions here: http://phil-a.github.io/getting-ghost-running-on-github-with-buster


text:
Q: Why Scrapy cannot find href here? I am trying to get several hrefs that are in html blocks like this one (sorry for formatting but I guess you need everything):

  Yo

My scrapy crawling is able to get the li elements as elmts I want but then when I am trying elmts.xpath('@href'), no link is returned.
I don't get it but I am 2 weeks old with Scrapy !

A: If you want the hrefs from the li's with the class evt-click you can use the following xpath:
xpath('//li[@class="evt-click"]/@href'))

In your own example you need:
 xpath("./@href")

The reason neither work is because what you are looking for does not exist in the html in the link you provided, there are 11 li class="evt-click" and none contain any href bar the js inside the a tag:

You can use scrapy-splash to allow the page to render fully to get the dynamically generated data, you need to install it as per the link instructions:
Add to setting.py:
DOWNLOADER_MIDDLEWARES = {
    'scrapyjs.SplashMiddleware': 725,
}

Start a docker instance:
docker run -p 8050:8050 scrapinghub/splash:

Then this is enough to get the data you want:
import scrapy

class MySpider(scrapy.Spider):
    name = "deez"
    start_urls = ["http://www.deezer.com/profile/154723101"]

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, self.parse, meta={
                'splash': {
                    'endpoint': 'render.html',
                    'args': {'wait': 1}
                }
            })

    def parse(self, response):
        print(response.xpath("//li[@class='evt-click']").extract())

Output:
$ scrapy crawl deez
.............................
2016-03-20 23:01:12 [scrapy] DEBUG: Crawled (200) <POST http://127.0.0.1:8050/render.html> (referer: None)
[u'/profile/154723101/loved', u'/profile/154723101/playlists', u'/profile/154723101/albums', u'/profile/154723101/artists', u'/profile/154723101/radios', u'/profile/154723101/following', u'/profile/154723101/followers']

selenium is also another option.


text:
Q: kafka monitoring using JMX when running kafka in docker in boot2docker I am trying to get JMX monitoring working to monitor a test kafka instance.
I have kafka (ches/kafka) running in docker via boot2docker but I can not get JMX monitoring configured properly.  I have done a bunch of troubleshooting and I know the kafka instance is running properly (consumers and producers work).  The issue arises when I try simple JMX tools (jconsole and jvisualvm) and both can not connect (insecure connection error, connection failed).
Configuration items of note: I connect to 192.168.59.103 (virtualbox ip found when running 'boot2docker ip') and the ches/kafka docker/kafka instance uses the port 7203 as the JMX_PORT (confirmed in the kafka startup logs).  Using jconsole, I connect to 192.168.59.103:7203 and that is when the errors occur.
Any help is appreciated.

A: For completeness, here is the solution that works:
I ran ches/kafka docker image as follows -- note that the JMX_PORT (7203) is now  published appropriately:
$ docker run --hostname localhost --name kafka --publish 9092:9092 --publish 7203:7203 --env EXPOSED_HOST=192.168.59.103 --env ZOOKEEPER_IP=192.168.59.103 ches/kafka

Also, the following environment is set in the kafka-run-class.sh (.bat for windows)
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

But I needed to add one additional item (thanks to one of the commenters for pointing this out):
-Dcom.sun.management.jmxremote.rmi.port=7203

Now, to run the ches/docker image in boot2docker you just need to set one of the recognized environment variables (KAFKA_JMX_OPTS or KAKFA_OPTS) to add the additional item and it now works.
Thanks for the help!

A: There's no reason the kafka docker port would bind to the same port in the boot2docker VM except if you specify it.
Try running it with -p 7203:7203 to force the 1:1 forwarding of the port.


text:
Q: Splitting field of $f(x)=x^2+1$ over $F={\bf Z}_2$ Note that $f(x)=x^2+1=(x+1)^2$ has distinct two roots $1,\ i$ so that it is separable polynomial.
Hence spliting field is $K={\bf Z}_2(i)=\{ 0,\ 1,\ i\}$
Over $K$, $f(x)$ has factorization $(x-1)(x-i)=x^2+x+ix+1\neq f(x)$
Why does such phenomenon happen ?
More detailed explanation :
Consider ${\bf R}$-case. For $f(x)=x^2+1 \in {\bf R}[x]$ has a root $\pm i$ so that we have an extension $$ K={\bf R}(i)={\bf C}={\bf R}[x]/(x^2+1)$$
and we have factorization $$ f(x)=(x+i)(x-i)$$ over $K$.
I want to do similar thing in case $F={\bf Z}_2$

A: There is no $\Bbb Z_2(i)$; it's nonsense to adjoin a complex number. Colloquially, though, this is meant to mean the splitting field of $x^2+1$ over $\Bbb Z_2$ - but this is $ \Bbb Z_2$, as $x^2+1=x^2+2x+1=(x+1)^2 \in \Bbb Z_2[x]$. There is, however, a field of characteristic 2 with 4 elements: the splitting field of $x^2+x+1$ over $\Bbb Z_2$.


text:
Q: Foreach loop where clause in Python similar to c# LINQ I'm attempting to replicate a c# LINQ foreach statement in python. I'm sure there is a better way.
Let's say I have (in c#):
    public class TestData
    {
        public int Id { get; set; }
        public string Something { get; set; }
    }

    void MyMethod()
    {
        List<TestData> myList = new List<TestData>();
        foreach (var i in myList.Where(x => x.Id > 5))
        {
            //do something
        }
    }

I'd like to do something exactly like this in python (2.7). All I need is the foreach loop. Everything else I've got down.
Can anyone point me in the right direction?

A: Yep, it's very easy.  The thing with the square braces is called a List Comprehension.
for i in [x for x in myList if x.Id > 5]:
    pass #do something


text:
Q: Python attribute of combination of two objects I am fairly new to OOP in Python. In a program, I have two types of class:
class Character:
    ... etc. ...

[Character1 and Character2 are instances of this]
and
class Room:
    ... etc. ...

[Room1 and Room2 are instances of this]
I want to have a variable pos for each Character and Room such that there is one attribute pos for each possible combination of the two classes:
For example:
Character1 with Room1 --> pos = (10, 4)
Character2 with Room1 --> pos = (6, 10)
Character1 with Room2 --> pos = (3, 12)
Character2 with Room2 --> pos = (7, 5)

Is there a simple way to create an attribute for a combination of classes as I have described? I have looked around the internet and have not found a way to do it.
Thanks in advance.

A: You may want to create a tuple of your character and room instances, then use that tuple as a key for a dict to store the value of the pos.
d = {}
d[(Character1, Room1)] = (10, 4)

You may also wish to create a collection of characters and rooms, to allow for iteration of each.

A: The easiest way to accomplish this would be with a dictionary used for lookup:
positions = {
  (character1, room1): (10, 4),
  (character2, room1): (6, 10),
  ...
}

You can then just lookup the position like so:
pos = positions[characterX, roomY]

Also as a side note that might interest you, unless you're using Python 3 only, always derive your classes from object:
class Character(object):
    ...

A: It sounds like you're thinking about this wrong. Here's what I've done in the past.
class Coordinate(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Coordinate({x},{y})".format(x=self.x, y=self.y)

class Room(object):
    def __init__(self,name):
        self.name = name
        self.contains = list()
    def addPerson(self,person,where):
        self.contains.append((person,where))
        #  maybe use a dict here? I'm not sure your use case

class Character(object):
    def __init__(self,name):
        self.name = name

Then use this to make people.
Adam = Character("Adam")
Steve = Character("Steve")
LivingRoom = Room("Living Room")
Kitchen = Room("Kitchen")

LivingRoom.addPerson(Adam, Coordinate(10,4))
LivingRoom.addPerson(Steve, Coordinate(6,10))
Kitchen.addPerson(Adam, Coordinate(3,12))
Kitchen.addPerson(Steve, Coordinate(7,5))

Then each room has contains which is iterable for each person and their location inside that room.
for person,location in LivingRoom.contains: # occupants might have been a better name
    print ("{0.name} is at ({1.x}, {1.y})".format(person,location))
# Adam is at (10, 4)
# Steve is at (6, 10)


text:
Q: GCC Compiler error linker command failed I have the following C File and I am using Mac OS X GCC Compiler.
You find the error below.
#include "support.h"

#ifdef _WIN32

#include <conio.h>

void support_init() {
    // not needed
}

void support_clear() {
    system("CLS");
}

int support_readkey(int timeout_ms) {
    Sleep(timeout_ms);
    if (!kbhit()) return 0;
    return getch();
}

#else

#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <sys/select.h>

void support_init() {
    struct termios tio;
    tcgetattr(STDIN_FILENO, &tio);
    tio.c_lflag &= (~ICANON & ~ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &tio);
}

void support_clear() {
    printf("\x1B[2J\x1B[0;0f");
}

int support_readkey(int timeout_ms) {
    struct timeval tv = { 0L, timeout_ms * 1000L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    int r = select(1, &fds, NULL, NULL, &tv);
    if (!r) return 0;

    return getchar();
}

#endif

And this is my Makefile:
CFLAGS=-std=c11 -Wall -g
CC=clang

all: snake

.PHONY: all clean

snake: snake.o support.o

snake.o: snake.c support.h

clean:
    rm -f snake
    rm -f snake.o support.o

When I try to compile with the command "make all" I get the following error:
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see
invocation)

Please help. I am new to C :-)

A: check the Architecture based on that the cflags shoule be updated to set to -m32 or -m64 ,
for successful compilation in 64 bit machine this has to set to -m64.
CFLAGS+= -m64


text:
Q: Can the spacing of menu bar apps be modified in Big Sur? It's much too wide, which is a problem if you use a lot of menu bar apps.

A: It is the approach Apple is taking, getting the menu bar items wider. Some conspiracy theories are stating that it might be the beginning of touch screen macs since the new UI is a lot more touch friendly. You can watch "Snazzy Labs" video about it while Big Sur was in beta. I believer it was called "Big Sur's Secret" or smt...
Back to your question, no. At this point, until a developer gets his hands on a 3rd party app or apple listens to its customers resisting the change, you cannot change any of the Big Sur spacings.
Addition: At the time of writing this answer, there were no software capable of doing such thing. However, as the answer above me mentioned a newer version of "Bartender" capable of such thing. This answer is obsolete.

A: Actually, there appears to be some way to do this, since the newest version of Bartender allows you to change or remove spacing in the menu bar. The app costs $15 (but offers a four-week free trial).
To change the spacing with Bartender, install the app, open the preferences window, and under "General" change "Menu bar item spacing" to "Small Spacing." After logging out and back in (or, if that doesn't work, rebooting), the changes should take effect.

A: You can hold Cmd ⌘ and drag some of the icons to remove them to reduce the amount you have in the menubar. With some of the new additions Apple has put in, there is some redundancy and you no longer need some of them. For example - you no longer need the Sound menubar item. I know it's not a huge help - but it seems these days every little bit counts, lol..
Good luck!


text:
Q: JQuery mobile load external script I have the following page in a jQuery mobile site:
<div data-role="page" id="myPage">
   <script type="text/javascript">alert("test");</script>
   <script src="https://someexternalscript.js"></script>
</div>

The first script tag, with the script contained in it, is evaluated properly. Every time I navigate to the page, an alert is shown. The second script tag however, is only evaluated when I navigate the browser directly to this page. When I navigate through the site itself, it isn't being evaluated.
I noticed with Fiddler that the source is being downloaded, it just doesn't seem to be evaluated.
Any ideas what could be causing this, and how it could be resovled?

A: script tag is is not self closing tag, so you need to close it using </script>


text: Q: Basic source (include?) command equivalent in sql I am new to SQL. What is the source command (#include command) in postgre-sql? I want to divide my script into multiple files and tell SQL to execute scripts from part01.sql, part02.sql,....


text:
Q: Filezilla client disconnects immediately after receiving hello message I've recently installed FileZilla server on my desktop, and a client on my laptop, both latest versions. When I try to establish a connection in my local network, everything works fine. However, trying to connect when laptop is on remote network I get this:
Status: Resolving address of my.ftp.server // this isn't the real address/ip of course
Status: Connecting to 24.123.185.9:5845...
Status: Connection established, waiting for welcome message...
Response: 220 hello
Command: USER anonymous
Error: Could not connect to server

And the server shows this:
(000031)18/12/2013 23:17:12 PM - (not logged in) (31.44.131.77)> Connected, sending welcome message...
(000031)18/12/2013 23:17:12 PM - (not logged in) (31.44.131.77)> 220 hello
(000031)18/12/2013 23:17:12 PM - (not logged in) (31.44.131.77)> disconnected.

This happens all the time.

*

*I checked my server on http://ftptest.net/ and it works fine, this is why I'm assuming it's a client problem.

*Problem occurred when firewall on both sides was turned off.

*Tried it with anonymous user and regular password protected user

Any ideas? Thanks!


text:
Q: Uncaught TypeError: Cannot read property 'ajax' of undefined I'm trying to show data from a JSON object in the content section of a WordPress website. The following static HTML works like a charm.
<!DOCTYPE html>

    <title>Now Playing</title>

Listeners: 00

Now Playing: LIVE

But when I put the JavaScript (without jQuery) into a separate file and wp_enqueue_script it in my functions.php like so
function kirtan_scripts() {
    wp_enqueue_script( 'kirtan-nowplaying', get_stylesheet_directory_uri() . '/js/nowplaying.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'kirtan_scripts' );

it logs the following error to the browser console:
Uncaught TypeError: Cannot read property 'ajax' of undefined radioTitle
(anonymous function)

Why is it undefined when I use it in a separate JavaScript file and not undefined when I put it inline into the HTML head?