text:
Q: Htaccess is not working for url php I am trying to make pretty url in PHP. URL is working but CSS and JS is not working.
File path is: example.com/store.php?brand=brand_name
Desired url : http://example.com/store/brand-name
Code:
RewriteEngine On
RewriteRule ^store/(.*)/?$ store.php?brand=$1    [NC,L]    # Handle product requests

A: Nothing to do with .htaccess. Actually your pages are not getting CSS and JS as paths are not correct, that's why issue is coming.
You need to set constant variable like BASE_URL for your domain that you will include for all your CSS and JS like below:
base_url.php
<?php
define('BASE_URL', 'http://example.com');
?>

index.php:
<?php
    include('base_url.php');
?>
<!DOCTYPE html>
<html>
  <head>
    <!-- // -->
    <link rel="stylesheet" href="<?php echo BASE_URL; ?>/css/styles.css" />
 </head>
 <body>
 <!-- // -->
 </body>
</html>

You can also add this constant variable if you have connection.php or any other common file that includes in all the pages where you are using CSS and JS.


text:
Q: Javascript object factory instanceof Why does the following object factory pattern code return false...
var Animal = function(name) {
var temp = new Object();
    temp.name = name;
    return temp;
}

var animal = Animal("fox");

console.log(animal instanceof Animal);

...while the following constructor pattern code returns true;
var Animal = function(name) {
    this.name = name;
}

var animal = new Animal("fox");

console.log(animal instanceof Animal);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to reverse a txt file in python 3.8? data = data2 = data3 = ""

with open('pushkin.txt', encoding='utf-8', mode='r') as fp:
    data = fp.read()

with open('romeo.txt', encoding='utf-8', mode='r') as fp:
    data2 = fp.read()
with open('byron.txt', encoding='utf-8', mode='r') as fp:
    data3 = fp.read()

data += "\n"
data += data2 + data3

with open('poems.txt', 'w', encoding='utf-8') as fp:
    fp.write(data)

With this code, I have transferred three text files into one.
Now I need to turn over text in that file, like this:
ABC       CDA
BCA  -->  BCA
CDA       ABC

but I don't know how. I thought using reverse() or reversed(), but that makes it just from
abc to cba

A: You can use reverse() to reverse the order of elements in a list after saving all the contents as list type to data variable, not the specific string, as follows:
data = []

with open('1.txt', encoding='utf-8', mode='r') as fp: # ABC
    data += fp.readlines()
    # data -> ['ABC\n']

with open('2.txt', encoding='utf-8', mode='r') as fp: # BCA
    data += fp.readlines()
    # data -> ['ABC\n', 'BCA\n']

with open('3.txt', encoding='utf-8', mode='r') as fp: # CDA
    data += fp.readlines()
    # data -> ['ABC\n', 'BCA\n', 'CDA\n']

data.reverse() # data becomes ['CDA\n', 'BCA\n', 'ABC\n']

with open('result.txt', 'w', encoding='utf-8') as fp:
    fp.write("".join(data))

# result.txt
CDA
BCA
ABC


text:
Q: How to start a new rails project without overhead of actioncable? I know most of the rails experts know the answer to this simple question but since not every new rails app is going to be a chat application or would even need a redis/websockets sitting in there, how to create a new rails project without actioncable?
$ rails new <project name> --option

A: Should be rails new --skip-action-cable
Found via rails new --help


text:
Q: What's a good pattern for iOS apps that have a lot of lookup tables? I've got an application that has a lot of (short) lookup tables (codes -> human readable string), what's the best way to implement looking up these codes in an ObjC/iOS app?
I was thinking a "Lookup" class that has a dictionary (property) for each lookup or maybe something with a plist?
I am wondering how others handle this kind of situation.

A: It depends what you mean by a lot. A plist would probably work fine. But if your storing a ton of data, and if you need store anything else associated with the codes, I would look into core data.This looks like a good tutorial on how to do that with a plist: http://iphonebyradix.blogspot.com/2011/03/read-and-write-data-from-plist-file.html


text:
Q: Pass variables from python file to robot framework variables I am assigning variables in robot framework as
*** Variables ***
${TestNAME}                       test

But can I pass variable value from python file?
#test.py
var = 'test'

Is it possible to assign var to ${TESTNAME}?

A: If you have a file named "test.py" that has variables defined in it, you can import the variables using the robot variable file feature.
Here's an example, using the pipe-separated format for clarity:
*** Settings ***
| Variables | test.py

*** Variables ***
| ${myTestName} | ${var}

This works because settings are processed before the Variables table. Any variables in the python file can be referenced using the standard robot syntax for variables (eg: python variable var is referenced as ${var})
Note, however, that ${Testname} is automatically set by robot, so your exact requirement can't be met. If you use a non-automatic variable, you can set it the way you want, which is why the above example used ${myTestName}.

A: eg:- The variable file is as shown - var.py
x = 10
y = 20
file1.robot can be written as shown:-
*** Settings ***
Variables  var.py
*** Test Cases ***
KEYW1
  Log  ${x}


text:
Q: how select with from mutiple table id  friend1 friend2
1   obi      ezenwa
2   obi      obinna
3   obi      ezenwa

this is how i select the list of friends from the table above
<?php

require("config.inc.php");

if (!empty($_POST)) {
$query = "SELECT users.* FROM users WHERE users.username IN
(SELECT friend2 FROM friends where friend1=:username
UNION
SELECT
friend1 FROM friends where friend2=:username)";

    $query_params = array(
        ':username' => $_POST['username']
    );

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}
$rows = $stmt->fetchAll();

if ($rows) {
    $response["success"] = 1;
    $response["message"] = "Post Available!";
    $response["posts"]   = array();

    foreach ($rows as $row) {
        $post             = array();

        $post["TAG_NAME"]    = $row["username"];

        array_push($response["posts"], $post);
    }

    echo json_encode($response);

} else {
    $response["success"] = 0;
    $response["message"] = "No Post Available!";
    die(json_encode($response));
}

} else {
?>

Login

        <form action="selectfriends.php" method="post">
            Username:

            <input type="text" name="username" placeholder="username" />

            <input type="submit" value="Login" />
        </form>
        Register
    <?php
}

?>

it works well i also have a table like this one below called chatt. where messages of users are saved.
                              Chatt
      fromm     too       message           time
        obi2    ezenwa  this is me yes  2015-02-08 23:47:31
        obi     ezenwa  ok i can see    2015-02-08 23:47:31
        obi     ezenwa  seems good      2015-02-12 17:44:10
        ezenwa  obi     i agree         2015-02-12 17:49:16
        obi     ezenwa  j man           2015-02-13 14:42:16
        obi     ezenwa  j man           2015-02-13 14:43:28
        obi2    ezenwa  this is cool    2015-02-13 14:58:28

i would like to display the last message between the username that has been enter and all his friends which contained in $row["username"] ...i just want the users list of friends and the last message between them just like blackberry messenger and WhatsApp ....


text:
Q: Java scanner skipping iterations I've been stuck for a while now in an issue, and the program is not doing what I believe it should be doing.
When I run the program and it gets to the part where it asks you for the name of the course,  the program skips the first iteration, or other depending how many courses were inputted. It only allows for input on the last iteration. For the following for loops, the program skips them without ever allowing in input.
My questions is, are the for loops incorrect or is the the String arrays that are not inputting the information correctly to their subscript?
    import java.util.Scanner;           //Needed for Scanner class
    public class StudentRecords
    {
    public static void main(String[] args)
    {
    int courses;
    int students;
    int[] course = new int[5];
    int[] student = new int[5];
    double GPA = 0;
    String[] courseNumber = new String[5];
    double[] creditHours = new double[5];
    String[] letterGrade = new String[5];

    //Scanner object for user input
    Scanner kb = new Scanner(System.in);

    System.out.println("This program will help you determine the GPA \n"
                        + "for each student entered.");
    System.out.println("");

    System.out.println("How many student's GPA are you going to calculate?");
    System.out.print("Enter amount of students (Maximum of 5 students): ");
    students = kb.nextInt();
    student = new int[students];

    System.out.println("");

    for(int index = 0 ; index < student.length; index++)
    {
        System.out.print("Student " + (index + 1) + " information: ");
        System.out.println("");

        System.out.print("How many courses did student " +
                            (index + 1)  + " take? ");
        courses = kb.nextInt();
        course = new int[courses];

        for(int i = 0; i < course.length; i++)
        {
            System.out.println("What is the name of course #" + (i + 1));
            courseNumber[i] = kb.nextLine();
        }

        for(int i = 0; i < course.length; i++)
        {
            System.out.println("How many credit hours is " + courseNumber[i]);
            creditHours[i] = kb.nextDouble();
        }

        for(int i = 0; i < course.length; i++)
        {
            System.out.println("What is the final letter grade for " + courseNumber[i]);
            letterGrade[i] = kb.nextLine();
        }

        for( i = 0; i < student.lenght<
    }
    }
 }

P.S. This is the question I am working on:

Write a program with the following inputs, all of which are stored in
  arrays (size 5). First how many courses the student took that semester
  (can't be greater than 5). Store in ARRAYS for each student, the
  course number/name (for example ICT 435), credit hour ( 1-4), and
  letter grade(A-F). Determine the GPA for the semester.

A: The nextLine() Scanner method can be kind of weird.  A beginning Java course I took mentioned that, after a method retrieving a number (nextDouble(), for example), there's a new line character at the end of the line.  The next time you use nextLine(), it reads that new line character as input, not giving you a chance to type anything.
If you put a nextLine() before the loop asking for the course names,
kb.nextLine(); // <-- here
for(int i = 0; i < course.length; i++)
{
    System.out.println("What is the name of course #" + (i + 1));
    courseNumber[i] = kb.nextLine();
}

it will pass that new line.  Any subsequent nextLine() calls will actually let you give input.  That is,   You'll need to do this before the letter grade loop as well,
kb.nextLine(); // <-- here
for(int i = 0; i < course.length; i++)
{
    System.out.println("What is the final letter grade for " + courseNumber[i]);
    letterGrade[i] = kb.nextLine();
}

since you ask for numbers before this loop too.
This worked for me.  Hope it helps!

A: try to use:
courseNumber[i] = kb.next();

and
letterGrade[i] = kb.next();

in your for loops while scanning the strings.
Instead of
courseNumber[i] = kb.nextLine();

and
letterGrade[i] = kb.nextLine();

see this link for more details:


text:
Q: Potential issues with passive voice usage I checked the grammar of my research article using a leading software. This is my sentence:

*

*A total of 12.3 million sequences was used for the establishment of database.
The error is: 'Potential issues with passive voice usage'
Anything wrong here?
(NOTE: Er, the OP's question is about passive voice, but the "duplicate" linked thread is about subject-verb number agreement. Perhaps there's a related issue here, on subject-verb number agreement (which is debatable), but the OP's main question on passive voice ought to be addressed. Anyway, a short answer post here would probably be more appropriate than a related link. -- F.E.)

A: A total (of 12.3 million sequences) was used (for the establishment (of database)).

subject + [v. to be] + [v. participle]

I think the sentence is correct.


text:
Q: Memory structure for an array of pointers to objects (visualization) I can visualize the situation when, for example, I have allocated memory in the following way:
Position* arr1 = new Position[5];

Position being a class in my program that describes a positional point with x and y values.
There would be a pointer on the stack that points to the first element (a Position object) of the array "arr1" on the heap so it would look something like this:

How would it look if I were to create an array of pointers though? For example:
Position** arr2 = new Position* [2];

arr[0] = new Position(3, 7); // Constructs a point with x and y values.
arr[1] = new Position(9,6);

Where are all the pointers and objects stored in the memory in my second example? Are there pointers on the stack that point to pointers on the heap which then point to the objects on the heap or something?
Also, if I were to delete [] arr2;, where would the objects remain in the memory?
Thanks.

A: *

*Every object created by new is on the heap. So in your example, the array of two pointers would be on the heap. arr2, as a local variable, would be on the stack.

*The Position objects, being separately allocated by new, are in their own separate heap blocks. They need to be deleted individually. Otherwise, they remain on the heap. An object cannot move between the stack and heap. (Although C++11 provides std::move, this is really a special kind of ownership transfer; it does not magically turn a heap address into a stack address.)

*delete [] arr2 would leave the objects in memory. As the array of pointers does not own the referenced objects, this code does not ask to destroy the indirectly referenced objects.

You should always avoid using new and delete directly in favor of container objects (std::vector or std::array would work here), or smart pointers such as unique_ptr and shared_ptr.

A: You have one automatic variable, arr2 pointer object. The rest is on the free store. If you only delete[] arr2, you'll free the memory for the pointers, and not the objects they point to.
arr2 ---+  +---------------------------------+
        |  |                                 |
        |  |                                 |
        +----> [Position*, Position*]        |
           |       |          |              |
           |       |          +----> [9, 6]  |
           |       v                         |
           |    [3, 7]                       |
           +---------------------------------+

A: The pointer of the array arr2 will be on the stack. The other pointers arr2[0], arr2[1] etc will be on heap and these pointers will point to different locations on the heap.

A: Your diagram would have an extra level of indirection. So replace myArray with arr2, having arr2[0] and arr2[1]. Then, still on the heap, draw another arrow from arr2[0] to a Position value, and from arr2[1] to another Position value.
If you used delete[] arr2, these values would remain at whatever position in memory they were assigned originally.


text:
Q: Check For Duplicate Values with ASP, javascript, and Ajax On submit, I have to check if the information that is being posted to the database matches anything that already exists in a table. If it does detect a duplicate, it will then interrupt the post and prompt the user that a duplicate already exists and allow them to change the data so they can resubmit. I am currently using asp and javascript to post the information to the DB, but have read for this ajax will be the way to go to check for duplicate values. By the way, I can't use PHP :(. Does anyone have some great resources or insight on how to do this? Thanks for your time and help!

A: Use Ajax Pagemothods calls from javascript and check for duplicate entry in db. This will not postback the page. Try the below link for pagemethods sample
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX


text:
Q: Remapping keyboard shortcuts to another key? I'm not sure if this is possible, but I am trying to remap keys on a web application so that if a user presses the 'Right' arrow key on their keyboard, it will to perform the same action as if they had pressed had pressed the 'CTRL-Shift-Right' keys?

A: You're going to want to use an event listener, something like
document.addEventListener('keyup',
            function (event) {
                 if (event.key === "something") {}
            });


text:
Q: How to Embed Mapbox in iOS WidgetKit I have been attempting to embed a mapbox view into an iOS widget using WidgetKit but am hung up on the following error:

Application extensions and any libraries they link to must be built with the APPLICATION_EXTENSION_API_ONLY build setting set to YES.

We are using CocoaPods for package management, and we have been using Mapbox in our main application for some time.
As far as I can tell, this is referring to the Mapbox POD and I don't believe I have the ability to modify that build setting. Can someone help set me straight here?

A: While you can't embed https://github.com/mapbox/mapbox-maps-ios in a Widget, you can use https://github.com/mapbox/MapboxStatic.swift to fetch Maps image and display it in a Widget.


text:
Q: Unable to pass dynamic value to window.open This code works as i have hardcoded "cmp4" but i needed it to be dynamic. When i pass it from a variable it doesn't work. window.open is a js function so I am not sure with R how it takes. It would be great if the solution is in js or R.
I want to pass like this: variable as<- "cmp4" instead of hardcoding it manually
output$createdash<- renderUI({
actionButton("sj", "Create Dashboard",

             onclick="window.open('http://192.168.63.198:3838/DS?screen=repdash&portfolio=COMP0004','_self')"

             ,style="color: #fff; background-color: #337ab7; border-color: #2e6da4")

})

A: Does the approach below help? It shows how you can use an input or reactive within paste0 inside an actionButton created with renderUI.
library(shiny)

shinyApp(

  ui = fluidPage(
    selectInput("url",
                "Choose URL:",
                choices = c("google" = "http://www.google.com",
                            "amazon" = "http://www.amazon.com")),
    uiOutput("action")
  ),

  server = function(input, output, session) {

    output$action <- renderUI({

      actionButton("sj", "Create Dashboard",

                   onclick=paste0("window.open('", input$url,"','_self')"),

                   style="color: #fff; background-color: #337ab7; border-color: #2e6da4")

    })
  }
)

A: In javascript ,
assuming u are taking "http://192.168.63.198:3838/DS?screen=repdash&portfolio=COMP0004  " dynamically from browser .  you can split it and take the last element of an array without the need to hardcode it.
lets say browser url is reflecting "http://192.168.63.198:3838/DS?screen=repdash&portfolio=COMP0004  since the last element has " =" , we can split based on this
const url = window.location.href
let tempArr = url.split("=")

// Approach 1 : getting the last COMP0004 dynamically from url
result = ""
for(let i = 0 ; i < tempArr.length;i++){
  if(i === tempArr.length - 2){
    result = tempArr[i];
    break
  }
}

//Approach 2 : appending COMP0004  to window.open()
function appenurl(c){
let result = ""
for(let i = 0 ; i < tempArr.length;i++){
  result += tempArr[i] + "="

  // getting the last element
  if(i === tempArr.length - 2){
    result += c;
    break
  }
}
return result;
}

onclick="window.open("+ appendurl("COMP0004") +",_self)"


text:
Q: Hide/Show a Panel depending on a CheckBox in Wicket I have this piece of code:
final WebMarkupContainer container = new WebMarkupContainer("container");
container.setVisible(aBooleanValue);
container.setOutputMarkupId(true);
container.setOutputMarkupPlaceholderTag(true);
add(container);

final CheckBox hideContainer = new CheckBox("hideContainer", new PropertyModel<Boolean>(getModel(), "hideContainer"));
container.add(hideContainer);
hideContainer.add(new AjaxFormComponentUpdatingBehavior("onchange") {

    private static final long serialVersionUID = 1L;

    @Override
    protected void onUpdate(AjaxRequestTarget target) {
        if (Boolean.TRUE.equals(getModelObject().getHideContainer())) {
            container.setVisible(false);
        } else {
            container.setVisible(true);
        }
        target.addComponent(MyForm.this.get("container"));

    }
});

Which creates a WebMarkupContainer and a Checkbox, if the checkbox is checked then the container should be hidden, if the checkbox is not checked, then the container should be visible.
But this doesn't work... what am I doing wrong?

A: You could try using AjaxCheckBox. Override onUpdate(AjaxRequestTarget) method and move code from behavior, as it should work correctly on all browsers.

A: A best wicket practice is to configure wicket components to pull data rather than pushing data to them. Instead of setting the visibility of the component can you please try to override the isVisible method of the component.
final WebMarkupContainer container = new WebMarkupContainer("container"){
   public boolean isVisible(){
      return showContainer;//showContainer is a boolean instance variable
   }

};
And in the onchange event change the showContainer value and add the component to target.


text:
Q: Kernel modules and major numbers I have been reading up on drivers implemented as kernel modules and am confused about the CMD argument to the system call. It seems that the CMD argument to the system call encodes amongst other information, the major number of the device. Why is that? Is this information absolutely necessary?
Suppose I perform a write to my device as "echo 5 > /dev/mytestdevice". I do not specify the major number, hence I believe that the kernel already has a means to associate the device with its kernel module. If that is the case, why do I need to provide that information in an ioctl call to the device(as I pass the fd to the device as the first argument)?
Summarising my questions are :-

*

*When I do a "echo 5 > /dev/mytestdevice", how does the kernel find the driver corresponding to that device?

*Why is the major number passed as an argument to an ioctl call?

A: i'm going to assume you are only talking about the ioctl system call here.  remember that there are many many more system calls out there and many of them do not operate on devices at all.
why do you think the cmd argument (the 3rd one) must have the major number encoded in it ?  the set of ioctl commands for any specific driver tend to pick an arbitrary value and encode that in its bits.  this is so it can be decoded easily by other tools.  but that value is not (or is not required to be) the major number.
the open/valid fd is used to route file based syscalls like read and write and ioctl.
you might want to look at the ioctl Documentation like Documentation/ioctl/ioctl-number.txt and Documentation/ioctl/ioctl-decoding.txt.

A:

*

*When I do a "echo 5 > /dev/mytestdevice", how does the kernel find the driver corresponding to that device?

Inode for device file /dev/mytestdevice is a special: instead of being associated with some file's content, it just contains major and minor numbers. When you tried to perform some operation with such file, the kernel firstly searches registered device with these identificators, and then redirect the operation for the device found.

*Why is the major number passed as an argument to an ioctl call?

It is not a true: cmd argument for ioctl call doesn't contain major number.


text:
Q: Debian-based can't find partitions My Issue
I attempted to download Kali-Linux on my desktop, and ran into the issue that it would not find any of my partitioning of the disk
Photo of partition from:
Windows (Disk Manager)
Kali Live (GParted) Note: In this photo, I attempt different partitioning format to see if that shows up
However, no matter what I do I end with only find the disk and no partitioning (Photo of installation partioning)
My attempts at fixing it
As alluded to, I have tried to different file system formats to see if that would show up.
The ones I have tried are NTFS and exFAT from windows Disk Manager and ex4 and FAT32 from GParted.
After this proved nothing I attempted to try different distros:
Debian
I went straight to the source and tried to install Debian.
It did not find any partitioning, and generally faced the same issue as Kali
Ubuntu
Then I tried to old and trusted Ubuntu, here I discovered a different issue:
no screen input after selection either "Try Ubuntu" or "Install", but before that shows up I get a
AE_AML_UNUNIZILIZED_ELEMENT error (There were more details, but it flashes quickly and I have no display after that). However, seeing as I wasn't really interested in Ubuntu, I moved onwards.
Fedora 32 (Beta)
I then tried a non-Debian based distro, to see if that could have been the issue.
Here I do get some similar errors, I get the: AE_AML_UNUNIZILIZED_ELEMENT and a "Cannot find TOCBlock, database might be corrupted" (I do nothing with that information as I get Fedora to work).
I get then run through the installation process, and it did not like the space being allocated. However, when I unallocated it, it install perfectly fine.
Kali after Fedora
This time around I notices Kali also reports the same error as both Fedora and Ubuntu did, I think it reported this the entire time, but they just flashed by as a block of text.
I also noticed a new "disk" called "LVM VG fedora_loaclhost_live, LV swamp00" which is Fedora's swap partition that should be a partition from the drive. But it still finds no partitions belong to the drive I am trying to get to work.
Notes
If I open up a shell and run fdisk it finds all the partitions
The drive is an SSD drive
It is a copy from an older SSD drive (Transferred a smaller Windows SSD drive to it)
On the Ubuntu installation, I tried to run with and without CSM.
All of the installations are run with secure boot set on "Other OS" (I have no options to disable it)


text:
Q: nuxt3: how to test SSR page with form, useFetch() and pinia? In my Nuxt3 project, I have a very basic login page which is SSR like the following:
pages/login.vue
<template>
    <form
        @submit.prevent="login">
        <input
            name="email"
            v-model="form.email"/>
        <input
            name="password"
            v-model="form.password"/>
        <button>login</button>
    <form>
</template>

<script setup>
import { useAuth } from '~/store/auth.js';

const auth = useAuth();
const form = ref({email: '', password: ''});
const router = useRouter();

const login = async () => {
    useFetch('/api/auth/tokens', {
        method: 'POST',
        body: form.value
    })
    .then(({ data }) => {
          const { token, user } =  data.value;
          auth.setUser(user);
          auth.setToken(token);
          router.push('/profile');
    })
}
</script>

*

*First, I try to test it like a SPA page:

import { describe, test, expect } from 'vitest';
import { mount } from '@vue/test-utils';
import LoginPage from '~/pages/login.vue';

describe('login page', async () => {

    test('store tokens', async () => {

        const wrapper = mount(LoginPage);

        const email = 'test@example.com';
        const password = 'password';

        await wrapper.find('[name="email"]').setValue(email);
        await wrapper.find('[name="password"]').setValue(password);

        await wrapper.find('form').trigger('submit.prevent');

        expect(
            wrapper.emitted('submit')[0][0]
        ).toStrictEqual({
            email,
            password,
        });

        // But this does not test the code in `then()` which handled the response and redirect to `/profile`
    });
});

Got error:

FAIL  tests/pages/login.spec.js > login page > store tokens
ReferenceError: document is not defined

*Then, I followed the Nuxt3 testing
import { describe, test, expect } from 'vitest';
import { setup, $fetch } from '@nuxt/test-utils';
import { JSDOM } from 'jsdom';

describe('login page', async () => {

    await setup();

    test('store tokens', async () => {

        const wrapper = (new JSDOM(await $fetch('/login'))).window.document;

        const email = 'test@example.com';
        const password = 'password';

        await wrapper.find('[name="email"]').setValue(email);
        await wrapper.find('[name="password"]').setValue(password);

        await wrapper.find('form').trigger('submit.prevent');

        expect($fetch).toHaveBeenCalledWith('/api/auth/tokens', {
            method: 'POST',
            body: {
                email: 'test@example.com',
                password: 'password'
            }
        });

    });
});

But wrapper there is just a jsdom document instance, it can't act like a Vue component.

I wonder:

*

*How to test the user input events?

*How to test the code in resovle of useFetch() (in the example, it's the code handling data with pinia)

same question in GitHub

A: I would unit test the component, so check if inputs work as expected and also if the correct action is triggered on submit. So don't render a whole page, just mount the component in the test.
I would test the login action afterwards separately meaning you mock the data from the API (token, user) and check if they are set correctly to the auth. Plus, if there's a redirect. This should be possible.
You want to test the whole feature (login) which is often referred as "feature testing". But the base is unit tests.


text:
Q: Ridiculously slow read/write between two SSDs (Linux) So I have a Kingston SSD (120Gb HyperX 3K; SH103S3/120G) that is about two years old and just picked up a new Kingston SSD (240GB SSDNow V300; SV300S37A/240G) to go along with it. I'm trying to transfer data over, except the read/write speeds are ridiculously slow. Like sometimes it starts at 150Mb/s, sometimes it starts at 25Mb/s, but either way it's under 10Mb/s within a minute. For large transfers > 5Gb it seems to stabilize around 2Mb/s.
The old drive benchmarks to around 300Mb/s for both read and write and the new drive to 400Mb/s. Looks like it's a serious problem with sustained transfers.
I'm on Linux, both drives formatted to Ext4, and using a 4 year old motherboard (ASUS M5A99X EVO); not sure if it would be more software or hardware related. I believe they're in SATA III although not 100% sure.
Anyone have ideas as to what might be causing the slowdown or how I can improve it?
It actually seems like it's a software limitation somewhere in Linux, writing my own file transfer script using shutil in python I can get a sustained 150-350Mb/s no problem.
Linux version 3.16.0-38-generic (buildd@allspice) (gcc version 4.8.2
(Ubuntu 4.8.2-19ubuntu1) ) #52~14.04.1-Ubuntu

Fresh install of Linux Mint Rafaela 64
Mate 1.10.0-1
Nemo 1.1.2?


text:
Q: My multiple plot using matplotlib.pyplot subplot dont have same position I'm trying to make 5 plots using for loop iteration in matplotlib, but my third picture moves a little bit to the right.
Do you have any idea to solve this issue?
Here is my code:
for i in range(len(sta310)):

    plt.figure(figsize = (15,10))
    plt.tight_layout()
    plt.subplot(5,1,i+1)
    plt.plot(t,sta310[i])
    plt.axvline(x = t[np.argmax(kurto)],color='red')

A: I have finally figured it out.
Sorry, I cant post any figure yet to make you more understanding my question since I'm just joining StackOverflow a few weeks
Here is the solution:
fig, axs = plt.subplots(5)
fig.set_figheight(10)
fig.set_figwidth(15)

for i in range(len(sta310)):
    axs[i].plot(t,sta310[i])
    axs[i].axvline(x = t[np.argmax(kurto)],color='red')


text:
Q: Does data.table dcast() drop 'data.table' attribute? it seems dcast() returns a data.frame although the input argument is a data.table:
d  <- data.table(id = c(1,2,3), group = c('a','a','b'), x = c(10,20,30))
dc <- dcast(d, id ~ group, value.var = 'x')

> class(d)
[1] "data.table" "data.frame"
> class(dc)
[1] "data.frame"

Is there a way to make dcast() return a data.table?
> sessionInfo('data.table')
R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

attached base packages:
character(0)

other attached packages:
[1] data.table_1.9.6


text:
Q: Kill process by fuser instead of pidfile? Recently I developed the habit of killing processes with
fuser -k -n tcp $PORT

which can hardly kill the wrong process. I prefer this over fiddling with a pidfile that may or may not be still there or may or may not contain the correct pid (OK, I am a bit dramatic here :-)
Yet the typical stop script I stumble over still uses a pidfile.
Am I missing an important feature of the pidfile approach or a misfeature of the fuser approach. My best guess is that fuser is not available. Though judging by search engine results, bsd, debian, suse, centos, aix, solaris all seem to have it.

A: The fuser command option -n <file|udp|tcp>is Linux-specific, while the PID-file-based solution is traditional across many Unix variants, and so guaranteed to be very portable.
And in Debian at least, the fuser command is in psmisc package, which has been designated "optional", and so it cannot be expected to always be present for all systems.

A: There are two potential issues with this approach that come to mind beyond what telcoM mentioned, and they both have to do with a socket option called SO_REUSEPORT.
This socket option allows multiple processes (all of which have to set the option) to bind to the same port and offload the load balancing of connections traditionally done by a master process to the kernel.
The two potential issues that come from this are:

*

*For servers that use process-based parallelism (NGinx for example) and use this option, the PID's that are connected to the socket will usually be children of the main process, and not the main process itself.  In such a situation, your fuser approach will kill all the children, but not send any signal to the main process, which may not terminate the service at all (if the main process just restarts the children), or might result in it being shut down in a manner that causes problems (the code may assume that the child process dying indicates a fatal error, and use a different exit path than it would if the main process had instead received the signal itself).

*This might kill other programs than what you want.  Such a case is not very likely to be a bad thing (about the only 'other' programs you could kill are things that are probably malware), but it is worht considering.


text:
Q: Word 2007 crashes on Server 2008 R2 terminal services We are finding that Word 2007 (with SP2) crashes when used on a Windows 2008 R2 terminal server. Typically it crashes when you click File/Open or File/Save, but not every time. Maybe one time in four, and just to be really confusing, on a test server in my office I can't make it crash. I have just today set up a brand new shiny 2k8 R2 terminal server with as simple a setup as possible, e.g. no anti-virus to confuse things, and we're still seeing crashes.
My question is has anyone else seen this, and if so any clues on what's happening?
We have a support case open with Microsoft, and the MS support engineer has conceded it's happening, but has so far been unable to find the reason.
On possible factor is that all the 2k8 R2 terminal servers I've seen this on have been Hyper-V VMs (running on a 2k8 R2 host). I'm about to put in a physical 2k8 R2 terminal server at the customer where we're seeing the most crashes, in case this is relevant. More news soon.
Sorry if this posting seems a bit vague, but this has just bitten us and is causing a lot of pain and sleepless nights :-( If anyone can help I'll be enormously grateful!
Update: we've given up and gone back to 2008 pre-R2. Both Office 2003 and 2007 both work fine now.
I think there are some problems with TS in R2. Googling doesn't find much, so I thought it was just me. It's reassuring to find that someone else has seen the same problem.

A: I think i've made progress!
Microsoft recommended i add WINWORD.exe, EXCEL.exe and Outlook.exe to DEP (Data Execution Prevention). (Silly I know considering it's a microsoft product!)
So far so good - havnt had a crash for 6 hours considering we would have up to 12 crashes in 1 hour.
I'll keep you posted.
If you wish to test for yourself follow the instructions below.

*

*Click Start, click Run, type sysdm.cpl, and then click OK.

*On the Advanced tab, under Performance, click Settings.

*On the Data Execution Prevention tab,

*Make sure The option "Turn on DEP for all programs and services except those I select" is selected

*Example: Add:  c:\Program Files (x86)\Microsoft    Office\Office12\excel.exe

*Add all exe    files for Outlook, word and excel.

* UDPATE *
Just to let you all know im confirming the above solution has resolved our problems with Word/Excel etc freezing up.

A: Try removing KB977724  That seems to have resolved the issue.

A: We should have thought of this earlier, but running Word 2007 in XP compatability mode stops the crashes. This is a workaround, not a solution so I'll leave this open for a bit in case anyone else has a better solution.
The fact that Word runs fine in compatability mode suggests that this really is an issue with 2008 R2, and not a quirk of this particular installation.
JR

A: I wanted to provide an update on this issue.
Microsoft analyzed a dump file created during the word crash and they said it is probably a known problem. Fixes for Server 2008 R2 and Office 2007 are in the making, but they cannot tell any release date.
They told me to run Process Monitor during a crash which i will do today to further analyze the problem.
update: I think i have found something which is worth testing.
In Hyper-V Manager i allocated 4 CPUs for the Terminal Server Virtual Machine to improve performance.
We have another Terminal Server 2008 R2 with less users than on the problematic one but also with Office 2007 SP2 installed. 4 Weeks ago i changed the CPU Ressource Allocation on that Terminal Server in Hyper-V Manager to use only one processor.
Since this change i have not noticed any word crash on that Terminal Server.
So i will try to set cpu back to one on the problematic server to see if this is the problem.

A: Here is an update from MS. Contains an update for the KB977724.
http://blogs.technet.com/office_sustained_engineering/archive/2010/03/11/issues-with-office-after-installing-kb977724.aspx

A: We had the same problem, turning on DEP was a good workaraound for us.

A: I Think it is a disaster that Microsoft don't see the need to fix this problem.
I have the same issue on several R2 TS installations, and I am quite frustrated about it, to say the least.
No fix, no help, and suggestions that seems to temporarily fix the problem (DEP) but then it returns after a couple of weeks, and now I cannot work around it anymore.
installing 2003 will be the solution if there is not a fix available soon...

A: Thanks for the info about KB977724, but that cannot be the issue that people here have complained about as it was only released on the 9th of March. The first post on this thread is on December 21st 2009.

A: I encountered the same problem with Server 2008 R2 and Office Ultimate 2007 SP2 in the last few days. KB72224 was not listed as an installed update. I resolved the problem (at least for now) by setting Word to compatibility mode for Server 2008 R1. I also made sure users had full file control and rna it as administrator in case it was bombing while trying to open a read only file in wrtie mode.
My situation may be uiniques because I am running on a MAC PRO under Server 2008 R2 with no MAC operating system.


text:
Q: string has trailing whitespaces that aren't white spaces? (i.e. strip doesn't get rid of it) I have the following string I got from parsing some html:
"this is my string  "
If I use .strip or .rstrip the string remains the same.
However if I literally type the string "this is my string  " and type .strip then the trailing spaces get stripped.
This leads me to believe the string I obtained from parsing html is not containing trailing white spaces. So the question I have is, 1) what is trailing the string if it isn't a white space? and 2) how do I get rid of it?

A: The unicode table contains several whitespace characters, and it is possible that all of these characters are not handle by the strip methods. If you want to use a regular expression with the sub method, you can try this simple pattern: /\p{Space}+\z/ or /[[:space:]]+\z/ to trim all the blank characters on the right. (obviously, the replacement string must be empty)
Note: the \s is equivalent to [ \t\r\n\f] in Ruby and doesn't contain all whitespaces of the unicode table.


text:
Q: Highcharts Export Server on AWS Lambda Has anybody successfully created a highcharts export server running on AWS Lambda? If so do they have a sample deployment package they might be willing to share.
The general goal is to be able to pass in an image type and chart options as the payload to lambda and have it return an image.
So far I have done the following:
# Created a folder and moved into it
cd ../highchart_export_server

# Im building Phantom on OSX do I need to set these to get Phantom to build
# for linux
export PHANTOMJS_PLATFORM="linux"
export PHANTOMJS_ARCH="x64"

# Created a new package and install highcharts per docs
npm init
npm install highcharts-export-server

# Create an index handler -> See the content of that file below

# zip the package up as a deployment and upload it to lambda
zip -r function.zip .

index.js
//Include the exporter module
const exporter = require('highcharts-export-server');

exports.handler = async (event) => {

    var type = event.body.type;
    console.log('Type: ' + type);

    //Export settings
    var exportSettings = {
        type: event.format,
        options: event.options;

    //Set up a pool of PhantomJS workers
    exporter.initPool();

    //Perform an export
    /*
        Export settings corresponds to the available CLI arguments described
        above.
    */
    exporter.export(exportSettings, function (err, res) {
        if (err) {
            console.log(err.stack);
        }

        //The export result is now in res.
        //If the output is not PDF or SVG, it will be base64 encoded (res.data).
        //If the output is a PDF or SVG, it will contain a filename (res.filename).

        //Kill the pool when we're done with it, and exit the application
        exporter.killPool();
        process.exit(1);
    });

    const response = {
        statusCode: 200,
        body: event,
    };
    return response;
};

When I test the function I am getting this error:
START RequestId: 97e615c4-5e42-457e-8c8a-02e7001957f5 Version: $LATEST
2019-07-18T15:20:57.128Z    97e615c4-5e42-457e-8c8a-02e7001957f5    ERROR   Uncaught Exception  {"errorType":"Error","errorMessage":"write EPIPE","code":"EPIPE","stack":["Error: write EPIPE","    at WriteWrap.afterWrite [as oncomplete] (net.js:779:14)"],"errno":"EPIPE","syscall":"write"}
2019-07-18T15:20:57.207Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    uncaughtException: { Error: write EPIPE
    at WriteWrap.afterWrite [as oncomplete] (net.js:779:14)
  errno: 'EPIPE',
  code: 'EPIPE',
  syscall: 'write',
  [Symbol(aws.lambda.Timestamp)]: 2019-07-18T15:20:57.128Z,
  [Symbol(aws.lambda.RequestId)]: '97e615c4-5e42-457e-8c8a-02e7001957f5' }
2019-07-18T15:20:57.247Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    Thu Jul 18 2019 15:20:57 GMT+0000 (Coordinated Universal Time) [error] phantom worker 1 error - /var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
2019-07-18T15:20:57.247Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    Thu Jul 18 2019 15:20:57 GMT+0000 (Coordinated Universal Time) [error] phantom worker 2 error - /var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
2019-07-18T15:20:57.247Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    Thu Jul 18 2019 15:20:57 GMT+0000 (Coordinated Universal Time) [error] phantom worker 3 error - /var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
2019-07-18T15:20:57.247Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    Thu Jul 18 2019 15:20:57 GMT+0000 (Coordinated Universal Time) [error] phantom worker 4 error - /var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
2019-07-18T15:20:57.248Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    Thu Jul 18 2019 15:20:57 GMT+0000 (Coordinated Universal Time) [error] phantom worker 5 error - /var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
2019-07-18T15:20:57.248Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    Thu Jul 18 2019 15:20:57 GMT+0000 (Coordinated Universal Time) [error] phantom worker 6 error - /var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
2019-07-18T15:20:57.248Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    Thu Jul 18 2019 15:20:57 GMT+0000 (Coordinated Universal Time) [error] phantom worker 7 error - /var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
2019-07-18T15:20:57.248Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    Thu Jul 18 2019 15:20:57 GMT+0000 (Coordinated Universal Time) [error] phantom worker 8 error - /var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory
2019-07-18T15:20:57.268Z    97e615c4-5e42-457e-8c8a-02e7001957f5    INFO    undefined
END RequestId: 97e615c4-5e42-457e-8c8a-02e7001957f5
REPORT RequestId: 97e615c4-5e42-457e-8c8a-02e7001957f5  Duration: 620.04 ms Billed Duration: 700 ms     Memory Size: 128 MB Max Memory Used: 81 MB
RequestId: 97e615c4-5e42-457e-8c8a-02e7001957f5 Process exited before completing request

Per the error it looks like libfontconfig.so.1 is missing but I can't find any way to add it to the dependencies.

A: In response to this I have created a Github repo with a dedicated project specifically for deploying the Highcharts export server onto Lamdba.
Github: https://github.com/tarkal/highchart-lambda-export-server
I have provided both detailed instructions for those wishing to build from scratch as well as a prebuilt zip that can be directly uploaded to Lambda.

This project contains a fix for the missing fonts mentioned in the comments.

A: For anyone finding this post in 2021, my advice to you is to completely avoid the export server provided by Highcharts. It's not well written, is full of memory leaks and will constantly clog your logs will error and crash messages.
We successfully moved our chart rendering into a simple headless chrome implementation in much less time than we initial spent trying to get the "ready to use" official render server working.
My advice is to steer clear completely and roll your own.


text:
Q: Deploying old Django project to new host I have Django 1.6 project and is run using the Gunicorn web application server behind the Nginx web server. Now I want to transfer that project to new host. For that I have copied all code across the new machine and install all required dependencies using pip install -r requirements.txt that went successful.
But after that if I am trying to do either of below python manage.py migrate or python manage.py runserver 0.0.0.0:8000 itt gives below error:
Unhandled exception in thread started by <function wrapper at 0x7f9a114e1938>
Traceback (most recent call last):
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
    fn(*args, **kwargs)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 102, in inner_run
    self.validate(display_num_errors=True)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 310, in validate
    num_errors = get_validation_errors(s, app)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/validation.py", line 34, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 196, in get_app_errors
    self._populate()
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 75, in _populate
    self.load_app(app_name, True)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 99, in load_app
    models = import_module('%s.models' % app_name)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/__init__.py", line 2, in <module>
    from filer.models.clipboardmodels import *
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/clipboardmodels.py", line 7, in <module>
    from filer.models import filemodels
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/filemodels.py", line 13, in <module>
    from polymorphic import PolymorphicModel, PolymorphicManager
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/polymorphic/__init__.py", line 13, in <module>
    _version_ = pkg_resources.require("django-polymorphic")[0].version
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 984, in require
    needed = self.resolve(parse_requirements(requirements))
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 875, in resolve
    raise VersionConflict(dist, req).with_context(dependent_req)
pkg_resources.ContextualVersionConflict: (Django 1.6.8 (/var/www/html/forttottensquare/env/lib/python2.7/site-packages), Requirement.parse('Django>=1.11'), set(['django-polymorphic']))
https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html

So how to solve it?
Update
After doing pip install django-polymorphic==1.3 its gives below error:
Unhandled exception in thread started by <function wrapper at 0x7f0dc09bd938>
Traceback (most recent call last):
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
    fn(*args, **kwargs)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 102, in inner_run
    self.validate(display_num_errors=True)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 310, in validate
    num_errors = get_validation_errors(s, app)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/core/management/validation.py", line 34, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 196, in get_app_errors
    self._populate()
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in _populate
    self.load_app(app_name)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/db/models/loading.py", line 99, in load_app
    models = import_module('%s.models' % app_name)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/__init__.py", line 2, in <module>
    from filer.models.clipboardmodels import *
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/clipboardmodels.py", line 7, in <module>
    from filer.models import filemodels
  File "/var/www/html/forttottensquare/env/local/lib/python2.7/site-packages/filer/models/filemodels.py", line 13, in <module>
    from polymorphic import PolymorphicModel, PolymorphicManager
ImportError: cannot import name PolymorphicModel

A: Do (downgrade)
pip install django-polymorphic==1.3

If not working, do bit more older version.


text:
Q: SPContext.Current vs SPContext.GetContext To get current SP objects (SPWeb, SPSite, SPList etc), I generally use SPContext.Current. In some situations, SPContext.GetContext is preferred because  SPContext.Current have many objects null depending on where the code runs (Webpart page, Edit item form etc).
Are you aware of any guidelines (may be from Microsoft) on the usage SPContext.Current and SPContext.GetContext ?

A: Another reason for using the SPContext.GetContext is to set the context of a control to one that is different than the context of the current page.  For example, you can set the ItemFieldIterator.ItemContext proprty to get information from a list on different SPWeb object.
myItemFieldIterator.ItemContext = SPContext.GetContext(Context, 0, ListId, oSPWeb);

A: SPContext.GetContext tends to be used if there is no current context (console app? timer job? FeatureUninstalling?), whereby in the case where you do, you would use the obviously named SPContext.Current.


text:
Q: Java SOAP 1.5 XML construction issues I am developing a Java SOAP 1.5 client application which communicates with a SOAP server endpoint.
However, the constructed XML request is not what I expect, and it is returning a fault response from the server.
Here is part of my code which constructs the XML envelope :
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPFactory soapFactory       = SOAPFactory.newInstance();

SOAPMessage soapMessage       = messageFactory.createMessage();

SOAPPart soapPart             = soapMessage.getSOAPPart();

// SOAP Envelope
SOAPEnvelope envelope         = soapPart.getEnvelope();
SOAPHeader header             = soapMessage.getSOAPHeader();

envelope.addNamespaceDeclaration("SOAP-ENV", "http://www.w3.org/2003/05/soap-envelope");
envelope.addNamespaceDeclaration("wsa", "http://www.w3.org/2005/08/addressing");
envelope.addNamespaceDeclaration("cs", "urn://Ocpp/Cp/2012/06/");

Now compare this to the request that is actually being sent :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope
    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:cs="urn://Ocpp/Cp/2012/06/"
    xmlns:wsa="http://www.w3.org/2005/08/addressing">
    <SOAP-ENV:Header>
        <cs:chargeBoxIdentity>Test</cs:chargeBoxIdentity>
        <wsa:Action>/ChangeConfiguration</wsa:Action>
        <wsa:MessageID>Fake OCPP571322528896</wsa:MessageID>
    </SOAP-ENV:Header>
    <SOAP-ENV:Body>
        <cs:changeConfigurationRequest>
            <cs:key>LaMa_ConnectionRate</cs:key>
            <cs:value>5120</cs:value>
        </cs:changeConfigurationRequest>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

See how xmlns:SOAP-ENV is actually different to what is intended. I don't know why this is. This can be part of the problem. Also, is it possible to strip the declaration <?xml version="1.0" encoding="UTF-8" standalone="no"?> from the request , as it could be an issue also.


text:
Q: Drupal 9 only homepage I'm very new to drupal and don't know anything about it. I'm, using OpenServer witha PHP 7.4, Apache 2.4, MySQL 5.7. I'v estracted everything into c/OsPanel/domains/cms/Drupal/freshmart/ (I have installed wordpress in c/OsPanel/domains/cms/WP/restaurant and everything works as it should. When I go to cms/drupal/freshmart, I have login page, I login and go to welcome page. When I try to acces anything else like structure, appearance and etc, I get "Page not found" and url is cms/drupal/freshmart/admin/content. In folders, there is no such folder as admin, but from what I know there shouldn't be it.

If you are using a temporary URL such as 192.168.0.42/~username because the domain has not been transferred yet or has not propagated yet, you would have the problem described above until the domain name is transferred over.
To be able to use Drupal before the domain name points over, you will need to change something in the .htaccess file:

Modify the RewriteBase if you are using Drupal in a subdirectory or in a
VirtualDocumentRoot and the rewrite rules are not working properly.
For example if your site is at http://example.com/drupal uncomment and
modify the following line:
RewriteBase /drupal

If your temporary URL is something like 192.168.0.42/~username then you will need to add the following line in .htaccess:
RewriteBase /~username
Once you point the domain name over to the website, be sure to comment out or delete that line.

I saw this on one of the forums, and I think it could be my problem. But I don't understand what should I write in RewriteBase/.
On server mod_rewrite is enabled, there is a .htaccess. What should I do?


text:
Q: When is the point where a JSON text file storage is not enough? I guess it was Robert C. Martin who campaigned against using SQL in one of his apps, where he was just fine without DB and SQL initially. Later, thanks to the abstraction a DB implementation could be built out on a single day (which later turned out to be unnecessary). I think his main point was just to not start out with the DB and then later implement it when it is deemed necessary.
So I was wondering when a DB is actually necessary, compared to writing the entire dataset into Json and reading it once the app starts?
Because my initial answer would be:
When the dataset cannot fit into memory.
At that point, there would be no workaround for ignoring an sql DB. I assume though the initial load times would get really high first, which would probably force me to reach for a DB approach.
But until then, I am far better off in terms of overall performance (everything is read from memory) and the amount of code I have to maintain (no SQL code and not to mention tests for the DB). I would only need a Parser that converts my text files to DTOs and a few Mapper functions that convert those DTOs to the classes I am using in the core of the app.
It seems like I probably would never even need the database, but I think that's a stretch and I may be missing something and the answer may not be dependent just on the sheer size of the dataset. What do you think is the turning point when a Json-text-file storage is not enough anymore?

A: There is no point.
Wow, talk about a "zen" answer. However, what I mean is that instead of a point, in reality you rather have a spectrum.
Hard criteria
Don't get me wrong, a hard criterium like your "the dataset cannot fit into memory", you were correct in it being "necessary" at that point. The same goes for other "hard" reasons, like several instances of your application wanting to access the data at the same time. (You can spend an enormous effort on making that work with a JSON file, but you'll pretty much end up writing your own SQ language, a.k.a. reinventing the wheel).
That's probably a little obvious and you wouldn't be asking the question here if it was about this. If it's really necessary, you don't have a choice either way, so it wouldn't make sense to ask for help in deciding. In the situation described by Martin, he didn't avoid SQL simply because it was not "necessary" - because neither was a simple configuration file. He avoided it because SQL is the more complex of the two and there was no (technical) reason for the added complexity.
Soft criteria
From here on out, I'll assume a situation where you aren't forced to use one over the other. From an engineering standpoint, there's pretty much only one soft reason to chose one over the other: Which one is more practical?
That's is a pretty general statement, but you can't go into too much detail here without the full context anyway. I assume that you as the developer will have an idea which one will e.g. be easier to use for you, or which one will have a bad performance for your specific needs.
The main point is that it's not about being necessary, but about which is more efficient in your situation.
Conclusion
Don't avoid an SQL DB until it's absolutely necessary. Use an SQL DB when it will make your life simpler.
What Martin tried to say was pretty much a different version of that statement; don't use an SQL DB (or any technology, really) just because everybody uses it and it's all the rage, when it actually makes things more difficult.
Additional info: Business reality
Even if we assume a clear metric for one being more practical than the other, that's not the end of it. In reality, your app's needs becoming more and more complex over time, until you switch over to SQL, would look something like this:
SQL < JSON
Starting out, JSON is simply the easier solution.
SQL > existing JSON
At some point SQL would be more practical/easier to use.
SQL - switching effort > existing JSON
At some point later, SQL being more practical starts to outweigh the effort it would take to switch.
SQL - switching effort - business needs > existing JSON
At some point even later, using JSON becomes so impractical that your company (or whoever calls the shots) thinks it's worthwhile to allocate the resources to actually make the switch.
Only at this point is the switch actually going to happen, but this is also heavily dependent on communication with higher-ups. It might have been better from a technical/engineering viewpoint and better for the company since 3 years, but just never happened because management does not deem it necessary.


text:
Q: Analysis crossover clinical trial I have data from a six-sequence 3-drug 3-phase crossover trial that had a 7-day baseline period pre-study (used to generate mean baseline value).  My outcome is a non-parametric continuous variable that becomes parametric with a log transformation. The outcome is an ocular measure that is measured in both eyes, 4 times a day in 9 individuals.
Outcome:TP
My fixed effects are: Phase (I,II,III), Day(1-7), Drug (A,B,C), BaselineTP + CarryOver

A: Parametric does not mean normally distributed. In fact, a parametric model for the response could be log-normal--in which case the logged response would be normal. Even if exploratory analyses suggest the log transform makes a normal-looking response, one does not justify fitting a model because the proposed change of variable makes the outcome normal. A log transform is used because it is a geometric mean difference that you are interested in reporting. For instance, if you fit the linear model:
$$E[\log Y|X] = \alpha + \beta X$$
You would report and interpret $\exp(\beta)$ as a percentage-difference in response comparing groups differing by one unit in $X$. This is often the correct model for analyzing concentrations, etc. But actually a log transform enjoys a wide variety of applications, especially in the context of a GLM where one might analyze a host of outcomes like test scores, proportions, or ordinal scaled values.
In an intent-to-treat analysis, you analyze patients as-randomized. That means the subject who is randomized to treatment A at time 1, treatment B at time 2, and treatment C at time 3 will have those assignments analyzed in whatever fashion was prespecified as part of a statistical analysis plan. A per-protocol analysis
A typical linear model for a change-from-baseline analysis is the ANCOVA specification where the post-baseline response is taken as an outcome and the baseline response is adjusted-for as a covariate.
If the response is assessed at multiple post-baseline time points, correlated data models may be used. An appropriate method for repeated measures should be used like a generalized least squares model, linear mixed model with random intercept, or generalized estimating equations.
If one adjusts for time, lagged effects, and possibly participant level effects, it is possible that the data may be conditionally independent (or approximately so) and so correlated data models don't need to be used. There are a few exploratory analyses that can assess that.


text:
Q: Alpine.js Cant bind x-data to functin in external js file I'm creating an app with alpine.js
this is the context of my index.html file
<!DOCTYPE html>

    <title>Hello Alpine</title>
    <meta charset="UTF-8" />

        <button x-on:click="open">Open</button>

          // Dropdown

This code is working fine, but however, if I move the app function to index.js I'm getting an error in the console.
index.html:
<!DOCTYPE html>

    <title>Hello Alpine</title>
    <meta charset="UTF-8" />

        <button x-on:click="open">Open</button>

          // Dropdown

and index.js
import "./styles.css";
import "alpinejs";

function app() {
  return {
    show: false,
    open() {
      this.show = true;
    },
    close() {
      this.show = false;
    },
    isOpen() {
      return this.show === true;
    }
  };
}

When I run this code, I get the following error:

alpine.js:1907 Uncaught TypeError: app is not a function
at eval (eval at tryCatch.el.el (alpine.js:NaN), :3:54)

CodeSandbox Link is here

A: By default, alpine is going to look for the component in the window level. So the issue can be solved by making an app variable in the window which is your exact same function.
import "./styles.css";
import "alpinejs";

window.app = function () {
  return {
    show: false,
    open() {
      this.show = true;
    },
    close() {
      this.show = false;
    },
    isOpen() {
      return this.show === true;
    }
  };
};

There's a free video tutorial about extracting alpine js components in Laracasts, you can view it here.


text:
Q: What does data-structure have to look like for inserting in table I have something like this in my_model.py
table_fields = [
    'my_name-string',
    'my_id-integer',
    ]

My goal is to create a table based on this information, so I tried:
fields_and_types_dict ={}
for tf in table_fields:
        fields_and_types = tf.split('-')
        fields_and_types_dict['%s' % fields_and_types[0]] = {}
        fields_and_types_dict['%s' % fields_and_types[0]]['type'] = '%s' % fields_and_types[1]

db.define_table('my_table', fields_and_types_dict)

It´s not working properly and I guess I don´t have the right data-structure.
Can anyone provide a hint how it must look like? Thank you in advance.
Solutions:
The most elegant solution to use is:
db.define_table('my_table', *[Field(*tf.split('-')) for tf in table_fields])

as suggested by Anthony.
The not-so-complex solution I used is:
tableDef = ['my_table']
for tf in table_fields:
    name, type = tf.split("-")
    tableDef.append(Field(name, type))
db.define_table(*tableDef)

as suggested by Vanojx1.

A: Based on DOC, try this:
tableDef = ['my_table']
for tf in table_fields:
    name, type = tf.split("-")
    tableDef.append(Field(name, type))
db.define_table(*tableDef)


text:
Q: Posting json requests to Ruby on Rails server app – 500 error I have a Ruby on Rails server application(hosted on Heroku) which is supposed to be able to receive HTTP POST requests with JSON strings and add the JSON objects to the database. There are two database models: thanksgivings and requests.
controller/request_controller.rb:
class RequestsController < ApplicationController
  [...]
  # POST /requests
  # POST /requests.json
  def create
    @request = Request.new(params[:request])

    respond_to do |format|
      if @request.save
        format.html { redirect_to @request, notice: 'Request was successfully created.' }
        format.json { render json: @request, status: :created, location: @request }
      else
        format.html { render action: "new" }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end
[...]
end

The JSON keys for the different database model objects values should be "thanks" and "request" for the Thankgiving DB model and Request DB model respectively.
model/request.rb:
class Request < ActiveRecord::Base
  attr_accessible :request
end

model/thankgiving.rb:
class Thanksgiving < ActiveRecord::Base
  attr_accessible :thanks
end

When I post an HTTP request to http://YADA.herokuapp.com/thanksgivings.json everything works fine, but when I send it to .../requests.json, I get a 500 error. If I use a faulty key in the JSON string, the request succeeds, but the value becomes null.
Request 1: (correct request to thanksgiving.json)
POST
Host: http://YADA.herokuapp.com/thanksgivings.json
Content-Type: application/json
Body: {"thanks":"qwerty"}
Request 2: (correct request to request.json – returns 500)
POST
Host: http://YADA.herokuapp.com/requests.json
Content-Type: application/json
Body: {"request":"qwerty"}
Request 3: (faulty key - will succeed: value will be null, key will be "request" in response, database element will be added)
POST
Host: http://YADA.herokuapp.com/requests.json
Content-Type: application/json
Body: {"abc":"qwerty"}
The strange thing is that the two controllers, thanksgivings_controller.rb and requests_controller.rb, are "identical" but their behavior differs.
Anyone knows how to do this successfully?

A: According to the server logs, there was a NoMethodError – stringify_keys. This question's answer was the solution: undefined method `stringify_keys'
Changing
@request = Request.new(params[:request])
to
@request = Request.new(:request => params[:request])
did the trick.


text:
Q: HTML/PHP/MYSQL Form with Grid sub entry I am trying to add a "Line Item" Grid to and html form that will update a DB table
Filling out the child data could be done using a pop up form or updating the grid in line... The hard part I think will be saving the form in a way where the data is linked together in the DB... the sudo code would look a little like the below I imagine the grid would have a + button to add multiple line items. The line items would be saved to one table with an association to the summary, I think to achieve that I could just parse the post data into separate mysql insert statements so I am not sure there has to be a ton of separation?
<form class="form-horizontal">
    <fieldset>

    <legend>Form Name</legend>

      Text Input

      <input id="textinput" name="textinput" type="text" placeholder="placeholder" class="form-control input-md">
      help

      Text Input

      <input id="textinput" name="textinput" type="text" placeholder="placeholder" class="form-control input-md">
      help

      Text Area

        <textarea class="form-control" id="textarea" name="textarea">default text</textarea>

    </fieldset>
    </form>


text:
Q: How do I actually get dask to compute a list of delayed or dask-container-based results? I have a trivially parallelizable task of computing results independently for many tables split across many files. I can construct delayed or dask.dataframe lists (and have also tried with, e.g. a dict), and I cannot get all of the results to compute (I can get individual results from a dask graph style dictionary using .get(), but again can't compute all results easily). Here's a minimal example:
>>> df = dd.from_pandas(pd.DataFrame({'a': [1,2]}), npartitions=1)
>>> numbers = [df['a'].mean() for _ in range(2)]
>>> dd.compute(numbers)
([<dask.dataframe.core.Scalar at 0x7f91d1523978>,
  <dask.dataframe.core.Scalar at 0x7f91d1523a58>],)

Similarly:
>>> from dask import delayed
>>> @delayed
... def mean(data):
...     sum(data) / len(data)
>>> delayed_numbers = [mean([1,2]) for _ in range(2)]
>>> dask.compute(delayed_numbers)
([Delayed('mean-0e0a0dea-fa92-470d-b06e-b639fbaacae3'),
  Delayed('mean-89f2e361-03b6-4279-bef7-572ceac76324')],)

I would like to get [3, 3], which is what I would expect based on the delayed collections docs.
For my real problem, I would actually like to compute on tables in an HDF5 file, but given that I can get that to work with dask.get() I'm pretty sure I'm specifying my deferred / dask dataframe step right already.
I would be interested in a solution that directly results in a dictionary, but I can also just return a list of (key, value) tuples to dict(), which is probably not a huge performance hit.

A: Compute takes many collections as separate arguments.  Try splatting out your arguments as follows:
In [1]: import dask.dataframe as dd

In [2]: import pandas as pd

In [3]: df = dd.from_pandas(pd.DataFrame({'a': [1,2]}), npartitions=1)

In [4]: numbers = [df['a'].mean() for _ in range(2)]

In [5]: dd.compute(*numbers)  # note the *
Out[5]: (1.5, 1.5)

Or, as might be more common:
In [6]: dd.compute(df.a.mean(), df.a.std())
Out[6]: (1.5, 0.707107)


text:
Q: Install SQL Server 2012 on ubuntu How can I install SQL Server 2012 on ubuntu?

A: You can't install MSSQL Server 2012 on Ubuntu. It's not on supported OS list.
But you can install MSSQL Server 2017. This doc page has instructions:

Import the public repository GPG keys:
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -

Register the Microsoft SQL Server Ubuntu
repository:
sudo add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/16.04/mssql-server-2017.list)"

Note

This is the Cumulative Update (CU) repository. For more information
    about your repository options and their differences, see Change source
    repositories.

Run the following commands to install SQL Server:
sudo apt-get update
sudo apt-get install -y mssql-server

After
  the package installation finishes, run mssql-conf setup and follow the
  prompts to set the SA password and choose your edition.
sudo /opt/mssql/bin/mssql-conf setup

Tip

If you are trying SQL Server 2017 in this tutorial, the following
    editions are freely licensed: Evaluation, Developer, and Express.

Note

Make sure to specify a strong password for the SA account (Minimum
    length 8 characters, including uppercase and lowercase letters, base
    10 digits and/or non-alphanumeric symbols).

Once the configuration is done, verify that the service is running:
systemctl status mssql-server

If you plan to connect remotely,
  you might also need to open the SQL Server TCP port (default 1433) on
  your firewall.

A: To install the mssql-server Package on Ubuntu, follow these steps:
Enter superuser mode. ...
Exit superuser mode. ...
Run the following commands to install SQL Server: sudo apt-get update sudo apt-get install -y mssql-server.
After the package installation finishes, run the configuration script and follow the prompts.
for more details look Installing SQL on Ubuntu


text:
Q: Scaling Up a Small Wordpress Site I apologize in advance if this has been asked/answered a lot. I don't know enough yet to know what I don't know.
We have a Wordpress site on a typical LAMP shared hosting platform that was getting hundreds of hits per day. We're getting more popular and this number is now approaching 1000.
At times it is SLOW or simply times out. The site allows for image downloads and tracks those by user in a database so it's essentially a very primitive, unpaid "store." I mention that because it will probably get slightly more DB inserts than a typical very small Wordpress site.
My question is: what are the factors that will matter most in scaling this up? Ideally, we would not recode anything and the server would magically handle the traffic better.
To my mind, there are 3 issues:

*

*The number of simultaneous visitors being served static pages

*The static content of all the images people might view or download (20gb)

*The mySQL databse processing each request via PHP.
I've seen various articles on dedicated servers, using several nameservers to load balance, managed hosts and cloud services.
As I wrote, I'd like some feedback as to how to measure what is causing the bottlenecks and then which types of services we should consider to make the greatest improvement with the least effort and cost for our scenario. IOW: how can I predict the impact of different upgrades we might attempt (VPS vs. cloud service vs. managed host, etc.)

A: The most bang for your buck, and really only option guaranteed to improve performance at all is to ditch the shared hosting.  Get a dedicated server, or at the very least, a VPS (virtual private server), so you have dedicated resources.
Your site does not sound very resource intensive, and it's not hyperbole in the least to say that it could be run on a modern smart phone.  This is to say that optimizing your site and improving your code's performance as a solution to the problem assumes that bottleneck is on your site, which is almost certainly not the case.  What's happening is that you are competing with all the other sites on this shared host, and when too many of them get too busy at the same time, there's not enough resources to service your site's requests (and it's a safe bet that the other sites on this particular shared host have these same problems at the same time your site does).
So your first course of action needs to be to get a small VPS or dedicated server.  Once you have your site (or a test version) on there, you can do benchmarking and testing and optimizations to determine what other improvements, if any are needed, but my money's on "if any."  I'd bet that simply eliminating the other sources of competition for computing resources will be enough to eliminate the problems you described.

A: As you've probably seen read elsewhere - swap out apache for NGINX .. it has a greater performance over apache.
Also just as easy to configure.
Or alternatively try having a look at Microsoft Azure platform (or others), let someone else take care of the infrastructure :) If you create a "Free Trial" Microsoft Azure account it will give you £130 (GBP) worth of credit for the first month. Plenty of time to experiment with it.


text:
Q: Odds of drawing at least k identical values among m after n draws? We draw $n$ values, each equiprobably among $m$ distinct values. What are the odds $p(n,m,k)$ that at least one of the values is drawn at least $k$ times? e.g. for $n=3000$, $m=300$, $k=20$.
Note: I was passed a variant of this by a friend asking for "a statistical package usable for similar problems".
My attempt: The number of times a particular value is reached follows a binomial law with $n$ events, probability $1/m$. This is enough to get odds $q$ that a particular value is reached at least $k$ times [Excel gives $q\approx 0.00340$ with =1-BINOMDIST(20-1,3000,1/300,TRUE)]. Given that $n\gg k$, we can ignore the fact that odds of a value being reached depends on the outcome for other values, and get an approximation of $p$ as $1-(1-q)^m$ [Excel gives $p\approx 0.640$ with =1-BINOMDIST(20-1,3000,1/300,TRUE)^300].
update: the exponent was wrong in the above, that's now fixed
Is this correct? (now solved, yes, but the approximation made leads to an error in the order of 1% with the example parameters)
What methods can work for arbitrary parameters $(n,m,k)$? Is this function available in R or other package, or how could we construct it? (now solved, both exactly for moderate parameters, and theoretically for huge parameters)
I see how to do a simulation in C, what would be an example of a similar simulation in R? (now solved, a corrected simulation in R and another in Python gives $p\approx 0.647$)

A: There are almost certainly easier ways, but one way of computing the value precisely is compute the number of ways of placing $n$ labeled balls in $m$ labeled bins such that no bin contains $k$ or more balls.  We can compute this
using a simple recurrence.  Let $W(n,j,m',k)$ be the number of ways of placing exactly $j$ of the $n$ labeled balls in $m'$ of the $m$ labeled bins. Then the
number we seek is $W(n,n,m,k)$.  We have the following recurrence:
$$W(n,j,m',k)=\sum_{i=0}^{k-1}\binom{n-j+i}{i}W(n,j-i,m'-1,k)$$ where $W(n,j,m',k)=0$ when $j<0$ and $W(n,0,0,k)=1$ as there is one way to pace no balls in no bins.  This follows from the fact that there are $\binom{n-j+i}{i}$ ways to choose $i$ out of $n-j+i$ balls to put in the $m'$th bin, and there are $W(n,j-i,m'-1,k)$ ways to put $j-i$ balls in $m'-1$ bins.
The essence of this recurrence if that we can compute the number of ways of placing $j$ out of $n$ balls in $m'$ bins by looking at the number of balls placed in the $m'$th bin.  If we placed $i$ balls in the $m'$th bin, then there were $j-i$ balls in the previous $m'-1$ bins, and we have already calculated the number of ways of doing that as $W(n,j-i,m'-1,k)$, and we have $\binom{n-j+i}{i}$ ways of choosing the $i$ balls to put in the $m'$th bin (there were $n-j+i$ balls left after we put $j-i$ balls in the first $m'-1$ bins, and we choose $i$ of them.) So $W(n,j,m',k)$ is just the sum over $i$ from $0$ to $k-1$ of $\binom{n-j+i}{i}W(n,j-i,m'-1,k)$.
Once we have computed $W(n,n,m,k)$ the probability that at least one bin has at least $k$ balls is $1-\frac{W(n,n,m,k)}{m^n}$.
Coding in Python because it has multiple precision arithmetic we have
import sympy
# to get the decimal approximation

#compute the binomial coefficient
def binomial(n, k):
    if k > n or k < 0:
        return 0
    if k > n / 2:
        k = n - k
    if k == 0:
        return 1
    bin = n - (k - 1)
    for i in range(k - 2, -1, -1):
        bin = bin * (n - i) / (k - i)
    return bin

#compute the number of ways that balls can be put in cells such that no
# cell contains fullbin (or more) balls.
def numways(cells, balls, fullbin):
    x = [1 if i==0 else 0 for i in range(balls + 1)]
    for j in range(cells):
        x = [sum(binomial(balls - (i - k), k) * x[i - k] if i - k >= 0 else 0
                 for k in range(fullbin))
             for i in range(balls + 1)]
    return x[balls]

x = sympy.Integer(numways(300, 3000, 20))/sympy.Integer(300**3000)
print sympy.N(1 - x, 50)

(sympy is just used to get the decimal approximation).
I get the following answer to 50 decimal places
0.64731643604975767318804860342485318214921593659347
This method would not be feasible for much larger values of $m$ and $n$.
ADDED
As there appears to be some skepticism as to the accuracy of this answer, I ran my own Monte-Carlo approximation (in C using the GSL, I used something other than R to avoid any problems that R may have provided, and avoided python because the heat death of the universe is happening any time now).  In $10^7$ runs I got 6471264
hits.  This seems to agree with my count, and is considerably at odds with whubers.  The code for the Monte-carlo is attached.
I have finished a run of 10^8 trials and have gotten 64733136 successes for a probability of 0.64733136.  I am fairly certain that things are working correctly.
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>

const gsl_rng_type * T;
gsl_rng * r;

int
testrand(int cells, int balls, int limit, int runs) {
  int run;
  int count = 0;
  int *array = malloc(cells * sizeof(int));
  for (run =0; run < runs; run++) {
    int i;
    int hit = 0;
    for (i = 0; i < cells; i++) array[i] = 0;
    for (i = 0; i < balls; i++) {
      array[gsl_rng_uniform_int(r, cells)]++;
    }
    for (i = 0; i < cells; i++) {
      if (array[i] >= limit) {
    hit = 1;
    break;
      }
    }
    count += hit;
  }
  free(array);
  return count;
}

int
main (void)
{
  int i, n = 10;

  gsl_rng_env_setup();

  T = gsl_rng_default;
  r = gsl_rng_alloc (T);

  for (i = 0; i < n; i++)
    {
      printf("%d\n", testrand(300, 3000, 20, 10000000));
    }

  gsl_rng_free (r);

  return 0;
}

EVEN MORE
Note: this should be a comment to probabilityislogic's answer, but it won't fit.
Reifying probabilityislogic's answer (mainly out of curiosity), this time in R because a foolish inconsistency is the hobgoblin of great minds, or something like that.  This is the normal approximation from the Levin paper (the Edgeworth expansion should be straightforward, but it is more typing than I'm willing to expend)
# an implementation of the Bruce Levin article here limit is the upper limit on
#   bin size that does not count
approxNorm <- function(balls, cells, limit) {
  # using N=s
  sp <- balls / cells
  mu <- sp * (1 - dpois(limit, sp) / ppois(limit, sp))
  sig2 <- mu - (limit - mu) * (sp - mu)
  x <- (balls - cells * mu) / sqrt(cells * sig2)
  p2 <- exp(-x^2 / 2)/sqrt(2 * pi * cells * sig2)
  p1 <- exp(ppois(limit, sp, log.p=TRUE) * cells)
  sqrt(2 * pi * balls) * p1 * p2
}

and 1 - approxNorm(3000, 300, 19) gives us $p(3000, 300, 20) \approx 0.6468276$ which is not too bad at all.

A: (Responding to the simulation question)
In R:
n <- 3000; m <- 300; k <- 20 # Problem parameters
nIterations <- 10000         # Number of iterations in the simulation
set.seed(17)                 # Make the output reproducible
#
# All the work is done in the following line.
#
t <- table(replicate(nIterations, any(tabulate(floor(runif(n, min=1, max=m+1))) >= k)))
t[["TRUE"]]/nIterations      # Convert the count to a proportion

Expected output:
[1] 0.6453

To see more deeply into what's going on, look at the detailed distribution in several experiments by executing this command several times:
table(tabulate(floor(runif(n, min=1, max=m+1))))

Typical output is
 2  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 21
 2  5 11 23 23 32 48 37 33 21 19 21  9  6  5  1  2  1

In this experiment, two values in the range 0..299 were observed 19 times (among 3000 independent draws) and one value was observed 21 times.  You will find that most of the time, at least one value occurs 20 or more times.  Because $1/m$ is small and $n$ is large, you should be seeing a Poisson distribution here.  Indeed,
1 - ppois(k-1, n/m)^m

returns
[1] 0.6458719

A: This is a harder question if you don't have the $n\gg k$ and assuming that this makes them 'close enough' to independent to not affect the answer non-trivially. Lets proceed with these assumptions. Let $X_j \sim Binomial(n,\frac{1}{m})$ $\forall j = 1,..,m$.
$$P(\max_j X_j \geq k) = 1 - P(\max_j X_j < k)$$
$$ = 1  - P(X_1 < k,...,X_m < k)$$
and, assuming independence of the $m$ random variables,
$$ = 1  - \prod^m_{j=1}P(X_j < k)$$
$$ = 1  - [P(X_1 < k)]^m$$
$$ = 1  - [\sum^{k-1}_{i=0} {n \choose i}(\frac{1}{m})^i(1-\frac{1}{m})^{n-i}]^m$$
or, if you have the binomial cdf function in the language you are using:
$$ = 1  - [Binomial\_cdf(k-1;n,\frac{1}{m})]^m$$

A: The collection of numbers has a multinomial distribution with $m$ categories and $n$ sample size.  Letting $N_i$ be the number of times the $i$th category is chosen/repeated, we have $$(N_1,\dots,N_m)\sim multinomial\left(n;\frac{1}{m},\frac{1}{m},\dots,\frac{1}{m}\right)$$ Now leveraging off of @danieljohnson's answer the probability we are after is
$$p(n,m,k)=1-Pr(N_1<k,\dots,N_m<k)$$
i.e. if all numbers are repeated less than $k$ times, then none are repeated at least $k$ times.  And "not none" is the same as "at least one" so we can take the probability away from one.  This could be computed via a "brute force" approach, as the pmf we have is particularly simple:
$$p(n,m,k)=1-m^{-n}\sum_{N_1<k,\dots,N_m<k|N_1+\dots+N_m=n}{n\choose N_1\dots N_m}$$
$$=1-\frac{n!}{m^{n}}\sum_{N_1=0}^{k-1}\sum_{N_2=0}^{k-1}\dots\sum_{N_{m-1}=0}^{k-1}\frac{1}{N_1!N_2!\dots N_{m-1}!(n-N_1-N_2-\dots-N_{m-1})!}$$
The last formula is correct provided we interpret a negative factorial as $\pm\infty$ (consistent with the gamma function) which eliminates these from the summation.
On doing a quick google search came up with Bruce Levin's article.  This gives a representation of the multinomial distribution as a collection of poisson random variables, with their sum being fixed.  (note this might explain why @whuber has found that poisson approximation works better than binomial).  Now, using the representation given in theorem 1 of the paper, we have:
$$p(n,m,k)=1-\frac{n!}{s^n\exp(-s)}\left[\prod_{j=1}^{m}Pr(X_j\leq k-1)\right]Pr(W=n)$$
Where $X_j\sim Poisson\left(\frac{s}{m}\right)$ and are independent, and $W=\sum_{j=1}^{m}Y_j$ is a sum of independent truncated poisson distributions - basically $Y_j$ is $X_j$ conditioned to be less than or equal to $k-1$.  Note that we can simplify the general formula by noting that the terms in the product do not depend on the index $j$, and so is just a single poisson cdf raised to the power of $m$.  Thus we have:
$$p(n,m,k)=1-\frac{n!}{s^n}\left[e_{k-1}\left(\frac{s}{m}\right)\right]^mPr(W=n)$$
Where $e_k(x)=\sum_{j=0}^{k}\frac{x^j}{j!}$ denotes the exponential sum function.  note that because we have factorial an powers of potentially large numbers, numerically it will probably be better to work in terms of the logarithm of the second term, and then exponentiate back at the end of the calculation.  Alternatively, we can choose the recommended $s=N$ as our algorithm parameter, and then make use of the stirling approximation to $n!$ - this is recommended in the paper and corresponds to "mean matching" of each poisson distribution with the multinomial cell (i.e. $E(X_i)=E(N_i)$).  Then we get $\frac{n!}{n^n}\approx\sqrt{2\pi n}$.
The paper provides two approximations for $Pr(W=n)$ on based on normal approximation, and another based on edgeworth expansion. details are in the paper (see equation 4).  Note though that his method allows for different probability parameters, so terms like $\frac{1}{t}\sum_{1}^t\sigma_l^2$ can be replaced with $\sigma_1^2$ and so on, which avoid unecessary computation.  Note that we also have the mallows bounds provided in the paper - which can be used to check the accuracy of the approximations.


text:
Q: Fix Script Only Updating One Record I'm failry new to Javascript and Servicenow so bear with me please. I'm creating a fix script to populate the incident breach time label on the incident task. It will show the same SLA as the parent incident. My below script returns the correct number of records that should be updated. However, when I go to update the record in my second GlideRecord, it only updates one record(Should be about 125). I commented the update portion of the code for testing purposes. Any suggestions? Thanks
var grSLA = new GlideRecord('u_incident_task');
grSLA.addEncodedQuery('u_incident_breach_timeISEMPTY^parentISNOTEMPTY^stateIN1,2,4');
grSLA.query();

var count=0;
gs.info("{0} of Itasks found to update", grSLA.getRowCount());

while (grSLA.next())
{
    var ipar = grSLA.parent.sys_id;
}
gs.print(ipar);

var grName = new GlideRecord('task_sla');
grName.addQuery('task', ipar);
grName.addQuery('stage', 'in_progress');
grName.query();

while (grName.next())
{
    var bTime = grName.planned_end_time.getDisplayValue();
    grSLA.u_incident_breach_time=bTime; //sets the Incident Breach Time on the iTask

    //grSLA.update();
    count++;
}

A: I believe you need to move your task_sla loop inside of your u_incident_task loop.
It is only updating the final one since ipar is the last record in the loop.
var grSLA = new GlideRecord('u_incident_task');
grSLA.addEncodedQuery('u_incident_breach_timeISEMPTY^parentISNOTEMPTY^stateIN1,2,4');
grSLA.query();

var count=0;
gs.info("{0} of Itasks found to update", grSLA.getRowCount());

while (grSLA.next())
{
    var ipar = grSLA.parent.sys_id;
    gs.print(ipar);

    var grName = new GlideRecord('task_sla');
    grName.addQuery('task', ipar);
    grName.addQuery('stage', 'in_progress');
    grName.query();

    while (grName.next())
    {
        var bTime = grName.planned_end_time.getDisplayValue();
        grSLA.u_incident_breach_time=bTime; //sets the Incident Breach Time on the iTask

        grSLA.update();
        count++;
    }
}


text:
Q: Eclipse project does not want to clean I have been working on eclipse helios, trying to SVN repository project. Safe to say it checked out correctly to a specific work-space.
however when I copy the file from the eclipse packaged folder into the root folder and restarting the eclipse.
The clean project function becomes inactive, which brings about a lot of errors such as the:

An internal error occurred during: "Launching
  iReadTrunk".java.lang.NullPointerException,

when I try running the app. Please! Help.

A: Upgrade to Eclipse Juno, Helios is very old.  http://www.eclipse.org/downloads/packages/release/juno/sr1


text:
Q: Kinvey vs StorageRoom vs Parse other BaaS I'm an iOS dev and I don't have heavy knowledge of web world, most of the time I develop an app I need to interface with a backends. Fortunately I found that there are a plenty of BaaS / CMS on the cloud that really reduce the time to market to implement such services.
Now I'm using StorageRoom (more CMS), I'm pretty happy about it.  It has various good features but it lack something else.
GOOD

*

*REST API are really simple and you can implement your own REST interface on mobile site. this is important because I trust only in one download manager, the MKNetworkKit, IMHO is the only one well studied and I don't want to digg into there frameworks and try to understand how they manages connections

*You can create different user to edit and make data entry the CMS (but this feature will need more flexibility, actually it shows all collections even if the user have not permissions to CRUD them)

*Webhooks makes very easy and flexible the connection with other services such as PUSH etc

*Low Price

*Quite abstract services so they're really really flexible

MISSING

*

*Custom business logic

*Advanced editor features

*A sort of social connection/login to create social applications faster

*An integrated service for Push and Passkit

*Since very abstract I'd like to see more facilities for collection management and social login

Can someone that uses Kinvey tell me if it has all the good features of Storageroom and the missing features and share his/her experience with that BaaS or another one?

A: Disclaimer: I am on the development team at Kinvey so this is largely biased towards what I have intimate knowledge on.
Responses to the Good section:

*

*Kinvey provides native libraries for development. This means you don't need to learn the network layer, manage security on the device side and worry about offline/cache support. We do our best to abstract all that away and make things easier.

*We have a collaboration feature which allows multiple people to administer your app. Currently it gives complete access to work with anything on your app. On the upside you can use the master-secret to have full administration features if you wanted to build out a custom editing interface.

*Push support is baked into our system, you can push to iOS and Android relatively easy.

*Our pricing model is success based pricing, you only pay when you actually hit load. Development is always free.

*We do our best to abstract as many problems away from you to make development as easy as possible.

Responses to the Missing section:

*

*Kinvey provides custom business logic out of the box, as should most reasonable BaaS solutions.

*As mentioned above, we don't provide a CMS interface for editing, but that does not prevent you from being able to roll your own using the master-secret.

*Kinvey provides social network login out of the box, along with most of the other BaaS companies.

*Kinvey does not integrate directly with Passkit.


text:
Q: basic HTTP Client from scratch So my assignment is as the title indicated. Take a url, get the hostname and pathname from it and then open a socket and write to/read from it.
I've split the url and tried making a socket as such:
    try {
        Socket socket = new Socket(hostname, port);
        InputStream inStream = socket.getInputStream();
        DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());

        outStream.writeChars(pathname);
        outStream.flush();
    }
    catch (Exception e) {
        System.out.println(e);
    }

Then I've tried a number of ways to get the response, for example I used:
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());

OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("test.txt")));
byte[] buf = new byte[256];
int n = 0;
while ((n=in.read(buf))>=0) {
    out.write(buf, 0, n);
}
out.flush();
out.close();

As well as a number of other variations but they always seem to get stuck at the while loop. I'm supposed to read the response as bytes and then convert the array of bytes into a string. Why is this getting stuck on the while loop?

A: you have to sent correct data in regard of HTTP protocol. try this
    try {
        String hostname = "stackoverflow.com";
        String requestHeaders[][] = {
            { "Host" , hostname } ,
            { "User-Agent" , "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" } ,

        };
        String pathname = "questions/33047629/basic-http-client-from-scratch/33047769#33047769";
        int port = 80;
        Socket socket = new Socket(hostname, port);
        InputStream inStream = socket.getInputStream();
        DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
        String data = "GET /"+pathname+" HTTP/1.1\r\n";
        for (int i=0;i<requestHeaders.length;i++){
            data += requestHeaders[0]+": "+requestHeaders[1]+"\r\n";
        }
        data += "\r\n";
        outStream.writeChars(data.getBytes());
        outStream.flush();
    }
    catch (Exception e) {
        System.out.println(e);
    }

there are some browsers plugins that shows which header are sent by your browser. you can learn them from plugin and implement them as I implemented for 2 headers

A: I think your condition is wrong, should be >0 and not >=0