text:
Q: Another memory leak question My application keeps running for 4 to 6 hours, During this time there is no contineous increase in memory or anything similar.
Then after 4 to 6 hours i start getting EOutofMemory Exceptions. Even still at that time there is only 900MB out of 3GB RAM is used as per task manager. And application itself is not using more then 200MB .
Then why i am getting EOoutofMEmory error ?
Does it mean that memory leak is not necessarily visible in task manager ?
Regagards

A: Use Process Explorer instead of Task Manager to look at the memory consumption of your application.

*

*Private Bytes: is the amount of memory that is used by your application.  This is also the value shown by Task Manager in the VM Size column (under XP)

*Virtual Memory Size: this is the largest address that is currently in use by your application.  This value is limited by 2 GB (for a 32-bit application in a 32-bit OS).

The different between Private Bytes and Virtual Memory Size is caused by memory fragmentation.  The only thing you can do about it is to use a memory manager that tries to reduce fragmentation, e.g. by using memory pools.
The DougLea memory manager is a free alternative.  There are also commercial memory manager.  You can also try to write your own memory manager (it's not that hard: you only have to override the new and delete operators).
There are also tricks to increase the limit of 2 GB.  If you link your application with the /LARGEADDRESSAWARE flag, your application will be able to allocate 3GB of memory (if XP is booted with the /3GB flag, for Vista/W7 there's probably a similar flag but I don't know this).  On 64-bit Operating systems, a LargeAddressAware executable can even use up to 4 GB of memory.

A: This may be caused by memory fragmentation. When the application runs for a long time, memory can be fragmented, which means it is filled by many small allocated blocks and free spaces. If you want to allocate a memory block larger than the largest free block, your allocation will fail, even though the total amount of free space suggests that there is enough memory for the allocation to succeed.
You may also want to check if you were not accidentally trying to allocate a huge block of memory at one point.
I suggest you check the size of the allocation that failed.


text:
Q: Disable image from caching? ** edit
it seems that when the javascript changes the image that the reflection gets an undefined src. Any thoughts on that **
I've got this problem where I'm using jquery to reflect an image. I've got this news title list and it's automatically jumping through titles. Each time it changes the image and the reflection.
This works prefectly the first time but when you navigate back to the page it has cached the image so that it only shows the reflection of the first image for all images.
Does anyone know how to disable image caching?
I'm using reflection.js
This is the function that rotates between images.
function changeId(){
    $(".speglun").unreflect();
    if(id < 5){
        id++;
        var eldri = id - 1;
    }else{
        id = 1;
        var eldri = 5;
    }

    $('#newsBgW'+id).css("background-position", "-477px 0px");
    $('#newsBgW'+eldri).css("background-position", "0px 0px");

    $('#frettaMynd').attr("src", myndir[id]);
    $(".speglun").reflect();
    t = setTimeout("changeId()", time);
}

A: When you build the URL for the image, add the current timestamp, so it looks sort of like image.jpg?20090305101423. This ought to prevent caching. Actually it will still cache, but a "different" image each time.
I answered this before you clarified. I have no idea about that jQuery plugin, but perhaps it still will be helpful..

A: to swap image use a jquery plugin,
its very cool
http://code.google.com/p/jquery-swapimage/

redpajama_set_name: RedPajamaStackExchange


text:
Q: ORACLE SQL missing right parenthesis bad syntax I can't seem to figure out where is the syntax mistake. Even though the query is very simple.
Thanks in advance!
UPDATE t_stock
set f_atcid = (select a.id from t_atc a where a.f_code = ' ' where rownum < 2)
where id in (select f_stockid from t_barcode where f_barcode = ' ');

A: The problem is two where clauses.  Change the second to and:
UPDATE t_stock
    set f_atcid = (select a.id
                   from t_atc a
                   where a.f_code = ' ' and
----------------------------------------^
                         rownum < 2
                  )
where id in (select f_stockid from t_barcode where f_barcode = ' ' );


text:
Q: PHP: nested try-catch does not work within a function Recently I have started playing around with Exceptions and their handling. Everything seemed to work just fine however I have just hit a brick wall and I'm not sure if there is a solution for my problem or should I remake my code base.
Situation:
I'm executing a small piece of code inside try block and I'm catching all exceptions and simply logging/outputing the errors. I'm trying to execute a function which deletes object from database:

*

*It removes the relationships;

*It removes the object.

What I want to accomplish is: if object removal fails - restore previously removed relationships.
I thought that putting a nested try-catch block inside a function at the place where the final deletion is being performed I would catch an exception and revert the changes, however this does not work inside a function and it simply ignores the try-catch block and goes to the top one.
HOWEVER: When I put the same piece of code outside of the function it works just fine and like intended!
Below are two pieces of code - working and not working.
EDIT: I forgot to mention that I purposely made a syntax mistake in "router" DELETE query and it always throws an exception during "$status_r = \sys\database\query($query, $db, $elem_t, $elem);" execution. In the first case it ignores the try-catch block inside the function "delete" and goes to the top try-catch block where function is called.
NOT WORKING AS INTENDED
try
{
    $db = \sys\database\connect();
    $status = ips\routers\delete($id, $db);
    echo "success";
    \sys\core\log_action("router_delete", "success", "Router '$id' successfully deleted", $db);
}
catch (Exception $ex)
{
    echo (sys\errors\is_error($ex->getMessage())) ? sys\errors\parse($ex->getMessage()) : $ex->getMessage();
    \sys\core\log_action("router_delete", "failure", $ex->getMessage(), $db);
}

Code inside delete function:
function delete($id, &$db = false)
{
    // Check if Any Interfaces are set on this router
    if (\ips\interfaces\exists(array("router", $id), $db) !== false)
        throw new \Exception(\sys\errors\exist("Router has active interfaces and cant be removed!"));

    $curr_ip_id = \ips\ips\get(array("router_id", $id), "id", $db);
    if (!\sys\validation\validate("numeric", $curr_ip_id[0]['id']))
        throw new \Exception(\sys\errors\database());

    $status = \ips\ips\revoke($curr_ip_id[0]['id'], NULL, $db);
    if ($status === true)
    {
        // if we get an error we need to revert changes - aka rebind IP to router
        try
        {
            $query = "DELETE FROM routers WHERE i = ?";
            $elem_t = "i";
            $elem = array($id);
            $status_r = \sys\database\query($query, $db, $elem_t, $elem);
            if ($status_r === true)
                return true;
            else
                throw new \Exception();
        }
        catch (Exception $ex)
        {
            $status_rebind = \ips\ips\set_owner(array("id", $curr_ip_id[0]['id']), $id, "router", $db);
            if ($status_rebind === true)
                throw \Exception(\sys\errors\database("Failed Deleting router at the last step. IP reassigned successfully!"));
            else
                throw \Exception(\sys\errors\database("Failed Deleting router at the last step. IP reassigned failed!"));
        }
    }
    else
        throw new \Exception(\sys\errors\database("Failed revoking IP address from router!"));
}

WORKING AS INTENDED
try
{
    $db = \sys\database\connect();

    if (\ips\interfaces\exists(array("router", $id), $db) !== false)
        throw new \Exception(\sys\errors\exist("Router has active interfaces and cant be removed!"));

    $curr_ip_id = \ips\ips\get(array("router_id", $id), "id", $db);
    if (!\sys\validation\validate("numeric", $curr_ip_id[0]['id']))
        throw new \Exception(\sys\errors\database());

    $status = \ips\ips\revoke($curr_ip_id[0]['id'], NULL, $db);
    if ($status === true)
    {
        // if we get an error we need to revert changes - aka rebind IP to router
        try
        {
            $query = "DELETE FROM routers WHERE i = ?";
            $elem_t = "i";
            $elem = array($id);
            $status_r = \sys\database\query($query, $db, $elem_t, $elem);
            if ($status_r === true)
                return true;
            else
                throw new \Exception();
        }
        catch (Exception $ex)
        {
            $status_rebind = \ips\ips\set_owner(array("id", $curr_ip_id[0]['id']), $id, "router", $db);
            if ($status_rebind === true)
                throw new \Exception(\sys\errors\database("Failed Deleting router at the last step. IP reassigned successfully!"));
            else
                throw new \Exception(\sys\errors\database("Failed Deleting router at the last step. IP reassigned failed!"));
        }
    }
    else
        throw new \Exception(\sys\errors\database("Failed revoking IP address from router!"));

}
catch (Exception $ex)
{
    echo (sys\errors\is_error($ex->getMessage())) ? sys\errors\parse($ex->getMessage()) : $ex->getMessage();
    \sys\core\log_action("router_delete", "failure", $ex->getMessage(), $db);
}

I'm not exactly sure why try-catch does not work inside the function. Any help would be highly appreciated.
Thanks in advance!


text:
Q: Tukey HSD plot_simultaneous - how does it work? I have performed a Tukey HSD in Python. I am not sure what values are plotted when using the .plot_simultaneous() command (see statsmodels documentation).
The resulting plot is:

I am wondering: how is the resulting mean and std calculated?
How can I interpret the graphic result of this?

A: Take this plot for example:

I have a data set of US climate normals for various stations and I've grouped those station by Physiographic province.  The plot shows the means (black dot) and the 95% confidence interval (not standard deviation) for each group.
You can interpret my plot as follows.  For the Wyoming Basin, it is significantly drier than say the Valley and ridge province, but it is not drier than the southern rocky mountains, bc they have overlapping confidence intervals.


text:
Q: How can I read the value of pointer in C# and convert the value to string? How can I define a pointer and read / write the other variable with it?
and how can I show the value of pointer in the textbox?

A: As from MSDN (note, this should be compiled with /unsafe switch)
int number;

unsafe
{
    // Assign the address of number to a pointer:
    int* p = &number;

    // Commenting the following statement will remove the
    // initialization of number.
    *p = 0xffff;

    // Print the value of *p:
    System.Console.WriteLine("Value at the location pointed to by p: {0:X}", *p);

    // Print the address stored in p:
    System.Console.WriteLine("The address stored in p: {0}", p->ToString());
}

// Print the value of the variable number:
System.Console.WriteLine("Value of the variable number: {0:X}", number);

A: You get a Pointer by calling &[Name of your Variable]
The Type of Pointers is [Type of your Variable]*
long number = 3;
long* ptr = &number;

You can change the Type of your pointer. This can end very dirty.
int* dirtyPtr = ((int*)ptr) + 1; //Takes only the second half of the long(8 Bytes) as int(4 Bytes)
// +1 refers to the length to the type, so you go 4 Bytes ahead

You can change the value of the variable behind the pointer with *[Name of Pointer] = Value
*dirtyPtr = 50;


text:
Q: Did you use to go to a gym in town? In the sentence "Did you use to go to a gym in town?" The Word program changed use to used. Is this correct?

A: No, "did you used to go" is incorrect. Compare:
Statement: I went to a gym.
Question: Did you go to a gym? (Not "did you went to a gym?")
Statement: I used to go to a gym.
Question: Did you use to go to a gym? (Not "did you used to go to a gym.")
Notice that in both questions, the auxiliary verb "do" is in the past tense ("did"), while the main verb ("go" in the first set of examples, "use" in the second) is in base form.


text:
Q: get the third cell in a table jQuery I thought I had a decent handle on this, but apparently not. So here we go again. I want the value of the cell two spaces over from where I click. It would be the 3rd column of the row. Here is some code to understand.
I create the table like this
php
$project_info = $db->prepare("
    SELECT  projects.id,
        projects.project_name,
        projects.pm,
        // ...more columns
    FROM projects
    WHERE account_id = ?
");

$project_info->bindValue(1, $aid, PDO::PARAM_STR);
$project_info->execute();

echo "
";
echo "" . "" . "	";
echo "" . "" . "	";
echo "" . "Job #" . "	";
// ...more headers

while ($row = $project_info->fetch(PDO::FETCH_ASSOC)) {
    echo "
";
    echo "" . "" . "	";
    echo "" . "" . "	";
    echo "" . "" . $row['id'] . "" . "	";
    // ...more td's
    echo "
";
}
echo "
";

and this code to get the value from the cell
jquery
$('body').on('click', '.edit_project_record', function() {
    pid = $(this).parent().find('td:eq(3)').text();
    alert(pid);
    loadEditProject();
});

Now when the alert fires it has nothing inside the dialog box. So I am not grabbing a value from the correct cell. I've tried to break this down logically, but I am stuck. Here is my understanding, which is obviously wrong

*

*$(this) = the image, inside 'td' element.

*parent() = the actual 'td' element holding the image

*find('td:eq(3)') = find a specfic 'td' from the parent location, in this case the third column of the row.

*.text() = the text value of the selected cell

Please explain to me where my logic is broken so I can fix this. Thank you

A: Take into account that eq is zero based so if you want to get the third column, you'll need to use eq(2)
pid = $(this).closest('tr').find('td:eq(2)').text();

As others answers already pointed out, parent won't give you the row as this parent is the td. You could use closest

A: A couple things:

*

*:eq() is zero-based, so you need td:eq(2).

*$(this) is the image, so $(this).parent() is the td. find() searches descendants, and there are no tds within the td you have selected.

So you need this:
$(this).closest('tr').find('td:eq(2)').text();

closest() starts at the current element and traverses up the DOM until it finds an element matching the selector. From the parent tr, you can find the tds.
Fiddle, with div instead of image: http://jsfiddle.net/bAz8P/

A: If you actually want the cell 2 cells to the right of the one you've clicked...
$('.projects_contentTable').on('click', 'td img', function() {
    var myTD = $('td').index(this);
    var pid = $(this).closest('tr').find('td:eq(myTD + 2)').text();
    alert(pid);
    loadEditProject();
 });

A: You could use .closest() to find the row and then find the cell (0 based on eq):
$('body').on('click', '.edit_project_record', function() {
    pid = $(this).closest('tr').find('td:eq(2)').text();
    alert(pid);
    loadEditProject();
});


text:
Q: Tiny MCE - set full-screen when editor is loaded? I use tiny_mce as word-like editor in textareas that are in iframes. I want to use whole iframe space. TinyMCE has a fullscreen button, but I need to set full-screen mode automatically when plugin has loaded. Is there a function/trigger to call this mode (or the button)? Thanks for help.

A: In the IFRAME document you can instruct TinyMCE to switch to fullscreen mode once the textarea has initialized. The following code will need to go into your IFRAME:
<script type="text/javascript">
tinyMCE.init({
    mode : "exact",
    elements : "description",  // This is the id of the textarea
    plugins : "fullscreen",
    theme : "advanced",
    theme_advanced_buttons1 : "fullscreen,code",
    theme_advanced_buttons2 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    oninit : function() {  // Once initialized, tell the editor to go fullscreen
        tinyMCE.get('description').execCommand('mceFullScreen');
    }
});
</script>

....

<textarea id="description"></textarea>

The TinyMCE fullscreen plugin will fill up the current window - and, since the IFRAME is it's own window, the this should fill the IFRAME.
Edit: This technique can also be used with the TinyMCE JQuery library. The options are the same but the invocation syntax is a little different. Again, the key lines are the oninit callback:
$(document).ready(function() {
    $('#description').tinymce({   // "description" is the id of the TEXTAREA
        // ... same options inserted here ...
        oninit : function() {
            tinyMCE.get('description').execCommand('mceFullScreen');
        }
    });
});

A: You just need to insert the following code into the tinyMCE.init({}) function:
setup : function(ed) {
  ed.on('load',function(e){
      ed.execCommand('mceFullScreen');
  });

},
Ps: remember the comma if you have other instruction after it or it will fail.
;-)

A: setTimeout(\'(function(){tinyMCE.get("YourElementID").execCommand("mceFullScreen");})()\',2500);


text:
Q: Enforcing initial containment of a JQuery draggable For a photography webpage I am implementing an image viewer that allows for selecting an area of interest in a scaled-down reference image by dragging a semi-transparent rectangle over the reference image. The selected area is continuously "mirrored" to a second image viewer, which shows the area with at 100% magnification ratio.
My solution uses XHTML/CSS and jQuery and I have a basic version that is working already – but suffers from a problem at initialization, which I cannot solve. I have set up the area of interest as a div that is made draggable using jQuery UI draggable. To constrain the area of interest to the image, I have used the containment property.
Initially the div is however shown outside of the image. As soon as I start dragging the area of interest div, the div snaps to the interior of the image and containment is properly enforced henceforth. All sample code I found, demonstrates containment with nested divs, which does not apply to my case since to my knowledge an image (XHML img) cannot contain other elements.
Is there a way how I can enforce that the draggable area of interest div is already contained when the webpage is initially rendered?
I have extracted to minimal code to illustrate the problem from my code, see below.
I will be glad for any hint.
Cheers,
 Christian
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

A: There are two ways to do this. First, you can try doing it without an image tag. Try placing #zoom_area inside #image_viewer, and using a CSS background image to include the image rather than an image tage.
HTML:

CSS:
#the_image {
    width: 640px;
    height: 427px;
    background-image:url('img/img1.jpg');
}

#zoom_area {
    width: 50px;
    height: 50px;
    background-color: #bbb;
    border: 1px dashed black;
    opacity: 0.6;
}

See this first example in action: http://jsfiddle.net/qUtEW/
If you need to use an image tag, then you can use the following code:
HTML

CSS:
#the_image {
    width: 640px;
    height: 427px;
}

#zoom_area {
    position: absolute;
    z-index:10;
    top:10px;
    width: 50px;
    height: 50px;
    background-color: #bbb;
    border: 1px dashed black;
    opacity: 0.6;
}

The trick here is to set position absolute and z-index 10.
See this second example in action: http://jsfiddle.net/pBRgb/


text:
Q: Why does printing this character value produce a number? #include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{
  // initialize the computer's random number generator
  srand(time(0)); rand();

  // declare variables
  char c1;
  char c2;
  char c3;

  c1 = 'R';
  c2 = 'P';
  c3 = 'S';

  // start loop
  while (true)
  {

    // determine computer's choice
    int result = rand() % 3; // 0 or 1 or 2

    if (result == 0)
      result = c1;

    if (result == 1)
      result = c2;

    if (result == 2)
      result = c3;

    // prompt for, and read, the human's choice

    char humanChoice;
    cout << "Rock, Paper, or Scissors? [R/P/S or Q] ";
    cin >> humanChoice;
    cin.ignore(1000, 10);

    // if human wants to quit, break out of loop
    if (humanChoice == 'Q') break;

    // print results
    cout << result << endl;
    cout << humanChoice << endl;

  // end loop
  }

  // end program

  return 0;
}

What's up guys? I am on my first step of my midterm project which is to create a rock-paper-scissors game. This is just the beginning, and I am far from done, but I already have run into an error. When I compile and run this, I am getting that the compute has chosen the number 83, when it must be either r p or s. Does anyone see where I went wrong with this?

A: result is of type int (and as such it is being interpreted as a decimal number by cout), you mean it to have type char (so that it is intepretted as a text character).
Also you have "overloaded" result to first hold the value of rand() % 3 and then second the character value.  In general, it's best to keep variables separate for readability - the optimizer can figure out to reuse the same storage for them to save stack space.
Try this:
char result;

switch (rand() % 3)
{
case 0: result = c1; break;
case 1: result = c2; break;
case 2: result = c3; break;
}

A: result is int, which will store (and print) the numeric representation of the character you assign to it.
There are multiple ways of fixing this, one would be to simply change result to char. You can still store numbers in it (limited to 0-255) and will have the correct output.
The better way, imho, would be a slight refactoring to first get the human input and then act upon the computers choice (preferrably with a switch).

A: The 83 refers to the unicode value of 's'. Since result is an int, when you assign the char 's' to result, it gets cast to an int. Therefore, it outputs 83.
Try using a different variable for the output. For example:
char response;
if(result==0)
    response = c1;
...
cout << response << end1

A: The input you're taking is of a char type. Casting that to an integer will give you the ASCII value of the char in question. The ascii value for P is 80, R is 82 and S is 83.
You'd be better off using an enum with a switch-case statement :
enum Choices { ROCK, PAPER, SCISSORS };

A: The cout << thing is overloaded. Behaves differently for int and for char. If it is an int whatever is the type of the variable then the output will be a number, if it is a char (character) (we don't care about the size, but we care about the type) then the output will be a character. So in order to fix this the result variables type has to be a char as previously was mentioned.


text:
Q: How do I search ??_doc.xml file in a specified folder in Finder? I have a lot of ??_doc.xml files in a folder, it's like:
13_doc.xml
16_doc.xml
87_doc.xml

The filenames are all like two digits with _doc.xml combined together.
I want to search them and have them showed in folder, and when I type ??_doc.xml in the search box, I get nothing.

Is there anything wrong with my query? What should I type there?
Thanks

A: The Finder search box does not support wildcards. You can add additional criteria to narrow down your search, though.

*

*Enter _doc in the search field to start a search.

*In the bar that appears (showing "Search: This Mac" etc) click the plus sign button all the way to the right.

*In the new row that appears, in the first combobox, select Name, then in the next one select Contains, then in the empty text box type _doc (without wildcards or the file extension).

*Click the plus sign button all the way to the right of this new row.

*In the first combobox of the second row, choose Kind. In the second combobox, choose Other. In the empty text box type xml (without the leading period).

This will narrow down your search to files whose names contain _doc and whose extensions are xml.


text:
Q: How to get FB like count for each post while pulling the feed via Open Graph API? I am trying to get all the posts for a page by using
https://graph.facebook.com/PAGE_ID/feed
And it works like a charm. I can get all the info for each post except the like count.
The feed does return "likes" for each post, but it shows the like info for the first 25 likes. I cannot know the like count of a post.
The closest solution I found on the net is to set "summary=1" when requesting info of a post, e.g.
https://graph.facebook.com/POST_ID/likes?summary=1
This will return a summary field that shows the like count of this post, which is exactly what I need.
However, if this is the only way to solve the problem, I have to make additional network request for each post just for getting the like count. I could originally finish the job with only ONE network request, but now I have make 1+N times (number of posts in the page feed) of network requests.
I think I must be missing something. FB must have some way to get the like count embedded in the feed info. Just like the FB app or website, all posts show their like counts immediately, there is no way to make additional N times of network requests in order to get the like count for each post.
Hope someone can help. Thanks a lot in advance.

A: Finally, I found there is a way to get the like/comment counts for each post while pulling the feed without making further network requests:
/url/feed?fields=likes.summary(1).limit(0)

Isn't it great?


text:
Q: Blog posts to separate pages? How can I have blogs on my expression engine site post directly to a new page with a url? Right now my blogs are static and taking up entire pages (up to 10 blogs on a page) Is there a way to automate this so that every blog that is posted automatically is set up on it's own page with a unique url?

A: There are a bunch of ways to do this.  EE has good documentation and this is pretty well covered.  I think you also get something like this pre-built for you in the default install.
In a nutshell tho what you probably want is an entry template.
So let's say you have a template now called "blog" and the template called "index" that you are now using for your multiple blog listing.
In your "blog" template group you want to create a new template called say, "entry". Then you want to build a link from each entry in the index to the individual entry page.  The path would be something like /blog/entry/{url_title}.
There's more to it than that but that but that should be enough to get you started.  If you have more questions you can ask another question and show us what you have tried.


text:
Q: getting started with Rails 3 forum engine Forem This (https://github.com/radar/forem) is the code for the Rails 3 forum engine, but there's also a sample app ( http://forem.heroku.com/ )
I've got the engine installed (and devise authentication! installed) but am having trouble going farther. I wonder, is there code for the sample app  ( http://forem.heroku.com/ ) that I can look at to learn from?
Right now, when I go to localhost:3000/forums, I get what you see in the attached image. I'm not 100% sure if that's what I'm supposed to see (i.e. I have to build out the models for topics, categories etc and create an admin user? )  or if there's supposed to be a forum ready-to-go out of the box.
If I could see the sample code for http://forem.heroku.com/ it would really help me learn (which is my primary objective...I'm a hobbyist )

A: I wrote Forem. I think I can answer this question.
The sample code lives at http://github.com/radar/forem.heroku.com. This example app contains a theme, installed exactly (or at least, I think exactly) the way that it suggests to install one in the README. The theme is the "twist" theme.
The system (as of this writing) doesn't come with a forum pre-built, but it's on the todo list. So you'll just have to create one yourself.


text:
Q: Large File FTP Upload Error '[WinError 10054] An existing connection was forcibly closed by the remote host' - Small Files Succesful I have been having trouble with a File upload via FTP.  I can upload small files and get a 226 stored message that everything works.  When I run a larger file (200mbs) that takes about 15 minutes to upload, I see that the file uploads when I look at FileZilla but I get the following error that breaks my try/except in python:
[WinError 10054] An existing connection was forcibly closed by the remote host

Here is my script (Thanks to this answered question, I was able to actually get my files uploaded using SmartFTP - Cannot list FTP directory using ftplib – but FTP client works):
class SmartFTP(FTP):
    def makepasv(self):
        invalidhost, port = super(SmartFTP, self).makepasv()
        return self.host, port

try:
    for file_name in os.listdir(fullPath):
        if file_name == 'file.csv':

            file_path = fullPath + "\\" + file_name
            print('Moving File - ' + file_path + ': ' + str(datetime.now()))

            with SmartFTP(FTP_HOST, FTP_USER, FTP_PASS, timeout=2700) as ftp, open(file_path, 'rb') as file:
                ftp.set_debuglevel(2)
                print('here1')
                test = ftp.pwd()
                print('here2')
                ftp.storbinary(f'STOR {file_name}', file)
                print('here3')
                print('FTP Move Completed')

except Exception as e:
    print("FTP and File Move process failed: " + str(e))

Moving File - file.csv: 2022-07-12 15:27:35.932522

here1

*cmd* 'PWD'

*put* 'PWD\r\n'

*get* '257 "/folder"\n'
*resp* '257 "/folder"'
here2
*cmd* 'TYPE I'
*put* 'TYPE I\r\n'
*get* '200 Transfer Mode: BINARY\n'
*resp* '200 Transfer Mode: BINARY'
*cmd* 'PASV'
*put* 'PASV\r\n'
*get* '227 Entering PASV Mode (numbers)\n'
*resp* '227 Entering PASV Mode (numbers)'
*cmd* 'STOR file.csv'
*put* 'STOR file.csv\r\n'
*get* '150 Connecting Data Port...\n'
*resp* '150 Connecting Data Port...'

Then it loads for about 15 minutes

*cmd* 'QUIT'
*put* 'QUIT\r\n'
FTP and File Move process failed: [WinError 10054] An existing connection was forcibly closed by the remote host

This what happens when I load a smaller file:
Moving File - file.csv: 2022-07-12 15:50:39.489980
here1
*cmd* 'PWD'
*put* 'PWD\r\n'
*get* '257 "/Atlas_In"\n'
*resp* '257 "/Atlas_In"'
here2
*cmd* 'TYPE I'
*put* 'TYPE I\r\n'
*get* '200 Transfer Mode: BINARY\n'
*resp* '200 Transfer Mode: BINARY'
*cmd* 'PASV'
*put* 'PASV\r\n'
*get* '227 Entering PASV Mode (numbers)\n'
*resp* '227 Entering PASV Mode (numbers)'
*cmd* 'STOR file.csv'
*put* 'STOR file.csv\r\n'
*get* '150 Connecting Data Port...\n'
*resp* '150 Connecting Data Port...'
*get* '226 Stored Message: [file.csv] Byte Count: [57824] bytes\n'
*resp* '226 Stored Message: [file.csv] Byte Count: [57824] bytes'
here3
FTP Move Completed
*cmd* 'QUIT'
*put* 'QUIT\r\n'
*get* '221 GoodBye\n'
*resp* '221 GoodBye'

They have a process that moves files from the folder I'm posting, into a downloaded folder.  Is this what is causing the issue?
I have tried setting the ftp.set_pasv(False), but this equates in the process loading forever (no end).
As requested, here is the log (and error) of what happens when loaded via FileZilla:
Status: Resolving address of web.com
Status: Connecting to IP:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Logged in
Status: Retrieving directory listing...
Status: Directory listing of "/directory" successful
Status: Resolving address of web.com
Status: Connecting to IP:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Logged in
Status: Starting upload of file.csv
Status: Server sent passive reply with unroutable address. Using server address instead.
Status: Disconnected from server: ECONNABORTED - Connection aborted
Command:    STOR file.csv
Response:   150 Connecting Data Port...
Error:  Disconnected from server: ECONNABORTED - Connection aborted
Error:  File transfer failed after transferring 90,439,680 bytes in 303 seconds

Fails here then retries (filezilla settings are to try twice I believe)

Status: Resolving address of web.com
Status: Connecting to IP:21...
Status: Connection established, waiting for welcome message...
Status: Insecure server, it does not support FTP over TLS.
Status: Logged in
Status: Starting upload of file.csv
Status: Retrieving directory listing of "/directory"...
Status: Server sent passive reply with unroutable address. Using server address instead.
Status: Server sent passive reply with unroutable address. Using server address instead.

Is there anything else I can try?  Thanks so much for any help!


text:
Q: Selenium code to open facebook messenger and send a message I'm just starting to learn a little bit of Selenium scripting (in Java). Currently I'm trying to open a chat box in Facebook and send a message.
I have gotten up to being able to open the chat box through selenium, however I can't figure out how to actually type things into the text box.
Currently here is my code:
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class practice {
    public static void main(String[] args) throws InterruptedException {
      System.setProperty("webdriver.chrome.driver", "C:/max/chromedriver.exe");

      WebDriver driver = new ChromeDriver();
      driver.get("http://facebook.com/login/");
      driver.manage().window().maximize();
      driver.findElement(By.name("email")).sendKeys("myemail@yahoo.com");
      driver.findElement(By.name("pass")).sendKeys("myPassword");
      driver.findElement(By.id("loginbutton")).click();
      driver.findElement(By.name("mercurymessages")).click();
      driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();
     // This has worked randomly. Sometimes the driver will work and open the chat box. Sometimes it will say element not found. I didn't include the full link of the conversation because apparently you don't have to. And it has worked like this in the past.
}
}

My current issue I'd like resolved is: why does this only work sometimes, and how do i find the text box area on the chat box? I did an Inspect Element and the chat box is very odd. It doesn't have anything like an id or a name, so i can't do By.id, or By.name. I can't figure out how to do it with By.cssSelector. This is what the inspect element for the text box looks like:
textarea class="uiTextareaAutogrow _552m" data-ft=".... more stuff here" onkeydown=" more stuff here" style= "more stuff here."

A: You have to learn Xpath and how to create Relative xpath.The xpath for the textarea
driver.findElement(By.xpath("//textarea[@class='uiTextareaAutogrow _552m']"));

Anyhow I've made few changes that Include instead of clicking on some other message.It will create a new message and send to your friend
driver.findElement(By.name("mercurymessages")).click();

    //wait for 20 seconds
    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("u_0_5")));
    driver.findElement(By.id("u_0_5")).click();//To click on Send a New Message Link

    //To enter a name into the to field
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@class='inputtext textInput']")));
    WebElement friendName = driver.findElement(By.xpath("//input[@class='inputtext textInput']"));

    friendName.sendKeys("Deep");//Change it with your friend name

    //wait for the user list to appear
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//li[@class='user selected']")));
    friendName.sendKeys(Keys.ENTER);

    WebElement messageBox = driver.findElement(By.xpath("//textarea[@class='uiTextareaAutogrow _552m']"));
    wait.until(ExpectedConditions.visibilityOf(messageBox));
    messageBox.sendKeys("Hi there");

    messageBox.sendKeys(Keys.ENTER);

A: Hi pal hope this gonna help you:
there is a method called By.className so in order to find elements without an id or a name you can use this method, the thing it's that sometimes the class name of the element it's used in other elements, so be aware of the uses in the current page, if you are lucky and the class name is unique then you can use it :)
System.setProperty("webdriver.chrome.driver", "C:/max/chromedriver.exe");

      WebDriver driver = new ChromeDriver();
      driver.get("http://facebook.com/login");
      driver.manage().window().maximize();
      Thread.sleep(5000);
      driver.findElement(By.name("email")).sendKeys("myemail@yahoo.com");
      driver.findElement(By.name("pass")).sendKeys("myPassword");
      driver.findElement(By.id("loginbutton")).click();
      Thread.sleep(5000);
      driver.findElement(By.name("mercurymessages")).click();
      Thread.sleep(7000);// here you have to use ExpectedConditions in order to verify that the elemnt  it´s "clickable"

      driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();

          Thread.sleep(5000);
      WebElement mssgbox = driver.findElement(By.cssSelector("textarea[class*='uiTextareaAutogrow _552m']"));
      mssgbox.click();
        mssgbox.sendKeys("hi");

hope this help you.
and some times elements in the pages changes so use ExpectedConditions to be sure the element its on the page

A: How to send message to your friend on Facebook:: Using Selenium WebDriver
// Find Username and Enter
        driver.findElement(By.id("email")).sendKeys("Email");
        System.out.println("Email");

        // Find Password and Enter
        driver.findElement(By.id("pass")).sendKeys("Password");
        System.out.println("Password");

        // Click Login
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        driver.findElement(By.xpath(".//*[@id='u_0_q']")).click();
        System.out.println("LogIn Successfull");
        Thread.sleep(2000);

        // Message
        driver.findElement(By.xpath(".//*[@id='u_0_f']/a/div")).click();
        driver.findElement(By
                .xpath(".//*[@id='u_0_f']/div/div[3]/div/div[1]/div/div/ul/li[2]/a/div/div[2]/div/div[2]/div/div[1]/strong/span"))
                .click();

        Thread.sleep(2000);

        driver.findElement(By.xpath("//*[@class='_1mf _1mj']//following :: div[11]")).click();
        Thread.sleep(2000);
        WebElement sendmsg = driver
                .findElement(By.xpath("//div[@class='_1ia']/descendant::div[@class='_5rpu' and @role='combobox']"));
        sendmsg.sendKeys("Just testing: using selenium webdriver" + Keys.ENTER);

A:                 IWebElement messageBox = driver.FindElement(By.ClassName("_1mj"));

                messageBox.SendKeys(string.Format("{0} Do not try to scam people anymore!!!", iteratia++));

                messageBox.SendKeys(Keys.Enter);

Using C#
I can access the message textbox to insert the message with the first line of code. The second line is inserting the message. The third line is sending it.
Result:


text:
Q: Regex | How to exclude specific patterns of characters In question, I need a Regex to accept everything except for specific patterns of strings. I've tried using negative lookahead examples from this Stackoverflow Question Forum:
Regex: match everything but specific pattern
But it looks that the patterns of words are different than a pattern of characters.
The patterns I need to exclude are the ones listed below:

A: This is the correct way of excluding the patterns:
^(?!.*:\/\/)(?!.*\.\.\/)(?!.*:\\)$


text:
Q: Usage of "to make something out of something" I wrote:

It (the software) divides the page into some slides and makes a video out of them.

Is it a correct usage of "out of"? as I searched out of means to create something of value from nearly worthless parts. Can I use from here?

A:
"It (the software) divides the page into slides and makes a video out of them."

This is correct. Please note that I have removed the word "some," which isn't necessary.
You can also write:

"It (the software) divides the page into slides and makes a video from them.

This is also correct, so you are right!
You did a good job constructing the statement and asking about the use of "from" as an alternative to "out of." Of the two, the first example is the most clear and immediately understandable to me, but both are correct and would work well for you. Developing skill in writing clear descriptions of software is an excellent practice, as much that is written is difficult for ordinary people like me to understand.


text:
Q: Primefaces datatable change paginationtemplate color Hi i am new to prime faces, what i am trying to achieve here is complete modification of the primefaces datatable.
Code:
<p:dataTable id="dataTable" var="c" value="#{databaseSearch.customerList}"
                                 paginator="true" rows="10"
                                 paginatorTemplate="Page {CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}  Rows per page {RowsPerPageDropdown}"
                                 rowsPerPageTemplate="5,10,15,30">

CSS Code:
#dataTable th {
    background: black;
    color: white;
    font-family: Verdana, Arial, sans-serif;
    font-size: small;

}
#dataTable td {
    background: maroon;
    color: white;
    font-family: Verdana, Arial, sans-serif;
    font-size: small;

}

I am able to change the color if the header and the rows but the options of paginatorTemplate such as {PageLinks} are still grey buttons

I want to change that grey color, Any suggestions ?

A: You try the following code:
    <style type="text/css">
      .ui-paginator-page{
        background-color:gray !important;
      }
      .ui-paginator{ // for navigation bar
          background-color:gray !important;
      }
    </style>

You can use Inspect element of browser to get component's css and element's css and then override them to get what you want.

A: Thank's. It's works fine, but:
See:
.ui-paginator, th {
   background-color: white !important;
   background-image: none !important;
}


text:
Q: Reading Co-ordinates from a Text File in C++ OK, so all I am trying to do is simply read some co-ordinates from a text file and use them to draw an array of bricks. I have this code:
ifstream infileScenario("scenario1.txt");

for (int i = 0; i < NUM_OF_BRICKS; i++)
{
    // read brick coordinates
    infileScenario >> bricks[i].m_x;
    infileScenario >> bricks[i].m_y;
    cout << bricks[i].m_x << "   " << bricks[i].m_y << endl;

    // set brick properties
    bricks[i].m_height = 0.1;
    bricks[i].m_width = 0.2;
    bricks[i].life = 3;
}

infileScenario.close();

But the only thing that I am getting printed to the console is a bunch of 0's. I've checked over my code again and again as well as double checking my text file and I still can't see where I am going wrong.
My text file is called scenario1.txt and it's contents are:
-0.6 0.7

-0.3 0.7

0 0.7

0.3 0.7

0.3 0.7

-0.6 0.5

-0.3 0.5

0 0.5

0.3 0.5

0.3 0.5

I wrote these values in myself which, if I had to hazard a guess, would think what could be causing my problem. Could it be to do with text encoding or am I wrong in thinking this?

A: I would suggest not using the stream classes, they are a little more difficult to check for errors, here is the same code converted (with error checks) using fscanf.
FILE *infileScenario;
int i;

if ((infileScenario = fopen("scenario1.txt", "r")) == NULL) //didnt open readonly
{
    printf("Error, could not open scenario1.txt\n");
    exit(-1); //terminate program with a code we can read by running echo $?
}
for (i = 0; i < NUM_OF_BRICKS &&
            fscanf(infileScenario, "%lf %lf",
                   &bricks[i].m_x, &bricks[i].m_y) != EOF;
    i++)
{
    // read brick coordinates
    printf("%lf %lf\n", bricks[i].m_x, bricks[i].m_y);
    // set brick properties
    bricks[i].m_height = 0.1;
    bricks[i].m_width = 0.2;
    bricks[i].life = 3;
}

fclose(infileScenario);

You can also g++ -g -o   and then gdb  and run the following in gdb:
b main
r
s
(each time the for loop hits bricks[u].life = 3, run)
p bricks[i]
(otherwise, keep running)
s

That should allow you to diagnose what the issue seems to be, if my solution did not just fix it.


text:
Q: Add column by reference on rolling join The main problem is described in the question title. Going straight to the example below.
I have two datasets:

library(data.table)
dt1 <- data.table(date = as.Date("2015-06-28")+c(0L,3L,5L,7L),
                  key="date")
dt2 <- data.table(date = as.Date("2015-06-30")+c(0:1,4L),
                  val = letters[7:9],
                  dummy = rep(NA,3),
                  key="date")

I want to have val column from dt2 added to dt1 using rolling join.
The following statement will produce similar output to the expected one:

dt2[dt1, roll=TRUE]
#          date val dummy
# 1: 2015-06-28  NA    NA
# 2: 2015-07-01   h    NA
# 3: 2015-07-03   h    NA
# 4: 2015-07-05   i    NA

The are two problems with that statement:
1. I didn't want to have dummy column
2. I want to do this by reference:

address(dt1)
# [1] "0x3b57540"
address(dt2[dt1, roll=TRUE])
# [1] "0x3b4e1f0"

So, I'm looking for rolling join and add column by reference for my dt1 and dt2, expected output:

#          date val
# 1: 2015-06-28  NA
# 2: 2015-07-01   h
# 3: 2015-07-03   h
# 4: 2015-07-05   i

And of course address(dt1) should match to address of the magic statement.

A: Here's a method that should scale.
address(dt1)
# [1] "0x265a060"
ix = dt2[dt1, roll=TRUE, which=TRUE]
dt1[, val := dt2[ix, val]]
dt1
#          date val
# 1: 2015-06-28  NA
# 2: 2015-07-01   h
# 3: 2015-07-03   h
# 4: 2015-07-05   i
address(dt1)
# [1] "0x265a060"

Or without creating the index, directly as:
dt1[, val := dt2[dt1, val, roll = TRUE]] ## (1)

Note that this is more efficient than doing:
dt1[, val := dt2[dt1, roll = TRUE]$val] ## (2)

(2) performs the entire join (materialises all the columns) and then extracts val, where as (1) directly just extracts column val.

A: Here's a workaround; not perfect because it still involves creating extra memory, though there may be a way to avoid this that's not coming to me right away (anyway the extra memory may be minimal):
> address(dt1)
[1] "0x57b5230"

rng<-range(dt1[,range(date)],dt2[,range(date)])

x<-data.table(date=seq(from=rng[1],to=rng[2],by="day"),
              key="date")

> address(x)
[1] "0x6aa2df0"

x[dt2,setdiff(names(dt2),"date"):=mget(setdiff(names(dt2),"date"))
  ][,val:=zoo::na.locf(val,na.rm=F)]

> address(x)
[1] "0x6aa2df0"

> dt1[x,val:=i.val][]
         date val
1: 2015-06-28  NA
2: 2015-07-01   h
3: 2015-07-03   h
4: 2015-07-05   i

> address(dt1)
[1] "0x57b5230"


text:
Q: Ios раскрывающийся список Srotyboard Вообщем такая проблема нужно в Storyborad для меню создать раскрывающиеся списки ну типо на них нажимаешь и он раскладывается ну думаю понятно. Я знаю что их можно как-то через UITableView делать, но как точно хз. Прошу помощи.
Вот примерно что мне надо:

A: Не совсем понятно, без скриншота. Но предположу два варианта:
1 Если вы имеете боковой бар то гуглите swift slide menu. А я посоветовал бы эту библиотеку
2 Если вы "выпадашку" имеете ввиду то гуглите swift drop down menu. Как вариант можно заюзать эту библиотеку или эту. Удачи.

A: Сделать такое через UITableView не составит труда, но будут дополнительные флаги для рендеринга использовать.

*

*Каждый раздел - это секция, сколько разделов столько и секций.

*Нужен массив булевых типов - по индексу секции флаг - развернут или скрыт. На swift - [Bool]

*В каждой секции кол-во ячеек: 1 если свернута или кол-во подсекций + 1 если раскрыто. Состояние свернутости можно получить из пункта 2.

*По клике на первую ячейку (всегда видимая часть) - меняй значение флага для этой секции на противоположное и сразу обновляй таблицу. Для начала сделай просто reloadData(), потом добавь анимацию (пункт 5) после того как все остальное работает.

*Анимацию можно добавить по быстрому - reloadSection с указанием одной секции которая изменилась. Но лучше анимация будет работать если учитывая флаг явно в один коммит добавишь / удалишь все под пункты с анимацией.

В методе получения секции всегда 1й row (индекс 0) - основной пункт, начиная с индекса 1 - подпункты секции, для них уже другой дизайн.


text: Q: How to restrict values in a filter in a pivot table Suppose I have a pivot table and I have 2 filtering criteria (state and zip code). Suppose for my first filter, state, I select CA. I want to only see zip codes that are in CA, in my second filter, zip code. However, I see all zip codes in the United States in my second filter, zip code. I am using Microsoft Excel 2007. Is there a way to correct this so I only see the zip codes that are conditional on the state I select?


text:
Q: Puppet - Error: Could not retrieve catalog; skipping run when I try to connect the puppet agent with puppet agent --test, I have this error :
Info: Retrieving plugin
Error: Could not retrieve catalog from remote server: Error 400 on SERVER :Could not find class <my_module> for <my_agent> on node <my_agent>
Warning: Not using cache on failed catalog
Error: Could not retrieve catalog; skipping run
I have import nodes on sites.pp and include <my_module> on nodes.pp
--edit--
Content of sites.pp :
import "nodes"
filebucket { main: server => "<my_master>" }
File { backup => main }
Exec { path => "/usr/bin:/usr/sbon:/bin:/sbin" }
Content of nodes.pp :
node "<my_agent>" {
    include <my_module>
}

--edit--
What is the real problem ?
Thanks

A: I have created another VM, and that's working now ! =)
Maybe I have taken a mistake in the network configuration.


text:
Q: Is this server setup efficent? I have a web server at home. My IP address changes very often. My domain registrar is GoDaddy, so DynDNS does not work because GoDaddy only allows IP addresses for the A DNS Record. I can set a CNAME for www.mydomain.com that points to mydomain.dyndns.org, but I can't set an A Record.
The only solution that I can come up with is to buy a web hosting service and "proxy" the traffic to my IP. I'd redirect all traffic from example.com/* to index.php (or a script using another language) using .htaccess. Then I'd use index.php to fetch the content from my server at home.
Are there better ways to implement this?

A: The fact that your registrar is GoDaddy doesn't mean you have to use GoDaddy's nameservers.
You can host your domain with any DNS hosting provider, just in registrar control panel you change  nameservers from godaddy's to those of your DNS hosting, like Dyn or whatever you like (the biased list may be helpful).

A: A records are IPv4 addresses, that's where the A comes from. You should set up a CNAME record.


text:
Q: JS: What is 'this' coercion? What does use-strict have to do with that? I read the following on a website:

Use-strict has an advantage. It eliminates this coercion. Without
  strict mode, a reference to a this value of null or undefined is
  automatically coerced to the global. This can cause many headfakes and
  pull-out-your-hair kind of bugs. In strict mode, referencing a a this
  value of null or undefined throws an error.

What exactly does this mean?  What does use-strict have to do with this coercion?

A: When you call a function in javascript, 'this' will refer to different things depending on the context:

*

*If the function has been bound, the 'this' will be set to whatever
it was bound to, e.g. fn.bind(x)()

*If you invoked the function using fn.call(x) or fn.apply(x), the
this will be set to x.

*If the function was defined using arrow notation, then the this
will be whatever was defined to be this when the function was
defined.

*If you call the function with thing.fn(), the this is what is
before the '.', in this case 'thing'.

*If you're in a constructor, called with new then this refers to
the new object under construction.

*If you are just calling a bare function, that isn't on any object,
that isn't bound, that isn't an arrow function and you're calling it
in the straightforward way, without using call or apply, then the
this will refer to the global object if you are not in strict mode,
and undefined if you are in strict mode.  This is what is referred to
as 'this coercion' by the quote.
That's why, if you open a browser console and type
Function('console.log(this)')()
the console will output the Window which is the global object in the browser.  However if you open the console and type
Function('"use strict";console.log(this)')()
the console will log undefined.
I'm using the Function constructor here, because it's a way to force the use of non-strict mode regardless of the situation it appears in - so these examples should still work, even if you run them from inside a file or console operating in strict mode.
this coercion can be the the most convenient way of getting the global object, i.e.
const global = Function('return this')()
works in both the browser and node, even in strict mode.
But most of the time, you want to fail fast, and having functions that you expected to operate on specific kinds of instances actually operate on your global object can mess things up badly.  Having attempts to write something to or read something from this throw exceptions when it isn't defined is almost always better than reading and writing to the global object.


text:
Q: Retrieving specified rows in Datatables The question
Is there a way to programmatically retrieve only the rows witch match some specific criteria - for example rows having specific indexes?
The API has a method - rows(), which results can be manipulated a little by providing a selector-modifier argument. However, using it I am able to use the current table search at most, not a custom one.
The problem
For better understanding, I'll provide more details about what I am trying to achieve.
I am using the Select extension. I would like to select some rows at once using an external trigger. Now I do it like this:
myTable.rows().every(function () {
    // ...
    // Check if the row should be selected and if so:
    this.select();
    // ...
});

However, this causes firing of the same number of select events on the table as the number of selected rows. I have a handler bound to this event, which performs a request to an external API, based on the selected rows. Since I cannot discern which select was the last one, my handler ends up spamming the external API needlessly because of the number of events.
Solutions

*

*Retrieve only matching rows and use rows().select() on them.

I think that would be the best solution, because the select event would be fired only once. However, I have no idea how to do it - hence this question.

*Prevent the handler from calling the external API until the selecting process is finished.

I thought up two hacky solutions which I'll use as a last resort:

*

*Not use an avent handler at all and simply call the API after the rows().every() loop - I still have to use the handler to deal with manual row selection, but that'll probably do.

*Iterate through the rows twice - first time to check which row would be the last to be selected, then disable the handler, do a second loop which actually selects the rows, and enable the handler before selecting the last row
I hope the whole question isn't too confusing. To be clear - the thing I would like to find an answer for is the question on the top, in italics.

A: The selector-modifier is only for when you're selecting all rows. It's not for limiting the rows by a selector. For that you would use the row-selector, which is much more flexible:
https://datatables.net/reference/type/row-selector
There are several examples on that page so I won't go through the options here.
As you suggest is the case, if you use this selector and then call .select() on the returned rowset, the callback will only fire once.


text:
Q: Equivalence of definitions of Cohen-Macaulay type I know that the Cohen-Macaulay type has these two definitions:

*

*Let $(R,\mathfrak{m},k)$ be a Cohen-Macaulay (noetherian) local ring and $M$ a finite $R$-module of depth $t$. The number $r(M) = \dim_k \mathrm{Ext}_R^t(k,M)$ is called the Cohen-Macaulay type of $M$.

*Denote by $\beta_i(M)$ the Betti numbers in a minimal free resolution of $M$ ($M$ is an $R$-module as before). Then the Cohen-Macaulay type of $M$ is the last non zero Betti number, that is, $r(M) = \beta_s(M)$.

So I would ask how to prove the equivalence of these two definitions. There are some books in which I can find this proof?

A: For the equivalence you need two more assumptions: (a) $M$ to have finite projective dimension and (b) $R$ to be Gorenstein. (a) is implicitly required in the second condition, otherwise you don't have the last nonzero Betti number. For necessity of (b), take $M$ to be $R$. Then the last betti is $1$, and the type of $R$ must be $1$ as well.
Assuming (a) and (b), one can prove the equivalence by induction on the projective dimension of $M$. It must be somewhere in the literature, perhaps Bruns-Herzog, but I do not have access to a precise reference right now.


text:
Q: Send variable length vector with constant header in one message I have n workers, 1 master (rank 0) and need to send messages via MPI from the n workers to the master. The message format is a variable length vector (float *dta) and constant size header struct { int32_t x, int32_t y } dtaHdr.
The master just loops through the incoming results and processes them. It is important for it to be able to associate which dtaHdrgoes with which dta.
I know how to:

*

*Create MPI_Datatype for the constant sized dtaHdr and send it via P2P MPI_Send/MPI_Recv.

*Send a variable length vector of any datatype (e.g. MPI_Float) via P2P MPI_Send/MPI_Recv.

The issue is I have no idea how to combine these two approaches.
I know that I could:

*

*Send header first and then the data second in two separate messages.

*

*That has the problem of reordering & interleaving of messages. I need a reliable, easy, and scalable way to associate the header and its data on master. With two messages I can't see a way how to always & simply get both a header and data for incoming message on the master. I.e. two workers could send hdr & data messages to master & they could become interleaved. (I'm not sure what the guarantees for ordering are TBH, even after reading MPI specification).

*Encode both the header and the data to a MPI_Byte array and send it esseentially as a binary blob.

*

*Sounds really dirty & breaks some guarantees.

My question is: how do I MPI-idiomatically send one identifiable logical message that contains both a constant sized header of one type and a variable sized vector of some second type.

A: This program uses MPI_Pack and MPI_Unpack to send two different types in the same message:
#include <mpi.h>
#include <stdio.h>

#define ARRAY_SIZE(array) \
    (sizeof(array) / sizeof(array[0]))

struct data_header {
    int32_t x;
    int32_t y;
};

MPI_Datatype dt_header;
MPI_Datatype dt_vector;

void sendmsg(void) {
    struct data_header header = { 1, 2 };
    float example[] = { 1.0, 2.0, 3.0, 4.0 };
    char buffer[4096];
    int position;

    MPI_Pack(&header, 1, dt_header, buffer, sizeof(buffer), &position, MPI_COMM_WORLD);
    MPI_Pack(example, 1, dt_vector, buffer, sizeof(buffer), &position, MPI_COMM_WORLD);
    MPI_Send(buffer, position, MPI_PACKED, 0, 0, MPI_COMM_WORLD);
}

void recvmsg(void) {
    struct data_header header;
    float example[4];
    char buffer[4096];
    int position = 0;

    MPI_Recv(buffer, sizeof(buffer), MPI_PACKED, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    MPI_Unpack(buffer, sizeof(buffer), &position, &header, 1, dt_header, MPI_COMM_WORLD);
    MPI_Unpack(buffer, sizeof(buffer), &position, example, 1, dt_vector, MPI_COMM_WORLD);

    printf("x = %d, y = %d\n", header.x, header.y);
    for (int index = 0; index < ARRAY_SIZE(example); index++) {
        printf("%f ", example[index]);
    }
    printf("\n");
}

int main(void) {
    int world_size;
    int world_rank;

    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);

    MPI_Type_contiguous(2, MPI_INT, &dt_header);
    MPI_Type_commit(&dt_header);
    MPI_Type_contiguous(4, MPI_FLOAT, &dt_vector);
    MPI_Type_commit(&dt_vector);

    if (0 == world_rank) {
        recvmsg();
    }
    else {
        sendmsg();
    }

    MPI_Finalize();

    return 0;
}

Output
x = 1, y = 2
1.000000 2.000000 3.000000 4.000000

This is really just proof-of-concept code. Hopefully, it will help you find the solution you are looking for.
Note
This code does no error checking and should not be used in a production environment.


text:
Q: Jquery:Getting parent's parent If i have some code like below, a element contains under 3 layers

    hello

Btn list

i want it to console the word "hello" inside class test2
i tried console.log($(this).parent().parent(".test2").text());
i must use this because i am using for loop to genarate datas if i set a consistence class it can't identify which is which

A: Jquery's .closest(selector) is what you need. Your selector can be ".test2" and you can tack on .text() after selecting the desired element.

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Of course, you should make sure your starting point is in fact a descendant of your target point in the data structure you're trying to navigate.  In the example given, hello does not have grandchildren for you to be starting from. You might be going up two levels and then go back down e.g. with find(".test2").

A: Use this one
$(this).parent().parent().find(".test2").text();


text:
Q: HTTP Error code when a related resource is not found Let's say I have an endpoint like PATCH /person/<personId> to which I post some JSON like
{ parent: <parentId> }

What would the appropriate HTTP response code be, if the person with id <parentId> is not found? It should clearly be 404 if the person with id <personId> is not found, but does this also apply to resources not directly mentioned in the URI of the request itself?
I've tried looking at some explanations of the HTTP error codes, but none were clear on this point.

A: You should use 422 to indicate that the given entity cannot be processed by the server. From the RFC 5789, the document the defines the PATCH method:

Unprocessable request:  Can be specified with a 422 (Unprocessable Entity) response when the server understands the patch document and the syntax of the patch document appears to be valid, but the server is incapable of processing the request.  This might include attempts to modify a resource in a way that would cause the resource to become invalid; for instance, a modification to a well-formed XML document that would cause it to no longer be well-formed. There may also be more specific errors like "Conflicting State" that could be signaled with this status code, but the more specific error would generally be more helpful.

Solutions to address similar situations have been previously described here and here.


text:
Q: Is chi square test appropriate for testing frequencies of modifications? I have a lot of sequence reads from next generation sequencing that I'm converting to a sequence of number of Stops, sorted by position on a specific gene. Such a sequence can look like:

0 0 0 0 1 0 0 123 0 0 2 1 0 16 0 0

I'd like to compare treated and untreated samples that may or may not differ in the amount of number of Stops. The paper I'm referencing to uses a chi square test for every position to filter out positions with signicantly more stops in the treated sample (compared to the untreated one) by using a 2x2 contingency table:

                                         Treated     Untreated
number of Stops as pos X on gene Y (k)        74            25
Total number of stops on gene Y    (z)      6047          3646

I assume the null hypothesis to be "the ratio of k/z is the same in treated as in untreated samples".
It this use of a chi square test appropriate? If not, what else should we look into?


text:
Q: greet with/through eyes What is the difference between

They exchange greetings through eyes

and

They exchange greetings with eyes

or even

They exchange greetings by eyes

This might seem like a simple and basic question about prepositions, but I want to know the subtle conecptual differences, through these examples.
Thank you.

A: You ask an excellent question about three prepositions of agency -- (1) through, (2) with, and (3) by -- used with the word eyes. Eyes have two capacities: (A) they are one way the world communicates to us (as the organs of sight) and (B) they are one way we communicate to the world. Sense A is seeing; sense B is looking at.
For sense B, we have the saying the eyes are the windows to the soul, i.e., our eyes reveal to others who we truly are. We say, "Her eyes flashed with anger" to indicate that somebody looks angry. And in your examples, two people send wordless messages to each other by a glance, a wink, or some other action using their eyes. All three prepositions are used in both senses.

*

*through (A) From Their Eyes Meeting the World: the drawings and
paintings of children by Robert Coles and Margaret Sartor
(1992)

She told us that you have to think of other people, and not just yourself, and try to see yourself through their eyes, and not
  just your own — but it's hard.

This is a common metaphorical expression for using another's eyes to mean to see what they see.
(B) From Return Trip Tango and Other Stories from Abroad by F MacShane
and M Carlson (1992)

It's through their eyes that I understand that animals are something else.

This is the other sense. The narrator is looking at animals' eyes for her understanding.

*with(A)With Blood in their Eyes by S G Lawrence (1961):

They'd simply followed his every footstep with their eyes,....

That is, they saw the footsteps.
(B) From Secrets from the Casting Couch: On Camera Strategies for
Actors from a Casting Director by Nancy Bishop (2009):

I believe that this was in part because they had so much practice with communicating with their eyes.

That is, they had other people looking at their eyes.

*by(A) From Intellectual Repository and New Jerusalem Magazine (Vol 5, 1839)

But spirits may be made sensible of the existence of the natural world by communication with the spirits of men while in the body, so
  as to see, as it were, by their eyes,

That is, inhabitants of the spiritual world may become aware of the
natural world by seeing things by using the eyes of humans.
(B) Holding the Dream by Nora Roberts (1997):

You can tell by their eyes. You can tell if you look in their eyes.

And here again, the other sense, of people looking at eyes.
Prepositions often have numerous shades of meaning and idiomatic usages, but in this context, they all mean the same thing, whether it's taking signals in (i.e, seeing) or by sending signals out.

As a side note, eyes in your examples needs a preceding determinative, probably their.


text:
Q: supervisor and uWSGI will not work together along with nginx I use supervisord for managing tornado with no issuse wnhile using nginx as a load balancer.
I am having severe issues with supervisor and uWSGI with nginx as a load blancer.  I am using bottle as the framework.
when I run the below from the command line and I load a page in FF hitting nginx, all works great.
sudo command = /usr/local/bin/uwsgi --loop gevent --socket 127.0.0.1:8070 --wsgi-file /home/ubuntu/workspace/uwsgiServer.py -b 32768 --master --async 5 --enable-threads --listen 100 --uid root

If I place the command line in supervior then I get page not found.
uWSGI Error
Python application not found

[program:uwsgi]
#autostart=true
#autorestart=true
#process_name = uwsgi-%(process_num)s
command = /usr/local/bin/uwsgi --loop gevent --socket 127.0.0.1:8070 --wsgi-file /home/ubuntu/workspace//uwsgiServer.py -b 32768 --master --async 5 --enable-threads --listen 100 --uid root
#--port=%(process_num)s
#--log_file_prefix=%(here)s/logs/%(program_name)s-%(process_num)s.log
#numprocs = 1
#numprocs_start = 8070

Here are the relevant portions of the nginx.conf file:
upstream uwsgi_b {
      server 127.0.0.1:8070;
    }

location /u/ {
                       include uwsgi_params;
                       uwsgi_param X-Real-IP $remote_addr;
                       uwsgi_param Host $http_host;
                       uwsgi_pass uwsgi_b;
                 }

A: You might probably add some more params to supervisord config, like --pp (python path) to the uwsgi command, and maybe some environment variables:
[program:uwsgi]
command = /usr/local/bin/uwsgi
    --loop gevent
    --socket 127.0.0.1:8070
    --wsgi-file uwsgiServer.py
    --buffer-size 32768 --master --async 5 --enable-threads --listen 100 --uid root
    --pp /home/ubuntu/workspace/

autostart=true
autorestart=true
environment=ENV_VAR='var'
user=root # or other
group=root # or other
directory=/home/ubuntu/workspace/
umask=022

EDIT: Removed Django-specific settings


text:
Q: unistall virtualbox I installed virtual box with
virtualbox-5.0_5.0.12-104815-Ubuntu-precise_amd64.deb
but because of some issues I tried to delete it.
First I deleted all the folders of virtualbox situated in /usr/bin/othe-folders. But if I clicked on virtualbox-5.0_5.0.12-104815-Ubuntu-precise_amd64.deb the USC shown me the reinstall button.
Then I tried
sudo dpkg -i virtualbox-5.0_5.0.12-104815-Ubuntu-precise_amd64.deb
but terminal shown  this message:
So with ps aux | grep virtualbox
I found the process.
But if I try to kill the process I get:
bash: kill: (8368) - No such process

The the strange thing is that every time I run ps aux | grep virtualbox the process ID changes. How can I solve?

A: Here's solution that worked:
1. Install midnight commander (sudo apt-get install mc)
2. Run it as root and navigate to the directory the package lies.
3. Enter the package (by taping [enter]), enter the directory CONTENTS and copy all the directories that have been removed manually back to theirs place.
4. Reinstall the package (just to be sure everything is 'by the book').
5. Remove the package using sudo apt-get remove virtualbox-5.0.

A: You have left the virtualbox package in a half-installed/half-uninstalled state. Manually deleting packages you have installed using a package manager is very bad and most often lead to scenarios like this one.
To proceed you have to find all installed virtualbox-packages using dpkg -l | grep virtualbox. Now purge each package with dpkg -P ..., replace ... with the package names found in the previous command.
Now you should be able to install virtualbox again.


text:
Q: Excel incorrectly calculating the average of numbers when using division I am trying to work out the average of scores for the male artists. When I tried using the AVERAGEIFs function it returned a #VALUE error and therefore I have created a table to work out the average manually. The expected score is 3.9 however when I use my table which adds up all the scores and then the number of scores which are not blank and divides the total score by number of scores the answer is 3.4.
Could you please advise on why this would be and if there is a way to calculate the average of male artists?
Here is an image of my spreadsheet:

A: To my knowledge, AVERAGEIFS() works on a single column / single row.
Thus, you need a helping row, showing you the AVERAGE per person, and then taking the average, with conditions such as Gender and Job.

I have 6.5 with this formula:
=AVERAGEIFS(F2:F5 F2:F5,B2:B5,B2,A2:A5,A2)

It simply gives the average of 2 and 11, as they are the only 2 male artists in my sample.
MSDN AVERAGEIFS
If you do not like the idea of additional column, then making a PIVOT table would be a good solution.


text:
Q: Show that $\ker(C)=\{0\}$ - what is wrong with this arguement? Consider the operator $C:X\to X$ where $X=C([0,1])$ and $y\in X$ where $Cy(t)=\int_0^ty(\tau)d\tau+y(t)$. I want to show that $\ker(C)=\{0\}$. Here is my arguement, but I am not convinced that it is a very good one - what is wrong with it?
Suppose that, $$Cy(t)=0$$
$$\implies\int_0^ty(\tau)d\tau+y(t)=0$$
$$\implies\int_0^ty(\tau)d\tau=-y(t)$$
$$\implies\int_0^1\int_0^ty(\tau)d\tau dt=-\int_0^1y(t)dt $$
$$\implies\int_0^ty(\tau)d\tau=-\int_0^1y(t)dt$$
Now, the upper limit $t$ in the left integral is such that it must be from the interval $(0,1]$. Without loss of generality, suppose that this upper limit is $t=1$. Then,
$$\implies\int_0^1y(\tau)d\tau=-\int_0^1y(t)dt$$
$$\implies y(t)\equiv0,\,\forall \, t\in(0,1]$$
As $y(t)\equiv0$ is the only function that could satisfy this equality. What is wrong with this arguement? Is it valid? I have doubts that it is...

A: There are precisely two errors in your reasoning (each of which was separately observed in the comments on your question):
The first error is that the passage from $$\int_0^1\int_0^ty(\tau)d\tau dt=-\int_0^1y(t)dt $$ to
$$\int_0^ty(\tau)d\tau=-\int_0^1y(t)dt$$ is completely unjustified. (Why did you drop the $\int_0^1 ... dt$ on the left? Are you assuming the integrand ($\int_0^ty(\tau)d\tau$) is constant with respect to the variable $t$? It is not.)
The second error is that $$\int_0^1y(\tau)d\tau=-\int_0^1y(t)dt$$ only implies that $\int_0^1y(t)dt = 0$; it does not follow that $y$ is itself constantly $0$.
All the rest of your reasoning would have been sound, but each of these steps is unsupported and in fact fallacious.

A: Arthur pointed out the main flaw in your argument. A possible argument goes like this. (thanks to Sridhar Ramesh for pointing out a mistake in my original argument)
The start of your argument is fine: take a function $y$ in Ker$(C)$, then
$$
\int_0^t y(\tau)d\tau = - y(t) .
$$
The left hand side of this equation is differentiable in $]0, 1[$, so the right hand side must also be differentiable in $]0, 1[$. Taking the derivative with respect to $t$ on both sides yields
$$
y(t) = -y'(t)
$$
for all $t \in ]0, 1[$. Recall from an elementary course in differential equations that the solutions to this equation are exactly of the form
$$
y(t) = Ke^{-t} \quad K \in \mathbb{R}.
$$
So the only possible elements of Ker$(C)$ must be of the form $Ke^{-t}$. On the other hand, if we plug in such a function into $C$ we get
$$
Cy(t) = \int_0^t K e^{-\tau}d\tau + Ke^{-t} = K(1 - e^{-t}) + Ke^{-t} = K
$$
which is $0$ if and only if $K = 0$. Hence, Ker$(C)$ = $\lbrace 0 \rbrace$.


text:
Q: Need timer countdown resetting to 60 when ends with Observables or in any way in Angular2 I am developing bidding website in Angular2. I need a timer for every product, which starts at 60 seconds and when it gets to 0 it resets again to 60.
countDown;
counter = 60;

constructor() {
        this.countDown = Observable.timer(0,1000)
            .take(this.counter)
            .map(() => --this.counter);
}

The counter starts with 60 seconds and ends up with 0. But I can't implement reset part which  reassigns 60 again to counter when its value gets to 0.
I know little about Obervables in RxJs. Can anyone help me?

A: Welcome to Stack Overflow!
We can use some math to achieve this. Please read bonus part to see an alternative
this.countDown = Observable
  .timer(0, 1000) // emits 0, 1, 2, 3, 4, 5, 6, 7, 8...
  .map(tick => 60 - (tick % 60)); // emits 60, 59, 58... 0, 60, 59...

We're taking the rest of division by 60 - tick % 60
1 % 60 = 1
2 % 60 = 2
...
60 % 60 = 0
61 % 60 = 1
...

If we want to count down from 60 then we need to subtract the rest of division from 60.
Bonus (answer to the question in the comment)
If you want to start with a random number, you have to keep some kind of state in the observable. scan operator serves this purpose. In this scenario, using timer operator is an overkill and we can use interval instead.
function getRandomNumber() { // returns a random integer from 1 to 60
    return Math.floor(Math.random() * 60) + 1;
}

Observable
      .interval(1000) // emits every second
      // `scan` works like `reduce` method of the array
      // it keeps its own internal state in `acc`
      // `acc` initial value is random and when it reaches 1, it has a new random integer assigned to it again
      .scan(acc => acc === 1 ? getRandomNumber() : acc - 1, getRandomNumber());
      // emits e.g. 5, 4, 3, 2, 1, 10, 9, 8, 7, 6...

Technically you can solve original problem by replacing getRandomNumber with a desired number.


text:
Q: Unable to set default browser in Windows 10 - "No installed app for this file or protocol" My wife's Windows 10 computer is having an issue where other programs are unable to open web sites because no application could be found to handle "http" or "https". She has both IE and Chrome installed on the machine, and both seem to work fine when opened from the start menu.
Trying to set the default web browser to Chrome from Chrome itself causes Windows to open the "Look for this app in the app store" prompt. Clicking on the app store link only shows four applications - only one of which is actually a browser called "Sidekick Private Browser". I'm loathe to install something like that since there are already two good working browsers on the machine.
Going into the Windows system settings and setting the default browser from Default Apps results in more or less the same thing - I click on "Choose a default" under the Web browser option and a modal comes up titled "Choose an app". The error message says "There is no installed app for this type of file or protocol" followed by a link to the app store.
My hunch is that there's either something corrupted in the registry that makes it so that http and https requests are mishandled since, in the very least, IE should come up as a default browser. However, I have no idea what that problem may be. I ran sfc /scannow, but no errors came up.
Any ideas? Thank you in advance!

A: Being fairly confident this is an issue with the registry, I decided to try reinstalling Chrome. Sure enough, doing so made it show up in the list of possible applications to set for the default web browser. Curious that IE still isn't listed there, but something must have blown away the registry entries that identify Chrome and IE as being capable of handling http and https requests. Also curious that passing that on to the Microsoft app store did not show ANY of the major browsers as possible contenders to handle this. In short, I think the registry is borked somehow and I still have no idea how to fix that. But, in the mean time, it looks like I'm at least able to set Chrome as a default. If this changes, I'll update again here.


text:
Q: How to Insert into DB2 with NativeQuery and get generated ID I'm trying to insert a row into DB2 but i can figure out how to get the generated ID.
With this code it's working but i can't get the ID:
    String sql = "INSERT INTO MY_TABLE (MY_COLUMN) VALUES (?)";
    Query query = entityManager.createNativeQuery(sql);
    query.setParameter(1, "MY_VALUE");
    query.executeUpdate();

I did some research, and tried to do like this:
    String sql = "INSERT INTO MY_TABLE (MY_COLUMN) VALUES (?)";
    Query query = entityManager.createNativeQuery(sql);
    query.setParameter(1, "MY_VALUE");
    BigDecimal id = (BigDecimal) query.getSingleResult();

But I got this error:
[org.hib.eng.jdb.spi.SqlExceptionHelper] (executor-thread-63) [jcc][t4][10103][10941][4.21.29] Method executeQuery cannot be used for update. ERRORCODE=-4476, SQLSTATE=null
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1535)
at org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1574)
...

What is the correct way to insert using NativeQuery and get the generated ID?

A: You can run comand like
-- You befor build str_sql in here
str_sql = 'INSERT INTO ............';
EXECUTE IMMEDIATE str_sql;


text:
Q: 403 Forbidden home on localhost with nginx server I install wordpress in nginx server on my localhost using debian OS, install is normally. But I only can login to my dashboard using  localhost/statistik/wp-admin/index.php not in localhost/statistik/wp-admin/ because its become 403 Forbidden, as same as if I access in my frontpage (localhost/statistik/) its become 403 Forbidden too.
After my search on google, I know this problem because nginx not working without extention php, but I dont know how to acsess my frontpage, I try localhost/statistik/index.php and localhost/statistik/front-page.php still not working.
I try to change the configuration nginx of my site in /etc/nginx/sites-enabled/statistik but still working. This is my configuration, please help me.

file in /etc/nginx/sites-enabled/statistik

server {
listen 80;
listen [::]:80;
server_name statistik;
root /var/www/html/statistik;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
index index.html index.htm index.php;

# Directives to send expires headers and turn off 404 error logging.
location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
   access_log off; log_not_found off; expires max;
}

location / {
    try_files $uri $uri.html $uri.php /index.php?q=$uri&$args $uri/ @php;
}

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php7.0-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location @php {
    rewrite ^/([^/]+)(/|$) /$1.php last;
}

}

file in /etc/nginx/sites-enabled/default

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    #
    #   # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    #   # With php-cgi (or other tcp sockets):
    #   fastcgi_pass 127.0.0.1:9000;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}

file in /etc/nginx/nginx.conf

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#mail {
#   # See sample authentication script at:
#   # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
#   # auth_http localhost/auth.php;
#   # pop3_capabilities "TOP" "USER";
#   # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
#   server {
#       listen     localhost:110;
#       protocol   pop3;
#       proxy      on;
#   }
#
#   server {
#       listen     localhost:143;
#       protocol   imap;
#       proxy      on;
#   }
#}

For information I using Debian 9, NGINX 1.13.3-1, MySQL community client&server 5.7.22-1, php7.0


text:
Q: how to compute a value based on input from 3 dropdown lists? I have three dropdown lists having 6,3,3 options in them respectively. I need to compute a value depending on the combination of values chosen from the dropdown lists.I have 54 different values for 54 different permutations and combinations for the dropdown menus. Please suggest an optimized way of achieving this in php.
enter code here
 <select name="designation" id="desg">
  <option value="1">International Doctor</option>
  <option value="2">Domestic Doctor</option>
  <option value="3">MBBS STUDENT</option>
  <option value="4">nursers </option>
  <option value="5">Postgraduates / Interns</option>
  <option value="6">Faculty</option>
</select>
<select name="workshop" id="wshop">

    <option value="None">None</option>

    <option value="workshop1">workshop1:PACET</option>

    <option value="workshop2">workshop2:PEMC</option>

    <option value="workshop3">workshop3:Research Workshop</option>

   </select>
   <select name="category" id="cat">

    <option value="None">None</option>

    <option value="1">1</option>

    <option value="2">2</option>

    <option value="3">3</option>
    </select>

if a user select his designation,category,workshop the corresponding amount should be displayed
picture contain a table with corresponding amount for different workshops,desginations,category

A: The Question is not very clear to me, but I am going to show an example which may help you.
This code may be similar to your code for this web page
<!DOCTYPE html>

    <title></title>

    <select name="l1" id='l1' onchange="displayMapping()">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <select name="l2" id='l2' onchange="displayMapping()">
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

You may create an assosiative array for your permutations (In this example array named mapping), then you can create a function which will automatically called when there will any change in your dropdown lists (In this case that function is displayMapping()).
This example uses javascript hence reflected in local machine, If you want to calculate in server side then it may not be very useful to you.

A: may be use like that
selectName[]
selectName2[]
etc.


text:
Q: PyQt5: How to drag text from QTextEdit into a QlistView? I'm currently building a GUI, to which I would like to add the possibility to drag a string from a QTextEdit, and drop it into a QListView so that the dropped string creates a new row.
But sadly I'm a bit confused with what I should be doing. There are tons of examples, but I can't see clearly what I should be doing.
From what I understand I have to reimplement functions but right now I'm more of an headless chicken.

from PyQt5 import QtCore, QtGui, QtWidgets
import testing_ground_lib, sys

class ListModel(QtGui.QStandardItemModel):
    def supportedDropActions(self):
        <MAYBE DO STUFF HERE>

    def dropMimeData(self, data, action, row, column, modelIndex):
        <MAYBE DO STUFF HERE>

class testing_ground(QtWidgets.QMainWindow, testing_ground_lib.Ui_TestWindow):

    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.setupUi(self)

        self.list_model = ListModel(0, 1, self)
        self.inputs_list.setModel(self.list_model)

sys.argv = ['']
app = QtWidgets.QApplication(sys.argv)
testing_ground = testing_ground()
testing_ground.show()
app.exec_()

testing_ground_lib is just the UI generated through QtDesigner, in which we have self.inputs_list.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop) and where my QTextEdit widget is defined (self.req_editor)
In reimplemented dropMimeData, I tried to print stuff just to see how it works but it did not do anything when I was trying to drop my string within QListView.
It is clear to me that I have to implement something that would append a row in ListView on drop of the string, and set the new item with the text from the string, I just can't get what is the starting point.
EDIT : after further investigation, I managed to make the item acceptable by adding :
    def mimeTypes(self):
        return ['text/plain']

in my ListModel class. Now I think I just have to properly reimplement dropMimeData and I think all will be good. I'll update this post if I manage to do so.

A: Here is a solution to drag the highlighted text in a QTextEdit and drop it into a QListView, adding a new row with that text. Subclass QListView and reimplement dragEnterEvent, dragMoveEvent, and dropEvent. In the dropEvent, add the new item with QStandardItemModel.appendRow().
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class ListView(QListView):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setAcceptDrops(True)
        self.setModel(QStandardItemModel(0, 1))

    def dragEnterEvent(self, event):
        event.accept() if event.mimeData().hasText() else event.ignore()

    def dragMoveEvent(self, event):
        event.accept() if event.mimeData().hasText() else event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasText():
            event.setDropAction(Qt.CopyAction)
            self.model().appendRow(QStandardItem(event.mimeData().text()))
            event.accept()
        else:
            event.ignore()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QWidget()
    hbox = QHBoxLayout(window)
    hbox.addWidget(QTextEdit())
    hbox.addWidget(ListView())
    window.show()
    sys.exit(app.exec_())

Result:


text:
Q: Jquery scroll check doing opposite of what I want? So all I want is for jquery to check weather the user has scrolled to the bottom of the page and then do something if they have..
But strangely enough it's doing the opposite, it'll alert when I scroll to the top, and not the bottom, any idea why this is? Am I looking at it and not seeing it?
Here is my code so far:
 <script>
     $(window).scroll(function() {
         if($(window).scrollTop() + $(window).height() == $(document).height()) {
            var img_no = $(".imgcontain").length;
            alert("There are "+img_no+" images on the page.");
     }
    });
  </script>

A: Ok, so I've done the stupidest thing, but I might as well confess in case others ever have the same problem.
I forgot the !DOCTYPE html.
Yup, it was really that stupid of me.


text:
Q: How do I set proxy in Nuxt3? I try to start a nuxt3 program, now I want to set server proxy.
A request to http://localhost:3000/api/v1 is supposed to return a response from our backend server on http://39.98.58.238:8594 , but now it gives me a 404 page.
At first, I follow the vite.js docs to set nuxt.config.js file
nuxt.config.js
export default defineNuxtConfig({
  ...
  vite: {
    server: {
      proxy: {
        '/api': {
          target: 'http://39.98.58.238:8594',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      },
    }
  },
})

page
<script setup>
  async function test() {
   await usefetch('/api/v1/xxx')
  }
</script>
<template>
  <div>
    <button @click="test">check</button>
  </div>
</template>

It didn't work, my request returned a 404 page.
Then I try to follow this issue: text, do not use vite proxy
nuxt.config.js
export default defineNuxtConfig({
  nitro: {
    devProxy: {
        '/api/': {
            target: 'http://39.98.58.238:8594/',
            changeOrigin: true
        }
    }
  }
})

But it's still not work. What can I do to solve the problem? Thanks!!!

A:    export default defineNuxtConfig({
        nitro: {
            devProxy: {
                "/devApi": {
                    target:"your url",
                    changeOrigin: true,
                    prependPath: true,
                }
            }
        },
    })


text:
Q: how to make correctly has many associations in Golang with go let say one teacher has many students and student only has one teacher, how to implement it on Gorm Golang ?
my opinion is
type Teacher struct {
   gorm.Model
   Name string
   Student []Student
}

type Student struct {
  gorm.Model
  Name string
}

is those correct ?? and if not how to make it to be associated? and how about if we query it to create ? should I create another StudentID on it ?

A: type Teacher struct {
   gorm.Model
   Name string
}

type Student struct {
  gorm.Model
  Name string
  TeacherId uint `gorm:"TYPE:integer REFERENCES teachers;index"`
}


text:
Q: What does implodeQuery mean? I was checking the source page of facebook . I found a function which frequently used there .
the line was
input_len=URI.implodeQuery(this.data).length

I cant understand what the line means and what implodeQuery  .
I also need th same function for php .
Please help me ! thanks

A: URI.implodeQuery appears to serialize the passed object into a query string (for something like a GET request).  This functions much like jQuery.param().
From the JavaScript console on Facebook:
> URI.implodeQuery({'greeting':'hello','number':2,'vegetable':'carrot'});
"greeting=hello&number=2&vegetable=carrot"

A: URI.implodeQuery() is not native to javascript.
It's a method defined somewhere else in the Facebook code.


text:
Q: How to check hashset for an existing element and then adding a count I'm a beginner in Java and is starting to learn how to use hashsets. I have a problem with my practice exercise. The goal is to remove the duplicate description and then adding the count of similar descriptions.
For example I have,
Computer Science - 15
Engineering - 20
Dentistry - 10
Architecture - 11
Computer Science - 25
Dentistry - 7
then the output should only be:
Computer Science - 40
Engineering - 20
Dentistry - 17
Architecture - 11
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    //printing summary report
    ArrayList<String>   summaryReport=  new ArrayList<String>();

    final String[] CourseDesc           = {"Computer Science", "Architecture", "Dentistry", "Computer Science"};
    final int[] CourseCount         = {15, 10, 10, 25};

    for (String element: CourseDesc) {
        for(int el: CourseCount){
             summaryReport.add(element + " "+ el);
        }
     }
   System.out.println(summaryReport);
  }
}

I'm just stuck on how to add the count of similar descriptions. Thanks!

A: A smart way to solve you problem would be to use Java Streams:
final String[] courseDesc = {"Computer Science", "Engineering", "Dentistry", "Architecture", "Computer Science", "Dentistry"};
final int[] courseCount = {15, 20, 10, 11, 25, 7};

Map<String, Integer> summaryReport = IntStream.range(0, courseDesc.length).boxed()
    .collect(Collectors.toMap(
        index -> courseDesc[index], index -> courseCount[index],
        (count0, count1) -> count0 + count1, LinkedHashMap::new
    ));

This creates a Map with the course as key and the sum as value. If the map contains an course and the same course is collected again the lambda expression (count0, count1) -> count0 + count1 handles it by summing the values. The LinkedHashMap::new is to maintain the order.
Now you can print the summary like this:
summaryReport.forEach((course, count) -> System.out.println(course + " - " + count));

Result:
Computer Science - 40
Engineering - 20
Dentistry - 17
Architecture - 11

A: From OP I can see that you need an association key-value container, so the most obvious way will be to use Map, check if the value present as a key, if not - add it with 1 counter, if present - add + 1:
void test() {
    Map<String, Integer> summaryReport = new HashMap<>();
    String curDesc = "whatever";

    Integer count = summaryReport.get(curDesc);
    if (count == null) {
        summaryReport.put(curDesc, 1);
    } else {
        summaryReport.put(curDesc, count + 1);
    }
}

Doing in more tricky way, you can use mutable AtomicInteger as a counter:
void test() {
    Map<String, AtomicInteger> summaryReport = new HashMap<>();
    AtomicInteger counter = summaryReport.putIfAbsent("whatever", new AtomicInteger(0));
    if (counter != null) {
        counter.incrementAndGet();
    }
}