text:
Q: Symfony2 WebTest Request is failing I have this functional test which is failing, giving not found, although when trying out in the browser, it works. I'm guessing it has to do with timing. Is it possible??
public function testCreateGet()
{
    $client = static::createClient();
    $client2 = static::createClient();

    $client->request('GET', '/user/create/Juan Lopez/1234.json');
    $id = $client->getResponse()->getContent();
    // e.g. $id = 1

    $client2->request('GET', '/user/getById/'.$id.'.json');
    $clientData = json_decode($client2->getResponse()->getContent());
    // Getting not found here

    $this->assertEquals("Juan Lopez", $clientData['name']);
}

A: I hadn't noticed the json format in the user creation response. Updated code, working:
$client = static::createClient();

$client->request('GET', '/user/create/Juan Lopez/1234.json');
$response = json_decode($client->getResponse()->getContent());
$id = $response->id;

$client->request('GET', '/user/getById/'.$id.'.json');
$clientData = json_decode($client->getResponse()->getContent());

$this->assertEquals("Juan Lopez", $clientData->name);


text:
Q: append dataframe in specific cell I am trying to grab data from a mysql database and put it in an excel template ( with macro's).
The template has mutiple sheets.I want to put the data in a specific sheet and specific cell ( B2 ) since the sheet already contains data.
The code i am using is:
wb= openpyxl.load_workbook('C:/Users/Olav/Desktop/Xenos/Nieuw.xlsx')
ws = wb['Dump Pickloc - del. web']

picklocaties = "SELECT Artikelnummer, Locatie,PICKZONE FROM picklocaties WHERE PICKZONE in ('BASIS','HL')"
df = pd.read_sql(sql=picklocaties, con=mydb)

rows = dataframe_to_rows(df)

for r in dataframe_to_rows(df, index=False, header=False):
    ws.append(r)

I tryed using to_excel but that just deletes everything.
The template in which i am putting the data looks like This.
It would be great if this code would work but it does not have that option:
for r in dataframe_to_rows(df, index=False, header=False, startrow=1, startcol=1):
    ws.append(r) \
Woah i'm half way there, woah living on prayer.
This codes gets me halfway. I get the columns now where i want without messing up the rest. But for some reason the rest of the data is not shown.
for col, text in enumerate(df, start=2):
    ws.cell(column=col,row=2, value=text)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Actual difference between end of line and end of file under windows? I understand EOF and EOL but when I was reading this question  (second part of answer) and i got my concepts broken :
Specially the para :

It won't stop taking input until it finds the end of file(cin uses
  stdin, which is treated very much like a file)

so i want to know when we do some thing like in c++ under windows :
std::cin>>int_var; , and we press enter , this end the input but according to reference link it should only stop taking input after hitting ctrl+z.
So i would love to know how std::*stream deal with EOF and EOL.
Second part:
please have a look at this example :

std::cin.getline(char_array_of_size_256 ,256);
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "artist is " << artist << endl;

If i remove std::cin.ignore() it simply stops taking input (which is known case) but when i keep it , it waits for a new input which is ended by '\n' . But it should simply clear up stream rather then waiting for any new input ending-up with '\n'.
Thanks for giving you time)

A: End-of-line and end-of-file are very different concepts.
End-of-line is really just another input character (or character sequence) that can appear anywhere in an input stream.  If you're reading input one character at a time from a text stream, end-of-line simply means that you'll see a new-line ('\n') character.  Some input routines treat this character specially; for example, it tells getline to stop reading.  (Other routines treat ' ' specially; there's no fundamental difference.)
Different operating systems use different conventions for marking the end of a line.  On Linux and other Unix-like systems, the end of a line in a file is marked with a single ASCII linefeed (LF, '\n') character.  When reading from a keyboard, both LF and CR are typically mapped to '\n' (try typing either Enter, Control-J, or Control-M).  On Windows, the end of a line in a file is marked with a CR-LF pair (\r\n).  The C and C++ I/O systems (or the lower-level software they operate on top of) map all these markers to a single '\n' character, so your program doesn't have to worry about all the possible variations.
End-of-file is not a character, it's a condition that says there are no more characters available to be read.  Different things can trigger this condition.  When you're reading from a disk file, it's just the physical end of the file.  When you're reading from a keyboard on Windows, control-Z denotes end-of-file; on Unix/Linux, it's typically control-D (though it can be configured differently).
(You'll usually have an end-of-line (character sequence) just before end-of-file, but not always; input can sometimes end in an unterminated line, on some systems.)
Different input routines have different ways of indicating that they've seen an end-of-file condition.  Read the documentation for each one for the details.
As for EOF, that's a macro defined in <stdio.h> or <cstdio>.  It expands to a negative integer constant (typically -1) that's returned by some functions to indicate that they've reached an end-of-file condition.
EDIT: For example, suppose you're reading from a text file containing two lines:
one
two

Let's say you're using C's getchar(), getc(), or fgetc() function to read one character at a time.  The values returned on successive calls will be:
'o', 'n', 'e', '\n', 't', 'w', 'o', '\n', EOF

Or, in numeric form (on a typical system):
111, 110, 101, 10, 116, 119, 111, 10, -1

Each '\n', or 10 (0x0a) is a new-line character read from the file.  The final -1 is the value of EOF; this isn't a character, but an indication that there are no more characters to be read.
Higher-level input routines, like C's fgets() and C++'s std::cin >> s or std::getline(std::cin, s), are built on top of this mechanism.

A: First "part"

so i want to know when we do some thing like in c++ under windows : std::cin>>int_var; , and we press enter , this end the input but according to reference link it should only stop taking input after hitting ctrl+z.

No, you're confusing formatted input operations with stream iterators.  The following will use the formatted input operation (operator>>) repeatedly until the end of file is reached because the "end iterator" represents the end of the stream.
std::vector<int> integers;
std::copy(
    std::istream_iterator<int>(std::cin),
    std::istream_iterator<int>(),
    std::back_inserter(integers));

If you use the following:
int i = 0;
std::cin >> i;

in an interactive shell (e.g. in console mode), std::cin will block on user input which is acquired line by line.  So, if no data (or only white space) is available, this operation will actually force the user to type a line of input and press the enter key.
However,
int i = 0;
int j = 0;
std::cin >> i >> j;

may block on one or two lines of input, depending on what the user types.  In particular, if the user types
1<space>2<enter>

then the two input operations will be applies using the same line of input.
Second "part"
Considering the code snippet:
std::cin.getline(char_array_of_size_256 ,256);
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "artist is " << artist << endl;

If the line contains 255 or less lines of character data, std::cin.getline() will consume the end-of-line character.  Thus, the second line will consume all characters until the next line is completed.  If you want to capture only the current line and ignore all characters past 256, I suggest you use something like:
std::cin.getline(char_array_of_size_256 ,256);
if (std::cin.gcount() == 256) {
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
cout << "artist is " << artist << endl;

A: On the second part:
When the linked answer said "read into a string", I guess they meant
std::string   s;
std::getline(std::cin, s);

which always reads the entire line into the string s (while setting s to the proper size).
That way there is nothing left over from the input line to clean up.


text:
Q: Dynamic tabs and load page in the tabs without using iframe in twitter bootstrap I am using twitter bootstrap. I have a menu and I want to add a dynamic tab when user click on the menu. New tab will load another page but I don't want to use iframe for loading the page.
Do you guys have any solution for that?

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="../ico/favicon.ico">

    <title>Theme Template for Bootstrap</title>

 Product

Catagory

Software

 Header 2

Link

Link

Header 2.1

Link

Link

Header 2.1.1

Link

Link

Header 2.2

Link

Link

Header 2.2.1

Link

Link

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

Dashboard

Label

                  Something else

Label

                  Something else

Label

                  Something else

Label

                  Something else

              <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

A: See http://www.jeasyui.com/documentation/index.php
      $('#tt').tabs('add',{
        title:title,
        //content:content,
        href: url, // remote url with content
        closable:true
      });

Also, using AJAX functions like jQuery.load() (https://api.jquery.com/load/) or jQuery.get() (http://api.jquery.com/jQuery.get/) is possible.


text:
Q: How do I clear the keystroke buffer from int 16h I've tried
Flush Keyboard Buffer x86 assembly using int 16h
's solution, and it didn't work. I did everything I could to stop the buffer from happening and nothing seems to work.
I am currently making a game in assembly, and when I press for example "w" for too long, the character will continue moving for a little more then half a second after I stopped pressing "w".
this is my mainloop that detects when a key is pressed, but for some reason remember previous keys:
mainloop:
    mov ah, 1h
    int 16h
    jz after_press
    mov ah, 0h
    int 16h
    cmp ah, 11h                 ; 11h == scancode for W
    jne mlr1
    call link_up
    mlr1:
        cmp ah, 1Eh             ; 1Eh == scancode for A
        jne mlr2
        call link_left
    mlr2:
        cmp ah, 1Fh             ; 1Fh == scancode for S
        jne mlr3
        call link_down
    mlr3:
        cmp ah, 20h             ; 20h == scancode for D
        jne after_press
        call link_right
    after_press:
        mov ax, 5h
        mov bx, 0h
        int 33h
        cmp ax, 1h
        jne asrd
        call use_sword
    asrd:
    call octorok_ai
    mov bx, 1h ; delay time
    call delay
    jmp mainloop

If someone can please tell me how do I clear the buffer, I will be gratefull


text:
Q: Gray tiles when using OpenTopoMap on R-leaflet I'm trying to use OpenTopoMap on a R Leaflet map. The basemaps from OSM, Esri and Stamen loads fine (thus no proxy problem) but when I try to load OpenTopoMap, all I get are gray tiles.
Anyone else has this problem? Bellow is the R code I use:
require(leaflet)

m <- leaflet() %>%
  addTiles(group = 'OSM') %>%
  addProviderTiles(providers$OpenTopoMap, group='Topo') %>%
  addProviderTiles(providers$Esri.WorldTopoMap, group='Esri') %>%
  addProviderTiles(providers$Stamen.Toner, group = "Toner") %>%
  addLayersControl(
    baseGroups = c('OSM', 'Topo', 'Toner', 'Esri'))

m


text:
Q: How to make UI changes on xcode appear directly? So the problem I'm facing is that I am changing the location of the label according to its width. and It's not taking effect immediately.
[self setItToFront:self.label];

Method setItToFront:
-(void) setItToFront: (UILabel*) label
{
    int labelWidth = label.frame.size.width;
    label.frame = CGRectMake(-(labelWidth), label.frame.origin.y, labelWidth,label.frame.size.height);
}

Now when I call the below method on a press of a button
    NSLog(@"%f",self.label.frame.size.width);

It gives me the initial width. Not the new width after changing its text.
The thing am doing is that am reading an xml webpage and updating the label's text with the webpage values. and am calling this method at the end to display the label with the new text at a certain location.

A: I just moved [self.label sizeToFit] before the method call
    NSLog(@"%f",self.label.frame.size.width);

and that was it :) It was really silly !


text:
Q: Horizontally aligning button I'm trying to horizontally align a button using CSS. Here's my markup:
<button type="button" class="primary-button download-button">Download</button>

And my relevant CSS:
.primary-button {
    font-family: Arial, sans-serif;
    font-size: 1.3em;
    color: #fff;
    border: 1px solid #004487;
    background-image: -webkit-gradient(linear, top, bottom, from(#5288bd), to(#2f659a));
    background-image: -webkit-linear-gradient(top, #5288bd, #2f659a);
    box-shadow: inset 0px 1px 0px rgba(255, 255, 255, 0.4), inset 0px 0px 0px 1px rgba(255, 255, 255, 0.2), 0px 1px 0px rgba(255, 255, 255, .7);
    text-shadow: 0px -1px 0px black;
    cursor: pointer;
}

.download-button {
    padding: 10px 20px;
    border-radius: 5px;
    display: block;
    margin: 10px auto 0px auto;
}

However, it's still aligned to the left. I thought setting margin: 10px auto 0px auto; would horizontally align it seen as it's now a block element but apparently not.
I've also tried wrapping it in a div and using text-align: center but that doesn't work either.

A: Give the button a width. See this jsFiddle example.
.download-button {
    padding: 10px 20px;
    border-radius: 5px;
    display: block;
    width: 130px;
    margin: 10px auto 0px auto;
}

Without a width, you're trying to center a block level element that is the full width of it's container. By explicitly setting a width (for example 130px on your button) the margin centering rule works.

A: Actually setting float to none if both have position: relative should work:
.container{
  text-align: center;
 }
.button{
  float: none;
}


text:
Q: Using the class type of an object to create a new instance I call a method with the signature save(Object o) this way:
EntityManager em = new EntityManager(); // My own EntityManager
User user = new User(); // Constructor provides values
em.save(user);

In the save-method I need to instantiate a new object, in this case it would be of type User this way: User user = (User) o;
Well, so far I can extract the class of the object with o.getClass(), which delivers class org.example.User, which is User.class I guess. But I can't figure out how I could realize the line User user = (User) o; with that.

A: To realise the line Clazz user = (Clazz) o;, in the save method, where Clazz is the class of the object passed to the save method, so in this case User, you can make use of generics in the signature of save as follows:
public <T> void save(T user) throws IllegalAccessException, InstantiationException, InvocationTargetException {
    int i = 0;
    List<Object> args = new ArrayList<>();
    args.add(0,"Example");
    T newUser = (T)user.getClass().getConstructors()[i].newInstance(args);
    // Exciting things...
}

Note that the type of newUser is inferred from the type of object passed to the method, and that you will need to know what objects are expected to be passed to the constructor of that type, to create the args array, otherwise an exception will be thrown. Similarly you'll need to know the position of the constructor in the array in order to set i.
In short, you need to be sure what kind of constructor the user argument will have, otherwise you'll run into troubles.
However, I believe this answers your question.

A: Is calling the method newInstance() on Class that you need ? it will have the same effect as new User()
Edit : i didn't understand your question as well, but i think i am right

A: If I understand you correctly, you are trying to instantiate a class using its class object?
You can get the class' available constructors via Class.getConstructors, then invoke any of them with Constructor.newInstance, passing your parameters.


text:
Q: Excel Codemodule properties I got a problem trying to retrieve name property of a codemodule from code (C#).
When I alt+f11 my excel file I have the following:
Chart1
Sheet2
Sheet3
ThisWorkbook
When displaying properties for these, they have following properties
(Name): Chart1
Name: Pass Rate
What I want to do is access the property "Name" from C#. Is this possible? All I seem te be able to retrieve is "(Name)".
Using interop 11.0.0.0 (office 2003)

A: This will give you the name of the worksheet
MessageBox.Show(ws.Name) ;

and this will give you the Code Name of the worksheet
MessageBox.Show(ws.CodeName) ;

Note: ws above is your worksheet object.


text:
Q: Error viewing Build definitions in VS 2012 / TFS 2012 I recently installed VS 2012 update 2 and now I get an error when I click on "Builds" under Team Explorer.  I've tried a repair of update 2.  I'd rather not do a complete reinstall unless I have to, so I'm hoping someone has run into this before.  Any help is appreciated.
 System.Exception: The component 'Microsoft.TeamFoundation.Build.Controls.BuildsPageView' does not have a resource identified by the URI '/Microsoft.TeamFoundation.Build.Controls;component/buildspage/buildspageview.xaml'.
    at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
    at Microsoft.TeamFoundation.Build.Controls.BuildsPageView.InitializeComponent()
    at Microsoft.TeamFoundation.Build.Controls.BuildsPage.CreateView(PageInitializeEventArgs e)
    at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.TeamExplorerPageBase.Initialize(Object sender, PageInitializeEventArgs e)
    at Microsoft.VisualStudio.TeamFoundation.Build.BuildsPageVs.Initialize(Object sender, PageInitializeEventArgs e)
    at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.Framework.TeamExplorerPageHost.Initialize(TeamExplorerPageContext context)

A: Do you also have the TFS Power Tools and Coderush 12.2.8 installed? If so, there seems to be a conflict between these versions.
Check out this bug report for more details: http://www.devexpress.com/Support/Center/Question/Details/Q488684
Installing the latest version of the TFS Power Tools that were released on April 18th fixed it for me.


text:
Q: Styles not loading in Django I have a site that needs some custom styles in Django and I can't get the static file to load.
I have a static folder inside my main folder - The one where manage.py lives, Inside there is a CSS folder that contains a style.css.
At the top of base.html, I load
{% load static %}

Then in the head of my HTML I load
 <link rel="stylesheet" href="{% static 'css/styles.css' %}">

and in my settings.py file I have loaded in
# Static file route
STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]

When I load I just get a blank CSS file and no styles load, I'm fairly new to Django so please be kind, and thanks in advance.
Also, I want make sure my static folder is created in the right place:

A: Try
STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / "static",
]

where BASE_DIR = Path(__file__).resolve().parent.parent
check also that you have
INSTALLED_APPS = [
    'django.contrib.staticfiles',
]

From your screen your static is css/style.css but you load <link rel="stylesheet" href="{% static 'css/styles.css' %}"> instead.
You need to load <link rel="stylesheet" href="{% static 'css/style.css' %}">

A: You have to run in terminal:
python manage.py collectstatic

After every change of static files if I remember correctly.
Other then that, pressing F12 in a browser can show why a specific file isn't loading. So can the terminal/console where Django is running(or log files if no access to it).


text:
Q: Flutter - Converting minutes into H:M I'm looking for a method to convert minutes into hours and minutes. I'm using the intl package through DateFormat but this requires both hours and minutes so it won't do.
If I have 100 minutes, I would like this to be converted to 01:40. Thanks

A: Does this work?
String durationToString(int minutes) {
    var d = Duration(minutes:minutes);
    List<String> parts = d.toString().split(':');
    return '${parts[0].padLeft(2, '0')}:${parts[1].padLeft(2, '0')}';
}

print(durationToString(100)); //returns 01:40

A: This will work for you

String getTimeString(int value) {
  final int hour = value ~/ 60;
  final int minutes = value % 60;
  return '${hour.toString().padLeft(2, "0")}:${minutes.toString().padLeft(2, "0")}';
}


text:
Q: how to get decimal values and special character using regex in oracle in my table has values like below and texts are in front and back text (not able to get value using  substring) decimal is not only like below.How to get these values from the specific columns
2.0GB/3.GB(not only GB  etc like many)
2.0/3.0 mp
2.0 GB/ 3.GB
2.0 /3.0 mp
2.0
2.0 mp
1

i used below query to get it is not work out for me . below query are
REGEXP_SUBSTR(column, '\d.*)

A: Use
REGEXP_SUBSTR(REGEXP_REPLACE(REGEXP_REPLACE(s, '^.*,', ''),'\[[0-9]+]|[0-9]+\s*-\s*[0-9]+|[a-zA-Z][0-9]+', ''), '[0-9][.0-9]*\s*[a-zA-Z]*([-/]\s*[.?0-9][.0-9]*\s*[a-zA-Z]*)?')

The first step is removing all up to the last comma:
REGEXP_REPLACE(s, '^.*,', '')

The second step is removing digit(s) inside square brackets, letters with digits after them and hyphen-separated ranges:
REGEXP_REPLACE(s,'\[[0-9]+]|[0-9]+\s*-\s*[0-9]+|[a-zA-Z][0-9]+', '')

Here, the pattern removes substrings matching:

*

*\[ - a [

*[0-9]+ - 1+ digits

*] - a ]

*| - or

*[0-9]+\s*-\s*[0-9]+ - 1+ digits ([0-9]+), a - enclosed with 0+ whitespaces and again 1+ digits

*| - or

*[a-zA-Z][0-9]+ - a letter with 1+ digits after it.

The third step is to extract the matches you need:

*

*[0-9][.0-9]* - a digit followed with 0+ digits or . symbols

*\s*  - 0+ whitespaces

*[a-zA-Z]* - 0+ letters

*([-/]\s*[.?0-9][.0-9]*\s*[a-zA-Z]*)? - an optional sequence of:

*

*[-/] - a - or /

*\s*  - 0+ whitespaces

*[.?0-9] - ., ? or digits

*[.0-9]*\s*[a-zA-Z]*  - see above

See the online demo:
with test(s) as (
    select 'text [1234] 1gb' from dual union all
    select '(some text)800 - 784(some text) 2 Gb' from dual union all
    select '2.0GB/3.GB' from dual union all
    select '2.0/3.0 mp' from dual union all
    select '2.0 /3.0 mp' from dual union all
    select '2.0' from dual union all
    select '2.0 mp' from dual union all
    select '1' from dual union all
    select '2.0 GB/ 3.GB' from dual
)
select s,
       REGEXP_SUBSTR(REGEXP_REPLACE(REGEXP_REPLACE(s, '^.*,', ''),'\[[0-9]+]|[0-9]+\s*-\s*[0-9]+|[a-zA-Z][0-9]+', ''), '[0-9][.0-9]*\s*[a-zA-Z]*([-/]\s*[.?0-9][.0-9]*\s*[a-zA-Z]*)?')
from test

Output:
1   abc1 1gb,tb1 1 gb,eard1 2 gb,help2 12 gb    12 gb
2   text [1234] 1gb                             1gb
3   (some text)800 - 784(some text) 2 Gb        2 Gb
4   2.0GB/3.GB                                  2.0GB/3.GB
5   2.0/3.0 mp                                  2.0/3.0 mp
6   2.0 /3.0 mp                                 2.0 /3.0 mp
7   2.0                                         2.0
8   2.0 mp                                      2.0 mp
9   1                                           1
10  2.0 GB/ 3.GB                                2.0 GB/ 3.GB


text:
Q: move old inline JavaScript I have this small component that opens a window onclick. The problem is its inline JavaScript, and I know that is dated and ugly. How can I move it down below and keep the same functionality? This isn't my code, I'm just trying to learn :) I've tried to target the a tag via its ID, and then add an event listener but then I get errors saying focus is undefined and  the link just uses its default functionality and take me to the url in the same window. Any pointer? I'd really appreciate the help!
<body>
    <a id="tower" href="http://static.slh.com/files//HUPARSR/Large_Gallery_02_HUPARSR_53800328_Exterior_-_Eiffel_tower_view_400x600_72.jpeg"
    onClick='showPDF(this.href);return(false);'>
            Click here to see the Eiffel Tower.
    </a>
<script>
function showPDF(url) {
newwindow=window.open(url,'name','height=400,width=600,top=100,left=100,resizable');
if (window.focus) {newwindow.focus()}
}
</script>
</body>

A: Remove onclick from the a element and attach an event listener with javascript:
<script>
document.getElementById("tower").addEventListener("click", function() {
    showPDF(this.href);
    return false;
});
// ... your other code below ...
</script>


text:
Q: GLUT mouse move , coordinates always on How to get the mouse coordinates always, without click on mouse?
void mouseMove(int mx, int my) {

}

int main(int argc, char ** argv){
    glutInit( &argc, argv );
    glutInitWindowSize( x, y );
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
    glutCreateWindow( "Freetype OpenGL" );
    glutReshapeFunc( reshape );
    glutDisplayFunc( display );
    glutKeyboardFunc(keyboard);
    glutMotionFunc(mouseMove);
    timer();
    glutMainLoop( );
    return 0;
};

A: glutMotionFunc() is called when the mouse moves within the window while one or more mouse buttons are pressed, and glutPassiveMotionFunc()  is called when the mouse moves within the window while no mouse buttons are pressed.
You probably want to use both of them, to cover all the cases.


text:
Q: Using ajax in zend framework 2 i am really new to the zend framework 2 and to the programming of web applications. In my application, i want to have a button which triggers a function that changes the content of a database and returns a String which i can use to update the visible content of the website. As i don´t want the website to reload when the button is clicked, i would like to do this using ajax. After reading a couple of ajax tutorials, i imagined that the solution would look somilar to this:
The HTML part:

 ......
 <button id="function_button" onClick="myFunction()">Click</button>

Initial text"

 ......

With the .php file function.php (for the beginning, i just want it to return a text value) :
<?php

     echo "Text triggered by the button click";
?>

When i try to test the button, nothing happens. Apparently, the xmlhttp.status is 404 and the function.php file can´t be found. I suppose that either the location where i put the function.php file (it is in the same folder as the .phtml - view file of the website) or the url i´m using in the xmlhttp.open - function is wrong. Could you please tell me how to use ajax in zf2 correctly? Thank you for your time, every answer is very much appreciated.

A: First of all i want to thank for all your answers. They really were a great help. Using jQuery is indeed much more comfortable, and not only for Ajax calls, than using pure Javascript. James, thank you very much for your answer. I tried to use it, but i probably did something wrong because it did not work. I found another solution for my problem and i want to post it here in order to round this question up.
The code that i am going to post is a little example that just does a simple thing: on a user click on a button in a website created by zend framework 2, an input field is read, the content of it is transfered to a server function, which, according to the data it receives, returns a certain result. After receiving the result, the website is updated without being reloaded.
As i am going to use Json objects for the communication, it is necessary to activate the Json strategies in zf2 by adding the following codeline to the module.config.php:
// module/Application/config/module.config.php

'view_manager' => array (
                'display_not_found_reason' => true,
                'display_exceptions' => true,
                'doctype' => 'HTML5',
                'not_found_template' => 'error/404',
                'exception_template' => 'error/index',
                'template_map' => array (
                        'layout/layout' => __DIR__ .
'/../view/layout/layout.phtml',
                        'application/index/index' => __DIR__ .
'/../view/application/index/index.phtml',
                        'error/404' => __DIR__ .
'/../view/error/404.phtml',
                        'error/index' => __DIR__ .
'/../view/error/index.phtml'
                ),
                'template_path_stack' => array (
                        __DIR__ . '/../view'
                ),
                'strategies' => array (            // Add
                                           // this
                        'ViewJsonStrategy' // line
                )

        ),

The view file of the website (called, for example example.phtml) will look similar to this:

<input id="input_to_read" type="text">
<button id="trigger">Klick</button>

The server function, that is going to be called when the button is clicked, is placed in the controller for the website (in this case, the ExampleController) and could look like this:
//Make sure to add this line to use Json objects
use Zend\View\Model\JsonModel;

....

public function answerAction(){

#read the data sent from the site
$text = $_POST['textData'];

#do something with the data

$text = $text . "successfully processed";

#return a Json object containing the data

$result = new JsonModel ( array (

                'text' => $text
        ) );
return $result;
}

A: Typically the way I would handle this, is to build an RPC controller to just return JSON, and then use some good javascript frameworks like jQuery, and Knockout JS, to dynamically update the relevant UI areas. I believe the base Zend controller class provides a $this->_helper->json method that will return JSON instead of returning what you have defined in a given view. In the case of Public_RpcController below I didn't even define a view at all. It returns JSON which I can use in conjunction with JS frameworks for client side markup manipulation. Using the JS frameworks has a bit of learning curve but well worth learning.
class Public_RpcController extends MySubClassed_Controller_Action
{
    public function getUserDataAction()
    {
        $output = array();
        $request = $this->getRequest();

        ...

        $output = array(
                'Value1'    => "foobar",
                'Value2'    => "foobar",
        );
        return $this->_helper->json($output);
    }
}

// Use Jquery to fetch JSON data to update.
$.getJSON( "/rpc/get-user-data", function( data ) {
    // Do something with the JSON data like bind to Knockout template.
});


text:
Q: Avoiding form resubmission in SPA (without P-R-G) I have a Single Page Application (SPA) built with DurandalJS v1.2 that integrates with a payment gateway. The SPA will go off to the payment gateway's page by doing a normal form POST to their page.
Once the user has finished on the payment gateways page, the payment gateway will then do a form POST back to my SPA.
Since it's a POST, I handle it server side in ASP.NET MVC by rendering out a require.js module definition for the various form parameters being sent, and this module is then used in the view model that needs to handle the result.
This is all working fine, I handle the result, and then stay on the same SPA page. This is different to the typical web pattern of Post-Redirect-Get, since the SPA doesn't do any redirects.
The issue now is when pressing the browser refresh button, it's bringing up the browser's retry post confirmation dialog (which I don't want).
Is there a way to avoid this by using JavaScript, or is the PRG pattern the only way?
Note: It appears that changing window.location, document.location, as well as using history.replaceState all do not work (at least in Chrome).

A: If you can modify the payment gateway, then intercept the form submission (<form onsubmit="...; return false">), process the form fields from JavaScript instead of letting the browser send them to the server.
If you can't modify the payment gateway, then modify the document.location from JavaScript just after the POST back (e.g. by adding a #). If the user presses reload after this, the browser won't ask for confirmation.


text:
Q: How manage resources childs when using resourceRender? I'm using fullcalendar in react and all works fine until I start using the resourceRender prop and the child resources are displaying not as a part of the resource parent expansion anymore.
How show the child of a resource as to how the default designs?
This is how my resources looks like
export const resources = [
  {
    id: 1,
    title: "Conversación estaciones",
  },
  {
    id: 2,
    title: "Renovaciones Las Americas",
  },
  {
    id: 3,
    title: "Remuneración II",
    children: [
      { id: "d1", show: true, title: "Room D1" },
      { id: "d2", show: false, title: "Room D2" }
    ],
  },
  {
    id: 4,
    title: "Actividades cotidianas",
  },
  {
    id: 5,
    title: "Actividades rudimentarias ",
  }
];

And this is how the children resources render in the calendar
this is how the children resources render in the calendar


text:
Q: Clearing a read() buffer while using a socket Recently I've been messing around with some sockets by trying to make a client/server program. So far I have been successful, but it seems I hit a roadblock. For some quick background information, I made a server that can accept a connection, and once everything is set up and a connection to a client is made, this block of code begins to exectue:
while(1){
        read(newsockfd, &inbuffer, 256);

        std::cout << "Message from client " << inet_ntoa(cli_addr.sin_addr) << " : ";
        for(int i = 0; i < sizeof(inbuffer); i++){
            std::cout << inbuffer[i];

        }
        std::cout << std::endl;

}

Now the client simply, when executed, connects to the server and writes to the socket, and then exits. So since one message was sent, this loop should only run once, and then wait for another message if what I read was correct.
But what ends up happenning is that this loop continues over and over, printing the same message over and over. From what I read (on this site and others) about the read() function is that after it is called once, it waits for another message to be recieved. I may be making a stupid mistake here, but is there any way I can have this read() function wait for a new message, instead of using the same old message over and over? Or is there another function that could replace read() to do what I want it to?
Thanks for any help.

A: You don't check the return value of read. So if the other end closes the connection or there's an error, you'll just loop forever outputting whatever happened to be in the buffer. You probably want:
while(1){
    int msglen = read(newsockfd, &inbuffer, 256);
    if (msglen <= 0) break;

    std::cout << "Data from client " << inet_ntoa(cli_addr.sin_addr) << " : ";
    for(int i = 0; i < msglen; i++){
        std::cout << inbuffer[i];
    }
    std::cout << std::endl;

}

Notice that I changed the word "message" to "data". Here's why:

So since one message was sent, this loop should only run once, and then wait for another message if what I read was correct.

This is incorrect. The code above does not have any concept of a "message", and TCP does not preserve application message boundaries. So not only is this wrong, there's no way it could be correct because the word "message" has no meaning that could possibly apply in this context. TCP does not "glue together" the bytes that happend to be passed in a single call to a sending function.


text:
Q: Postgresql: how to set the date in all rows of table? I have a table A with field duedate.
I want to set all rows which duedate is less than today to be today+3 months.
for example:
id duedate
1   2015-08-15
2   2014-07-15
3   2015-03-01
4
5   2015-03-02

will be (today is: 2015-07-06):
id duedate
1   2015-08-15
2   2015-10-06
3   2015-10-06
4   2015-10-06
5   2015-10-06

A: To get "today plus three month", simply add those three month to current_date:
update A
  set duedate = (current_date + interval '3' month)::date
where duedate < current_date
   or duedate is null;

The result of "date + interval" is a timestamp not a date, therefor this needs to be cast back to a date.
To handle the null values, just include an additional condition in the where clause. The comparison where duedate < current_date will fail for those rows where duedate is null but they will be included because of the additional condition.


text:
Q: Oracle DataSource Doubts?
*

*When we get a connection using datasource say oracleDatasource .
Lets say during programming, some developer does not close the connection
explicity. Will that connection be returned to connection or will it
be considered as connection leak?

*As it is said, datasource is created, deployed, and managed separately(by appserver) from the applications that use it. There are two ways in which we can create datasource

*

*From appserver admin console.(I understand that datasource can be managed by appserver here)

*Second way is to create datasource in your pragramme like
Datasource ds = new OracleDataSource();
But how will datasource be managed by appserver api in this case as we are creating it in our programme?


text:
Q: Gunicorn SyntaxError in Heroku build I am getting the following SyntaxError in my Heroku build, any ideas on what the problem might be? Using Gunicorn 19.9.0
2019-03-10T21:11:24.936875+00:00 heroku[web.1]: Starting process with command `gunicorn main: app.server`
2019-03-10T21:11:27.137010+00:00 heroku[web.1]: State changed from starting to up
2019-03-10T21:11:26.929950+00:00 app[web.1]: [2019-03-10 21:11:26 +0000] [4] [INFO] Starting gunicorn 19.9.0
2019-03-10T21:11:26.930979+00:00 app[web.1]: [2019-03-10 21:11:26 +0000] [4] [INFO] Listening at: http://0.0.0.0:32580 (4)
2019-03-10T21:11:26.931151+00:00 app[web.1]: [2019-03-10 21:11:26 +0000] [4] [INFO] Using worker: sync
2019-03-10T21:11:26.935311+00:00 app[web.1]: [2019-03-10 21:11:26 +0000] [9] [INFO] Booting worker with pid: 9
2019-03-10T21:11:36.572657+00:00 app[web.1]: [2019-03-10 21:11:36 +0000] [9] [ERROR] Exception in worker process
2019-03-10T21:11:36.572690+00:00 app[web.1]: Traceback (most recent call last):
2019-03-10T21:11:36.572693+00:00 app[web.1]: File "/app/.heroku/miniconda/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2019-03-10T21:11:36.572695+00:00 app[web.1]: worker.init_process()
2019-03-10T21:11:36.572697+00:00 app[web.1]: File "/app/.heroku/miniconda/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2019-03-10T21:11:36.572699+00:00 app[web.1]: self.load_wsgi()
2019-03-10T21:11:36.572701+00:00 app[web.1]: File "/app/.heroku/miniconda/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2019-03-10T21:11:36.572702+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2019-03-10T21:11:36.572704+00:00 app[web.1]: File "/app/.heroku/miniconda/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2019-03-10T21:11:36.572705+00:00 app[web.1]: self.callable = self.load()
2019-03-10T21:11:36.572707+00:00 app[web.1]: File "/app/.heroku/miniconda/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2019-03-10T21:11:36.572709+00:00 app[web.1]: return self.load_wsgiapp()
2019-03-10T21:11:36.572710+00:00 app[web.1]: File "/app/.heroku/miniconda/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2019-03-10T21:11:36.572712+00:00 app[web.1]: return util.import_app(self.app_uri)
2019-03-10T21:11:36.572714+00:00 app[web.1]: File "/app/.heroku/miniconda/lib/python3.6/site-packages/gunicorn/util.py", line 362, in import_app
2019-03-10T21:11:36.572715+00:00 app[web.1]: app = eval(obj, vars(mod))
2019-03-10T21:11:36.572717+00:00 app[web.1]: File "<string>", line 0
2019-03-10T21:11:36.572719+00:00 app[web.1]:
2019-03-10T21:11:36.572721+00:00 app[web.1]: ^
2019-03-10T21:11:36.572723+00:00 app[web.1]: SyntaxError: unexpected EOF while parsing
2019-03-10T21:11:36.575629+00:00 app[web.1]: [2019-03-10 21:11:36 +0000] [9] [INFO] Worker exiting (pid: 9)
2019-03-10T21:11:36.946391+00:00 app[web.1]: [2019-03-10 21:11:36 +0000] [4] [INFO] Shutting down: Master
2019-03-10T21:11:36.946455+00:00 app[web.1]: [2019-03-10 21:11:36 +0000] [4] [INFO] Reason: Worker failed to boot.
2019-03-10T21:11:37.037342+00:00 heroku[web.1]: State changed from up to crashed
2019-03-10T21:11:37.020575+00:00 heroku[web.1]: Process exited with status 3

I am in need of matplotlib.use("Agg") for all matplotlib uses in my app, this error shows up when adding that to my code, otherwise I run into issues described here: https://github.com/matplotlib/matplotlib/issues/9954/
EDIT:
Code (main.py):
import dash_core_components as dcc
import dash_html_components as html
import matplotlib
from dash.dependencies import Input, Output

matplotlib.use("Agg")

from app import app
from parameters import material, geometry, settings, mesh_tallies_xsections, runtime, postprocessing

app.layout = html.Div([
    dcc.Location(id='url', refresh=False, pathname='/parameters/material'),

    # TODO: Storage data not persist through pathname change -> storage_type to 'memory' has no effect
    # Materials
    dcc.Store(id='material-stores', storage_type='session'),
    # Geometry
    dcc.Store(id='color-stores', storage_type='session'),
    dcc.Store(id='cell-stores', storage_type='session'),
    dcc.Store(id='injection-stores', storage_type='session'),
    dcc.Store(id='temp-assembly-stores', storage_type='session'),
    dcc.Store(id='assembly-stores', storage_type='session'),
    dcc.Store(id='boundary-stores', storage_type='session'),
    # Mesh
    dcc.Store(id='mesh-stores', storage_type='session'),
    # Scores
    dcc.Store(id='mesh-score-stores', storage_type='session'),
    # Cross-Sections
    dcc.Store(id='xsection-stores', storage_type='session'),
    # Settings
    dcc.Store(id='settings-stores', storage_type='session'),

    dcc.Link('Materials', href='/parameters/material'), html.Br(),
    dcc.Link('Geometry', href='/parameters/geometry'), html.Br(),
    dcc.Link('Mesh, Tallies/Scoring, Cross-sections', href='/parameters/mesh_tallies_xsections'), html.Br(),
    dcc.Link('Settings', href='/parameters/settings'), html.Br(),
    dcc.Link('Verification & Run', href='/parameters/runtime'), html.Br(),
    dcc.Link('Postprocessing', href='/parameters/postprocessing'), html.Br(),

    html.Div(id='page-content'),
])

@app.callback(Output('page-content', 'children'),
              [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/parameters/material':
        return material.layout

    elif pathname == '/parameters/geometry':
        return geometry.layout

    elif pathname == '/parameters/settings':
        return settings.layout

    elif pathname == '/parameters/mesh_tallies_xsections':
        return mesh_tallies_xsections.layout

    elif pathname == '/parameters/runtime':
        return runtime.layout

    elif pathname == '/parameters/postprocessing':
        return postprocessing.layout

    else:
        return '404 Page not Found'

if __name__ == '__main__':
    app.run_server(debug=True)

Code (app.py):
import dash

    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    server = app.server
    app.config.suppress_callback_exceptions = True

*Note the below are all module level imports:
from app import app
    from parameters import material, geometry, settings, mesh_tallies_xsections, runtime, postprocessing
runtime contains a package import that uses matplotlib causing the other error not posted here. The dash app creates a flask-based server

A: Didn't realize no space in web: gunicorn main:app.server was vital i.e.
INCORRECT: web: gunicorn main: app.server
CORRECT: web: gunicorn main:app.server


text:
Q: What is Equivalent of Oracle Exception type in SQL SERVER What is the Equivalent of Oracle Exception type in SQL SERVER?
For example, I Oracle I have:
ER_Wrong_Option EXCEPTION;
Is there is a similar type for TSQL? at least I could not find any.


text:
Q: Codeigniter file upload and resize I'm uploading profile pictures to my website and the first upload is working fine, but when I try and resize the image and reupload it to the same folder it breaks. From testing, I know it is going through the array and it is inserting the data into the database, but just not re-saving into the folder.
This is what I have going one.
$config['upload_path'] = './uploads/';
$config['file_name'] = $this->user->pen_name.'.jpg';
$config['file_path'] = './uploads/'.$this->user->pen_name.'.jpg';
$config['max-size'] = 2000;
$config['overwrite'] = TRUE;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['remove_spaces'] = true;
$config['max_width'] = 2000;
$config['max_height'] = 3000;
$this->load->library('upload', $config);

if ( ! $this->upload->do_upload()){

        $error = array('error' => $this->upload->display_errors());
}else{
    $resize['source_image'] = base_url().'/uploads/'.$config['file_name'];
    $resize['new_image'] = './uploads/';
    $resize['file_path'] = './uploads/'.$this->user->pen_name.'.jpg';
    $resize['create_thumb'] = false;
    $resize['maintain_ratio'] = true;
    $resize['width'] = 200;
    $resize['height'] = 300;
    $resize['overwrite'] = TRUE;
    $this->load->library('image_lib', $resize);
    $this->image_lib->resize();
    $this->load->library('upload', $resize);
    $this->users_model->uploadPic($resize['file_path']);
    redirect($_SERVER['HTTP_REFERER']);
}

Any help would be much appreciated!

A: Just had the same issue, and solved it as follows:
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);

if (!$this->upload->do_upload('logoUpload')) {
    $this->data['error'] = array('error' => $this->upload->display_errors('
', '
'));
    //error
} else {

    $upload_data = $this->upload->data();

    //resize:

    $config['image_library'] = 'gd2';
    $config['source_image'] = $upload_data['full_path'];
    $config['maintain_ratio'] = TRUE;
    $config['width']     = 150;
    $config['height']   = 50;
    $this->load->library('image_lib', $config);
    $this->image_lib->resize();

    //add to the DB
    $this->settings_model->upload_logo($upload_data);
}

A: These are the default config from codeigniter, just put unlink at the end:
$config['image_library'] = 'gd2';
$config['source_image'] = '/path/to/image/mypic.jpg';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;

$this->load->library('image_lib', $config);

$this->image_lib->resize();

//remove original file
@unlink( $config['source_image'] );


text:
Q: get selected value in controller - jsp/spring I am trying to pass value from  in jsp to POST controller.
i have the controller get:
@RequestMapping(value = "/matches/{pageNumber}/", method = RequestMethod.GET)
public String games( @PathVariable Integer pageNumber, Model model ) {

    ....

    //build map for dropdown compatitions
    HashMap<Integer, String> leaguesMap = new HashMap<Integer, String>();
    leaguesMap.put(1, "Top Leagues");
    leaguesMap.put(2, "All");
    for (Competition competition : competitions) {
        if(!leaguesMap.containsKey(competition.getApiId())){
            leaguesMap.put(competition.getApiId(), competition.getName());
        }
    }

    model.addAttribute("leaguesMap", leaguesMap);
    .....
    return "upcomingMatches";
}

And then in jsp:
 <form:form  modelAttribute="leaguesMap" action="drop" class="dropdown-leagues" method="POST">
                                       <form:select path="${leaguesMap.value}"  id="league-selection"   onchange="this.form.submit()"   class="form-control select-filter select2-hidden-accessible"   aria-hidden="true">
                                            <form:options items="${leaguesMap}" />
                                     </form:select>
                                  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
                           </form:form>

I am trying to get the selected value in POST controller:
@RequestMapping(value = "/matches/{pageNumber}/drop", method = RequestMethod.POST)
 public String games( @ModelAttribute("leaguesMap")  String leaguesMap, @PathVariable Integer pageNumber, BindingResult result) {

    String fff = leaguesMap;
    System.out.println("asadasdadsa"+fff);

    return "redirect:/matches/{pageNumber}/";
}

But getting always null.
If you can give me direction how to proceed , it will be great.
Thanks!

A: Create a model class League.class
public class League {
    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Change your get controller:
    @RequestMapping(value = "/matches/{pageNumber}/", method = RequestMethod.GET)
        public String games( @PathVariable Integer pageNumber, Model model ) {
            ....

            //build map for dropdown compatitions
            HashMap<Integer, String> leaguesMap = new HashMap<Integer, String>();
            leaguesMap.put(1, "Top Leagues");
            leaguesMap.put(2, "All");
            for (Competition competition : competitions) {
                if(!leaguesMap.containsKey(competition.getApiId())){
                    leaguesMap.put(competition.getApiId(), competition.getName());
                }
            }
            model.addAttribute("leaguesMap", leaguesMap);
            model.addAttribute("league", new League());

            .....

       return "upcomingMatches";
    }

Change your jsp:
<form:form  modelAttribute="league" action="drop" class="dropdown-leagues" method="POST">
    <form:select path="id"  id="league-selection"   onchange="this.form.submit()"   class="form-control select-filter select2-hidden-accessible"   aria-hidden="true">
        <form:options items="${leaguesMap}" />
    </form:select>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form:form>

And finally your post controller:
@RequestMapping(value = "/matches/{pageNumber}/drop", method = RequestMethod.POST)
public String games( @ModelAttribute("league") League league, @PathVariable Integer pageNumber, BindingResult result) {

    System.out.println("asadasdadsa" + league.getId());

    return "redirect:/matches/{pageNumber}/";
}


text:
Q: Communication from IdentityServer to API I am currently building an identity server with Duende IdentityServer v6.1. I separated the identity server from my API into two different subdomains. People can register an account with the IdentityServer, but I also want some registration information to be saved to the API-database. So I want IdentityServer to be able to communicate to the API. Is this possible and if so, how?

A: It is described in the documentation of IdentityServer: https://docs.duendesoftware.com/identityserver/v6/tokens/internal/


text:
Q: Converting an old VBScript to JavaScript I'm working on my employer's internal web presence and there's an old piece of VBScript that they want to save. It displays in IE but doesn't work in any other browsers because, well, VBScript from what I understand is deprecated. This script takes the current date and calculates what "unit" day it is on a Fire Department unit day calendar. Today (February 26th) for instance is "1 Unit" or "Green Unit" with the next in line being 2 Unit/Blue Unit and then 3 Unit/Red Unit. If it's a leap year then the extra day is considered "0 Unit" or "White Unit".
So here is the old VBScript:
Sub UpdateClock()
  Dim iDOW, iElapsed, iLeapYears, iUnit, sDate, sTime, aDOW, aUnitColor, sHTML

  aUnitCOlor = Array("white", "green", "blue", "red")
  aDOW = Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")

  iElapsed = DateDiff("d", "3/10/2008", Date)
  iDOW = WeekDay(Date)
  iLeapYears = Int((Year(Date)-2008)/4)
  If Month(Date) > 2 Then iLeapYears = iLeapYears
  iElapsed = iElapsed + iLeapYears
  iUnit = (iElapsed Mod 3) + 1
'  sDate = aDOW(iDOW) & " " & FormatDateTime(Date,2)
  sDate = WeekdayName(DatePart("w", Now())) & " " & FormatDateTime(Date, 2)

  sTime = FormatDateTime(Time, 3)

  sHTML = "" & sDate & "; " & sTime & "
"
  sHTML = sHTML & "" & CStr(iUnit) & " Unit
"

  Clock.innerHTML = sHTML
End Sub

setInterval "UpdateClock()", 1000

And here is the JavaScript I've written to try to recreate it:
// This script is intended to calculate the fire department "unit" day
var d, sd, pd, psd, iElapsed, iLeapYears, iUnit
// Sets start date
sd = new Date("March 10, 2008");
// Sets current date
d = new Date();

// Calculates the milliseconds between each date and January 1, 1970
psd = sd.getTime();
pd = d.getTime();
// Calculates milliseconds between the two dates and divides by the number of milliseconds in a day to determine how many days have passed
iElapsed = (pd - psd) / 86400000;

// Calculates leap year
if (d.getMonth() > 1) {
  iLeapYears = (d.getFullYear() - 2008) / 4;
} else {
  iLeapYears = 0;
}
iElapsed = iElapsed + iLeapYears;
iUnit = (iElapsed % 3 + 1);

document.getElementById("DisplayUnitDay").innerHTML = iUnit;

For the current date it gives me a result of 3.9499762037034998 (based on my last refresh) but it should be telling me the unit day is 1 and not 3. 3 Unit is two days from now. I feel like I'm either missing something simple or the VBScript I'm working from is flawed (or maybe I'm not interpreting it correctly).
Can anyone point me in a direction? I mean my employer requires IE for all internal computers anyway but, personally, I'd like for it to work on other browsers as well.

A: There's a few factors to take into account in your re-write:

*

*It is not clear whether sd is 10th March 2008 or 3rd October 2008 - in any case it seems they both give an answer of 1 which may be a lucky coincidence!

*The VBScript says If Month(Date) > 2 Then but your javascript says if (d.getMonth() > 1) so that needs a correction

*The VBScript has this line iLeapYears = Int((Year(Date)-2008)/4) - you should use Math.floor as the equivalent of VBScript int in this section: iLeapYears = (d.getFullYear() - 2008) / 4;

*Use a modern library like moment.js to rid yourself of the heavy lifting around the date manipulation and formatting etc.

*Did it ever work for white team? iUnit = (iElapsed Mod 3) + 1 is never going to be 0 for +ve iElapsed. VBScript can have 0- or 1-based arrays but there's no Option Base 1 there so have to assume that for aUnitCOlor = Array("white","green","blue","red") then aUnitCOlor(0) is white.
So 27/2/17 is a green day for maybe because my time zone is GMT+11. What time zone are you in?

// unit colors
var unitColor = ['white', 'green', 'blue', 'red'];

// elapsed days
var start = moment(new Date('March 10, 2008'));
var today = moment(new Date);
var elapsed = today.diff(start, 'days');

// update for leap year
if (today.format('M') > 2) {
  elapsed += Math.floor((today.format('Y') - 2008) / 4);
}

// get unit
unitIndex = (elapsed % 3) + 1;

// render
el = document.getElementById('out');
el.innerHTML = today.format('YYYY-MM-DD') + ' is a day for the ' + unitColor[unitIndex] + ' team';


text:
Q: Request_Begin never called I have the following in an ASP.NET 2.0 page.
<script type="text/javascript">
function pageLoad()
{
    var manager = Sys.WebForms.PageRequestManager.getInstance();
    if (manager !=null)
    {
        debugger;
        manager.add_beginRequest(Request_Begin);
        manager.add_endRequest(Request_End);
    }
}

 function Request_Begin(sender, args)
 {
     debugger;
     ....
 }

 function Request_End(sender, args)
 {
     ....
 }
 </script>

The pageLoad is called but the code inside of Request_Begin never appears to be hit.

Any clue as to why?

A: The callbacks will be hit when you trigger an AJAX request using the Microsoft scripts (from an UpdatePanel for instance):
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
        function pageLoad() {
            var manager = Sys.WebForms.PageRequestManager.getInstance();
            if (manager != null) {
                manager.add_beginRequest(Request_Begin);
                manager.add_endRequest(Request_End);
            }
        }

        function Request_Begin(sender, args)
        {
            debugger;
        }

        function Request_End(sender, args) {
            debugger;
        }
    </script>
</head>
<body>
    <form id="Form1" runat="server">
        <asp:ScriptManager ID="scm" runat="server" />
        <asp:UpdatePanel ID="up" runat="server">
            <ContentTemplate>
                <%= DateTime.Now.ToLongTimeString() %>
                <asp:LinkButton ID="link" runat="server" Text="update" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

If you use jQuery to do your AJAX stuff forget about those being ever fired.

A: I think attaching it in Page_Load is too late. Try attaching it in PreInit.


text:
Q: permission denied when importing recapcha I'm using recapcha on a Django site. It shows up on forms properly, the problem comes in when I try to check if it was entered correctly:
from recaptcha.client import captcha

Gives me the error:
[Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/WebError-0.10.3-py2.7.egg/EGG-INFO/top_level.txt'

Google's not helping me on this one. Any ideas how to fix this?

A: Check the write/read permissions on that file, or set full permissions for dist-packages to avoid similar future problem.


text:
Q: How to append more than one element using appendChild I have one cell (columns), in which I want to add two buttons. This is what I created:
var editbtn = document.createElement('button');
editbtn.type= "button";
editbtn.className= "editbtn";
editbtn.id= "edit-button-"+(i+1);
editbtn.innerHTML= "Edit";
editbtn.onclick = editRow.bind(this, i + 1);

var savebtn = document.createElement('button');
savebtn.type= "button";
savebtn.className= "savebtn";
savebtn.id= "save-button-"+(i+1);
savebtn.innerHTML= "Save";
savebtn.onclick = saveRow.bind(this, i + 1);

cell3.appendChild(editbtn);
cell3.appendChild(savebtn);

However, only the savebtn appears. How to append two buttons or more in the same column?

A: You can easily do that with an array and a for loop:
var names = ['edit', 'save'];
var editRows = [editRow, saveRow];

for ( var i = 0; i < names.length; i++ )
{
    var btn       = document.createElement('button');
    btn.type      = "button";
    btn.className = names[i] + "btn";
    btn.id        = names[i] + "-button-" + (i+1);
    btn.innerHTML = names[i];
    btn.onclick   = editRows[i].(this, i + 1);

    cell3.appendChild( editbtn );
}

You can add as many button as you want then just updating names and editRows accordingly, no need to touch the for loop.


text:
Q: How to setup fetch-mock with node-fetch, supertest and typescript I am trying to add some jest tests to my node typescipt project. I would like to use supertest to call my koa router, but also use fetch-mock to mock requests that are made using node-fetch.
My solution so far is below, but the fetch in my router does not use the mocked fetch setup with fetch-mock. The unit test fails because the expected response I mocked is not returned. I have tried following the documentation for global fetch mocking but without success, and typescript makes it difficult to follow the non-typescript solutions I have found. I would like to avoid using the non-global sandbox if possible as I would have to re-write a lot of code to pass the fetch around.
server.spec.ts
import * as fetchMock from 'fetch-mock';
import * as request from 'supertest';
import server from './server';

afterEach(() => {
  server.close();
  fetchMock.reset();
});

describe('router', () => {
  test('GET: should return data', async () => {
    const expectedResponse = { test: 'TEST' };
    fetchMock.get('https://myapi.com/test', expectedResponse);

    const response = await request(server).get('/test');
    expect(response.status).toEqual(200);
    expect(response.body).toMatchObject(expectedResponse);
  });
});

server.ts
import * as Koa from 'koa';
import * as Router from 'koa-router';
import fetch from 'node-fetch';

const app = new Koa();

const router = new Router();

router.get('/test', async ctx => {
  const options = { method: 'GET' };
  try {
    const response = await fetch('https://myapi.com/test', options);
    ctx.body = await response.json();
  } catch (error) {
    error.fetchUrl = url;
    throw error;
  }
});

app.use(router.routes());

const server = app.listen(3000);

export default server;

A: I tried to get node-fetch mocks working with jest and typescript using manual global mocking and a bunch of different packages as suggested in other answers. Here is the only thing that worked for me;

install 'jest-fetch-mock'

Create the tests;
// To mock fetch we need to import and enable before all other imports
import { enableFetchMocks } from 'jest-fetch-mock';
enableFetchMocks();
import ...
import ...
import ...
import fetch from 'node-fetch';

describe("I lost too many hours on this", () => {
    let spyFetch;

    beforeAll(() => {
        spyFetch = (fetch as jest.MockedFunction<typeof fetch>);
        spyFetch.mockImplementation(() => Promise.resolve({json: () => 'YMMV'}));
    });

    afterEach(() => {
        spyFetch.mockClear();
    });

    it("Call method which contains fetch", async () => {
        // Setup
        ...

        await exampleClass.methodContainingFetch('TestUrl');

        expect(spyFetch.mock.calls[0][0]).toBe('TestUrl');
    });
});

If you are having issues with typescript type-hinting, for a while I used
spyFetch = (fetch as any)

The above is missing supertest but I doubt people stumbling across this question are having issues with that part.

A: You can mock node-fetch module manually by yourself. Here is the solution:
server.ts:
import Koa from 'koa';
import Router from 'koa-router';
import fetch from 'node-fetch';

const app = new Koa();

const router = new Router();

router.get('/test', async ctx => {
  const options = { method: 'GET' };
  const url = 'https://myapi.com/test';
  try {
    const response = await fetch(url, options);
    ctx.body = await response.json();
  } catch (error) {
    error.fetchUrl = url;
    throw error;
  }
});

app.use(router.routes());

function createHttpServer() {
  return app.listen(3000);
}

if (require.main === module) {
  createHttpServer();
}

export default createHttpServer;

server.spec.ts:
import request from 'supertest';
import createHttpServer from './server';
import fetch from 'node-fetch';

const { Response } = jest.requireActual('node-fetch');
const server = createHttpServer();

jest.mock('node-fetch', () => jest.fn());

afterAll(done => {
  server.close(done);
});

describe('router', () => {
  test('GET: should return data', async () => {
    const expectedResponse = { test: 'TEST' };
    (fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(new Response(JSON.stringify(expectedResponse)));

    const response = await request(server).get('/test');
    expect(response.status).toEqual(200);
    expect(response.body).toEqual(expectedResponse);
  });

  test('GET: should throw error', async () => {
    const mockedFetchError = new Error('some error');
    (fetch as jest.MockedFunction<typeof fetch>).mockRejectedValueOnce(mockedFetchError);
    const response = await request(server).get('/test');
    expect(response.status).toEqual(500);
  });
});

Unit test result with coverage report:
 PASS  src/stackoverflow/56735795/server.spec.ts (8.487s)
  router
    ✓ GET: should return data (51ms)
    ✓ GET: should throw error (15ms)

  console.error node_modules/koa/lib/application.js:200
    undefined

  console.error node_modules/koa/lib/application.js:201
      Error: some error
          at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:26:30)
          at step (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:32:23)
          at Object.next (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:13:53)
          at /Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:7:71
          at new Promise (<anonymous>)
          at Object.<anonymous>.__awaiter (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:3:12)
          at Object.<anonymous> (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/src/stackoverflow/56735795/server.spec.ts:25:35)
          at Object.asyncJestTest (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:102:37)
          at resolve (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:43:12)
          at new Promise (<anonymous>)
          at mapper (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
          at promise.then (/Users/ldu020/workspace/github.com/mrdulin/jest-codelab/node_modules/jest-jasmine2/build/queueRunner.js:73:41)
          at process._tickCallback (internal/process/next_tick.js:68:7)

  console.error node_modules/koa/lib/application.js:202
    undefined

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |    95.24 |       50 |      100 |    94.12 |                   |
 server.ts |    95.24 |       50 |      100 |    94.12 |                28 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.36s

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56735795


text:
Q: How do I use an arbitrary string as a lock in C++? Let's say I have a multithreaded C++ program that handles requests in the form of a function call to handleRequest(string key). Each call to handleRequest occurs in a separate thread, and there are an arbitrarily large number of possible values for key.
I want the following behavior:

*

*Simultaneous calls to handleRequest(key) are serialized when they have the same value for key.

*Global serialization is minimized.

The body of handleRequest might look like this:
void handleRequest(string key) {
    KeyLock lock(key);
    // Handle the request.
}

Question: How would I implement KeyLock to get the required behavior?
A naive implementation might start off like this:
KeyLock::KeyLock(string key) {
    global_lock->Lock();
    internal_lock_ = global_key_map[key];
    if (internal_lock_  == NULL) {
        internal_lock_  = new Lock();
        global_key_map[key] = internal_lock_;
    }
    global_lock->Unlock();
    internal_lock_->Lock();
}

KeyLock::~KeyLock() {
    internal_lock_->Unlock();
    // Remove internal_lock_ from global_key_map iff no other threads are waiting for it.
}

...but that requires a global lock at the beginning and end of each request, and the creation of a separate Lock object for each request. If contention is high between calls to handleRequest, that might not be a problem, but it could impose a lot of overhead if contention is low.

A: It will depend on the platform, but the two techniques that I'd try would be:

*

*Use named mutex/synchronization
objects, where object name = Key

*Use filesystem-based locking, where you
try to create a non-shareable
temporary file with the key name. If it exists already (=already
locked) this will fail and you'll
have to poll to retry

Both techniques will depend on the detail of your OS. Experiment and see which works.
.

A: Perhaps an std::map<std::string, MutexType> would be what you want, where MutexType is the type of the mutex you want. You will probably have to wrap accesses to the map in another mutex in order to ensure that no other thread is inserting at the same time (and remember to perform the check again after the mutex is locked to ensure that another thread didn't add the key while waiting on the mutex!).
The same principle could apply to any other synchronization method, such as a critical section.

A: Raise granularity and lock entire key-ranges
This is a variation on Mike B's answer, where instead of having several fluid lock maps you have a single fixed array of locks that apply to key-ranges instead of single keys.
Simplified example: create array of 256 locks at startup, then use first byte of key to determine index of lock to be acquired (i.e. all keys starting with 'k' will be guarded by locks[107]).
To sustain optimal throughput you should analyze distribution of keys and contention rate. The benefits of this approach are zero dynamic allocations and simple cleanup; you also avoid two-step locking. The downside is potential contention peaks if key distribution becomes skewed over time.

A: You could do something similar to what you have in your question, but instead of a single global_key_map have several (probably in an array or vector) - which one is used is determined by some simple hash function on the string.
That way instead of a single global lock, you spread that out over several independent ones.
This is a pattern that is often used in memory allocators (I don't know if the pattern has a name - it should).  When a request comes in, something determines which pool the allocation will come from (usually the size of the request, but other parameters can factor in as well), then only that pool needs to be locked.  If an allocation request comes in from another thread that will use a different pool, there's no lock contention.

A: After thinking about it, another approach might go something like this:

*

*In handleRequest, create a Callback that does the actual work.

*Create a multimap<string, Callback*> global_key_map, protected by a mutex.

*If a thread sees that key is already being processed, it adds its Callback* to the global_key_map and returns.

*Otherwise, it calls its callback immediately, and then calls the callbacks that have shown up in the meantime for the same key.

Implemented something like this:
LockAndCall(string key, Callback* callback) {
    global_lock.Lock();
    if (global_key_map.contains(key)) {
        iterator iter = global_key_map.insert(key, callback);
        while (true) {
            global_lock.Unlock();
            iter->second->Call();
            global_lock.Lock();
            global_key_map.erase(iter);
            iter = global_key_map.find(key);
            if (iter == global_key_map.end()) {
                global_lock.Unlock();
                return;
            }
        }
    } else {
        global_key_map.insert(key, callback);
        global_lock.Unlock();
    }
}

This has the advantage of freeing up threads that would otherwise be waiting for a key lock, but apart from that it's pretty much the same as the naive solution I posted in the question.
It could be combined with the answers given by Mike B and Constantin, though.

A:       /**
      * StringLock class for string based locking mechanism
      * e.g. usage
      *     StringLock strLock;
      *     strLock.Lock("row1");
      *     strLock.UnLock("row1");
      */
      class StringLock    {
      public:
          /**
           * Constructor
           * Initializes the mutexes
           */
          StringLock()    {
              pthread_mutex_init(&mtxGlobal, NULL);
          }
          /**
           * Lock Function
           * The thread will return immediately if the string is not locked
           * The thread will wait if the string is locked until it gets a turn
           * @param string the string to lock
           */
          void Lock(string lockString)    {
              pthread_mutex_lock(&mtxGlobal);
              TListIds *listId = NULL;
              TWaiter *wtr = new TWaiter;
              wtr->evPtr = NULL;
              wtr->threadId = pthread_self();
              if (lockMap.find(lockString) == lockMap.end())    {
                  listId = new TListIds();
                  listId->insert(listId->end(), wtr);
                  lockMap[lockString] = listId;
                  pthread_mutex_unlock(&mtxGlobal);
              } else    {
                  wtr->evPtr = new Event(false);
                  listId = lockMap[lockString];
                  listId->insert(listId->end(), wtr);
                  pthread_mutex_unlock(&mtxGlobal);
                  wtr->evPtr->Wait();
              }
          }
          /**
          * UnLock Function
          * @param string the string to unlock
          */
          void UnLock(string lockString)    {
              pthread_mutex_lock(&mtxGlobal);
              TListIds *listID = NULL;
              if (lockMap.find(lockString) != lockMap.end())    {
                  lockMap[lockString]->pop_front();
                  listID = lockMap[lockString];
                  if (!(listID->empty()))    {
                      TWaiter *wtr = listID->front();
                      Event *thdEvent = wtr->evPtr;
                      thdEvent->Signal();
                  } else    {
                      lockMap.erase(lockString);
                      delete listID;
                  }
              }
              pthread_mutex_unlock(&mtxGlobal);
          }
      protected:
          struct TWaiter    {
              Event *evPtr;
              long threadId;
          };
          StringLock(StringLock &);
          void operator=(StringLock&);
          typedef list TListIds;
          typedef map TMapLockHolders;
          typedef map TMapLockWaiters;
      private:
          pthread_mutex_t mtxGlobal;
          TMapLockWaiters lockMap;
      };


text:
Q: Python regex - why does end of string ($ and \Z) not work with group expressions? In Python 2.6. it seems that markers of the end of string $ and \Z are not compatible with group expressions. Fo example
import re
re.findall("\w+[\s$]", "green pears")

returns
['green ']

(so $ effectively does not work). And using
re.findall("\w+[\s\Z]", "green pears")

results in an error:
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.pyc in findall(pattern, string, flags)
    175
    176     Empty matches are included in the result."""
--> 177     return _compile(pattern, flags).findall(string)
    178
    179 if sys.hexversion >= 0x02020000:

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.pyc in _compile(*key)
    243         p = sre_compile.compile(pattern, flags)
    244     except error, v:
--> 245         raise error, v # invalid expression
    246     if len(_cache) >= _MAXCACHE:
    247         _cache.clear()

error: internal: unsupported set operator

Why does it work that way and how to go around?

A: Square brackets don't indicate a group, they indicate a character set, which matches one character (any one of those in the brackets)  As documented, "special characters lose their special meaning inside sets" (except where indicated otherwise as with classes like \s).
If you want to match \s or end of string, use something like \s|$.

A: A [..] expression is a character group, meaning it'll match any one character contained therein. You are thus matching a literal $ character. A character group always applies to one input character, and thus can never contain an anchor.
If you wanted to match either a whitespace character or the end of the string, use a non-capturing group instead, combined with the | or selector:
r"\w+(?:\s|$)"

Alternatively, look at the \b word boundary anchor. It'll match anywhere a \w group start or ends (so it anchors to points in the text where a \w character is preceded or followed by a \W character, or is at the start or end of the string).

A: Martijn Pieters' answer is correct. To elaborate a bit, if you use capturing groups
r"\w+(\s|$)"

you get:
>>> re.findall("\w+(\s|$)", "green pears")
[' ', '']

That's because re.findall() returns the captured group (\s|$) values.
Parentheses () are used for two purposes: character groups and captured groups. To disable captured groups but still act as character groups, use (?:...) syntax:
>>> re.findall("\w+(?:\s|$)", "green pears")
['green ', 'pears']


text:
Q: Can I detect the user viewable area on the browser? As you can see the image below, there is "A", "B", "C", "D" and "E" on the website, and the user may only can see the A, B, and a little parts of D in their browser. They need to require to scroll down the browser or some users may have a bigger screen, or a longer window on their browser that allow they can even see the element C.
Ok, my question is, is this possible to let me know what the user seeing on their browser using javascript? In this element, is "A", "B" and "D".

A: Basically, you'd first have to measure the viewport dimentions, by using the window object, then you'd need to loop through each of the elements that you want to check, and calculate wether they fit.
See this jsfiddle for an example.
Here's the code (for posterity's sake):
HTML:

A big list!

CSS:
#info{
    position: fixed;
    right: 0px;
    text-align: center;
    background: white;
    border: 2px solid black;
    padding: 10px;
}

JS:
    $(function(){

    $(window).bind('scroll.measure resize.measure',function(){

        // Gather together the window width, height, and scroll position.
        var winWidth = $(window).width(),
            winHeight = $(window).height(),
            winLeft = $(window).scrollLeft(),
            winTop = $(window).scrollTop(),
            winBottom = winTop + winHeight,
            winRight = winLeft + winWidth,
            inView = [];

        // Loop over each of the elements you want to check
        $('.inview').each(function(){

            // Get the elements position and dimentions.
            var pos = $(this).position(),
                width = $(this).outerWidth(),
                height = $(this).outerHeight();

            // Set bottom and right dimentions.
            pos.bottom = pos.top + height;
            pos.right = pos.left + width;

            // Check whether this element is partially within
            // the window's visible area.
            if((
                pos.left >= winLeft &&
                pos.top >= winTop &&
                pos.right <= winRight &&
                pos.bottom <= winBottom
            ) || (
                pos.left >= winLeft && pos.top >= winTop &&
                pos.left <= winRight && pos.top <= winBottom
            ) || (
                pos.right <= winRight && pos.bottom <= winBottom &&
                pos.right >= winLeft && pos.bottom >= winTop
            )){
                // Change this to push the actual element if you need it.
                inView.push( $(this).text() );
            }
        });

        // For the purposes of this example, we only need the
        // first and last element, but in your application you may need all.
        var first = inView.shift(),
            last = inView.pop();

        // Show the details in the info box.
        $('#info .wxh').text( winWidth+' x '+winHeight );
        $('#info .txl').text( winTop+' x '+winLeft );
        $('#info .report').text( 'Showing from '+first+' to '+last );
    });

    // The rest is just setup stuff, to make the area scrollable.
    for( var i=0; i<100; i++ ){
        $('ul').append('
List item '+i+'
');
    }

    $(window).trigger('resize.measure');
})

A: You can get window's visible area by,
var pwidth = $(window).width();
var pheight = $(window).height();

Then get document scroll,
$(document).scroll(function(e) {
       var top = $(this).scrollTop();
       $("h1").html("total visible area is from:"+ top +" to "+ (pheight + top) +"px");
    });

Full example is here : http://jsfiddle.net/parag1111/kSaNp/

A: Using the following, you can get the browser's viewport size.
window.innerHeight;
window.innerWidth;

Refer to: http://www.javascripter.net/faq/browserw.htm
If you want to detect how far they have scrolled down the page, you can use
window.scrollX;   // Horizontal scrolling
window.scrollY;   // Vertical scrolling

Also, I have found a window object - window.screen. On my system it has the following data:
window.screen.availHeight = 994;
window.screen.availLeft = 0;
window.screen.availTop = 0;
window.screen.availWidth = 1280;
window.screen.colorDepth = 32;
window.screen.height = 1280;
window.screen.pixelDepth = 32;
window.screen.width = 1280;

A: Try it :) http://jsfiddle.net/Aj2fU/5/
$('input').click(function(){
   // check for visible divs with class 'check'
    $('.check').each(function(){
        var pos = $(this).offset(),
            wX = $(window).scrollLeft(), wY = $(window).scrollTop(),
            wH = $(window).height(), wW = $(window).width(),
            oH = $(this).outerHeight(), oW = $(this).outerWidth();

        // check the edges
        // left, top and right, bottom are in the viewport
        if (pos.left >= wX && pos.top >= wY &&
            oW + pos.left <= wX + wW && oH + pos.top <= wY + wH )
            alert('Div #' + $(this).attr('id') + ' is fully visible');
        else // partially visible
        if (((pos.left <= wX && pos.left + oW > wX) ||
             (pos.left >= wX && pos.left <= wX + wW)) &&
            ((pos.top <= wY && pos.top + oH > wY)   ||
             (pos.top  >= wY && pos.top  <= wY + wH)))
            alert('Div #' + $(this).attr('id') + ' is partially visible');
        else // not visible
            alert('Div #' + $(this).attr('id') + ' is not visible');
    });
});

Updated to work with very wide divs. Basically it checks whether the left, top and right, bottom edges of the divs are both in the visible part of the screen, partially or outside of the viewport.


text:
Q: How to get variable value outside angular function I have been hours trying to understand why I don't get the value of a variable, outside an Angular.js function. First I get the value from a Firebase database, here is my reference :
var refspaedtServ = new Firebase(FBURLSPA + $routeParams.id);
$scope.spaedServ = $firebaseObject(refspaedtServ);

Then I have the function:
        /////  IMAGE REFERENCE  ////
        var lafoto = '';
        refspaedtServ.on("value", function(rootSnapshot) {
           lafoto = rootSnapshot.val().foto;
           console.log("Inside image ", lafoto)
       });

As you can see, I define my variable 'lafoto' as global
With the console.log Inside image, I can see the value is correct
But when I try to get the value of "lafoto" variable, outside the function, I'm getting "undefined", I mean no value.
console.log("Outside Image ", lafoto)

It seems silly, but I'm reaching madness for that.
Can anybody give me a hint please?
Regards,
Victor

A: It's pretty simple, let's see it by your code, assuming your function in the 'value' event needs 1500ms to complete:
var lafoto = '';
console.log('start');

//listening for the event
refspaedtServ.on("value", function(rootSnapshot) {
    //after ~1500ms...
    lafoto = rootSnapshot.val().foto;
    console.log("Inside", lafoto)
});

console.log('outside', lafoto); //executed immediately

In console, you will receive as result:
'Start'
'outside'
'inside'

that's because you are waiting asynchronously for the event: hence, "outside" the .on function you are executing the code before the code inside.
So, your variable lafoto will always result undefined, because it has not been already assigned.
.
Edit 1
You can use a callback function to perform code after the .on event:
 var lafoto = '';
console.log('start');

//listening for the event
refspaedtServ.on("value", function(rootSnapshot) {
    //after ~1500ms...
    lafoto = rootSnapshot.val().foto;
    console.log("Inside", lafoto)
    myAfterFunction();
});

function myAfterFunction(){
    console.log('myAfterFunction', lafoto);
}

console.log('outside', lafoto); //executed immediately

In console, you will receive as result:
'Start'
'outside'
'inside'
'myAfterFunction'


text:
Q: Conversion Type Error: Type String cannot be converted to Integer Hi Guys I keep getting an Exception error that string cannot be converted to integer and not quite sure why...Ive tried adding the toString() method to many different places to try and resolve and nothing has worked...can you please just glance over this and see where I am being dumb. I am basically trying to see when a new item is found to see if it starts with all the lines in History split it at the word """URL"""
I commented just above the if statement that throws the exception.
the exact error is:

System.InvalidCastException: 'Conversion from string "{ "Title": "Item 1" to type 'Integer' is not valid.'

Inner Exception

FormatException: Input string was not in a correct format.

Dim History = File.ReadAllLines("history.json")
Dim NewestItems = File.ReadAllLines("items.json")
Dim InitialItems = File.ReadAllLines("Init-items.json")

For x As Integer = 0 To InitialItems.Length - 1
        Dim current As String = InitialItems(0)
        Dim splitAt As String = """Url"""
        Dim index As Integer = current.IndexOf(splitAt)
        Dim output As String = current.Substring(0, index + splitAt.Length)
        Dim recurringItemFound = 0
        If Not NewestItems(x).StartsWith(output) And Not History.Contains(NewestItems(x)) Then

            If cbxRecurringItemsOff.Checked = True Then
                For Each RecurringItem In History
                    Dim indexHistory As Integer = NewestItems(x).IndexOf(splitAt)
                    Dim outputHistory As String = NewestItemss(x).Substring(0, indexHistory + splitAt.Length)
                    '********the below if statement throws an Exception error*********
                    If NewestItems(RecurringItem).StartsWith(outputHistory) Then
                        recurringItemFound = 1
                    End If
                Next
            End If
Next

A: Use Option Strict and Option Explicit - this would have flagged some issues.
In this context, you are using RecurringItem as an index in the array NewestItems so it is trying to convert RecurringItem to an Integer. However, RecurringItem comes from History which I assume is an array of String. So, you are trying to use a string that you have read from a file as an integer and the program is now "chucking a whammy".
Did you really mean NewestItems(x).StartsWith(outputHistory)?


text:
Q: Draw 3D log likelihood plot in R I want to try and use R to draw me a 3D log likelihood plot for a model with two parameters.
My function is given below:
  negL=function(theta,data){
    mu=theta[1]
    tau=theta[2]

  n11=data$ev.trt
  n12=data$n.trt-data$ev.trt
  n21=data$ev.ctrl
  n22=data$n.ctrl-data$ev.ctrl
  odds=(n11*n22)/(n12*n21)
  logodds=log(odds)
  varodds=(1/n11)+(1/n12)+(1/n21)+(1/n22)

  x=logodds
  sigma=varodds

  L=-(1/2)*sum(log((2*pi)*(sigma+tau)))-(1/2)*sum((((x-mu)^2))/(sigma+tau))
  return(-L)
  }

Here L is my likelihood function.
I want to try and draw the log likelihood plot based on this data:
          Author ev.ctrl n.ctrl ev.trt n.trt duration
1         RAPID1      15    199    146   393    6.150
2         RAPID2       4    127     80   246    5.850
3        Kim2007       9     63     28    65    6.850
4          DE019      19    200     81   207   10.950
5         ARMADA       5     62     37    67   11.650
6  Weinblatt1999       1     30     23    59   13.000
7          START      33    363    110   360    8.100
8         ATTEST      22    110     61   165    7.850
9        Abe2006       1     47     15    49    8.300
10    Strand2006       5     40      5    40   11.250
11      CHARISMA      14     49     26    50    0.915
12        OPTION      22    204     90   205    7.650

I have calculated maximum likelihood estimators of theta to be (1.6760569 0.2112315) using R optim()
Basically I am wanting mu to appear on the x axis, tau on the y axis and then the log likelihood -L on the z axis.
I tried adding this onto my function
  persp3d(negL, c(0,6), c(-1,3), col="red", xlab="mu", ylab="tau^2", zlab="Likelihood",
      main="Perspective plot of Likelihood")

from the rgl package after seeing it on another webpage but I am getting an error saying:
Error in (function (theta)  :
  unused argument (c(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96,
-0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96, -0.96,

when I try and run it.
Any ideas of how to do this and functions to use would be greatly appreciated.
Many thanks

A: Is this what you're trying to achieve?
negL<- function(mu,tau,data){
  n11=data$ev.trt
  n12=data$n.trt-data$ev.trt
  n21=data$ev.ctrl
  n22=data$n.ctrl-data$ev.ctrl
  odds=(n11*n22)/(n12*n21)
  logodds=log(odds)
  varodds=(1/n11)+(1/n12)+(1/n21)+(1/n22)
  x=logodds
  sigma=varodds
  L=-(1/2)*sum(log((2*pi)*(sigma+tau)))-(1/2)*sum((((x-mu)^2))/(sigma+tau))
  return(-L)
}
f <- Vectorize(negL,vectorize.args=c("mu","tau"))
library(rgl)
mu  <- seq(0,6,0.1)
tau <- seq(0,3,0.1)
z <- outer(mu,tau,f,data=data)
zlim    <- range(z[!is.na(z)])
palette <- rev(rainbow(20))
colors  <- palette[19*(z-zlim[1])/diff(zlim) + 1]

persp3d(mu,tau,z,col=colors)

So there are a couple of issues.
First, persp3d(...) takes 3 arguments: x is a vector defining the x-axis, y is a vector defining the y-axis, and z is a matrix with dimensions length(x) x length(y) where each element is a value of z for that combination of x and y. You have to set up the vectors x and y and the matrix z (as in the code above).
One way to set up the z matrix is using the outer(x,y,FUN) function (read the documentation). This takes two vectors, x, and y, and returns the result of evaluating the function FUN on every combination of x and y. But it requires the FUN be vectorized, which your negL(...) is not. So we create a new function, f(...) which is a vectorized version of negL(...).
Third, the function negL(...) has to take two arguments, mu and tau, rather than a vector with two elements (theta). So I changed the function's signature to do that. Other than that the function is identical to your question.
Finally, in your question you (seem to...) want to use negative values of tau. But negL(...) is undefined for tau < 0.


text:
Q: OpenACC: nested loops with private variable I want to accelerate these nested loops. Because of the dimension of v (NMAX=MAX(NX1, NX2, NX3)), I understand that can be a conflict in the parallelization of the two external loops. I tried to use the private clause:
  static double **v;

  if (v == NULL) {
    v = ARRAY_2D(NMAX_POINT, NVAR, double);
  }

  #pragma acc parallel loop present(V, U) private(v[:NMAX_POINT][:NVAR])
  for (k = kbeg; k <= kend; k++){ g_k = k;
  #pragma acc loop
  for (j = jbeg; j <= jend; j++){ g_j = j;

    #pragma acc loop collapse(2)
    for (i = ibeg; i <= iend; i++) {
    for (nv = 0; nv < NVAR; nv++){
      v[i][nv] = V[nv][k][j][i];
    }}

    #pragma acc routine(PrimToCons) seq
    PrimToCons (v, U[k][j], ibeg, iend);
  }}

I get these errors:
Generating present(V[:][:][:][:],U[:][:][:][:])

     Generating Tesla code

    144, #pragma acc loop seq

    146, #pragma acc loop seq

    151, #pragma acc loop gang, vector(128) collapse(2) /* blockIdx.x threadIdx.x */

    154,   /* blockIdx.x threadIdx.x collapsed */

144, Accelerator restriction: induction variable live-out from loop: g_k

     Complex loop carried dependence of v->-> prevents parallelization

146, Accelerator restriction: induction variable live-out from loop: g_j

     Loop carried dependence due to exposed use of v prevents parallelization

     Complex loop carried dependence of V->->->->,v->-> prevents parallelization

g_k and g_j are extern int. I've never seen the message "induction variable live-out from loop" before.
EDIT:
I modified the loop as suggested but it sill doesn't work
#pragma acc parallel loop collapse(2) present(U, V) private(v[:NMAX_POINT][:NVAR])
  for (k = kbeg; k <= kend; k++){
  for (j = jbeg; j <= jend; j++){

    #pragma acc loop collapse(2)
    for (i = ibeg; i <= iend; i++) {
    for (nv = 0; nv < NVAR; nv++){
      v[i][nv] = V[nv][k][j][i];
    }}
    PrimToCons (v, U[k][j], ibeg, iend, g_gamma);
  }}

I get this error:
Failing in Thread:1
call to cuStreamSynchronize returned error 700: Illegal address during kernel execution

It's as if the compiler cannot find v, U or V but in the main function I use these directives:
#pragma acc enter data copyin(data)
 #pragma acc enter data copyin(data.Vc[:NVAR][:NX3_TOT][:NX2_TOT][NX1_TOT], data.Uc[:NX3_TOT][:NX2_TOT][NX1_TOT][:NVAR])

data.Vc and data.Uc are V and U in this routine I want to parallelize.

A:
g_k and g_j are extern int. I've never seen the message "induction
variable live-out from loop" before.

When run in parallel, the order in which the loop iterations are executed is non-deterministic. Hence the values of g_k and g_j once exiting the loop would be what ever iteration that happens to be last.  This creates a dependency since in order to get correct answers (i.e. answers that would agree with those when running serially), the "k" and "j" loops must be run sequentially.
If "g_k" and "g_j" were local variables, then the compiler would implicitly privatize them in order to remove this dependency.  However since they are global variables, it must assume other portions of the code uses the results and hence can't assume they can be made private.  If you know the variables aren't used elsewhere, then you can fix this issue by adding them to your "private" clause.  Note, it doesn't appear that these variables are used the loop itself so could be removed and just assigned the values "kend" and "jend" outside of the loop.
Unless "g_k" and "g_j" are used in the "PrimToCons" subroutine?  In that case, you have a bigger problem in that this would cause a race condition in that the variables values may be updated by other threads and no longer be the value expected by the subroutine.  In this case, the fix would be to pass "k" and "j" as arguments to "PrimToCons" and not use "g_k" and "g_j".
As for "v", it should be private to the "j" loop as well, not just the "k" loop.  To fix, the I'd recommend adding a "collapse(2)" clause to the "k" loop's pragma and remove the loop directive about the "j" loop.


text:
Q: Density Lp spaces If $ 1 \leq p \leq r \leq q < \infty$ and $f \in L^r(\mathbb{R})$. Why is $f \chi _{\lbrace x : \frac{1}{n} \leq |f| \leq n \rbrace} \in L^p \cap L^q $ for all n?
I've tried to show that the set ${\lbrace x : \frac{1}{n} \leq |f| \leq n \rbrace}$ is of finite measure by using chebychev-ish bounds but this hasn't gotten me anywhere.
(This question refers to Is $L^p \cap L^q$ dense in $L^r$?).

A: Use the inequalities $|f|^p \le  n^{r-p} |f|^r$ and $|f|^q \le n^{q-r} |f|^r$ which are both valid on the set $\{1/n \le |f| \le n\}$.

A: In fact any bounded measurable function on a set $E$ of finite measure belongs to $L^s(E), 0 < s\le \infty.$ That has a very simple proof. Now in your problem, set $E= \{1/n\le |f| \le n\}.$ To show $E$ has finite measure, note
$$\infty > \int_E |f|^r \ge (1/n)^r\mu(E).$$


text:
Q: Select empty values in dataframe, python I have a dataframe with empty values:

I want to select non-empty values for field 'latitude'. I've tried
df[df['latitude'].notnull()]

and
df[df['latitude'] != '']

But these phrases select all values.