text:
Q: SQL Server Compare rows of one table with all rows of other table I have 2 tables which contains firstname, surname,dob.
First table has datatype as varchar for all columns and second table is varchar(50),varchar(50),datetime datatype.
Ex:
1st table
fname surname dob
a       b      04/12/1948
a       b      05/08/1984

 2nd table
fname surname dob
a       b      05/08/1984
a       b      04/12/1948

when i do Intersect is not matching the decors (possibly b'ze of datatype)
and except give me result.
Is there any way to select all record from table 1 with matching records of table 2.
Any help much apprecciated

A: SELECT fname, surname, CAST(dob AS DATETIME) AS dob FROM table1
INTERSECT
SELECT fname, surname, dob FROM table2

A: Both EXCEPT and INTERSECT work:
Declare @tblA AS TABLE(
    FirstName VARCHAR(50),
    SurName VARCHAR(50),
    Dob VARCHAR(50)
)

Declare @tblB AS TABLE(
    FirstName VARCHAR(50),
    SurName VARCHAR(50),
    Dob Date
)

INSERT INTO @tblA VALUES
('a','b','04/12/1948'),
('a','b','05/08/1948')

INSERT INTO @tblB VALUES
('a','b','04/12/1948'),
('a','b','05/09/1948')

SELECT
    *
FROM @tblA
INTERSECT
SELECT
    *
FROM @tblB

SELECT
    *
FROM @tblA
EXCEPT
SELECT
    *
FROM @tblB

Output:

A: Use this query.
Select * from table1 as a
Inner join table2 as b
on a.fname = b.fname and a.surname = b.surname and cast(a.dob as date)=b.dob

A: SELECT * FROM #Table1 JOIN #Table2 ON #Table2.dob = CONVERT(DATETIME,#Table1.dob,101)


text:
Q: How do I change a PPA from 11.10 to 11.04? How do I change Oneiric to Natty in sources list? I want to know this cause Oneiric has a problem with the PPA.

A: To change your personal PPAs:

*

*Open Repositories and type the administrator password when asked;

*Select the Other Software tab;

*Select the PPA you want to edit and hit the Edit button;

*In the Distribution field, just change the text oneiric to natty.

Be careful and remember, this operation may break things.

A: If Oneiric has "a problem" (you did not specify) with the PPA, it is likely that the PPA has not been updated to support Oneiric as yet.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compute symbolic/numeric Fourier transforms in SageMath, and define a function out of it? I am new to SageMath and Python and I am writing simple Jupyter notebooks to learn them. I have experience in Mathematica and I am trying to mimic what I can do in a Mathematica notebook, to understand if I can migrate to SageMath for my work.
I would like to compute a symbolic Fourier transform of a real function f(x) and define a SageMath symbolic function out of it. In Mathematica I would write
foo[k_] := FourierTransform[f[x],x,k]
and this would do the job. In SageMath 9.0, I started with
from sympy import fourier_transform as ft
from sympy import inverse_fourier_transform as ift

and then
g(x) = exp(-x**2)
exp_ft(k) = ft(g(x),x,k)

which seems to work properly; I evaluated exp_ft(k) at certain values, I differentiated it, plotted it, checked that the variable k is local by evaluating exp_ft(t) and getting the same functional expression with t instead of k. The first question is: is this the correct/best way to perform such operation is SageMath?
In Mathematica, I can also define a function as
foo[k_?NumericQ] = FourierTransform[f[x],x,k]
to improve efficiency. Is there any way to do this in SageMath? In other words, are the delayed := and non-delayed = assignment present in SageMath/Python, and is there the possibility to write conditional statements in the arguments of a function, as it can be done in Mathematica (see above)?
Also, if I compute the Fourier transform of cos(x),
ft(cos(x),x,k)
the result is 0. Isn't this wrong? The result should be the sum of two Dirac deltas. A similar issue shows up if I compute the inverse Fourier transform of 1, which is the Dirac delta. I get an implicit expression, not the delta. However, if I compute the Fourier transform of the Dirac delta, I get 1. How to deal with this?
Thanks in advance for the help!


text:
Q: I cannot find updater option on Acrobat Reader DC preferences I have lost this feature on Acrobat Reader DC

A: You did not lose it. Adobe has removed Update Control from its free Product. It updates automatically.
The subscription product (Acrobat DC) retains the Update Option.
I have both Reader DC (one machine) and Acrobat Pro DC (other machine) and that is how it works.
Adobe Reader works fine, so we just adapt to the automatic updating.


text:
Q: Why can I not call a form object in two events? I'm making like a add contact form with two buttons, ADD CONTACT and EDIT CONTACT. When a user clicks add contact, it pops up another form where the user can add contact information.
I want to give them the option to edit that info by clicking the EDIT CONTACT button which should pop up the SAME form.
However its not letting me call the object of the form twice, saying that I cannot press the edit button after the add button.
How do I call a form object twice?
    //instatiating an object of the form
    FormContact contactForm = new FormContact();

    public FormManager()
    {
        InitializeComponent();
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        //displaying it when the user clicks add button
        contactForm.Show();
    }

    private void btnEdit_Click(object sender, EventArgs e)
    {
        //trying to display it again but gives this exception

        ///System.ObjectDisposedException: 'Cannot access a disposed
        ///object.
        ///Object name: 'FormContact'.'

        contactForm.Show();
    }

        Error:
        ///System.ObjectDisposedException: 'Cannot access a disposed
        ///object.
        ///Object name: 'FormContact'.'

A: The problem is you're closing the form after you've shown it.

*

*You click the Show button

*Your only instance of the form is shown

*You close it with the X in the top corner

*The runtime destroys the form (disposes it) after it is closed

*You try to show it again but this this it's gone, trashed, doesn't exist any more, waiting to be garbage collected

Either make a new form each time you open it (to reduce code clutter, assign this same event handler to both button clicks, or copy paste it out twice if you want them to be coded differently eventually):
private void btnAddOrEdit_Click(object sender, EventArgs e)
{
    new FormContact().Show();
}

Or intercept the FormClosing event of the FormContact form and cancel the closing, and perform a Hide() instead so that instead of being destroyed your form is made invisible. It will then still exist and can be Show()n the next time. To handle the event, open the FormContact designer, click anywhere in the form background, click lightning bolt in properties grid, double click the FormClosing entry:
private void FormClosing(object sender, FormClosingEventArgs e){
  e.Cancel = true;
  this.Hide();
}

Which method you choose depends how you want your program to behave:
If you make a new form each time, and you Show instead of ShowDialog your user could click Add twice and see two forms. Then could click Add 10 times and see 10 forms. Using ShowDialog means that the main window won't accept any more clicks until the FormContact is closed. You might or might not want this either
If you Hide (not close; hiding is different from closing) and Show the same form rather than making a new one then the user can click Add 10 times but they still only see one form

A: FormContact contactForm = new FormContact(); is a Member variable, it's scope is Private and is visible to the entire class.
After you first Show the form:
contactForm.Show();
The form is already showing. Therefore if you call Show again, it won't do anything as the instance of the form/class is already showing.
If you want to show two instances of the form, you will need to instantiate two instances eg:
private void btnAdd_Click(object sender, EventArgs e)
{
    FormContact contactForm = new FormContact();
    contactForm.Show();
}

private void btnEdit_Click(object sender, EventArgs e)
{
    FormContact contactForm = new FormContact();
    contactForm.Show();
}

Or make two instances of it:
FormContact contactForm1 = new FormContact();
FormContact contactForm2 = new FormContact();

private void btnAdd_Click(object sender, EventArgs e)
{
    contactForm1.Show();
}

private void btnEdit_Click(object sender, EventArgs e)
{
    contactForm2.Show();
}

Or add a argument in the parameter of the Constructor to indicate Add or Edit, eg:
public class FormContact
{
   public FormContact(int id)
   {
     if (id > 0)
     {
        //Load contact for Editing
     }
     else
     {
        //Clear all fields for Adding
        foreach(var ctrl in this.Controls)
        {
             if (ctrl Is TextBoxBase) ctrl.Text = string.Empty
             //TODO other controls types... if (ctrl Is ....
        }
     }
   }
}

Then you can call it passing a contactID to edit or 0 to add:
FormContact contactForm = new FormContact(contactID);
contactForm.Show();

A: I've got another answer, in both methods simply show your form modally:
contactForm.ShowModal();


text:
Q: Get single QuerySet object from two different models using Django My First models
class UserModel(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
profile_pic = models.CharField(max_length=50)
gender = models.CharField(max_length=20)
college_name = models.CharField(max_length=50)
user_id = models.CharField(max_length=15, unique=True)
user_password = models.CharField(max_length=15)

class Meta:
    db_table = 'user'

Second Model
class GroupPostCommentsModel(models.Model):
comment_text = models.CharField(max_length=1000)
likes = models.IntegerField(default=0)
time_stamp = models.DateTimeField(auto_now=True)
comment_by_user = models.ForeignKey(UserModel, on_delete=models.CASCADE)
post_id = models.ForeignKey(GroupPostsModel, on_delete=models.CASCADE)

class Meta:
    db_table = 'group_posts_comments'

I want data as follows :
[id,first_name, last_name, profile_pic, comment_text, likes]

My Serializer
class GroupPostCommentsSerializerGetInfo(serializers.Serializer):
id = serializers.IntegerField()#it is primary key of GroupPostCommentsModel
comment_text = serializers.CharField(max_length=1000)
likes = serializers.IntegerField(default=0)
time_stamp = serializers.DateTimeField(default='')
first_name = serializers.CharField(max_length=20)# From UserModel
last_name = serializers.CharField(max_length=20)# From UserModel
profile_pic = serializers.ImageField(default='')# From UserModel

first_name, last_name, profile_pic : from UserModel
comment_text, likes : from GroupPostCommentsModel

python3 --version
Python 3.6.9
Django==3.2.10
I am stuck in the project for a long time please help. :)


text:
Q: CAN bus - voltage drop with new component I am trying to connect a new board to my CAN bus and I have an issue with the voltage. The new board is a Raspi 4 and has a "RS485 CAN HAT" connected to it. To debug, I use can-utils.
When I am testing the bus and sending some dummy CAN frames, I have the following :

However, when my board is connected to the CAN bus AND I activate the link (sudo ip link set can0 type can bitrate 125000 + sudo ifconfig can0 up), I obtain the following :

It looks like to me that the signal is not at all correct. Interestingly, if the link is disabled (sudo ifconfig can0 down), I get the normal waveform.
I already checked the resistance and it's 60 ohm between CAN_L and CAN_H. (in both cases)
Does anyone know what's happening? (My suspicion is that the CAN hat is not working properly.)

A: My error was to assume an 8M crystal (according to the pdf datasheet). However, the webpage of the CAN HAT specifies that the new version has a 12M crystal. (It needs to be dtoverlay=mcp2515-can0,oscillator=12000000,interrupt=25,spimaxfrequency=2000000 in /boot/config.txt)
Thank you Klas-Kenny for the tip !


text:
Q: Can I access the data from SQLAlchemy database writing a separate backend on Django Rest Framework? Consider that someone wrote a user backend. So the backend consists of users and their houses. The backend uses SQLAlchemy to store the users and their houses (so a user can have multiple houses). Both users and houses have their unique IDs.
Now, I want to write a separate backend in Django Rest framework in order for the users to be able upload the house pictures for their houses.
Will it be possible to do that? To be more specific, my thought is to connect to that SQLAlchemy database and whenever the user types a url (.../user34/house55/) my code triggers my model which retrieves the Token and extracts the user ID and house ID and gets ready for the POST from that specific user. So when the user uploads the image, my backend simply saves a new field in SQLAlchemy. Or would that be impossible as the user backend does not have a field for that?


text:
Q: mongoDB multiple instances or multiple databases I chose to use docker with node-js and mongoDB to make a game, and set all of my game sections (battles, chat, resources, etc) into different servers so each section will have its own process, because for example my resource server will be running a lot as it will do all the calculation of the resources of each user every second and will handle requests from other servers, like if the user have enough resources to build a building or how much resources the player will lose if attacked etc.
For my alpha and beta versions i'm planning on running one server, that will run all the sections of my game, but the way i'm doing it now, every section is having its own mongodb instance, so i have resourcesDB, mainDB (users info, login info and stuff), all the instances won't have many collections, for example resourcesDB have only 2 collections, resource collections, which each user will have 1 document with stuff related to resources, and logs collection that will store all user's usage (building upgrades, battles lost etc.)
I have read about multi instances on the same servers, and they all said that its not the best way to do it, as it will have an impact on my performance, in the future i am planning on separate all of my sections into different servers so each section will have its own server and DB server if needed.

*

*Should I maybe build 1 instance and separate it on the database level? that means that I will have to connect to the same instance from multiple servers, resource server will update all the user's resources count every second, combine that with battle server that will update the state of troops in DB and more for each war that is going on, i will also have chat database that will be updating with each private message or chat message, will it cause any issues? or it will cause problems only if I connect to a single database and separate it on the collections level?

*Is there a reason why i should not continue with creating multiple instances? i read that there might be a problem with config files if using multiple instances on same server, but i assume docker handle that part.
UPDATE - i have found an excellent answer here: https://dba.stackexchange.com/questions/156811/mongodb-in-micro-services-structure/156984#156984

A: Using microservice architecture for your app is good idea but I don't see a good reason to separate the database. MongoDB can handle it for you (Sharding). Also MongoDB not block write to collection A when you write to collection B. if you will separate your app to multiple database it will be hard to do backups and to maintain the app.
You can read here about concurrency options for MongoDB and see how MongoDB handle collection level locking.
https://docs.mongodb.com/manual/faq/concurrency/


text:
Q: Laravel page could not be found when file request , in nginx centos7 the routes of Laravel project in centos7 server with nginx are working but any file requesting from my upload directory in public returns "the page you are looking for could not be found." my API is ok , just file urls are not work.
font-end project is angularjs in root directory and laravel back-end is in core folder.
server config :
 server {
listen 80 default_server;
    listen [::]:80 default_server;

    root /usr/share/nginx/html/core/public;
    #root /var/www/html;

    index index.php index.html;

    location / {
            alias /usr/share/nginx/html/;
            #index index.html;
            #try_files $uri $uri/ /index.php?$query_string;
            try_files $uri $uri/ /index.html?$args;
    }

location /api{
            #alias /usr/share/nginx/html/core/public;
            #index index.php;
            try_files $uri $uri/ /index.php?$query_string;
    }
location /upload{
            root /usr/share/nginx/html/core/public/upload;
            try_files $uri $uri/ /index.php?$query_string;
    }

location ~ \.php$ {
            try_files $uri /index.php =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            rewrite ^/api/(.*)$ /$1 break;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

#location ~ /\. {
            #deny all;
    #}
 }


text:
Q: Всевозможные произведения в массиве Не могу написать рабочий алгоритм нахождения всех возможных произведений элементов массива. То есть к примеру у нас есть массив на n элементов. Требуется найти произведение любых пар элементов, любых троек и так далее до произведений всех элементов.

A: #include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> count = {10,15,30,100};
    vector<int> res;
    res.reserve(1 << count.size());
    res.push_back(1);
    for (unsigned int mask = 1; mask < (1 << count.size()); mask++)
        res.push_back ( res[ mask & (mask - 1) ] * count [ __builtin_ctz(mask) ] );
    for (int x: res)
        cout << x<< " ";
    return 0;
}

Например так...
По просьбе @VladD - генератор стиль (без доп памяти)
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> count = {10,15,30,100};

    for (unsigned __int128 mask = 0; mask < (1 << count.size()); mask++){
        unsigned long long res = 1;
        __int128 tm = mask;
        for ( ; tm ; tm &= (tm - 1) )
            res *= count [ __builtin_ctz(tm) ];
        cout << res<<" ";
    }
    return 0;
}

A: Нашел тут, когда-то сочинял генератор кодов Грея. Поскольку работает и для этой задачи годится - вот не самое, конечно, эффективное, но решение :) Просто если в массиве нет нулевого значения, то на каждом очередном шаге новое произведение можно вычислить только одним делением или умножением, не перебирая все элементы массива.
#include <vector>
#include <string>
#include <iostream>
#include <iomanip>

using namespace std;

class Gray
{
public:
    Gray(int N):N(N),a(N+1,false),last_(-1){}
    ~Gray() = default;
    Gray(const Gray&) = default;
    Gray(Gray&&)      = default;
    Gray& operator=(const Gray&) = default;
    Gray& operator=(Gray&&)      = default;

    size_t size() const { return N; }
    void reset(size_t newN = 0)
    {
        if (newN) N = newN;
        vector<bool> b(N+1,false);
        std::swap(a,b);
        last_ = -1;
    }

    bool operator[](size_t idx) const { return a[idx]; }

    int  last() const { return last_; }

    bool next()
    {
        size_t j;
        if (!a[N]) j = 0; else {
            for(j = 0; j < N; ++j) if (a[j]) break;
            ++j;
        }
        if (j == N) return false;
        a[N] = !a[N];
        a[j] = !a[j];
        last_ = j;
        return true;
    }
private:
    vector<bool> a;
    size_t N;
    int last_;
};

int main(int argc, const char * argv[])
{
    int m[] = { 2, 3, 5, 7 };

    Gray g(sizeof(m)/sizeof(m[0]));
    do {
        if (g.last() >= 0)
        {
            int p = 1;
            for(size_t i = 0; i < g.size(); ++i) if (g[i]) p *= m[i];
            cout << setw(6) << p << " = ";
            for(size_t i = 0, first = 1; i < g.size(); ++i)
                if (g[i]) {
                    if (!first)
                    {
                        cout << " * ";
                    }
                    else
                    {
                        first = 0;
                    }
                    cout << m[i];
                }
            cout << "\n";
        }
    } while(g.next());

    // Только произведения - если нет нулевого элемента.

    g.reset();

    int p = 1;
    do {
        if (g.last() >= 0)
        {
            if (g[g.last()]) p *= m[g.last()]; else p /= m[g.last()];
            cout << setw(6) << p <<"\n";
        }
    } while(g.next());

}


text:
Q: Trying out Scrapy + Splash So I'm playing around with Scrapy & Splash and I'm running into some issues.
I tried running my spiders, and kept getting HTTP 502 & 504 errors.  Okay, so I tried to check out Splash in my browser.
First I did "sudo docker run -p 8050:8050 -p 5023:5023 scrapinghub/splash --max-timeout 3600 -v3" to start Splash running, then I went to localhost:8050.  Web UI opens up properly, and I'm able to enter code.
Here is the basic function I'm trying to run:
function main(splash, args)
  assert(splash:autoload("https://code.jquery.com/jquery-3.1.1.min.js"))
  splash.resource_timeout = 30.0
  splash.images_enabled = false
  assert(splash:go(args.url))
  assert(splash:wait(0.5))
  return {
    html = splash:html(),
    --png = splash:png(),
    --har = splash:har(),
  }
end

I try to render http://boingboing.net/blog, using this function, and get an 'invalid hostname' LUA error; here are the logs:
2017-08-01 18:26:28+0000 [-] Log opened.
2017-08-01 18:26:28.077457 [-] Splash version: 3.0
2017-08-01 18:26:28.077838 [-] Qt 5.9.1, PyQt 5.9, WebKit 602.1, sip 4.19.3, Twisted 16.1.1, Lua 5.2
2017-08-01 18:26:28.077900 [-] Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609]
2017-08-01 18:26:28.077984 [-] Open files limit: 65536
2017-08-01 18:26:28.078046 [-] Can't bump open files limit
2017-08-01 18:26:28.180376 [-] Xvfb is started: ['Xvfb', ':1937726875', '-screen', '0', '1024x768x24', '-nolisten', 'tcp']
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'
2017-08-01 18:26:28.226937 [-] proxy profiles support is enabled, proxy profiles path: /etc/splash/proxy-profiles
2017-08-01 18:26:28.301002 [-] verbosity=3
2017-08-01 18:26:28.301116 [-] slots=50
2017-08-01 18:26:28.301202 [-] argument_cache_max_entries=500
2017-08-01 18:26:28.301530 [-] Web UI: enabled, Lua: enabled (sandbox: enabled)
2017-08-01 18:26:28.302122 [-] Site starting on 8050
2017-08-01 18:26:28.302219 [-] Starting factory <twisted.web.server.Site object at 0x7ffa08390dd8>
2017-08-01 18:26:32.660457 [-] "172.17.0.1" - - [01/Aug/2017:18:26:32 +0000] "GET / HTTP/1.1" 200 7677 "-" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
2017-08-01 18:27:18.860020 [-] "172.17.0.1" - - [01/Aug/2017:18:27:18 +0000] "GET /info?wait=0.5&images=1&expand=1&timeout=3600.0&url=http%3A%2F%2Fboingboing.net%2Fblog&lua_source=function+main%28splash%2C+args%29%0D%0A++assert%28splash%3Aautoload%28%22https%3A%2F%2Fcode.jquery.com%2Fjquery-3.1.1.min.js%22%29%29%0D%0A++splash.resource_timeout+%3D+30.0%0D%0A++splash.images_enabled+%3D+false%0D%0A++assert%28splash%3Ago%28args.url%29%29%0D%0A++assert%28splash%3Await%280.5%29%29%0D%0A++return+%7B%0D%0A++++html+%3D+splash%3Ahtml%28%29%2C%0D%0A++++--png+%3D+splash%3Apng%28%29%2C%0D%0A++++--har+%3D+splash%3Ahar%28%29%2C%0D%0A++%7D%0D%0Aend HTTP/1.1" 200 5656 "http://localhost:8050/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
2017-08-01 18:27:19.038565 [pool] initializing SLOT 0
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
process 1: D-Bus library appears to be incorrectly set up; failed to read machine uuid: UUID file '/etc/machine-id' should contain a hex string of length 32, not length 0, with no other text
See the manual page for dbus-uuidgen to correct this issue.
2017-08-01 18:27:19.066765 [render] [140711856519656] viewport size is set to 1024x768
2017-08-01 18:27:19.066964 [pool] [140711856519656] SLOT 0 is starting
2017-08-01 18:27:19.067071 [render] [140711856519656] function main(splash, args)\r\n  assert(splash:autoload("https://code.jquery.com/jquery-3.1.1.min.js"))\r\n  splash.resource_timeout = 30.0\r\n  splash.images_enabled = false\r\n  assert(splash:go(args.url))\r\n  assert(splash:wait(0.5))\r\n  return {\r\n    html = splash:html(),\r\n    --png = splash:png(),\r\n    --har = splash:har(),\r\n  }\r\nend
2017-08-01 18:27:19.070107 [render] [140711856519656] [lua_runner] dispatch cmd_id=__START__
2017-08-01 18:27:19.070270 [render] [140711856519656] [lua_runner] arguments are for command __START__, waiting for result of __START__
2017-08-01 18:27:19.070352 [render] [140711856519656] [lua_runner] entering dispatch/loop body, args=()
2017-08-01 18:27:19.070424 [render] [140711856519656] [lua_runner] send None
2017-08-01 18:27:19.070496 [render] [140711856519656] [lua_runner] send (lua) None
2017-08-01 18:27:19.070657 [render] [140711856519656] [lua_runner] got AsyncBrowserCommand(id=None, name='http_get', kwargs={'url': 'https://code.jquery.com/jquery-3.1.1.min.js', 'callback': '<a callback>'})
2017-08-01 18:27:19.070755 [render] [140711856519656] [lua_runner] instructions used: 70
2017-08-01 18:27:19.070834 [render] [140711856519656] [lua_runner] executing AsyncBrowserCommand(id=0, name='http_get', kwargs={'url': 'https://code.jquery.com/jquery-3.1.1.min.js', 'callback': '<a callback>'})
2017-08-01 18:27:19.071141 [network] [140711856519656] GET https://code.jquery.com/jquery-3.1.1.min.js
qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method
qt.network.ssl: QSslSocket: cannot resolve SSLv2_server_method
2017-08-01 18:27:19.082150 [pool] [140711856519656] SLOT 0 is working
2017-08-01 18:27:19.082298 [pool] [140711856519656] queued
2017-08-01 18:28:39.151814 [network-manager] Download error 3: the remote host name was not found (invalid hostname) (https://code.jquery.com/jquery-3.1.1.min.js)
2017-08-01 18:28:39.152087 [network-manager] Finished downloading https://code.jquery.com/jquery-3.1.1.min.js
2017-08-01 18:28:39.152202 [render] [140711856519656] [lua_runner] dispatch cmd_id=0
2017-08-01 18:28:39.152268 [render] [140711856519656] [lua_runner] arguments are for command 0, waiting for result of 0
2017-08-01 18:28:39.152339 [render] [140711856519656] [lua_runner] entering dispatch/loop body, args=(PyResult('return', None, 'invalid_hostname'),)
2017-08-01 18:28:39.152400 [render] [140711856519656] [lua_runner] send PyResult('return', None, 'invalid_hostname')
2017-08-01 18:28:39.152468 [render] [140711856519656] [lua_runner] send (lua) (b'return', None, b'invalid_hostname')
2017-08-01 18:28:39.152582 [render] [140711856519656] [lua_runner] instructions used: 79
2017-08-01 18:28:39.152642 [render] [140711856519656] [lua_runner] caught LuaError LuaError('[string "function main(splash, args)\\r..."]:2: invalid_hostname',)
2017-08-01 18:28:39.152816 [pool] [140711856519656] SLOT 0 finished with an error <splash.qtrender_lua.LuaRender object at 0x7ffa08477e48>: [Failure instance: Traceback: <class 'splash.exceptions.ScriptError'>: {'error': 'invalid_hostname', 'type': 'LUA_ERROR', 'source': '[string "function main(splash, args)\r..."]', 'message': 'Lua error: [string "function main(splash, args)\r..."]:2: invalid_hostname', 'line_number': 2}
    /app/splash/browser_tab.py:1180:_return_reply
    /app/splash/qtrender_lua.py:901:callback
    /app/splash/lua_runner.py:27:return_result
    /app/splash/qtrender.py:17:stop_on_error_wrapper
    --- <exception caught here> ---
    /app/splash/qtrender.py:15:stop_on_error_wrapper
    /app/splash/qtrender_lua.py:2257:dispatch
    /app/splash/lua_runner.py:195:dispatch
    ]
2017-08-01 18:28:39.152883 [pool] [140711856519656] SLOT 0 is closing <splash.qtrender_lua.LuaRender object at 0x7ffa08477e48>
2017-08-01 18:28:39.152944 [render] [140711856519656] [splash] clearing 0 objects
2017-08-01 18:28:39.153026 [render] [140711856519656] close is requested by a script
2017-08-01 18:28:39.153304 [render] [140711856519656] cancelling 0 remaining timers
2017-08-01 18:28:39.153374 [pool] [140711856519656] SLOT 0 done with <splash.qtrender_lua.LuaRender object at 0x7ffa08477e48>
2017-08-01 18:28:39.153997 [events] {"user-agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "error": {"error": 400, "info": {"error": "invalid_hostname", "type": "LUA_ERROR", "source": "[string \"function main(splash, args)\r...\"]", "message": "Lua error: [string \"function main(splash, args)\r...\"]:2: invalid_hostname", "line_number": 2}, "type": "ScriptError", "description": "Error happened while executing Lua script"}, "active": 0, "status_code": 400, "maxrss": 107916, "qsize": 0, "path": "/execute", "timestamp": 1501612119, "fds": 18, "args": {"render_all": false, "http_method": "GET", "png": 1, "url": "http://boingboing.net/blog", "wait": 0.5, "html": 1, "response_body": false, "har": 1, "load_args": {}, "lua_source": "function main(splash, args)\r\n  assert(splash:autoload(\"https://code.jquery.com/jquery-3.1.1.min.js\"))\r\n  splash.resource_timeout = 30.0\r\n  splash.images_enabled = false\r\n  assert(splash:go(args.url))\r\n  assert(splash:wait(0.5))\r\n  return {\r\n    html = splash:html(),\r\n    --png = splash:png(),\r\n    --har = splash:har(),\r\n  }\r\nend", "resource_timeout": 0, "uid": 140711856519656, "save_args": [], "viewport": "1024x768", "timeout": 3600, "images": 1}, "client_ip": "172.17.0.1", "rendertime": 80.11527562141418, "method": "POST", "_id": 140711856519656, "load": [0.46, 0.51, 0.54]}
2017-08-01 18:28:39.154127 [-] "172.17.0.1" - - [01/Aug/2017:18:28:38 +0000] "POST /execute HTTP/1.1" 400 325 "http://localhost:8050/info?wait=0.5&images=1&expand=1&timeout=3600.0&url=http%3A%2F%2Fboingboing.net%2Fblog&lua_source=function+main%28splash%2C+args%29%0D%0A++assert%28splash%3Aautoload%28%22https%3A%2F%2Fcode.jquery.com%2Fjquery-3.1.1.min.js%22%29%29%0D%0A++splash.resource_timeout+%3D+30.0%0D%0A++splash.images_enabled+%3D+false%0D%0A++assert%28splash%3Ago%28args.url%29%29%0D%0A++assert%28splash%3Await%280.5%29%29%0D%0A++return+%7B%0D%0A++++html+%3D+splash%3Ahtml%28%29%2C%0D%0A++++--png+%3D+splash%3Apng%28%29%2C%0D%0A++++--har+%3D+splash%3Ahar%28%29%2C%0D%0A++%7D%0D%0Aend" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
2017-08-01 18:28:39.154237 [pool] SLOT 0 is available

If I try it without loading up JQuery first, I get a 'network5' LUA error (which is some species of timeout). Logs for that are as follows:
2017-08-01 18:31:07.110255 [-] "172.17.0.1" - - [01/Aug/2017:18:31:06 +0000] "GET /info?wait=0.5&images=1&expand=1&timeout=3600.0&url=http%3A%2F%2Fboingboing.net%2Fblog&lua_source=function+main%28splash%2C+args%29%0D%0A++--assert%28splash%3Aautoload%28%22https%3A%2F%2Fcode.jquery.com%2Fjquery-3.1.1.min.js%22%29%29%0D%0A++splash.resource_timeout+%3D+30.0%0D%0A++splash.images_enabled+%3D+false%0D%0A++assert%28splash%3Ago%28args.url%29%29%0D%0A++assert%28splash%3Await%280.5%29%29%0D%0A++return+%7B%0D%0A++++html+%3D+splash%3Ahtml%28%29%2C%0D%0A++++--png+%3D+splash%3Apng%28%29%2C%0D%0A++++--har+%3D+splash%3Ahar%28%29%2C%0D%0A++%7D%0D%0Aend HTTP/1.1" 200 5658 "http://localhost:8050/" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
2017-08-01 18:31:07.489653 [pool] initializing SLOT 1
2017-08-01 18:31:07.490576 [render] [140711856961016] viewport size is set to 1024x768
2017-08-01 18:31:07.490692 [pool] [140711856961016] SLOT 1 is starting
2017-08-01 18:31:07.490829 [render] [140711856961016] function main(splash, args)\r\n  --assert(splash:autoload("https://code.jquery.com/jquery-3.1.1.min.js"))\r\n  splash.resource_timeout = 30.0\r\n  splash.images_enabled = false\r\n  assert(splash:go(args.url))\r\n  assert(splash:wait(0.5))\r\n  return {\r\n    html = splash:html(),\r\n    --png = splash:png(),\r\n    --har = splash:har(),\r\n  }\r\nend
2017-08-01 18:31:07.493641 [render] [140711856961016] [lua_runner] dispatch cmd_id=__START__
2017-08-01 18:31:07.493782 [render] [140711856961016] [lua_runner] arguments are for command __START__, waiting for result of __START__
2017-08-01 18:31:07.493865 [render] [140711856961016] [lua_runner] entering dispatch/loop body, args=()
2017-08-01 18:31:07.493937 [render] [140711856961016] [lua_runner] send None
2017-08-01 18:31:07.494010 [render] [140711856961016] [lua_runner] send (lua) None
2017-08-01 18:31:07.494270 [render] [140711856961016] [lua_runner] got AsyncBrowserCommand(id=None, name='go', kwargs={'baseurl': None, 'http_method': 'GET', 'headers': None, 'body': None, 'url': 'http://boingboing.net/blog', 'errback': '<an errback>', 'callback': '<a callback>'})
2017-08-01 18:31:07.494416 [render] [140711856961016] [lua_runner] instructions used: 166
2017-08-01 18:31:07.494502 [render] [140711856961016] [lua_runner] executing AsyncBrowserCommand(id=0, name='go', kwargs={'baseurl': None, 'http_method': 'GET', 'headers': None, 'body': None, 'url': 'http://boingboing.net/blog', 'errback': '<an errback>', 'callback': '<a callback>'})
2017-08-01 18:31:07.494576 [render] [140711856961016] HAR event: _onStarted
2017-08-01 18:31:07.494697 [render] [140711856961016] callback 0 is connected to loadFinished
2017-08-01 18:31:07.495031 [network] [140711856961016] GET http://boingboing.net/blog
2017-08-01 18:31:07.495617 [pool] [140711856961016] SLOT 1 is working
2017-08-01 18:31:07.495741 [pool] [140711856961016] queued
2017-08-01 18:31:37.789845 [network-manager] timed out, aborting: http://boingboing.net/blog
2017-08-01 18:31:37.790154 [network-manager] Finished downloading http://boingboing.net/blog
2017-08-01 18:31:37.791064 [render] [140711856961016] mainFrame().urlChanged http://boingboing.net/blog
2017-08-01 18:31:37.796078 [render] [140711856961016] mainFrame().initialLayoutCompleted
2017-08-01 18:31:37.796343 [render] [140711856961016] loadFinished: RenderErrorInfo(type='Network', code=5, text='Operation canceled', url='http://boingboing.net/blog')
2017-08-01 18:31:37.796420 [render] [140711856961016] loadFinished: disconnecting callback 0
2017-08-01 18:31:37.796518 [render] [140711856961016] [lua_runner] dispatch cmd_id=0
2017-08-01 18:31:37.796576 [render] [140711856961016] [lua_runner] arguments are for command 0, waiting for result of 0
2017-08-01 18:31:37.796640 [render] [140711856961016] [lua_runner] entering dispatch/loop body, args=(PyResult('return', None, 'network5'),)
2017-08-01 18:31:37.796699 [render] [140711856961016] [lua_runner] send PyResult('return', None, 'network5')
2017-08-01 18:31:37.796765 [render] [140711856961016] [lua_runner] send (lua) (b'return', None, b'network5')
2017-08-01 18:31:37.796883 [render] [140711856961016] [lua_runner] instructions used: 175
2017-08-01 18:31:37.796943 [render] [140711856961016] [lua_runner] caught LuaError LuaError('[string "function main(splash, args)\\r..."]:5: network5',)
2017-08-01 18:31:37.797093 [pool] [140711856961016] SLOT 1 finished with an error <splash.qtrender_lua.LuaRender object at 0x7ffa083ff828>: [Failure instance: Traceback: <class 'splash.exceptions.ScriptError'>: {'error': 'network5', 'type': 'LUA_ERROR', 'source': '[string "function main(splash, args)\r..."]', 'message': 'Lua error: [string "function main(splash, args)\r..."]:5: network5', 'line_number': 5}
    /app/splash/browser_tab.py:533:_on_content_ready
    /app/splash/qtrender_lua.py:702:error
    /app/splash/lua_runner.py:27:return_result
    /app/splash/qtrender.py:17:stop_on_error_wrapper
    --- <exception caught here> ---
    /app/splash/qtrender.py:15:stop_on_error_wrapper
    /app/splash/qtrender_lua.py:2257:dispatch
    /app/splash/lua_runner.py:195:dispatch
    ]
2017-08-01 18:31:37.797158 [pool] [140711856961016] SLOT 1 is closing <splash.qtrender_lua.LuaRender object at 0x7ffa083ff828>
2017-08-01 18:31:37.797217 [render] [140711856961016] [splash] clearing 0 objects
2017-08-01 18:31:37.797310 [render] [140711856961016] close is requested by a script
2017-08-01 18:31:37.797430 [render] [140711856961016] cancelling 0 remaining timers
2017-08-01 18:31:37.797491 [pool] [140711856961016] SLOT 1 done with <splash.qtrender_lua.LuaRender object at 0x7ffa083ff828>
2017-08-01 18:31:37.798067 [events] {"user-agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0", "error": {"error": 400, "info": {"error": "network5", "type": "LUA_ERROR", "source": "[string \"function main(splash, args)\r...\"]", "message": "Lua error: [string \"function main(splash, args)\r...\"]:5: network5", "line_number": 5}, "type": "ScriptError", "description": "Error happened while executing Lua script"}, "active": 0, "status_code": 400, "maxrss": 113372, "qsize": 0, "path": "/execute", "timestamp": 1501612297, "fds": 21, "args": {"render_all": false, "http_method": "GET", "png": 1, "url": "http://boingboing.net/blog", "wait": 0.5, "html": 1, "response_body": false, "har": 1, "load_args": {}, "lua_source": "function main(splash, args)\r\n  --assert(splash:autoload(\"https://code.jquery.com/jquery-3.1.1.min.js\"))\r\n  splash.resource_timeout = 30.0\r\n  splash.images_enabled = false\r\n  assert(splash:go(args.url))\r\n  assert(splash:wait(0.5))\r\n  return {\r\n    html = splash:html(),\r\n    --png = splash:png(),\r\n    --har = splash:har(),\r\n  }\r\nend", "resource_timeout": 0, "uid": 140711856961016, "save_args": [], "viewport": "1024x768", "timeout": 3600, "images": 1}, "client_ip": "172.17.0.1", "rendertime": 30.308406591415405, "method": "POST", "_id": 140711856961016, "load": [0.39, 0.42, 0.49]}
2017-08-01 18:31:37.798190 [-] "172.17.0.1" - - [01/Aug/2017:18:31:37 +0000] "POST /execute HTTP/1.1" 400 309 "http://localhost:8050/info?wait=0.5&images=1&expand=1&timeout=3600.0&url=http%3A%2F%2Fboingboing.net%2Fblog&lua_source=function+main%28splash%2C+args%29%0D%0A++--assert%28splash%3Aautoload%28%22https%3A%2F%2Fcode.jquery.com%2Fjquery-3.1.1.min.js%22%29%29%0D%0A++splash.resource_timeout+%3D+30.0%0D%0A++splash.images_enabled+%3D+false%0D%0A++assert%28splash%3Ago%28args.url%29%29%0D%0A++assert%28splash%3Await%280.5%29%29%0D%0A++return+%7B%0D%0A++++html+%3D+splash%3Ahtml%28%29%2C%0D%0A++++--png+%3D+splash%3Apng%28%29%2C%0D%0A++++--har+%3D+splash%3Ahar%28%29%2C%0D%0A++%7D%0D%0Aend" "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"
2017-08-01 18:31:37.798294 [pool] SLOT 1 is available

If I additionally comment out the resource_timeout line, I get a network3 LUA error (again, invalid hostname, but this time presenting differently).
Any idea what I'm doing wrong?

A: As it turns out, it wasn't a Scrapy/Splash issue at all -- it was a Docker / IP route / network admin issue.  The network admins set it up so that I can only make HTTP requests through a particular destination; adding "--net=host" to my docker start-up seems to have fixed this.
This webpage was very helpful.

A: Try changing
function main(splash, args)
    ...
    assert(splash:go(args.url))
    ...

to
function main(splash)
    ...
    assert(splash:go(splash.args.url))
    ...

At least that's how it reads when I open Splash on port 8050 in the default script. With that change, your script works for me.


text:
Q: Does Clear() method of STL containers calls delete on heap objects?
Possible Duplicate:
Does std::vector.clear() do delete (free memory) on each element?

I have a map where second elements are heap allocated.
Shall I explicitly call delete while iterating or does method erase() and clear() do that for me?
Here is my destructor which erases second element that are allocated with new
        ~Event()
        {
            auto iter = mapper.begin();
            while (iter != mapper.end())
            {
                mapper.erase(iter++); // heap object
            }
        }

A: You will have to explicitly call delete on each new element.
Standard Library containers do not take ownership of the dynamic memory allocated to pointers.
You should use Smart pointers as container elements if you need automatic cleanup.

A: No, it won't. You have to call delete yourself (or use smart pointers).


text:
Q: Error Formulating Crash Report: dyld_process_snapshot_get_shared_cache failed after upgrading Flutter to 3.7.1, from the Ios emulator "Error Formulating Crash Report: I started getting the dyld_process_snapshot_get_shared_cache failed" error. Can you help on the subject?
MacBook Air M1
macOS Venture 13.2
Xcode 14.2


text:
Q: how to make bash/shell script that make a 'shortcut' for a command Write a shell script 'shortcut' that does the following: You
will need to use temporary files.
Associates the tag 'myls' with the command 'ls -lart'
dirk@linux /home/dirk> ./shortcut -a myls ls -lart

runs "ls -lart"
   dirk@linux /home/dirk> ./shortcut myls

delete myls
dirk@linux /home/dirk> ./shortcut -d myls
OK, shortcut 'myls' deleted.

show content of myls
dirk@linux /home/dirk> ./shortcut -l myls

Shortcut 'myls' = ls -lart
dirk@linux /home/dirk>

You will need to create an shortcuts associations file.
Call it ".shortcuts" in the current working directory.
I would like to put this into case/if elif statement, where I can put the 'command ls -lart' into 'myls', every i exec., ./shortcut -a myls ls -lart, the command 'ls -lart', will be inputted to 'myls', and when i run the 'myls' like, './shorcut myls', it will exec., the command on the 'myls'.. thanks

A: You can do the same using alias command. See alias man page for details
1) To associate:
alias myls='ls -lart'

2) You can use the command as myls. U can see existing aliases with alias -p. You can list myls as alias -p | grep myls
3) To delete myls:
unalias myls


text:
Q: Problem while using Replace function Python name = "RED BLUE"
rname = str(name).replace("R", "A")
rname = str(name).replace("E", "B")
rname = str(name).replace("D", "C")
rname = str(name).replace("B", "D")
rname = str(name).replace("L", "E")
rname = str(name).replace("U", "F")
rname = str(name).replace("E", "G")

print(rname)

It should give me an output saying:
ABC DEFG

But it didn't, I tried to search in Internet but it didn't not help so I came here.
Can anybody help me?
Thank you in advance.

A: As mentioned by @Patrick Artner you are not using rname but doing operations on name. Every time are reinitializing the rname variable also.
There is an elegant way to do this in python using str.translate
name = "RED BLUE"

name = name.translate(str.maketrans({'R': 'A',
                'E':'B',
                'D':'C',
                'B':'D',
                'L': 'E',
                'U': 'F',
                'E': 'G'}))
print(name)

'AGC DEFG'

A: you are overwriting the variable rname. just use:
name = "RED BLUE"
rname = name.replace(name , "ABC DEFG")


text:
Q: Get pointer to argv element Boost Program Options I'm making the assumption that the array of strings passed into the main function as argv in void main( int argc, char* argv[] ) remains in scope for the duration of the application.
My question is therefore whether it is possible, using boost::program_options to get a pointer to the actual element in argv which represents a particular option.
That is, rather than allocating a std::string when parsing, it is possible to just get a pointer to the start of a string option value.


text:
Q: On a type of equations that involve certain multiplicative functions and polynomials, in relation to their number of solutions Past weekend I was interested in the sequence A058891 from the On-Line Encyclopedia of Integer Sequences, from this, inspired by the equation due to Benoit Cloitre (2002) that shows the comments, I stated the following claim where for an integer $n\geq 1$ we denote the Euler's totient function as $\varphi(n)$, its number of divisors $\sum_{1\leq d\mid n}1$ as $\tau(n)$ and the product of distinct primes dividing to $n$ denoted by $$\operatorname{rad}(n)=\prod_{\text{primes }p\mid n}p$$
with the definition $\operatorname{rad}(1)=1$ (all these arithmetic functions are multiplicative).
Claim 1. Let $x=O_n=2^{2^{n-1}-1}$ (be a term of the sequence A058891), then for each integer $n>1$ we've that $x=O_n$ satisfies $$\operatorname{rad}(x)^{\tau(x)}=4^{\varphi(\tau(x))}.\tag{1}$$
Motivated by simple experiments with Pari/GP scripts, I wrote the following claims that seem similar, and that involve other sequences of integers: the known as Mersenne primes and Fermat primes.
Claim 2. Let $x=M_n=2^n-1$ be a Mersenne prime, then $x$ satisfies $$\operatorname{rad}(x+1)^{\tau(x+1)}=2\varphi(x)+4.\tag{2}$$
Claim 3. Let $x=F_n=2^{2^n}+1$ be a Fermat prime, then the identity $$\operatorname{rad}(x-1)^{\tau(x-1)}=2\varphi(x),\tag{3}$$
holds.

Question. I would like to know what is more plausible, if the existence of different $P(x)\neq Q(x)$ and positive polynomials  $P(x)>0$ and $Q(x)>0$ for all integer $x\geq 2$, with integer coefficients $P,Q\in\mathbb{Z}[X]$, and say the same degree $1\leq\deg P=\deg Q$ such that there exist positive constants $A\geq 1$ and $B\geq 0$ for which you can to prove, for one of such suitable choices, that the equation
$$\operatorname{rad}(P(x))^{\tau(P(x))}=A\varphi(Q(x))+B,\tag{E}$$ have infinitely many solutions, or well, for the same set of conditions for our polynomials and constants, the equation $\text{(E)}$ should to have finitely many solutions. If you want you can study this, answering, from a theoretical point of view, or providing examples of equations $\text{(E)}$ that have infinitelty many or finitely many solutions.
Many thanks.

Thus with the question what is more plausible (my English is bad) I am asking  about an answer that shows ditect examples, or well a discussion using your knowledges in number theory about if the equation of the form $\text{(E)}$ should to have infinitely many solutions for a a suitable proposal of constants $A$ and $B$ and polynomials $P(x)$ and $Q(x)$, or well if this problem should this problem should have only a finite number of solutions for any choice of constants and polynomials that satisfy previous conditions.


text:
Q: Combining $parent and $index in a foreach I have a view model that has two arrays. I want to iterate over one array and access the value at the same index on the other array, but it seems that you can't use $parent with $index. See here:
function viewModel(factors,models) {
    this.name="parent View model";
    this.factors = ko.observableArray(factors);
    this.models = ko.observableArray(models);
}

function subViewModel(name, array) {
    this.anotherArray = ko.observableArray(array);
    this.name = name;
}

ko.applyBindings(new viewModel(
    ["factor1","factor2"],
    [ new subViewModel("model1", ["foo","bar"]),
    new subViewModel("model2", ["one","two"])
]));

If you change $parent.factors()[$index] to $parent.factors()[0] it will display the right entry from the factors array. If you replace it with just $index, you get the right indexes. But if you combine them, it seems knockout isn't able to parse $index in an expression that already has $parent?
Anybody else seen this?
I know I could combine my arrays into a single array of a view model that combines the properties, but I have a reason for not doing that. This is part of a much more complex view model.

A: $index is an observable itself.
From the documentation:

This is the zero-based index of the current array entry being rendered
  by a foreach binding. Unlike the other binding context properties,
  $index is an observable...

So you need to write $index() if you are using it inside in an expression:

Demo JSFiddle.


text:
Q: Show $ f(x) = (\frac{2x+1}{2x+2})^{ x+\frac{1}{2} } $ then $f''(x)f(x) > {f'(x)}^{2}$ Function $f(x)$ is defined on $[0,\infty)$ as $f(x) = \left(\frac{2x+1}{2x+2}\right)^{ x+\frac{1}{2} } $.
problem is show that $f''(x)f(x) > {f'(x)}^{2}$
I was trying to get derivative of $f(x)$, but it was very hard and bored. How can I approach to show this inequality?

A: i have got $$f''(x)f(x)-(f'(x))^2=1/2\, \left(  \left( 1/2\,{\frac {2\,x+1}{x+1}} \right) ^{x+1/2}
 \right) ^{2} \left( x+1 \right) ^{-2} \left( 2\,x+1 \right) ^{-1}
$$ and this is positive in the given interval


text:
Q: If my web service allows the clients to do **deletes** using **POST** requests, is it still considered RESTful? If my web service allows the clients to do deletes using POST requests, is it still considered RESTful?

A: Strictly speaking I think that it is not, although I would still consider it RESTful.  There are times when it is not possible to use all of the HTTP verbs, this causes many REST APIs to allow other actions via either POST or GET.

A: I don't think the question should be whether the API is "RESTful" because that has become a buzzword.  A more important issue is whether this is a good use of the HTTP protocol, which is defined in RFC 2616.  Here is the relevant section: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html.
It says "The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line."  POSTs are normally used to create a new item in a collection or annotating existing resources.  While annotating something by deleting it isn't actually prohibited, and there are no issues of safety and idempotency to be violated, doing a delete on a POST is not using HTTP as it was intended.
That said, if you do a POST to modify and existing resource by "setting a delete flag" within the resource, you would be following modern RESTful API practice.  But to completely whack it?  No, that is what HTTP DELETE is for.

A: As there is no official RESTful standard, you're fine as long as the method 'override' is explicitly passed in a parameter, such as method=DELETE.

A: The short answer is no, although from a practical standpoint it might be easier for clients to implement, particularly if they are unsophisticated and don't know how to do a DELETE.
With that said, it's your web service, so you should do whatever best meets your business needs. A complete implementation of REST is much less important than great client documentation of how to operate your API.

A: No it isn't RESTful in the way that HTTP is intended to be. A way to allow clients that do not support DELETE or PUT to interact with resources that are designed to support them is to use a custom header that indicates which operation to perform. Then have a layer in your framework inspect that header and call the correct method in your resource code. The approach that I've seen used most widely is to use a header called X-HTTP-Method-Override. If the client cannot manipulate HTTP headers, then the same approach (event using the same name) can be used with a request parameter.


text:
Q: Picking a video, decoding it, changing its fps, encoding and saving using mediacodec Would like to pick a video from the device and decode it inorder to change its frame rate and then encode and save it to the device. How is this possible using MediaCodec? Went through many documentations, but couldn't find a method. I have the following code for decoding. Will it be of any good for my purpose. If yes how to use that decoded data to save it with changed fps.
 MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", 1080, 720);
            mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 2500000);
            mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 20);
            try {
                decoder = MediaCodec.createDecoderByType("video/avc");
            } catch (IOException e) {
                Log.d("Error", "Fail to create MediaCodec: " + e.toString());
            }

            ///Commenting for testing...
            /*
            // Pass the decoded data to the surface to display
            decoder.configure(mediaFormat, null, null, 0);
            //decoder.configure(mediaFormat, null, null, 0);
            decoder.start();

            */
            ///Commenting for testing...

            // new BufferInfo();

            ByteBuffer[] inputBuffers = decoder.getInputBuffers();
            ByteBuffer[] outputBuffers = decoder.getOutputBuffers();
            if (null == inputBuffers) {
                Log.d("Error", "null == inputBuffers");
            }
            if (null == outputBuffers) {
                Log.d("Error", "null == outbputBuffers 111");
            }

            FileInputStream file = null;
            try {
                file = new FileInputStream(data.getData().getPath().toString());
            } catch (FileNotFoundException e) {
                Log.d("Error", "open file error: " + e.toString());
                return;
            }
            int read_size = -1;
            int mCount = 0;

            for (; ; ) {
                byte[] h264 = null;
                try {
                    byte[] length_bytes = new byte[4];
                    read_size = file.read(length_bytes);
                    if (read_size < 0) {
                        Log.d("Error", "read_size<0 pos1");
                        break;
                    }
                    int byteCount = bytesToInt(length_bytes, 0);

                    //Changed to .length
                    //int byteCount=length_bytes.length;

                    Log.d("Error", "byteCount: " + byteCount);

                    h264 = new byte[byteCount];
                    read_size = file.read(h264, 0, byteCount);
                    // Log.d("Error", "read_size: " + read_size);
                    if (read_size < 0) {
                        Log.d("Error", "read_size<0 pos2");
                        break;
                    }
                    // Log.d("Error", "pos: " + file.)
                } catch (IOException e) {
                    Log.d("Error", "read_size 2: " + read_size);
                    Log.d("Error", "e.toStrinig(): " + e.toString());
                    break;
                }

                int inputBufferIndex = decoder.dequeueInputBuffer(-1);
                if (inputBufferIndex >= 0) {
                    ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
                    inputBuffer.clear();
                    inputBuffer.put(h264);
                    // long sample_time = ;
                    decoder.queueInputBuffer(inputBufferIndex, 0, h264.length, mCount * 1000000 / 20, 0);
                    ++mCount;
                } else {
                    Log.d("Error", "dequeueInputBuffer error");
                }

                ByteBuffer outputBuffer = null;
                MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
                int outputBufferIndex = decoder.dequeueOutputBuffer(bufferInfo, 0);
                while (outputBufferIndex >= 0) {
                    outputBuffer = outputBuffers[outputBufferIndex];
                    decoder.releaseOutputBuffer(outputBufferIndex, true);
                    outputBufferIndex = decoder.dequeueOutputBuffer(bufferInfo, 0);
                }

                // Pass the decoded data to the surface to display
                decoder.configure(mediaFormat,mPreview.getHolder().getSurface() , null, 0);
                //decoder.configure(mediaFormat, null, null, 0);

                decoder.start();

                if (outputBufferIndex >= 0) {
                    decoder.releaseOutputBuffer(outputBufferIndex, false);
                } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
                    outputBuffers = decoder.getOutputBuffers();
                    Log.d("Error", "outputBufferIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED");
                } else if (outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                    // Subsequent data will conform to new format.
                    Log.d("Error", "outputBufferIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED");
                }

                try {
                    Thread.sleep(1000/20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
    }
}
public int bytesToInt(byte[] src, int offset) {
    int value;
    value = (int) ((src[offset] & 0xFF)
            | ((src[offset+1] & 0xFF)<<8)
            | ((src[offset+2] & 0xFF)<<16)
            | ((src[offset+3] & 0xFF)<<24));
    return value;
}

A: You can take a look at DecodeEditEncode, a great starting point for decoding and re-encoding using surfaces (output surface for decoder -> input surface for encoder).
Take a look especially  at this method
private void editVideoData(VideoChunks inputData, MediaCodec decoder,
            OutputSurface outputSurface, InputSurface inputSurface, MediaCodec encoder,
            VideoChunks outputData)

The working flow that you have to follow is similar to bellow:

*

*Extract video track (MediaExtractor)

*Feed the decoder input buffers

*render the decoded frame to the surface

*When rendered, the encoder will get the frame (you have to set timestamp too)

*Use MediaMuxer to mux the encoder frame with audio track.

Extra links : some examples
ExtractDecodeEditEncodeMuxTest
VideoResample.java (very interesting)


text:
Q: How can I handle conditional callbacks in javascript while keeping it DRY? I have been playing with NodeJS lately and i found myself stuck with a regular pattern issue :
I have a main operation running on, depending on some config parameters, i need to perform an extra step, but this step is async :
    if(request.config.save) {

        fs.writeFile(request.config.save, decryptedData, function(err) {
            // Continue the operation with a callback...
            // Perform some other ops.
            if(typeof callback == 'function') callback(decryptedData);
        }.bind(this));

    } else {

        // Continue the same operation without a callback
        // Perform some other ops.
        if(typeof callback == 'function') callback(decryptedData);

As you can see this code is not DRY as the main ending (callback) is called twice.
Only way I see is to use functions (but once again the function call is not DRY... And code could be really bloated this way...
So is there a pretty ninja trick to solve this?

A: Well, a single line of code isn't all that repetitive, but if you're doing more than that it can get very non-dry. What about just wrapping your final logic into a function, and calling that inside your conditionals?
var endTick = function(){
    if(typeof callback == 'function') callback(decryptedData);
}

if(request.config.save) {

    fs.writeFile(request.config.save, decryptedData, function(err) {
        // Continue the operation with a callback...
        // Perform some other ops.
        endTick();
    }.bind(this));

} else {

    // Continue the same operation without a callback
    // Perform some other ops.
    endTick();
}

A: function cb() {
   if (typeof arguments[0] === 'function')
      arguments[0].apply(null, Array.prototype.slice.call(arguments,1));
}

Shouldn't be more than around 10 characters longer (might have to bind) than a normal function call without the typeof check, and assuming no bind it shouldn't be more than 4.
There is no way to solve this without paying some price, somewhere.


text:
Q: Close button in qt4 not working Here is my code:
self.retranslateUi(MainWindow)
    QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8("clicked()")), self.destroy)

When i run my program it says:

File "myui.py", line 52
      QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8("clicked()")), self.destroy)
      ^
  IndentationError: unexpected indent

A: Are you using PySide or PyQt? You should be using new-style signals and slots, either way.
For me, or anybody for that matter to give a more useful answer you should really provide more details - more code, what you've tried already that didn't work, etc. Make sure you've correctly defined destory(), it's in-scope or imported or whatever, and switch to new-style signals/slots. Shouldn't be too hard from there.
Hope that helps.


text:
Q: What permissions should I give /var and /media? I understand that magento says to have /var and /media at 700 for folders and 600 for files but when I do this, it breaks certain parts of my site. I am curious to see what permissions most people use for these folders.

A: While Phil's solution is good I use a little bit different approach. In addition to making the "php/webserver user" owner of files I create additional group. Usually it's called dev. And I add "php user" and myself and other developers to that group dev. Then I do chgrp so that all files in Magento project subtree have group dev.
I add +s bit to folders that ensures the newly created subfolders get the same permissions.
I've created a public gist with my fix_permissions.sh script. Feel free to use it:) It helps you to keep your whole Magento project subtree with good permissions.
https://gist.github.com/svenvarkel/8062778#file-fix_permissions-sh
The original question - var and media must have such permissions that "php user" can read and write to these folders. It must be able to write cache, session files etc under var and it must be able to write product image cache and images under media. So do as Phil advises: chown or chgrp these to "php user" and give rw permissions to "php user".
I think it's more correct to refer to "php user" in context of FPM (CGI). Webserver user can be different of that one that's running PHP.

A: I haven't see many mentions of using 700 and 600 but it is generally good advice. Unfortunately every server set up is different and needs to be weighed up against convenience (user access to update/edit files).
The underlying approach should be to only give away as little as possible and lock it down as much as you can (700/600 is good for this). In that respect the "official" advice on the wiki wants to apply to as many circumstances as possible and suggests read permissions for everyone (which means any compromised other service on the server will then for example be able to read app/etc/local.xml with your db configuration).
In your case it currently sounds like the files are owned by a different user than what your webserver/php process runs under. Changing the ownership of the files to the webserver should solve your original issue.
Please note that using 700 / 600 and assigning the files to the webserver means your normal user would not be able to edit the files.
The below I feel is a good compromise for convenience vs lock down. All files are owned by user:webservergroup
var and media 770 / 660
The server and your user is allowed to read and write from the var and media folders (session/cache/images).
the rest 750 / 640
Your user is able to edit/update the code.
The webserver is able to read the files for execution/display.

A: In general all files should be 644 and all folders should be 755 and should be owned by the user your web server runs under. The mage executable should be given 550 permissions to allow execution.
This shell script should patch things up if run from your Mage root:
#!/bin/sh
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod 550 mage

Source: http://www.magentocommerce.com/wiki/groups/227/resetting_file_permissions

A: /var - magento use to write cache, session etc data.
/media - magento use to updload product image, category image (any type of image).
So these two folders you should have to use read+write permission. Other file you should to use read+execution permission.

A: File permission is 644. Run below code in the root directory using ssh.
find .
-type f -exec chmod 644 {} \;

Folder permission is 755. Run below code in the root directory using ssh.
find .
-type d -exec chmod 755 {} \;

Var folder permission is 777. Run below code in the root directory using ssh.
chmod -R 777 var

Static folder permission is 777. Run below code in the root directory using ssh.
chmod -R 777 pub/static

Media folder permission is 777. Run below code in the root directory using ssh.
chmod -R 777 pub/media

A: From here:
http://devdocs.magento.com/guides/m1x/install/installer-privileges_after.html
find . -type f -exec chmod 400 {} \;
find . -type d -exec chmod 500 {} \;
find var/ -type f -exec chmod 600 {} \;
find media/ -type f -exec chmod 600 {} \;
find var/ -type d -exec chmod 700 {} \;
find media/ -type d -exec chmod 700 {} \;
chmod 700 includes
chmod 600 includes/config.php


text:
Q: Get page content that required authentication in PHP I want to get the content of page which required authentication (username and password ) , i can only access this page using valid username and password , i want to access this page using php library. can you please suggest a method or library using which i can access this page. Thanks .

A: Try this:
//CHANGE THIS
$username='YOUR_USERNAME';
$password='YOUR_PASSWORD';
$location='http://YOUR_ADDRESS/YOUR_FILE.php';

$ch = curl_init ();
curl_setopt($ch,CURLOPT_URL,$location);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
curl_setopt($ch, CURLOPT_TIMEOUT, 10);

$result = curl_exec ($ch);


text:
Q: Keyed Collection in Python? Is there any equivalent to KeyedCollection in Python, i.e. a set where the elements have (or dynamically generate) their own keys?
i.e. the goal here is to avoid storing the key in two places, and therefore dictionaries are less than ideal (hence the question).

A: You can simulate that very easily:
class KeyedObject(object):
    def get_key(self):
        raise NotImplementedError("You must subclass this before you can use it.")

class KeyedDict(dict):
    def append(self, obj):
        self[obj.get_key()] = obj

Now you can use a KeyedDict instead of dict with subclasses of KeyedObject (where get_key return a valid key based on some object property).

A: Given your constraints, everyone trying to implement what you're looking for using a dict is barking up the wrong tree. Instead, you should write a list subclass that overrides __getitem__ to provide the behavior you want. I've written it so it tries to get the desired item by index first, then falls back to searching for the item by the key attribute of the contained objects. (This could be a property if the object needs to determine this dynamically.)
There's no way to avoid a linear search if you don't want to duplicate something somewhere; I am sure the C# implementation does exactly the same thing if you don't allow it to use a dictionary to store the keys.
class KeyedCollection(list):
     def __getitem__(self, key):
         if isinstance(key, int) or isinstance(key, slice):
             return list.__getitem__(key)
         for item in self:
             if getattr(item, "key", 0) == key:
                 return item
         raise KeyError('item with key `%s` not found' % key)

You would probably also want to override __contains__ in a similar manner so you could say if "key" in kc.... If you want to make it even more like a dict, you could also implement keys() and so on. They will be equally inefficient, but you will have an API like a dict, that also works like a list.

A: I'm not much of a C#'er, but I think dictionaries is what you need.
http://docs.python.org/tutorial/datastructures.html#dictionaries
http://docs.python.org/tutorial/datastructures.html
Or maybe lists:
http://docs.python.org/library/functions.html#list

A: @Mehrdad said:

Because semantically, it doesn't make as much sense. When an object
  knows its key, it doesn't make sense to put it in a dictionary -- it's
  not a key-value pair. It's more of a semantic issue than anything
  else.

With this constraint, there is nothing in Python that does what you want.  I suggest you use a dict and not worry about this level of detail on the semantics.  @Gabi Purcaru's answer shows how you can create an object with the interface you want.  Why get bothered about how it's working internally?
It could be that C#'s KeyedCollection is doing the same thing under the covers: asking the object for its key and then storing the key for fast access. In fact, from the docs:

By default, the KeyedCollection(Of TKey, TItem) includes a lookup
  dictionary that you can obtain with the Dictionary property. When an
  item is added to the KeyedCollection(Of TKey, TItem), the item's key
  is extracted once and saved in the lookup dictionary for faster
  searches. This behavior is overridden by specifying a dictionary
  creation threshold when you create the KeyedCollection(Of TKey,
  TItem). The lookup dictionary is created the first time the number of
  elements exceeds that threshold. If you specify –1 as the threshold,
  the lookup dictionary is never created.

A: Why not simply use a dict?  If the key already exists, a reference to the key will be used in the dict; it won't be senselessly duplicated.
class MyExample(object):
    def __init__(self, key, value):
        self.key = key
        self.value = value

m = MyExample("foo", "bar")
d = {}

d[m.key] = m

first_key = d.keys()[0]
first_key is m.key  # returns True

If the key doesn't already exist, a copy of it will be saved, but I don't see that as a problem.
def lame_hash(s):
    h = 0
    for ch in s:
        h ^= ord(ch)
    return h

d = {}
d[lame_hash(m.key)] = m
print d  # key value is 102 which is stored in the dict

lame_hash(m.key) in d  # returns True

A: I'm not sure if this is what you meant, but this dictionary will create it's own keys as you add to it...
class KeyedCollection(dict):
    def __init__(self):
        self.current_key = 0
    def add(self, item):
        self[self.current_key] = item

abc = KeyedCollection()
abc.add('bob')
abc.add('jane')
>>> abc
{0: 'bob', 1: 'jane'}

A: How about a set()? The elements can have their own k

A: To go a little more in detail that the already correct answer from @Gabi Purcaru's answer, here a class that do the same as gabi one's but that also check for correct given type on key and value (as the TKey and TValue of the .net KeyedCollection).
class KeyedCollection(MutableMapping):
    """
    Provides the abstract base class for a collection (:class:`MutableMappinp`) whose keys are embedded in the values.
    """
    __metaclass__ = abc.ABCMeta
    _dict = None  # type: dict

    def __init__(self, seq={}):
        self._dict = dict(seq)

    @abc.abstractmethod
    def __is_type_key_correct__(self, key):
        """
        Returns: The type of keys in the collection
        """
        pass

    @abc.abstractmethod
    def __is_type_value_correct__(self, value):
        """
        Returns: The type of values in the collection
        """
        pass

    @abc.abstractmethod
    def get_key_for_item(self, value):
        """
        When implemented in a derivated class, extracts the key from the specified element.
        Args:
            value: the element from which to extract the key (of type specified by :meth:`type_value`)

        Returns: The key of specified element (of type specified by :meth:`type_key`)
        """
        pass

    def __assert_type_key(self, key, arg_name='key'):
        if not self.__is_type_key_correct__(key) :
            raise ValueError("{} type is not correct".format(arg_name))

    def __assert_type_value(self, value, arg_name='value'):
        if not self.__is_type_value_correct__(value) :
            raise ValueError("{} type is not correct".format(arg_name))

    def add(self, value):
        """
        Adds an object to the KeyedCollection.
        Args:
            value: The object to be added to the KeyedCollection (of type specified by :meth:`type_value`).
        """
        key = self.get_key_for_item(value)
        self._dict[key] = value

    # Implements abstract method __setitem__ from MutableMapping parent class
    def __setitem__(self, key, value):
        self.__assert_type_key(key)
        self.__assert_type_value(value)
        if value.get_key() != key:
            raise ValueError("provided key does not correspond to the given KeyedObject value")
        self._dict[key] = value

    # Implements abstract method __delitem__ from MutableMapping parent class
    def __delitem__(self, key):
        self.__assert_type_key(key)
        self._dict.pop(key)

    # Implements abstract method __getitem__ from MutableMapping parent class (Mapping base class)
    def __getitem__(self, key):
        self.__assert_type_key(key)
        return self._dict[key]

    # Implements abstract method __len__ from MutableMapping parent class (Sized mixin on Mapping base class)
    def __len__(self):
        return len(self._dict)

    # Implements abstract method __iter__ from MutableMapping parent class (Iterable mixin on Mapping base class)
    def __iter__(self):
        return iter(self._dict)
        pass

    # Implements abstract method __contains__ from MutableMapping parent class (Container mixin on Mapping base class)
    def __contains__(self, x):
        self.__assert_type_key(x, 'x')
        return x in self._dict


text:
Q: Visual UI Automation Verify shows DisconnectedItem in ContextMenu (WPF) Stackoverflow.
I've looked through a good amount of questions\answers, and still not found the clue to the issue I'm facing in Visual UI Automation Verify (2.0).
I have a ContextMenu in TreeList (DevExpress control):
<dxg:TreeListControl.ContextMenu>
                <ContextMenu x:Name="TreeListContextMenu" DataContext="{Binding Path=Data, Source={StaticResource Proxy}}" ItemsSource="{Binding Path=Data.SelectedItemContextMenuItemCollection, Source={StaticResource Proxy}}"/>
            </dxg:TreeListControl.ContextMenu>

I have a simple binding proxy, like this one declared with the following code:
<dataStructures:BindingProxy x:Key="Proxy" Data="{Binding}" />

DataContext of the User Control and DataContext of the ContextMenu are bound to Data property on the proxy (because ContextMenu doesn't belong to the same visual tree).
In the non-shared MenuItem style I'm assigning the value from Data property of the proxy to the attached property of the MenuItem:
<Setter Property="helpers:ParentControlDataContextBindingHelper.ParentControlDataContext" Value="{Binding Path=Data, Source={StaticResource Proxy}}" />

The reason it's done this way:
In the tree there are various objects. Each object might have different ContextMenu item list based on object's certain property value. I'm handling the "ContextMenuOpening" event by routing it to the Command:
<i:Interaction.Triggers>
                        <i:EventTrigger EventName="ContextMenuOpening">
                            <prism:InvokeCommandAction Command="{Binding ContextMenuOpeningCommand}"/>
                        </i:EventTrigger>
<i:Interaction.Triggers/>

In ContextMenuOpeningCommand command I'm clearing and then filling up SelectedItemContextMenuItemCollection (which consists of MenuItem Visual Models - binding sources for Header, Command and Icon for the MenuItem) based on the property of the SelectedItem
When the context menu is called the first time - it appears on Visual UI Automation Verify (with the correct ContextMenuItem headers), but it can't be tested after it is closed - its contents in Visual UI Automation Verify are DisconnnectedItems. If I call next ContextMenu on the different type of element and the list of ContextMenu items is different - Visual UI Automation Verify doesn't show even headers of the menu items (the headers are empty because DataContext of menu item is DisconnectedItem after menu closes). If I'm using "hardcoded" ContextMenu with all bindings and items in XAML - everything is ok.
I'm not sure if this behavior is actually by design or not. Is it possible to test ContextMenu with non-static items collection with Visual UI Automation Verify? Inspect.exe in WindowsKits behaves the same way. What's more important - how I can get around that to be able to test the menu with VisualUIAVerify?


text:
Q: How to keep subsets disjoint? Given positive integers $n$ and $k\le 2^n$, how to choose a subset $C\subset\{0,1\}^n$ of size $|C|=k$ to maximize the number of pairs $(c_1,c_2)\in C\times C$ with the supports of $c_1$ and $c_2$ disjoint (in other words, with $c_1$ and $c_2$ orthogonal)? If $k=1+n+...+\binom ns$, should one choose $C$ to be the set of all vectors with at most $s$ coordinates equal to $1$?
Some equivalent restatements:

*

*How to choose a family of $k$ subsets of a fixed $n$-element set to maximize the number of pairs of disjoint subsets?

*How to choose a binary code of length $n$ and size $k$ to maximize the number of pairs of codewords with disjoint supports?

*How to choose a simplicial complex on $n$ vertices with $k$ faces to maximize the number of pairs of disjoint faces?
(For the last restatement observe that the optimal set $C$ is monotonic, aka "downset".)

UPDATE
As indicated by Sergey Norin (see his answer below), this problem originates from a question of Erdos, and is considered in a 1985 paper by Alon and Frankl. However, establishing a rather strong result for $k$ "small", their paper does not give any information in the case where $k=2^{\gamma n}$ with $\gamma>1/2$.
DISCUSSION There is interesting phenomenon here which seems to be unexplored as yet. For (roughly) $k<2^{n/2+\epsilon}$, a construction from Alon-Frankl shows that the number of pairs can be $\Omega(k^2)$ for a suitable choice of $C$. However, for $k>2^{\gamma n}$ with $\gamma>1/2$, this construction does not work. Indeed, it is not difficult to show that for $k$ "large" the situation breaks in the sense that $\Omega(k^2)$ cannot give the right order of magnitude any longer. It is quite possible that in this case, the set of all vectors with small support is optimal, exhibiting a kind of threshold behavior.

A: As far as I know, a paper of Alon and Frankl "The Maximum Number of Disjoint Pairs
in a Family of Subsets" (available here) contains state of the art knowledge on the problem.
Briefly outlining some of its conclusions, let me mention that for a wide range of values of $k$ keeping the sets in $C$ supported on disjoint subsets of $[n]=\{1,2,\ldots,n\}$ works much better than keeping them individually small. For example, for even $n$ and $k=2^{n/2 +1}-1$, if we choose $C$ to consist of sets of smallest possible size than typical set in $C$ will have size $\Omega(n/\log{n})$ and two such sets almost surely intersect. On the other hand, if we choose $A$ to be the set of all subsets of $\{1,\ldots,n/2\}$, $B$ to be the set of all subsets $\{n/2+1, \ldots, n\}$ and $C =A \cup B$, then at least half of the pairs of sets in $C$ are disjoint. Solving a problem of Erdős, Alon and Frankl show that this example is essentially the best possible.


text:
Q: error message while installing R Markdown on R version 4.0.1 on Windows I am new to R and trying to install R Markdown on RStudio but it keeps giving me error messages eg
Warning in install.packages :
  package '(tools)' is not available (for R version 4.0.1)
Warning in install.packages :
  unable to access index for repository https://cran.rstudio.com/bin/windows/contrib/4.0:
  cannot open URL 'https://cran.rstudio.com/bin/windows/contrib/4.0/PACKAGES'

A: Are you sure you have internet? try install.packages("Rmarkdown", dep = TRUE) you may also need to install latex for your system


text:
Q: Очистка вывода в командной строке В общем, есть следующая ситуация:
Существует программа, выводящая нечто несколько раз посредством System.out.print().
Как можно очистить консоль (появляющуюся после запуска java %имя%) от вывода?
Пробовал сделать так:
Runtime runtime = Runtime.getRuntime();
    try {
        Process process = runtime.exec("cls");
    }
    catch (Exception e) {}

- не работает.
Также пытался таким образом:
Runtime.getRuntime().exec("cls");

Ничего, как и в первом случае не вышло.

A: Чтобы заработало в Windows вам следует запустить процесс и прикрепить текущий потоки ввода вывода к нему, тогда должно все получиться:
new ProcessBuilder("cmd", "/c", "cls")
                                      .inheritIO()
                                      .start()
                                      .waitFor();


text:
Q: Exponential Regression Line in R I was plotting some data and was trying to plot exponential regression line through the data points. I have done quite a bit research on how to do that, and finally came across an instruction that I could understand and perform. However, when I continued to use the same method for other plots, the regression line did not seem to fit the data points. I could not figure out why. Can i get some help please?
This link is where i found the instruction.
Below are my codes and results:
exponential.model <- lm(A~log(B), AB)
bvalues <- seq(0,180,0.1)
exponential <- predict(exponential.model, list(B = bvalues))
plot(A~B, AB, log="y")
lines(bvalues, exponential, lwd = 2, col = "red")

exponential.model <- lm(C~log(D), CD)
dvalues <- seq(0,1380,0.1)
exponential <- predict(exponential.model, list(D = dvalues))
plot(C~D, CD, log="y")
lines(dvalues, exponential, lwd = 2, col = "red")

A: I think that your code is fine.  Your problem is just that the exponential model is not an adequate model for the data, and the fit is rather poor.


text:
Q: Get Distribution Group Members I'm simply trying to get a list of users/email addresses that are members of a given Exchange Distribution Group.
It's a Mail Universal Distribution Group, and it does have members. (I double checked)
Per the MSDN examples I've found, this is the code I am using.
I always get back an exception of "No results found". Not a 'normal" message saying it found nothing, an actual exception.
_service is my Exchange Service (which is working properly).
It errors out on the ExpandGroup line.
    try
    {
        // Return the expanded group.

        Microsoft.Exchange.WebServices.Data.ExpandGroupResults myGroupMembers = _service.ExpandGroup(distributionListMember).;

        // Display the group members.
        foreach (Microsoft.Exchange.WebServices.Data.EmailAddress address in myGroupMembers.Members)
        {
            Console.WriteLine("Email Address: {0}", address);
            //listBox1.Items.Add(address.Address);
        }
    }
    catch (Microsoft.Exchange.WebServices.Data.ServiceResponseException ex)
    {
        MessageBox.Show(ex.Message);
    }
    catch (Exception)
    {

        MessageBox.Show(ex.Message);
    }

Is there something I'm missing? This group is not a Dynamic Distribution Group nor a Mail Universal Security Group. 100% Mail Universal Distribution Group.

A: This is a known Microsoft Exchange Server 2010 issue.

This issue occurs because the ExchangeService.ExpandGroup method that
EWS uses does not expand the Dynamic Distribution Group when it tries
to determine the list of members.

To resolve this issue, install the following update rollup:
2608646 Description of Update Rollup 6 for Exchange Server 2010 Service Pack 1

Note: There is a full stop at the end of this line which I think shouldn't be there.
_service.ExpandGroup(distributionListMember).;


text:
Q: Javascript convert time to get different between windows and linux I converted time value at client side, when I tested it from same browser:chrome on linux and windows.
windows:
    var d = new Date(1995,9,1,1,15,0,0)
    d
    Sun Oct 01 1995 01:15:00 GMT+1300 (New Zealand Daylight Time)
    d.getTime()
    **812463300000**
    var d = new Date(1995,9,1,3,15,0,0)
    d
    Sun Oct 01 1995 03:15:00 GMT+1300 (New Zealand Daylight Time)
    d.getTime()
    **812470500000**

linux :
 var d = new Date(1995,9,1,1,15,0,0)
   d
   Sun Oct 01 1995 01:15:00 GMT+1200 (NZST)
   d.getTime()
   **812466900000**
   var d = new Date(1995,9,1,3,15,0,0)
   d
   Sun Oct 01 1995 03:15:00 GMT+1300 (NZDT)
   d.getTime()
   **812470500000**

The problem is the server which installed at same linux pc will get different milliseconds value which I convert at client side, the next step is the server convert the value with server timezone to string value.
I know it should be resolved by converting the string value at server side, but if I must convert it at client side, anyone can give me a correct direction to resolve this problem.
Thanks

A: Don't depend on the client (end user) clock -- get the time on the server as you said.
Always use GMT / UTC and only convert it to a local time when you're displaying it to a person.

A: The date:
var d = new Date(1995,9,1,1,15,0,0)

will be converted to a local time using the current system settings. To make everything consistent, send the UTC time since epoch from the server and convert that, e.g.:
new Date(812463300000); // Sat Sep 30 22:15:00 UTC+1000 1995

will create a date object for exactly the same instant regardless of where the server is located or what the system settings are.


text:
Q: Time complexity of greedy algorithm Good morning,
I'm trying to find a way to calulate time complexity (average and worst) of greedy algorithm. I know that final formula is: O(nlogn + n) which is O(nlogn). I will appreciate any suggestion/hints how I can calculate this.
Regards

A: Because the greedy algorithms can be conclude as follows:
Initially let R be the set of all requests,and let A be empty
While R is not yet empty
    Choose a request iR that has the smallest finishing time
    Add request i to A
    Delete all requests from R that are not compatible with request i
EndWhile
Return the set A <is the set of accepted requests

Therefore, the running time of it is consist of:

*

*Sorting the n requests in order, which costs O(nlogn).

*Constructing the array containing sorted requests, which costs O(n).

*Iterating through the intervals in the array, which costs O(n).
Actually, the second and the third step can often be merged into one step. Thus, the running time of the algorithm is O(nlogn).
(References: Jon,Kleinberg, and Éva,Tardos. Algorithm Design)


text:
Q: Auto commit and auto push changes in local repo to git I have a local development system where I have a Ubuntu-Server VM and I use eclipse in windows host. I develop in eclipse using Remote System Explorer & SSH. I want that whenever I save a file or do some changes in ubuntu-server's /var/www/site-folder it automatically commits and pushes the changes in my git repo. I did try the google but it wasn't much of a help. Any help is appreciated guys. Really wanna improve my workflow.

A: This sounds like something you'll have to script. If you save as much as I do (a lot), then you'll end up with a lot of commits. Unless you're careful about when you save, you'll probably end up with a messy history, unless you squash things later.
Are you sure that you want to commit and push automatically every time you save? It also matters whether or not you're pushing to your own private branch or repo.

A: Actually I think there are use cases where this /is/ a good idea.  If you work on two different machines (even not simultaneously), for instance, you cannot share the Eclipse workspace.  One simple way to overcome this is to put a bare git repository on a cloud server (dropbox, copy, one drive, etc) and push all work, completed or otherwise, to that everytime you close eclipse.
Will the repo be messy?  Sure, but that's not the point.
I could find no easy hooks within Eclipse itself to automate this so I simply put an invocation of Eclipse in a script and finished off with:
git commit -a -m "WIP commit"
git push origin

You just have to watch out for newly-created files and remember to add those before you exit.


text:
Q: sum by hours/days/month based on timestamp in mongoengine/pymongo At first - I am a beginner with mongodb. So i have next probleb. I am using such a model as below with mongoengine:
class Stats(Document):
    Name = StringField(max_length=250)
    timestamp = LongField(default=mktime(datetime.now().timetuple()))
    count = IntField()
    <some other fields>

What exactly I want is to filter by the name (it's clear) and use aggregation operation sum over field count. But I want to count the sum of records grouped by hours/days/months.
As example, if we have records with such timestamps [1532970603, 1532972103, 153293600, 1532974500], then 1-2 form first group, and 3-4 form second group.
And that is where I have stuck. I have some ideas about grouping by every n records, or by dividing timestamp on 3600
(1 hour = 3600 seconds), but how to make it with mongoengine. Or even how to insert some expressions with python in a pipeline?
I will very appreciate any help.

A: I would recommend to use ISO date format and store complete date in timestamp. Here is your model
class Stats(Document):
    Name = Document.StringField(max_length=250)
    timestamp = Document.DateTime(default=datetime.utcnow()) //ISO time format recommended
    count = Document.FloatField()
    meta = {'strict': False}

Now you can aggregate them accordingly.
Stats.objects.aggregate(
    {
        '$group': {
            '_id': {'year': {$year: '$timestamp'},
                    'month': {$month: '$timestamp'},
                    'day' : {$dayOfMonth: '$timestamp'},
                    'hour': {'$hour: '$timestamp'},
            }
        }
    }
)


text:
Q: How to load input from keyboard into an array in 8086? I am practicing Input and Output of strings in assembly language - 8086 environment. I came across the following code:
 org 100h

 .DATA

 SNAME DB 21,0,22 DUP('$')
 .CODE

 MOV AH, 0AH
 LEA DX, SNAME

 INT 21H
 MOV AH, 9H
 LEA DX, SNAME +2;
 INT 21H
 ret

I know the program accepts input as a string from the keyboard and displays it on the screen. However,I am  missing two things here:

*

*How do we tell that the user input is to be stored in variable SNAME? Does the instruction LEA make the program know that? I have asked this because in high level languages we could say SNAME=someUserInput; - here I am not seeing an MOV SMANE,someUserInput;

*Why are we adding 2 in this instaruction LEA DX,SNAME +2?

A:
How do we tell that the user input is to be stored in variable SNAME?

Because your program uses the DOS input function 0Ah that requires you to setup a buffer to recieve the inputted characters. The byte at offset 0 must specify how many bytes you got available starting at offset 2. Specifying 21 means that you'll be able to input 20 characters. The extra byte will be filled with a carriage return (ASCII 13).

Why are we adding 2 in this instaruction LEA DX,SNAME +2?

The DOS input function stores the inputted characters starting at offset 2 within the buffer that you specified. At offset 1 you'll find a byte containing the number of characters that were inputted. Behind these inputted characters DOS adds a carriage return (ASCII 13). This means that printing the way you did will inevitably leave the cursor at the start of the line.


text:
Q: Error al intentar coger una array en Firebase RealTIme Tengo el problema que cuando intento coger una array de firebase realtime, no me entra al método, no se si hago mal algo.
En firebase tengo esta array

Intento de coger los datos de la siguiente manera :
  fun getFirebaseCategory() {
        categorias = ArrayList()
        val database = Firebase.database.reference
        Log.d("Categorias", "En categorias")
        database.child("categorias").addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (snapshot in dataSnapshot.children) {
                    categorias.add(snapshot.getValue(String::class.java)!!)
                    categorias.forEach {
                        Log.d("Categorias", "la lista de categorias es : $it")
                    }
                }
            }
            override fun onCancelled(error: DatabaseError) {
                Log.d("Categorias", "Error : loadPost:onCancelled $error")
            }
        })
    }

El problema que tengo es que me entra en el primer log(En categorías) pero en los demás no.

A: están bien los métodos, el fallo se debe a que han de importar implementaciones adicionales en el Gradle
implementation platform('com.google.firebase:firebase-bom:26.3.0')
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-database-ktx'
implementation 'com.google.firebase:firebase-storage-ktx'
implementation 'com.google.firebase:firebase-auth'
implementation 'com.google.firebase:firebase-firestore-ktx:23.0.0'


text:
Q: PHP/AJAX Why is my getAttribute only targeting the first line in the foreach code So what I'm trying to do here is to show a list of users. In this list, each user has a button that sends two Ids to my database which is different for every user in the array. I send this data with an ajax call which you can see below.
The problem is, that the code only works for the first user in the list and not the others. My guess is that it is not working properly because every list item has the same id name so it only targets the first item with the .getelementbyid selector.
So my question is if there is any other way to make the buttons send the ids for each user individually.
I have tried using the .sibling selector but I'm not really sure how to implement it correctly.

        <?php foreach ($module as $row) :?>

                    ▾Show More
                    ▴ Show Less

<p id="post" data-id="<?php echo $row['id'] ?>"><?php echo $row['naam'] ?>

<?php echo $row['beschrijving'] ?>

                                <?php foreach ($patient as $row2): ?>

                                                <p class="text-left border-bottom post2" id="post2" data-id="<?php echo $row2['id'] ?>"><?php echo $row2['voornaam'].' '.$row2['achternaam'];?>

                                                <input id="btnSubmit" type="submit" value="Module toewijzen"/>

                                <?php endforeach; ?>

        <?php endforeach; ?>

$(document).ready(function () {
    $("#btnSubmit").on("click", function (e) {
        console.log("clicked");

        // tekst vak uitlezen
        var module_id = document.getElementById("post").getAttribute("data-id");
        var user_id = document.getElementById("post2").getAttribute("data-id");
        // via AJAX update naar databank sturen
        $.ajax({
            method: "POST",
            url: "AJAX/clientmodule.php",
            data: {user_id: user_id,module_id: module_id} //update: is de naam en update is de waarde (value)

        })

            .done(function (response) {

                // code + message
                if (response.code == 200) {

                }
            });

        e.preventDefault();
    });
});

A: The issue is because you're duplicating the same id within HTML output by the loop. That's invalid.
Use classes to group elements instead. You can then use DOM traversal to find the elements related to the clicked button and retrieve their values before sending the AJAX request.
Also note that if you use the success property of $.ajax then you don't need to check that the response code is 200 as it's guaranteed. It's also more robust as a 204 is also a valid response, but would technically not be caught in your original logic.
Finally, you were using a mix of jQuery and native methods where it's best to stick to only one or the other. To get the data-id attributes of the elements you can use data().
With all that said, try this:
$(function() {
  $(".btnSubmit").on("click", function(e) {
    e.preventDefault();

    var $container = $(this).closest('.col-md-8');
    var module_id = $container.find(".post").data('id');
    var user_id = $container.find(".post2").data('id');

    $.ajax({
      method: "POST",
      url: "AJAX/clientmodule.php",
      data: {
        user_id: user_id,
        module_id: module_id
      },
      success: function() {
        // callback logic here...
      }
    });
  });
});

    <?php foreach ($module as $row) :?>

          ▾Show More
          ▴ Show Less

          <p class="post" data-id="<?php echo $row['id'] ?>">
            <?php echo $row['naam'] ?>

              <?php echo $row['beschrijving'] ?>

          <?php foreach ($patient as $row2): ?>

                  <p class="text-left border-bottom post2" data-id="<?php echo $row2['id'] ?>">
                    <?php echo $row2['voornaam'].' '.$row2['achternaam'];?>

                  <input class="btnSubmit" type="submit" value="Module toewijzen" />

          <?php endforeach; ?>

    <?php endforeach; ?>

A: Thanks that definitely helped me in the right direction. with your code, all the buttons started working but I still had the problem that it only posted the ids from the first line.
this is how I eventually solved it:
$(function() {
    $(".btnSubmit").on("click", function(e) {
        e.preventDefault();
        console.log("clicked");

        var $container = $(this).closest('.col-md-10');
        var module_id = $container.closest('.col-md-8').find(".post").data('id');
        var user_id = $container.find(".post2").data('id');

        console.log("module : "+module_id);
        console.log("user : "+user_id);

         $.ajax({
            method: "POST",
            url: "AJAX/clientmodule.php",
            data: {
                user_id: user_id,
                module_id: module_id
                },
        success: function() {
    // callback logic here...
          }
      });
   });
});