text:
Q: CCC and point separating weight CCC means countable chain condition;
A cover $\cal A$ of  a set $E$ is separating if for each $p\in E$, $\bigcap \{A: A \in \mathcal{A}, p\in A\}=\{p\}.$ The point separating weight of $X$, denoted $psw(X)$, is the smallest infinite cardinal $\kappa$ such that $X$ has a separating open cover $\cal V$ with ord$(p, \cal V)\le \kappa$ for each $p\in X$.
Let $X$ be a CCC space and has countable point separating weight. Is the cardinality of $X$ always at most $2^\omega$?
Thanks for any help:)

A: $\newcommand{\supp}{\operatorname{supp}}$The cardinality of the space can by arbitrarily large.
Let $\kappa$ be any infinite cardinal. Let $\varphi:[\kappa]^{<\omega}\to\kappa$ be any injection with the property that $\varphi(F)\notin F$ for each $F\in[\kappa]^{<\omega}$. For each $\xi<\kappa$ let $X_\xi$ be a copy of $[0,1]$, and let $X=\prod_{\xi<\kappa}X_\xi$, with the product topology. For $F\in[\kappa]^{<\omega}$ let
$$X_F=\left\{x\in X:x_{\varphi(F)}=1\text{ and }\forall\xi\in F\Big(x_\xi\in(0,1)\Big)\text{ and }\forall\xi\in\kappa\setminus\big(F\cup\{\varphi(F)\}\big)(x_\xi=0)\right\}\;.$$
Finally, let $$Y=\bigcup_{F\in[\kappa]^{<\omega}}X_F$$
with the subspace topology inherited from $X$, and for each $x\in Y$ let $\supp(x)$ be the unique $F\in[\kappa]^{<\omega}$ such that $x\in X_F$.
Let $\mathscr{I}=\{(p,q):p<q\text{ and }p,q\in\Bbb Q\cap(0,1)\}$, and let $\mathscr{J}=\{(p,1]:p\in\Bbb Q\cap(0,1)\}.$ For each $F\in[\kappa]^{<\omega}$, function $I:F\to\mathscr{I}$, and $J\in\mathscr{J}$ let
$$B(F,I,J)=\left\{x\in Y:\forall\xi\in F\Big(x_\xi\in I(\xi)\text{ and }x_{\varphi(F)}\in J\Big)\right\}\;,$$
and let $$\mathscr{B}=\left\{B(F,I,J):F\in[\kappa]^{<\omega}\text{ and }I:F\to\mathscr{I}\text{ and }J\in\mathscr{J}\right\}\;;$$ clearly $\mathscr{B}$ is an open cover of $Y$. Suppose that $x\in B(F,I,J)\in\mathscr{B}$. Then $x_\xi\ne 0$ for each $\xi\in F\cup\{\varphi(F)\}$, so $F\cup\{\varphi(F)\}\subseteq\supp(x)$, and it follows immediately that $\operatorname{ord}(x,\mathscr{B})=\omega$. It's also clear that for each $x\in Y$ we have $\bigcap\{B\in\mathscr{B}:x\in B\}=\{x\}$, so $\operatorname{psw}(Y)=\omega$.
Finally, $X$ is a product of separable spaces, so $c(X)=\omega$, and $Y$ is dense in $X$, so $c(Y)=\omega$ as well.


text:
Q: List row and count from another tables in SQL I have the following tables:
___Support
SUP_Id | SUP_Message
-------+------------
1      | Lorem...
2      | Ipsum...

___SupportMessage
SUM_Id | SUM_TicketId
-------|-------------
60     | 1
61     | 1
62     | 1
63     | 1
64     | 2
65     | 2

I need to list all the tickets contained in ___Support and count the ticket messages (stored in ___SupportMessages) I have for each ticket.
I should have :

*

*4 messages for ticket # 1

*2 messages for ticket # 2

My actual try is the following:
SELECT *,
    COUNT(
        SELECT *
        FROM ___SupportMessages
        WHERE ___SupportMessages.SUM_TicketId = ___Support.SUP_Id
)
FROM ___Support

Thanks.

A: Close.  Put the count() in the select:
SELECT s.*,
      (SELECT COUNT(*)
       FROM ___SupportMessages sm
       WHERE sm .SUM_TicketId = s.SUP_Id
      )
FROM ___Support s

A: you can achieve this by below
 select count(SUM_Id),SUM_TicketId from ___SupportMessage where SUM_TicketId in (select
 SUP_Id from ___Support) group by SUM_TicketId

A: select sm.SUP_Message, count(*) as [count]
from ___Support sm
join ___SupportMessage st
  on sm.SUP_Id = st.SUM_TicketId
group by sm.SUP_Message

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert documents in collection from array of objects in Meteor I have an array dataRows consisting of multiple objects, e.g.
{
  'The Name': 'John',
  'My Age': 44,
  'My Address': 'Some street',
  [...]
}

I want to insert these objects into a collection.
Since I could just use MyCollection.insert( object ), I guess I can just insert the objects directly into a collection; however, the problem is that the keys in my objects are differently named than the field names in my collection and I don't want to insert all of the fields in my collection.
I could just do this:
dataRows.forEach( function ( row ) {
  MyCollection.insert( {
    name: row['The Name'],
    age: row['My Age'],
    address: row['My Address'],
  } );
} )

but I think it would be better if I could manipulate the array dataRows directly.
Besides, I don't want to skip fields with empty values.
Edit
I have an array
[
  {
    'The Name': 'John',
    'My Age': 44,
    'My Address': 'Some street',
    [...]
  },
  {
    'The Name': 'Michael',
    'My Age': 57,
    'My Address': '',
    [...]
  },
  {
    'The Name': 'Anne',
    'My Age': 31,
    'My Address': 'Some other street',
    [...]
  },
  [...]
]

I want to manipulate the array, so the keys can be renamed (e.g. The Name should be name, My Age should be age, etc.), fields with no value should be removed (e.g. the second object in the array has a key My Address with an empty value. The key should be removed from this object), and I want which keys should be kept and the rest of the keys should be remove (e.g. all objects in the array should have fields name, age, address and all other fields should be removed from each object.
I guess I should use array.map(), array.filter(), etc.
I hope it clarifies my question.

A: You can still manipulate the array using the forEach() method and within the loop take advantage of using a write commands Bulk API that allows for the execution of bulk insert operations which are simply abstractions on top of the server to make it easy to build bulk operations, thus streamlining your inserts. These bulk operations come mainly in two flavours:

*

*Ordered bulk operations. These operations execute all the operation in order and error out on the first write error.

*Unordered bulk operations. These operations execute all the operations in parallel and aggregates up all the errors. Unordered bulk operations do not guarantee order of execution.

You can get raw access to the collection and database objects in the npm MongoDB driver through rawCollection and rawDatabase methods on Mongo.Collection. For example, manipulate the array using forEach(), construct the object to be inserted within the loop, send the insert operations in batches for improved write perfomances as follows:
MyCollection = new Meteor.Collection("mycollection");

if (Meteor.isServer) {
    Meteor.startup(function () {
        Meteor.methods({
            insertData: function() {
                var bulkOp = MyCollection.rawCollection().initializeUnorderedBulkOp(),
                    counter = 0,
                    dataRows = [...]; // the raw array

                dataRows.forEach(function(row) {
                    var data = {
                        name: row['The Name'],
                        age: row['My Age'],
                        address: row['My Address'],
                    };
                    bulkOp.insert(data);

                    counter++;
                    if (counter % 1000 == 0) {
                        // Execute per 1000 operations and re-initialize every 1000 update statements
                        bulkOp.execute(function(e, rresult) {
                            // do something with result
                        });
                        bulkOp = MyCollection.rawCollection().initializeUnorderedBulkOp();
                    }
                });

                // Clean up queues
                if (counter % 1000 != 0){
                    bulkOp.execute(function(e, result) {
                        // do something with result
                    });
                }
            }
        });
    });
}


text:
Q: Run Apache / PHP / MySQL (CakePHP) application on a USB stick? I have an existing CakePHP that runs on a LAMP environment and need to install it on a USB drive for mass public distribution.
There are a few requirements:

*

*Protect the source code

*No installation required

*Windows support essential

*MAC & Linux would be a bonus

*Must run offline, without Internet connection

*Ability to sync with server for data transfer and updates

I have conducted a large amount of research into the options and am keen to learn what other developers think.
Potential solutions:
 - Flash / XML
 - Adobe AIR app
 - USB webserver (Server2Go, Portable Apps XAMPP)
Has anyone used any of the above, any comments would be greatly appreciated.
Thanks

A: Similar thread here :
Portable USB Webserver
If you ask me, XAMPP should do, because it offers a "plain unzip" version. There's lots of variety out there - Bitnami also offers a nice bunch of stacks, although they may not be good for this particular task.
To keep the same scripts in both Windows and Linux, you could consider using UnxUtils which is a port of all common Linux commands. This will be very handy if you are good at Linux bash shell scripting but not good at Windows batch files.
Protecting the source code is a bit troublesome. Do you really, really need to do so? Because there's a ton of great open source code out there which already does practically everything in most common business domains - sourceforge.net.
And if someone's taking your code and calling it their own, you can just name them on the internet if you can prove it. That itself will be bad publicity for them. That said, I obviously don't know your specific need. So that is just my opinion.

A: You will have problems with this, no matter how you go about it.  Each step is a little more unusual it seems.
You'll need to use a source code obfuscator to protect your source.  I recommend the one by Zend, not from experience, but because Zend makes awesome products.  Never used a source protector myself.
You'll need three custom LAMP/MAMP/XAMP installs, one for each target OS.  They should point to a directory that is shared on the USB drive.  Make sure you configure them to use an unprotected port, otherwise the user will need admin privileges to run the server software.  And getting the server stuff up and running will likely result in a few hiccups as well.
I would actually recommend finding something that will allow you to distribute a binary, or something like an AIR app that is intended for this type of distribution.  You may have to rewrite lots of code, but it'll be easier to fix than all the niggling little install errors you'll see on the client end.  To package scripts into binaries without rewriting stuff, check out http://www.scriptol.com/apollo.php and similar products.
But I'd suggest you make a standalone app in adobe air that will sync with your server (maybe even some google gears integration, to have it function offline).  Don't try to force a PHP app into this distribution model, it'll create nightmarish problems.

A: You can use MAMP for Mac, you'll just need to edit the config to properly point the sites directory.
however you would have the problem that the mysql db would not necessarily work with windows. if you switched the db to sqlite, you could sync the sqlite db file fairly easily.
XAMPP would work for the windows side
sorry dont know about the linux side.

A: Out there is a CakePHP InstaWeb Server
http://bakery.cakephp.org/articles/view/the-cakephp-instaweb-webserver
that runs on python and doesn't need an installation. This plus some additional goodies should get you already half the way.

A: This is what I used to run a CakePHP app from a DVD. Worked on USB too (while I was still developing it).
http://www.server2go-web.de/

Server2Go is a Webserver that runs out of the box without any installation and on write protected media. This means that web applications based on Server2Go can be used directly from cdrom, a usb stick or from any folder on a hard disk without the hassle of configuring Apache, PHP or MySQL.
  Server2Go allows you to create a standalone working web site or PHP application on a CD-ROM.

It's really nice.


text:
Q: How to do a jquery http post request to an API? I have some problems to understand how I have to do to save a new user  with myKeyVals  username : "bruno", password : "login" to the API.
I have tried to use the code bellow, and It is displaying an alert"Save Compplete", but where have I saved  username : "bruno", password : "login"?
How can I do a jquery post request to an API, with url: http://192.168.8.143/api/v11/login/?username=ith&password=ithith (I can open the file url local)?
Can somebody gice me a hint?
var myKeyVals = { username : "bruno", password : "login"}

var saveData = $.ajax({

    type: 'POST',
    url: "http://192.168.8.143/api/v11/login/?username=ith&password=ithith",
    data: myKeyVals.toString(),
    dataType: "text",
    success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });

A:
You should not convert the object myKeyVals to string.
So your code should look like:
var myKeyVals = {
    username : 'bruno',
    password : 'login'
};

var jqxhr = $.ajax({
    type: 'POST',
    url: 'http://192.168.8.143/api/v11/login/?username=ith&password=ithith',
    data: myKeyVals,
    dataType: 'json'
});

jqxhr.done(function(data, textStatus, jqXHR) {
    console.log('Succeed:', data);
});

jqxhr.fail(function(jqXHR, textStatus, errorThrown) {
    console.log('Failed:', errorThrown);
});

Update (server side):
From the server side you should answer with valid JSON string.
As you said in comments you use PHP on the server so the example could look like:
<?php
$response = array("success" => true,);
header('Content-Type: application/json');
echo json_encode($response);

A: Hmm, I could be wrong but it seems that you're passing username and password twice: one in data and another in the url via GET "?username=ith&password=ithith" ?
Try this:
var myKeyVals = { username : "bruno", password : "login"};

var saveData = $.ajax({

    type: 'POST',
    url: "http://192.168.8.143/api/v11/login/",
    data: myKeyVals,
    success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });


text:
Q: Python: how to access list of dictionary and matching the value of key element I have a list of dictionary like this, I want to loop through all the "message" value and then if the value match  "App init" , then i will sys.exit(0) if the "message" value match "Error" I will sys.Exit(1).
But the problem is I don't see  the code match the( log[index]['message'] in 'App init') conditon since I don't see the printout "haha The application is running".
I am new in python, can someone tell me what went wrong? I have been googling for some time, and trying different approach, but it doesn't work.....
log =    [{'timestamp': 1666791137689, 'level': 'ALL', 'message': '10-26 14:54:33.389  7768  7793 D EGL_emulation: app_time_stats: avg=16.67ms min=15.85ms max=17.49ms count=60'},
    {'timestamp': 1666791137689, 'level': 'ALL', 'message': '10-26 14:54:34.390  7768  7793 D EGL_emulation: app_time_stats: avg=15.44ms min=14.40ms max=16.90ms count=60'},
    {'timestamp': 1666791137689, 'level': 'ALL', 'message': '10-26 14:54:35.406  7768  7793 D EGL_emulation: app_time_stats: avg=15.54ms min=11.85ms max=17.15ms count=61'},
    {'timestamp': 1666791137689, 'level': 'ALL', 'message': '10-26 14:54:35.654   218  7685 I keystore2: keystore2::watchdog: Watchdog thread idle -> terminating. Have a great day.'},
    {'timestamp': 1666791137689, 'level': 'ALL', 'message': '10-29 05:04:01.873 Default [Info ] App init'}]

message_list = []
for index in range(len(log)):
        message_list.append(log[index]['message'])
        print(log[index]['message'])

        if(log[index]['message'] in 'App init'):
            print("haha The application is running" + log[index]['message'])
            sys.exit(0)
        elif(log[index]['message'] in 'ERROR'):
            print("haha The application is having ERROR" + log[index]['message'])
            sys.exit(1)

with open('message_log.txt', 'w') as f:
    f.write(str(message_list))

A: log[index]['message'] in 'App init' should be reversed: 'App init' in log[index]['message']. The same for ERROR


text:
Q: PAGINATION PROBLEM ON MODELS CREATED WITH ELEMENTOR I'm currently working on a site on which I've created models with elementor's theme builder. After using my template and enabling pagination in a layout on an elementor page, I noticed that pagination doesn't work. When I want to see the other pages it reloads the first page each time.
Please help me to solve this problem please.
Thank you

A: Hello this is work for me.
Drag HTML widget to your page and paste :
code
Source Discussion


text:
Q: Get employees birthdays within next 3 days including today in Laravel I'm truing to get the employees that have birthday within next 3 days. I tried to do that by using the following query.
public function upcomingBirthdays()
{
    $from = now()->format('m-d');
    $to = now()->addDays(3)->format('m-d');

    $employees = Employees::whereRaw("DATE_FORMAT(dob, '%m-%d') BETWEEN '{$from}' AND '{$to}'")
                          ->where('team_id', 13)
                          ->where('status', 1)
                          ->orderBy('dob', 'DESC')
                          ->get();

    return view('frontend.employee.birthdays', compact('employees'));
}
// End Method

But this is not returning expected data.
Today is 2022-11-09
This is returning employees with birthdays between 2022-11-08 and 2022-11-10. But not returning employees that have birthdays on 11-11 and 11-12.

A: The problem is probably related with the date formatting. Using DD instead of d you get a leading zero for single digit day of the month. Same for month: use MM instead of m.
Note: This will still fail for birthdays falling on January 1, 2 and 3.

A: You probably need a Carbon package from nesbot to handling date.
I haven't tested querying within date with built-in PHP but my code works with Carbon package.
So, on your case, try this:
$employees = Employee::whereBetween('dob', [Carbon::now(), Carbon::now()->addDay(3)])->get();

A: The solution that finally worked for me:
$employees = Employees::where('team_id', 13)
                        ->where('status', 1)
                        ->where(function($q){
                            $q->where('dob', 'like', '%' . Carbon::now()->format('m-d'))
                            ->orWhere('dob', 'like', '%' . Carbon::now()->addDays()->format('m-d'))
                            ->orWhere('dob', 'like', '%' . Carbon::now()->addDays(2)->format('m-d'))
                            ->orWhere('dob', 'like', '%' . Carbon::now()->addDays(3)->format('m-d'))
                            ->orderBy(DB::raw("DATE_FORMAT(dob,'%m-%d')"), 'ASC');
                        })
                        ->get();


text:
Q: KnockoutJS - Using custom bindings to add animation I'd like to make use of custom bindings to display a progress icon (spinner or bar) whilst a price is being updated via an ajax call.
Before I started using Knockout I just called onUpdating() at the start of my ajax method and then onUpdated(price) when the ajax successfully returned a price.
function onUpdating() {
    $(".price").empty().html('');
}

function onUpdated(price) {
    $(".price").empty().html('£' + price);
}

As I'm now using Knockout I'd like to use the custom bindings but I just cant get my head around how it works.
I guess something like this:
    ko.bindingHandlers.showProgress = {
        init: function (element, valueAccessor) {
            $(element).empty().html('');
        },
        update: function (element, valueAccessor) {
            $(element).empty().html('£' + valueAccessor());
        }
    }

    Price:

However, this doesn't work at all. Any help greatly appreciated.
EDIT
The following seems to be getting there but its not showing the progress bar whilst updating:
    ko.bindingHandlers.showProgress = {
        update: function (element, valueAccessor) {
            $(element).empty().html('');
            var value = ko.utils.unwrapObservable(valueAccessor());
            $(element).empty().html('£' + value);
        }
    }

A: I think that an easy way to handle this one is to add something like a loading sub-observable to the observable that you are updating.  Then, set loading to true when you are starting your AJAX request.  Set loading to false when your data arrives.
Then, you can bind the visibility of your image to yourobservable.loading.
Here is a sample: http://jsfiddle.net/rniemeyer/kyaKc/
Also, one tip about your custom bindings:  The binding's update function will only run again when any of the observables that have their value accessed are updated.  So, in your case it would only run when price is updated.  You could set the price to null before your AJAX request, then in your binding show the loading image when the value is null, otherwise show the actual value of your observable (which you would have updated when your AJAX request succeeded).


text:
Q: How to mock a method of the same class? In the testing method, there are methods of the same class. How to mock the methods of the same class?
An example is as follows.
I am testing method2. It involves method1 which is in the same class. How to mock this method1?
public class A
{
  public void method1(int a, int b){

  }

  public void method2(){

      int value = method1(10,20);
  }
}

A: You can use a Spy to do this, in combination with doReturn to stub out the method for which you want to provide canned behavior.  There are many examples available on how to use a spy.  Check out these tutorials and documentation:

*

*Mockito: mocking a method of same class called by method under test when using @InjectMocks

*https://www.baeldung.com/mockito-spy

*Mockito: Trying to spy on method is calling the original method
Example:
   List list = new LinkedList();
   List spy = spy(list);

   //Use doReturn to change the behavior of a method call
   doReturn("foo").when(spy).get(0);


text:
Q: How to add new line inside I am doing a jsp code where need to iterate a foreach and need to dispaly value of that list in new line.
<c:forEach var="customer"  varStatus="status" items="${customerForm.customerAccessForm.customerDetails}">
<c:if test="${empty customer.hasPin}">
 <c:set var="name" value="${name}{customer.name}"/> ----<%-- trying concatinate the name of the customer who does not have any pin and later we will print it.-->
</c:forEach>

But I want it to print each customer in the next line.Its coming in same line now. How to do that I don't know.
Please post your suggestion.


text:
Q: C, calloc automatically takes care of overflow? matrix* make_matrix(size_t width, size_t height, size_t k, options opt){

    matrix *m= malloc(sizeof(matrix));
    if(m==NULL) return NULL;

    m->width = width;
    m->height = height;
    m->k = k;

    /*
    Since m->data is a int **, it points to int *,
    so I have to allocate a number of int *-sized objects to store in it.
    */
    //m->data = malloc(sizeof(int *)*height);
    m->data = calloc(height, sizeof(int*));

    if(m->data == NULL){
        free(m);
        return NULL;
    }

    for(size_t i=0; i < height; i++){
        //m->data[i] = malloc(sizeof(int)*width);
        m->data[i] = calloc(width, sizeof(int));

        if(m->data[i] == NULL){
            for(size_t j = 0; j < i; j++) free(m->data[j]);
            free(m->data);
            free(m);
            return 0;
        }
        /*
        for(size_t j = 0; j < width; j++){
            m->data[i][j] = 0;
        }*/
    }

    return m;
}

I am generating an 2d array and I used malloc instead of calloc. And it turned out that this is going to be a sparse matrix where most of the elements will be zero. So I decided to use calloc. My question is that do I stil need to keep the if statement
        if(m->data[i] == NULL){
            for(size_t j = 0; j < i; j++) free(m->data[j]);
            free(m->data);
            free(m);
            return 0;
        }

I wrote this because malloc doesn't take care of the stack over flow issue so in case of it fails then I have to free those blocks in reverse order. Do I still keep this code with calloc?

A: Yes. calloc can (and will) fail just as hard as malloc.

A: This is not a case of "stack overflow", as you are allocating objects on the heap.
The if is required for both malloc and calloc. What it does is that if you fail half-way through your allocation, it will delete the parts you already have allocated. The order is not important.


text:
Q: run adhoc wait_for with delegate_to my Makefile has the following steps
   create:
       do create stuff
       # extra ansible adhoc command to wait for ssh

   setup:
       do other stuff

I'd like to add a step after do create stuff that waits until all hosts have their ssh port accesible, but i dont want to have to commit an extra playbook that just does this:
  - hosts: all
    tasks:
      - name: wait for ssh port
        wait_for:
          host: '{{ ansible_ssh_host }}'
          port: 22
          timeout: 300
        delegate_to: localhost

I've tried using an adhoc command that will run the command above but with local action
ansible all -i inventory -m local_action -a 'wait_for port=22 timeout=300'

but thats not correct cause
ERROR! this task 'local_action' has extra params, which is only allowed in the following modules: command, win_command, shell, win_shell, script, include, include_vars, add_host, group_by, set_fact, raw, meta

A:
my Makefile has the following steps
create:
   do create stuff
   # extra ansible adhoc command to wait for ssh

From comments:

*

*So you want to check whether all the target servers are pingable or not ? – Shasha99

*Not pingable. Ssh-able.

I have no clue why you want to employ Ansible to do this. Here's a simple bash loop (add an outer one to iterate over your hosts):
for i in {1..30}; do
  ssh $host true 2> /dev/null
  if [ $? -eq 0 ]; then
    exit
  else
    sleep 10
  fi
done

A: @Shasha99's suggestion worked for me to verify that wait_for works the way I expect:
ansible --inventory=PATH -m wait_for -a 'host=IP port=PORT delay=10 timeout=300' 127.0.0.1


text:
Q: Need help to understand this code to find the position of 1's in a given number The following code helps us in finding position of the one bits in a given number:
    int n = in.nextInt();
    for (int d = 30; d >= 0; d--){
        if (n << ~d < 0){
            System.out.print(d + " ");
        }
    }

For example: If n = 5, its binary representation is 101 and the 1s are at the 0th and 2nd positions, so the output will be 2 0.
Some more examples:
n        Output
8        3
149      7 4 2 0

I am unable to understand the meaning of this code:
n << ~d < 0.

I know the concept of right shift and compliment but want to know how this specific expression evaluates to a negative number when n has a bit set at position d.

A: This code is trickier than it looks and looks like it's designed to use bitwise operations in places where simpler arithmetic operations might be a bit clearer.
Because integers in Java are represented in the signed two's-complement representation, taking the bitwise complement of a number is equivalent to negating it and adding one. Restated mathematically:

~x = -x + 1

This means that the code
n << ~d

is equivalent to
n << (-d + 1).

Now that's weird, because that would mean that you're left-shifting by a negative amount... which doesn't make much sense. This is where we need to go to the Java Language Specification on the subject, which says the following about a left-shift:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

In other words, the shift operation completely ignores everything except the bottom five bits of the numeric value. This means that we're not actually shifting by a negative amount - we're shifting by a positive amount, and the specific amount depends on the lowest five bits of the quantity ~d. (I'm switching back to using complement rather than negative values, since at this point it seems like the arithmetic interpretation of ~d might not be all that useful.)
If we take the number d, flip all the bits, then just focus on the lowest five bits, it ends up being equivalent to evaluating 31 - d. To see this, notice that 31 has binary representation 11111, so if we start with 11111 and subtract out the number d, then every 1 bit gets flipped to a 0 (1 - 1 = 0) and every zero bit gets flipped to a 1 (1 - 0 = 1). In other words, the expression
n << ~d

is completely equivalent - in this context - to
n << (31 - d)

because d is always between 0 and 31.
This now gives us more of a clue what's going on here. Remember that in a signed 32-bit representation of an integer, the very first bit of the integer is the sign bit. If it's 1, the value is negative, and if it's 0, the value is nonnegative. So if we take n and shift it forward 31 - d positions, then we're pushing the dth bit of the number into the very first bit position (play around with this a bit if it's not clear why). If the dth bit is a 1, then this sets the sign bit and makes the number negative, and if the dth bit is a 0 this sets the sign bit to zero and makes the number nonnegative. This is why
(n << ~d) < 0

tests whether the bit is set - it's checking whether the 1 bit in the original position triggers the sign bit in the resultant number.
Having said all this, I feel like this is way more complex than it needs to be. It's probably clearer to test the bit directly by masking off everything else and seeing if anything's left:
if ((n & (1 << d)) != 0)

which is (probably) a bit easier to read.


text:
Q: How to filter REST API JSON result by passing params I'm trying to consume JIRA 2 API and trying to get custom fields. I want to further filter by passing appropriate criteria in URI itself. Current query I'm using is something similar to this:
http://localhost:8522/jira522/rest/api/2/issue/createmeta?expand=projects.issuetypes.fields

The result I'm getting from above request is about 2000 lines.. How can I further filter to get only Custom_fields and also under custom fields I need to only the ones which are required?
I'm pretty new to REST API. Please guide me If anything is wrong... TIA. I spent a lot of time browsing but don't know what exactly I need to search for or where exactly I need to get started.

A: You can use another queryParam just like expand and add further filtering or pagination.
http://localhost:8522/jira522/rest/api/2/issue/createmeta?expand=projects.issuetypes.fields&limit=1000


text:
Q: How to set custom xhr header with PJAX? I'm trying to set a custom header with pJax so I can render things on the server side. Per the pjax docs, I can use pjax:beforeSend to set xhr headers.
Getting the following error:
typeerror xhr.setrequestheader is not a function

The code i've tried:
$(document).on('pjax:beforeSend', function(xhr) {
    if ($(event.target).data('rendertimeline') !== undefined) {
        xhr.setRequestHeader('X-RENDERTIMELINE', 'true');
    }
});

basically, i'm adding a data attribute to certain links and would link to check for that attribute. if its there, send a custom HTTP header along side the standard HTTP_X_PJAX header. Seemed fairly simple but i'm coming up short somewhere.

A: Looks like you have started using PJAX recently first argument is not xhr but event object add that and it should work.Don't know why they skipped it in docs but most events like start,end etc will have event as their first argument .
$(document).on('pjax:beforeSend', function(event,xhr, options)


text:
Q: KML balloon height style in Google Maps I'm trying to limit the description balloon height in the following KML for use with Google Maps. In Google Earth, this is achieved by using the style element of a div wrapper, so the following KML works fine. However, when referenced via Google Maps, the height attribute is stripped out resulting in a large balloon when the maker is clicked.
<?xml version="1.0" encoding="utf-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Placemark>
    <name>Test Mark</name>
    <description>
       <![CDATA[

Row 1	some data

Row 2	some data

Row 3	some data

Row 4	some data

Row 5	some data

Row 6	some data

Row 7	some data

Row 8	some data

Row 9	some data

Row 10	some data

Row 11	some data

Row 12	some data

Row 13	some data

Row 14	some data

Row 15	some data

Row 16	some data

Row 17	some data

Row 18	some data

Row 19	some data

Row 20	some data

Row 21	some data

Row 22	some data

Row 23	some data

      ]]>
    </description>
    <Point>
    <coordinates>1,23</coordinates>
    </Point>   </Placemark> </kml>

Here is how the KML looks in Google Maps
In my project, it is feasible that the tables I'm creating in the balloon description's could be quite long, so I need to make the balloon contents scrollable.

A: Just swap height for max-height like so:


text:
Q: Run a couple of C# commands with a different user I have a winform C# application that needs to have access to different folders. To access each folder, I have to use different credentials.
I need to read the content the files inside the folders. The user who is running the application even doesn't have access to the check folders exists.
in other words
File.Exists

doesn't function due to lack o permission for the current user, which means to check the existence of folder I have to run File.Exists command by another user.
Is there any way to run a couple of C# commands with a user then a couple of other lines with other users?
Please note that I don't want to create a temp batch file then execute it as a bat script.
I was thinking of using
System.Diagnostics.Process

Is there any best practices or pattern for this problem?


text:
Q: how force pc client to join local specific domain controller first We have one forest (and one Domian) Active Directory Windows 2008 R2 with 4 physical sites. Each sites have 2 DC.
When we add a PC client to our Domain, it'going to different domain controler first. We want the PC is going to 1 local DC first.
It's possible ?
"Sites and active directory" are well set up, and the first primary DNS is a local DC.
thanks

A: EDIT
As per joeqwerty's comment, take my first 2 sentences with a grain of salt
and consult this document for more information

I don't think you have a well setup forest.
Ideally you should have  created Consider having 1 domain per physical site depending on the geographical dispersion of your sites.
A node joins a domain not a DC. You shouldn't bother with which particular DC you authenticate,etc.
Having said that, if your DC holds the GC and it's DNS has the appropriate _kerberos and _ldap SRV records , all the networking makes sense (subnets,routes and so on) , you might want to check this thread on serverfault as well.


text:
Q: Reverting from Nvidia back to Nouveau I installed Nvidia drivers, but something went wrong, and I ended up with a console. I don't really want to waste my and your time with it right now. So I tried to revert the changes. I uninstalled nvidia-driver and nvidia-settings and ran Xorg -configure. There was also some error. But the final result is, now the X and KDE are running. What I don't know why happened and what's more - how to fix it, is this:

I am without effects and most certainly without HW acceleration and possibly other things.
The integrated graphics card is as follows:
$ lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation 4th Gen Core Processor Integrated Graphics Controller (rev 06)

EDIT1:
XRender works, OpenGL does not
EDIT2:
$ lsmod:
http://pastebin.com/RuG5vJuy
EDIT3:
xorg.conf file
http://pastebin.com/2SkLeSkS

A: It looks like the nouveau module is not actually currently loaded. This is likely because the nvidia installer blacklisted it to avoid conflicts, then neglected to undo this when it was uninstalled.
Look in /etc/modprobe.d; there should be one or more files. One of them may well contain a line with
blacklist nouveau

or similar. Edit that file to remove the line, then try rebooting.


text:
Q: ltrim a substring I am using the below after select in a SQL query. Some of the results have a space at the start so I believe I would need to use ltrim to display as I'd like them.
SUBSTRING(mf_mm.DisplayName,8,15) as 'Name'

Could someone tell me the syntax to use ltrim in this case?

A: Just LTRIM(SUBSTRING(mf_mm.DisplayName,8,15)) as 'Name' in T-SQL

A: Try this:-
LTRIM(SUBSTRING(mf_mm.DisplayName,8,15)) as 'Name'

A: SELECT SUBSTRING(LTRIM(mf_mm.DisplayName),8,15) as 'Name'
FROM MyTable mf_mm

Or if your allowed just update the table.
UPDATE YourTable
SET mf_mm.DisplayName = LTRIM(mf_mm.DisplayName)


text:
Q: SKLearn MLP Classifier returning meaningless Rating values I'm making a MLP Classifier using SKLearn. I have a dataframe consisting of 'age', 'book_title', 'book_author', 'year_of_publication', 'publisher', 'Category' and 'country' and I want to predict 'rating' for them, ranging from 0-10.
I've encoded entire string columns (like 'book_author' and 'publisher') using LabelEncoder() and scaled all columns (because MLP is too sensitive) using StandardScaler(), so my X_train dataset looks like this:
    age book_title  book_author year_of_publication publisher   Category    country
0   -0.183911   1.255606    -0.122783   0.271406    -0.814572   0.685256    0.427726
1   -0.183911   1.255606    -0.122783   0.271406    -0.814572   0.685256    0.427726
2   -0.084496   1.255606    -0.122783   0.271406    -0.814572   0.685256    0.427726
3   -0.680984   1.255606    -0.122783   0.271406    -0.814572   0.685256    0.427726
4   -0.482155   1.255606    -0.122783   0.271406    -0.814572   0.685256    0.427726
... ... ... ... ... ... ... ...
131174  -1.078643   0.146868    -0.689864   -1.438894   -0.566305   -0.520461   0.427726
131175  2.599699    0.146868    -0.689864   -1.438894   -0.566305   -0.520461   0.427726
131176  1.704967    0.146868    -0.689864   -1.438894   -0.566305   -0.520461   0.427726
131177  0.114333    0.146868    -0.689864   -1.438894   -0.566305   -0.520461   0.427726
131178  -0.183911   0.146868    -0.689864   -1.438894   -0.566305   -0.520461   0.427726

Training MLP classifier:
clf = MLPClassifier(
    hidden_layer_sizes=(50,50,50),
    max_iter=2000,
    activation='tanh',
    solver='adam'
    ).fit(X_train, Y_train)

While trying to predict ratings:
Y_pred = clf.predict(X_test)
Y_pred.nonzero()

I get something like:
(array([   91,   133,   223,   319,   392,   410,   441,   517,   675,
          741,   941,   951,  1173,  1195,  1215,  1400,  1406,  1410,
         1488,  1521,  1534,  1614,  1668,  1735,  1827,  1847,  1888,
         2048,  2051,  2111,  2115,  2206,  2357,  2384,  2501,  2556,
         2595,  2633,  2650,  2721,  2763,  2806,  2860,  2986,  3147,
         3208,  3240,  3247,  3282,  3393,  3446,  3708,  3884,  3974,
         3987,  4184,  4219,  4317,  4544,  4639,  4762,  4833,  4841,
         ...

Which obviously are not suitable ratings.
What can I fix in the code so the returned ratings range from 0-10?
Thanks in advance!
Edit: I've scaled X_test as well:

age book_title  book_author year_of_publication publisher   Category    country
0   -0.077752   0.866863    0.611836    0.833366    0.492138    0.691504    0.416835
1   -0.178117   0.226488    -0.247449   0.833366    1.173585    -1.312952   0.416835
2   -0.278482   0.834665    0.446589    -1.618859   -0.581657   -0.444354   0.416835
3   -0.278482   1.009964    0.735772    0.078835    1.503983    -1.312952   0.416835
4   0.825535    1.521548    -0.305286   0.267468    1.545283    0.691504    0.416835
... ... ... ... ... ... ... ...
32790   2.331013    -0.825302   -0.305286   0.833366    0.079140    -1.312952   0.416835
32791   -0.178117   1.110134    -1.619001   0.078835    0.533438    0.691504    0.416835
32792   -1.081404   1.099401    -0.420959   -0.298430   -0.808806   0.691504    0.416835
32793   1.929552    -0.249322   -1.693362   0.833366    -1.345704   0.691504    0.416835
32794   -0.178117   -1.590890   -0.718404   -0.298430   0.987736    -0.577985   0.416835


text:
Q: how do I convert text to jsonB What is the proper way to convert any text (or varchar) to jsonB type in Postgres (version 9.6) ?
For example, here I am using two methods and I am getting different results:
Method 1:
dev=# select '[{"field":15,"operator":0,"value":"1"},{"field":15,"operator":0,"value":"2"},55]'::jsonb;
                                            jsonb
----------------------------------------------------------------------------------------------
 [{"field": 15, "value": "1", "operator": 0}, {"field": 15, "value": "2", "operator": 0}, 55]
(1 row)

Method 2 , which doesn't produce the desired results, btw:
dev=# select to_jsonb('[{"field":15,"operator":0,"value":"1"},{"field":15,"operator":0,"value":"2"},55]'::text);
                                              to_jsonb
----------------------------------------------------------------------------------------------------
 "[{\"field\":15,\"operator\":0,\"value\":\"1\"},{\"field\":15,\"operator\":0,\"value\":\"2\"},55]"
(1 row)

dev=#

Here, it was converted to a string, not an array.
Why doesn't the second method creates an array ?

A: According to Postgres documentation:

to_jsonb(anyelemnt)
Returns the value as json or jsonb. Arrays and composites are
  converted (recursively) to arrays and objects; otherwise, if there is
  a cast from the type to json, the cast function will be used to
  perform the conversion; otherwise, a scalar value is produced. For any
  scalar type other than a number, a Boolean, or a null value, the text
  representation will be used, in such a fashion that it is a valid json
  or jsonb value.

IMHO you are providing a JSON formatted string, then you should use the first method.
to_json('Fred said "Hi."'::text)  --> "Fred said \"Hi.\""

If you try to get an array of element using to_json(text) you'll get the next error:
select *
from jsonb_array_elements_text(to_jsonb('[{"field":15,"operator":0,"value":"1"},{"field":15,"operator":0,"value":"2"},55]'::text));

cannot extract elements from a scalar

But if you previously cast it to json:
select *
from jsonb_array_elements_text(to_jsonb('[{"field":15,"operator":0,"value":"1"},{"field":15,"operator":0,"value":"2"},55]'::json));

+--------------------------------------------+
|                    value                   |
+--------------------------------------------+
| {"field": 15, "value": "1", "operator": 0} |
+--------------------------------------------+
| {"field": 15, "value": "2", "operator": 0} |
+--------------------------------------------+
| 55                                         |
+--------------------------------------------+

A: If your text is just a json format text, you could just explicitly cast it to json/jsonb like this:
select '{"a":"b"}'::jsonb

A: Atomic type conversion and CSV-to-JSONb
A typical parse problem in open data applications is to parse line by line a CSV (or CSV-like) text into JSONB correct (atomic) datatypes. Datatypes can be defined in SQL jargon ('int', 'text', 'float', etc.) or JSON jargon ('string', 'number'):
CREATE FUNCTION csv_to_jsonb(
  p_info text,           -- the CSV line
  coltypes_sql text[],   -- the datatype list
  rgx_sep text DEFAULT '\|'  -- CSV separator, by regular expression
) RETURNS JSONb AS $f$
  SELECT to_jsonb(a) FROM (
      SELECT array_agg(CASE
          WHEN tp IN ('int','integer','smallint','bigint') THEN to_jsonb(p::bigint)
          WHEN tp IN ('number','numeric','float','double') THEN  to_jsonb(p::numeric)
          WHEN tp='boolean' THEN to_jsonb(p::boolean)
          WHEN tp IN ('json','jsonb','object','array') THEN p::jsonb
          ELSE to_jsonb(p)
        END) a
      FROM regexp_split_to_table(p_info,rgx_sep) WITH ORDINALITY t1(p,i)
      INNER JOIN unnest(coltypes_sql) WITH ORDINALITY t2(tp,j)
      ON i=j
  ) t
$f$ language SQL immutable;

-- Example:
SELECT csv_to_jsonb(
  '123|foo bar|1.2|true|99999|{"x":123,"y":"foo"}',
  array['int','text','float','boolean','bigint','object']
);
-- results  [123,   "foo bar", 1.2,    true, 99999,  {"x": 123, "y": "foo"}]
-- that is: number, string,   number,  true, number, object


text:
Q: Mean squared error vs. mean squared prediction error What is the semantic difference between Mean Squared Error (MSE) and Mean Squared Prediction Error (MSPE)?

A: The difference is not the mathematical expression, but rather what you are measuring.
Mean squared error measures the expected squared distance between an estimator and the true underlying parameter:
$$\text{MSE}(\hat{\theta}) = E\left[(\hat{\theta} - \theta)^2\right].$$
It is thus a measurement of the quality of an estimator.
The mean squared prediction error measures the expected squared distance between what your predictor predicts for a specific value and what the true value is:
$$\text{MSPE}(L) = E\left[\sum_{i=1}^n\left(g(x_i) - \widehat{g}(x_i)\right)^2\right].$$
It is thus a measurement of the quality of a predictor.
The most important thing to understand is the difference between a predictor and an estimator. An example of an estimator would be taking the average height a sample of people to estimate the average height of a population. An example of a predictor is to average the height of an individual's two parents to guess his specific height. They are thus solving two very different problems.

A: There is a correction to the second equation about:

$MSPE(L)=\mathbb{E}\Big[\Big(g(X))-\widehat{g}(X)\Big)^{2}\Big]$;
where $X$ is a random variable.
It is important to remember that when we are working with MSPE or MSEP (I usually use the last expression) we are dealing with random variables. We want to predict an unobserved random variable $X$ using an estimator which is also a random variable (usually constructed with a sample data). There, we have a great difference with the most used expression MSE. In that case, we are dealing with a population parameter  $\theta$ that it is a constant and the estimator is again a random variable.
In a more realistic scenario, we are dealing with conditional expectation for the MSPE because if we want to predict we need to measure the quality of our estimator based on the information used in the sample data. So, our definition of MSPE would be:
$MSPE(L)=\mathbb{E}\Big[\Big(g(X))-\widehat{g}(X)\Big)^{2}\Big|\;\mathcal{G}\; \Big]$; where $\mathcal{G}$ is a $\sigma$-algebra and $\widehat{g}(X)$ is $\mathcal{G}$-measurable. We can say that $X$ is $\mathcal{F}$-measurable in the measurable space $(\Omega, \mathcal{F})$ and $g$ is a borel-measurable function, so by Doob-Dynkin $g(X)$ is also $\mathcal{F}$-measurable.

A: Typically, MSE involves only training data. The error here refers to how far the observed training response data is from the fitted response data (based on a model fit on the training data itself).
On the other hand, MSPE typically involves a testing set that was not part of the model training. The error here refers to how far the predicted testing data (predicted based on a model already fit on the training data) is from the observed testing data.


text:
Q: Nifi: Change the same values of all elements in an array (e.g. test="nio" => test=0) Edit1: Any number of new attributes with the same name can be added, for which the value is also to be changed. Therefore, several attributes with the same name and the same value can occur, which must all be exchanged. Therefore it should be dynamic.
I can no longer get on in Nifi at the following point. I would like to change the values of certain attributes in an array on the same basis. In my case, for example, the following change would be desired:
test="nio" => test=0
test="io" => test=1
My first guess is to implement this with JOLT, but I currently lack any approach in this regard.
Input:
{
  "counterTop": {
    "loaf1": [
      {
        "type": "white",
        "unit": "mm",
        "test": "nio"
      },
      {
        "type": "black",
        "unit": "cm",
        "test": "io"
      },
      {
        "type": "black123",
        "unit": "mm",
        "test": "io"
      }
    ]
  }
}

Expected output:
{
  "counterTop": {
    "loaf1": [
      {
        "type": "white",
        "unit": "mm",
        "test": "0"
      },
      {
        "type": "black",
        "unit": "cm",
        "test": "1"
      },
      {
        "type": "black123",
        "unit": "mm",
        "test": "1"
      }
    ]
  }
}

Does anyone here have a solution?
Thanks in advance!

A: You can divide upto the innermost by roaming through "*" wildcards firstly, then conquer by combining within counterTop.loaf1[&..] such as
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "*": "counterTop.loaf1[&1].&",
            "test": {
              "nio": {
                "@(2,&1)": { "*": { "#0": "counterTop.loaf1[&].&4" } }
              },
              "io": {
                "@(2,&1)": { "*": { "#1": "counterTop.loaf1[&].&4" } }
              }
            }
          }
        }
      }
    }
  }
]

where the rightmost .&4 represents going 4 level up in order to reach the key test, and the rightmost .& represents the values for the rest of the keys.
Edit : Considering your last case with multiple elements, you can prefer using the following instead of the above one as a generic case
[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "*": "loaf1[&1].&",
            "test": {
              "nio": {
                "@(2,&1)": { "*": { "#0": "&4" } }
              },
              "io": {
                "@(2,&1)": { "*": { "#1": "&4" } }
              }
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "test": {
        "*": "counterTop.loaf1[&].&1",
        "@(1,loaf1)": "counterTop.loaf1"
      }
    }
  }
]

A: Here is an example how to achieve this with ReplaceText processor:

Pay attention to the replace text configuration:
Downside of such approach is that you need separate processor for every mapping. To overcome it, you can use ReplaceTextWithMapping, here is a great explanation


text:
Q: link table in cakephp and habtm Before any advice to read google and etc, i must write that i read a lot of articles and blogs, and for now i cant figure out how to use HABTM in my case... ;]
I have order system with 3 tables and 3 models:

*

*ORDERS (order_id, customer_id, paymenyOption, etc...)

*ITEMS (item_id, size, color, etc...)

*CUSTOMERS (customer_id, name, telephone, etc...)

For now i have relationship between ORDERS<->CUSTOMERS (which works fine), but i need to have 'link table' in which will be order_id, product_id, quantity.
To be clear,

*

*one order can have many items

*one items can be in many orders

*one customer can have many orders (but one order can have one customer)
(normal order-system philoshopy)
In order view i must have details for 'item', 'customer', and 'order', something like:
Name: Johny Deep (from CUSTOMERS model)
Date ordered: 13-08-2013 (from ORDERS model)
Products: 2x apple, 2x watermelon (from ITEMS model)

I dont know if i must use hasMany or hasAndBelongsTo, and make another model for 'link table'?
Can anyone explain me this beautiful sh** in cakephp 2.x ? ;-)

A: There is nothing unique about this situation that you couldn't find elsewhere.
Using model name instead
Order (order_id, customer_id, paymentOption, etc...)
Item (item_id, size, color, etc...)
Customer (customer_id, name, telephone, etc...)
OrderItem (order_id, item_id)

Relationships
Order belongsTo Customer
Order hasMany OrderItem
Item hasMany OrderItem
Customer hasMany Order
OrderItem belongsTo Order
OrderItem belongsTo Item

If you are looking up details on an order you can do
find('first', array(
    'conditions' => array(
        'Order.id' => $order_id // which would have to be defined earlier, perhaps from a param passed in the route
    ),
    'contain' => array(
        'Customer',
        'OrderItem => array(
            'Item'
        )
    )
));

Likewise, it is very easy to pull up all orders by Customer, all order by specific Item, the sum of times a customer has placed an order, the sum of times an Item has been ordered, and the sum of times a customer has ordered a specific item, etc etc etc

A: @bowlerae:
I found this solution earlier, and it works in 50% in my query, i have code:
$products = $this->Order->find('first', array(

            'contain' => array (
                'Customer',
                'OrderItem' => array(
                    'Item'
                )
            )
                 ));

above (i omit array 'Order' and 'Customer' - are no important now):
array(

'OrderItem' => array(
        (int) 0 => array(
            'order_id' => '1',
            'item_id' => '4',
            'quantity' => '2',
            'Item' => array()
        ),
        (int) 1 => array(
            'order_id' => '1',
            'item_id' => '6',
            'quantity' => '1',
            'Item' => array()
        ),
        (int) 2 => array(
            'order_id' => '1',
            'item_id' => '7',
            'quantity' => '1',
            'Item' => array()
        ),
        (int) 3 => array(
            'order_id' => '1',
            'item_id' => '8',
            'quantity' => '1',
            'Item' => array()
        )
    )
)

1.So how can I get all 'products' now ? i started with something similar to this but i know that it is bad because i must write ['0']...['1]... which is dynamic variable
<?php echo h($products['OrderItem']['0']['item_id']); ?>

2.As you can see

'Item' => array()

is null ;-) so i cant get for example the name of the item from a Item table/model


text:
Q: List of Anonymous Functions or Thousand of Classes I wish to create an online quiz that can ask any question from thousands of programmed questions. Each question is created via a function that is given an array of int whose values determine the exact question displayed. I have each question as a class:
public class AddingTwoDigitNumbers : IQuestion
{
    public string QName() { return "Adding Two-Digit Numbers" };
    public int[] QParams() { return int[]() {Random(10, 99), Random(10, 99) };
    public void Question(int[] values) {
        Console.WriteLine(string.Format("What is {1} + {2}?", values[0], values[1]);
    }
    public void Answer(int[] values) {
        Console.WriteLine(values[0] + values[1]).ToString());
    }
}

QParams creates the array of int (to determine exactly the question created), that is given to both Question and Answer to create the question and answer.
I want a List of questions searchable by QName but would rather not have to create (and name) thousands of classes all implementing IQuestion.
So here is my second solution:
public class Question
{
    public string QName { get; set; }
    public Func<int[]> QParams { get; set; }
    public Action<int[]> Question { get; set; }
    public Action<int[]> Answer { get; set; }
}

public class QuestionRepository
{
    public static Dictionary<string, Question> Questions = new Dictionary<string, Question>();
    public static void AddQuestions(Question[] qs) {
        foreach (Question q in qs) Questions.Add(q.QName, q);
    }
}

public class FirstSetOfQuestions
{
    static void AddQuestions()
    {
        QuestionRepository.AddQuestions(new Question[]
        {
            new Question()
            {
                QName = "Adding Two-Digit Numbers",
                QParams = () => int[]() {Random(10, 99), Random(10, 99) },
                Question = (v) => {Console.WriteLine(string.Format("What is {1} + {2}?", v[0], v[1]);},
                Answer = (v) => {Console.WriteLine(values[0] + values[1]).ToString());}
            },
            new Question()
            {
                QName = "Subtracting Three-Digit Numbers",
                QParams = () => int[]() {Random(100, 999), Random(100, 999) },
                Question = (v) => {Console.WriteLine(string.Format("What is {1} - {2}?", v[0], v[1]);},
                Answer = (v) => {Console.WriteLine(values[0] - values[1]).ToString());}
            }
        }
    }
}

So my question is which is better? Do I create thousands of classes, having to provide a name for each one, or do I create thousands of anonymous functions and a class that stores these using (I assume) delegates? Is there a problem with the second solution if I have thousands of questions, or even a better way to do this?
(Obviously the questions I wish to create are much more complicated than shown here, and involve fractions, algebra etc.)

A: Just to get you started with fluent syntax, throwing in some stubs and ideas in there as well.
class Question
{
    public string Name { get; set; }
    public string QuestionFormat { get; set; }
    public List<Range> Args { get; set; }
    public Expression<Func<int[], int>>  ValExp { get; set; }

    public Question(string name, string questionFormat)
    {
        this.Name = name;
        this.QuestionFormat = questionFormat;
        this.Args = new List<Range>();
    }

    public Question Rand(int min, int max)
    {
        this.Args.Add(new Range(min, max));
        return this;
    }

    public void Val(Expression<Func<int[], int>> exp)
    {
        this.ValExp = exp;
    }

    public CompiledQuestion Compile()
    {
        // Generate args in the appropriate ranges
        // Evaluate the result with the ValExp
        // Return a new CompiledQuestion with the information -
        //    basically just replacing Args, ValExp with RealArgs, Val
    }

    public ICoolDataObject Save()
    {
    }

    public static Question Load(ICoolDataObject hmm)
    {
    }
}

class Range
{
    public int Min { get; set; }
    public int Max { get; set; }

    public Range(int min, int max)
    {
        this.Min = min;
        this.Max = max;
    }
}

It's almost fun, creating questions now:
new Question("simple addition",
             "whats {0} + {1}?")
    .Rand(10, 99)
    .Rand(10, 99)
    .Val(v => v[0] + v[1]);

You can obviously add some validation checks to avoid bad number of arguments due to late hours of work, and use double or decimal instead of int wherever.

A: Both approaches are wrong.  I presume you are not going to have thousands of different types of calculations.  You are only going to have a dozen or a few dozen different types of calculations, operating on a huge variety of data.
So, you need to normalize your data so as to end up with about a dozen or a few dozen different well defined calculations on a database of well defined data, end then write about a dozen or a few dozen classes, one for each kind of calculation, only.
You might think that this is too complicated, and you might think that writing thousands of classes (or delegates, it does not really matter) might be a lot of work but each piece is small and easy, but trust me, you will bitterly regret doing it this way as soon as something needs to change on the interface or the implementation of all of these classes, and most chances are that something will need to change at some point in time.


text:
Q: How to call Yelp API for access token? I'm trying to send a POST request to Yelp API to get an access token using these instructions: https://www.yelp.com/developers/documentation/v3/get_started
However, the code below isn't printing anything to the console. I'm not sure what the issue is or if I've set up the POST request properly. What's wrong with my code? :(
foodfinder.html:
<!DOCTYPE html>
<html lang="en">
<head>

    <script src="./public/foodfinder.js"></script>
    <meta charset="UTF-8">
    <title>Food Finder</title>
    </head>

    <body>

    Hello world

    </body>
    </html>

foodfinder.js:
$(function () {

var API_HOST = "api.yelp.com";
var SEARCH_PATH = "/v3/businesses/search";
var BUSINESS_PATH = "/v3/businesses/";
var TOKEN_PATH = "/oauth2/token";
var GRANT_TYPE = "client_credentials";

var CLIENT_ID = "abc";  // dummy id for stackoverflow purposes
var CLIENT_SECRET = "xyz";  // dummy secret for stackoverflow purposes

var SEARCH_TERM = "food";
var SEARCH_RADIUS = 500;        // radius is in meters
var SORT_BY = "distance";

$.ajax(API_HOST + TOKEN_PATH, {
    type: "POST",
    data: {
        grant_type: GRANT_TYPE,
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET
    },
    contentType: "application/x-www-form-urlencoded",
    dataType: "json",
    success: function (data) {
        console.log(data);

    },
    error: function () {
        console.log("post call error");
    }

})
});

A: maybe you need the https in the HOST variable, like
var API_HOST = "https://api.yelp.com";
when i test the call without the https, i get an error:
{"error": {"description": "/oauth2/token", "code": "VALIDATION_ERROR"}}


text:
Q: How can i stop the background colour of a UIView from disappearing when cell is selected? I have a tableView which contains a label, image and UIVIew with a red background colour.
This is a picture of a row in my tableView which displays a label, image and a UIView that has a red background colour

But whenever I select a cell, the background colour of the UIVIew disappears and all I can see is the label and image
This is the same row when I select it

I was wondering if there was a way to stop the background colour of the view from disappearing whenever the cell is selected.

A: It is happening because cell selection style is set to default, change the UITableViewCell selection style to none.
Objective C:
cell.selectionStyle = UITableViewCellSelectionStyleNone;

Swift 3:
cell.selectionStyle = .none

If you want to notify user has selected the cell, Maintain a property of NSArray which contains list of indexpath object.
Update the NSArray on delegate method didSelectRowAtIndexPath method.
In cellForRowAtIndexPath method change background color if indexpath exists in NSArray
Finally on didSelectRowAtIndexPath reload the selected row.

A: Try this:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      //Just add this below line didSelectRowAt
      tableView.deselectRow(at: indexPath, animated: true)

}

A: It's a little better. I extracted from MBProgressHUD/Demo
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           [tableView deselectRowAtIndexPath:indexPath animated:YES];
       });
   }


text:
Q: HTML code is showing in .PHP page i'm writing my first page with PHP and HTML mixed.
This page shows the visitor's ip address (ipv4 or ipv6). The PHP script is working fine, but the HTML code is showing as text instead of rendering.
<!doctype html>

<title>mioipv6.it</title>

<?php
header('Content-type: application/json');
if ( array_key_exists('addr', $_GET) )
$ip = $_GET['addr'];
else
$ip = $_SERVER['REMOTE_ADDR'];
$v6 = preg_match("/^[0-9a-f]{1,4}:([0-9a-f]{0,4}:){1,6}[0-9a-f]{1,4}$/", $ip);
$v4 = preg_match("/^([0-9]{1,3}\.){3}[0-9]{1,3}$/", $ip);
if ( $v6 != 0 )
$type = "IPv6";
elseif ( $v4 != 0 )
$type = "IPv4";
else
$type = "unknown";
echo json_encode(array("Il tuo indirizzo" => $ip, "Tipo" => $type));
?>

you can see the page here: www.mioipv6.it

A: Remove
header('Content-type: application/json');


text:
Q: R fails render on Shiny DashBoard after editing tabitems library(shiny)
library(tidyverse)
library(leaflet)
library(shinydashboard)
library(RColorBrewer)
library(viridis)
library(shinyWidgets)

ui <- dashboardPage(
    dashboardHeader(title = "Basic dashboard"),
    dashboardSidebar(
        sidebarMenu(
            menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")

                ),
            menuItem("Widgets", tabName = "widgets", icon = icon("th"))
        )
    ),
    dashboardBody(
        # Boxes need to be put in a row (or column)
        tabItems(
            # First tab content
            tabItem(tabName = "dashboard",
                    fluidRow(
                        box(plotOutput("plot1", height = 250)),
                        box(
                            title = "Controls",
                            sliderInput("slider", "Number of observations:", 1, 100, 50)
                        )
                    )
            ),
            # Second tab content
            tabItem(tabName = "widgets",
                    h2("Widgets tab content")
            )
        )
    )
)
server <- function(input, output) {
    set.seed(122)
    histdata <- rnorm(500)
    output$plot1 <- renderPlot({
        data <- histdata[seq_len(input$slider)]
        hist(data)
    })
}
shinyApp(ui, server)

The above example, the output renders when the tabs dashboard and widgets are clicked seperately. In the dashboard tab, i have my slider input in the body.
Now when I change my slider to have it at the sidebar:
library(shiny)
library(tidyverse)
library(leaflet)
library(shinydashboard)
library(RColorBrewer)
library(viridis)
library(shinyWidgets)

ui = dashboardPage(
    dashboardHeader(title =  "Dashboard"),
    dashboardSidebar(
        sidebarMenu(
            id = "sidebarmenu",
            menuItem("menuItem1",
                     tabName = "tab1",
                     sliderInput("slider", "Number of observations:", 1, 100, 50)
            )
            ,
            menuItem("menuItem2", tabName = "tab2")
        )
    ),
    dashboardBody(
        tabItems(
            tabItem(tabName = "tab1",
                    tableOutput("myTable"),
            ),
            tabItem(tabName = "tab2",
                    h2("Placeholder Cloud"),
                    plotOutput("myPlot"))
        )
    )
)

server <- function(input, output, session) {

    tableData = reactiveVal(data.frame(x = 1:10, y = LETTERS[1:10]))
    plotData = reactiveVal()

    observeEvent(input$sidebarmenu, {

        if(input$sidebarmenu == "tab2"){
            #Code for tab 2
            req(is.null(plotData()))
            print("Tab 2 code is run")
            plotData(runif(100))

        }

    })

    output$myTable = renderTable({
        tableData()
    })

    set.seed(122)
    histdata <- rnorm(500)
    output$myPlot = renderPlot({
        data <- histdata[seq_len(input$slider)]
        hist(data)
    })
}

shinyApp(ui, server)

Problem here:
1) The text placeholder cloud, initially only rendered when the tab menuItem2 is clicked, now gets rendered together with the histogram which was supposed to render only when i clicked menuItem1
2) clicking on menuItem2 does not do anything. I would like to have tab2 when clicked, show a scatterplot as seen in this below block of code.
i.e., i would like to "integrate the below 3rd block of code" into the 2nd, the above so when i run the second block of code, when i click tab1, the input for the slider appears and renders the histogram. when i click tab2, the scatterplot will be rendered
library(shiny)
library(tidyverse)
library(leaflet)
library(shinydashboard)
library(RColorBrewer)
library(viridis)
library(shinyWidgets)

ui = dashboardPage(
    dashboardHeader(title =  "Dashboard"),
    dashboardSidebar(
        sidebarMenu(
            id = "sidebarmenu",
            menuItem("menuItem1",
                     tabName = "tab1")
                ,
            menuItem("menuItem2", tabName = "tab2")
        )
    ),
    dashboardBody(
        tabItems(
            tabItem(tabName = "tab1",
                    tableOutput("myTable")),
            tabItem(tabName = "tab2",
                    h2("Placeholder Cloud"),
                    plotOutput("myPlot"))
        )
    )
)

server <- function(input, output, session) {

    tableData = reactiveVal(data.frame(x = 1:10, y = LETTERS[1:10]))
    plotData = reactiveVal()

    observeEvent(input$sidebarmenu, {

        if(input$sidebarmenu == "tab2"){
            #Code for tab 2
            req(is.null(plotData()))
            print("Tab 2 code is run")
            plotData(runif(100))

        }

    })

    output$myTable = renderTable({
        tableData()
    })

    output$myPlot = renderPlot({
        plot(plotData())
    })
}

shinyApp(ui, server)

Any help is appreciated.I am new to Shiny.

A: for your 2nd part you said "clicking on menuItem2 does not do anything."... but you don't have any action for menuItem2 see
menuItem("menuItem2", tabName = "tab2")


text:
Q: Redshift svv_table_info pct_used From the docs for svv_table_info, pct_used is

Percent of available space that is used by the table

So then I wondered,  what is the defintion for 'available space' ?
Google led me to an article that said this :

The query below will give you the percentage of storage used in your
cluster, which you can use to check if this is the reason for slow
query performance. If you're nearing capacity (80% or greater),
consider adding some more nodes or truncating some unused historical
data.
SELECT sum(pct_used) FROM svv_table_info;

That doesn't make sense, as svv_table_info only shows you tables in the current database, not for all tables in all databases the cluster, so could never reflect cluster capacity !?
I ran that query in 1 database and it resulted in 0.9490
So is it telling me that the current Database is at 94% capacity ?
If so, what defines the capacity for each of my numerous databases within the cluster ?
Logging in to the AWS console, my cluster is running at 1% capacity.
Can anyone help me make sense of all this please ?
I'm sure its very simple, but finding documentation seems to be sketchy.
Thanks


text:
Q: Having a single event listener for custom events generated by any element in the page I am in the process of creating a huge web application, with a JavaScript based UI, and many events generated continuously.
To avoid bad performance due to the huge amount of the event listeners needed, I of course opted to use a single event listener which will catch all the events generated from the children elements (event bubbling).
The problem is, this application is designed in such a way that one or more modules can be loaded into the main JavaScript library I'm coding (which is responsible for controlling the UI and every other aspect of the program). Of course every module should be completely independent from each other, so you can choose which methods to load, without affecting the general functionality of the library, only adding or removing features.
Since every module can operate in different DOM elements, I need to have at least a single event listener for each module, since two modules can listen for events generated by html elements placed in different DOM branches.
http://jsfiddle.net/YRejF/2/
In this fiddle for example, the first button will let the first paragraph trigger an event, and its parent will catch it. The second button will let the second paragraph fire the event, but the div listening for the same event won't catch it, because it's not fired from one of its sons.
So my question is: is it possible to have a single event listener, able to listen also to events triggered from elements that are not its sons (elements placed everywhere on the page)?
I was thinking about having a js object, or a dom node, which store the data of the element which triggered the event, and the event itself, then a general event will be fired on the global event listener (no matter where it's placed in the dom), and it will then read the data to discover which element generated which event, and act accordingly.
Any help or suggestion about better ways of achieving this?

A: jQuery has a special binder for this kind of cases: live(). It let's all events bubble to the document and then handles them accordingly. However, if you use div or other containers for different panels etc, maybe using delegate() makes more sense. Don't worry too much about the number of bound elements. Believe me, it will run as well with 50 binds or 10 delegates as it will with 1 live.


text:
Q: React native background service I am making a react native app and I want to fetch data from the Internet every 15 minutes. The approach I take must fetch the data in the background and work cross-platform. Is there a method for doing this?

A: Use fetch api with react-native-timer
        import timer from 'react-native-timer';

        timer.setInterval("instanceName",function get() {
          return fetch(URL)
            .then(response => response.json())
            .then(responseJson =>{
               console.log("json",responseJson) //set in state here
               })
            .catch(error => {
              console.error("api call error", error);
              throw error;
            });
        },15*60*1000);

    timer.clearInterval(instanceName);


text:
Q: Unable to cast COM object of type 'System.__ComObject' to interface type for IRTDUpdateEvent I have spent a lot of time trying to figure out why I am getting the following error when trying to run RTD Server (Excel RTD Server) that I have developed when installing it via RegAsm. It works fine if I set the Register for COM interop flag on my dev machin, but not when install it using RegAsm.
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'IRTDUpdateEvent'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{A43788C1-D91B-11D3-8F39-00C04F3651B8}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Any Ideas?

A: does your Interface "IRTDUpdateEvent" has this Guid?

A: Thanks Arthur,
I have at last managed to crack it. The problem was that when creating a setup package, I referenced the Assembley in my Custom Installation. It obviously did not like that when runing RTD. The RegAsm was in my custm installation. I solved the problem by leaving Register for COM interop flag checked and then adding the Assembley in my setup project by right clicking and sellecting Add --> Assembley.
Thanks


text:
Q: How to ordinalize a day using php? Using PHP I want to show the day of the month in ordinal way like ::
1   first
2   second
3   third
4   fourth
5   fifth
6   sixth
7   seventh
8   eighth
9   ninth
10  tenth
11  eleventh
12  twelfth
13  thirteenth
14  fourteenth
15  fifteenth
16  sixteenth
17  seventeenth
18  eighteenth
19  nineteenth
20  twentieth
21  twenty-first
22  twenty-second
23  twenty-third
24  twenty-fourth
25  twenty-fifth
26  twenty-sixth
27  twenty-seventh
28  twenty-eighth
29  twenty-ninth
30  thirtieth
31  thirty-first
e.g.
if date is 22-Feb it should show : twenty-second Feb
Thanks in advance....

A: Well, you already have your "array" there, just put it in code:
$ordinals = array(
    1=>"first",
    2=>"second",
    // ...
);

Then you can access the array:
echo $ordinals[date("d")];


text:
Q: RewriteRule to capture specific url and allow a substring of the same url I have a rule that works for this url:
/cobrand/partner;jsessionid=YIMle3Ap0AKEp?code=SOMEPARTNERCODE
RewriteRule ^/shop/partner /cobrand/partner [QSA,R=301]
RewriteRule ^/shop/Partner(.*) /cobrand/partner$1 [QSA,R=301]

RewriteCond %{QUERY_STRING} (?:^|&)code=([^&]+) [NC]
RewriteRule ^/?cobrand/partner(.*)$ /store/affiliate/cobrand/redirect/code/%1? [R=301,L]

What I would like is to have a rule that will allow this url to be parsed as is whilst allowing the above to also match:
cobrand/partner?code=SOMEPARTNERCODE&init=true
Also I have a catch all for shop to store at the end of my file


text:
Q: Will adding my own 'textarea' directive overwrite the native Angular directive? I'm looking to handle all events by textareas and inputs in an angular app.  Normally I'd probably use jQuery to bind a live/on handler to listen for the events I'm after.  But I can't and don't want to use the full jQuery lib, but instead use the native Angular jQuery lite library to accompplish the same effect.
I've tried adding a directive 'textarea' and 'input' that causes my global event to occur.  So essentially I can add a new directive 'textarea' and 'input' to my app, but 'should I'?
Also, I'm not interested in adding a new directive to every input or textarea in the app.  I want to handle this use case globally.  I don't want to have to remember, or have other developers remember to add this directive to all their inputs and textareas, I just want to handle it globally.
But...
Will adding my own 'textarea' or 'input' directive in an Angular app dislodge/overwrite the native Angular textarea directive?

A: You can definitely define directives with the same name as Angular's built-in directives (or any other module's for that matter). In that case all directives are going to be applied - none is going to be overwritten or "shadowed".
See, also, this short demo. Opening the DevTools' console, you will find the logs proving that both directives with the same name are applied to the element.

So, in order to apply textarea-wide behaviour, a textarea directive is the way to go.


text:
Q: Sum of a countable dense set and a set of positive measure Assume $A$ is a countable dense set in $\mathbb{R}$, and set $B$ has positive (Lebesgue) measure. Prove that $A+B=\{a+b:a\in A, b\in B\}=\mathbb{R}\backslash N$, where $N$ is a set of measure zero.
I haven't come up with a good idea.
Thanks in advance!

A: Some more details for the answer by Kena Bel P: $A+B$ is measurable because it's the union of countably many translates of the measurable set $B$.  Let $N$ be its complement and suppose, toward a contradiction, that $N$ had positive measure.  Then by the cited theorem of Steinhaus, there would be an interval included in $\{n-a:a\in A, n\in N\}$.  As $B$ is dense, this interval contains some element $b$ of $B$.  But then we have, for this $b$, that $b=n-a$ for some $a\in A$ and $n\in N$.  That is, $n=a+b$, contradicting the fact that $n\in N=\mathbb R\setminus(A+B)$.

A: This follows from the following Steinhaus theorem: if $A,B$ are subsets of the real line of positive measure then $A-B$ contains an interval.

A: Edit: On further inspection and cleanup, this has pretty much just reduced to a standard proof of the Steinhaus theorem.  The Fourier transform appearing in a previous version was unnecessary.   I'll just leave this in case anyone is interested.
Without loss of generality, we can assume $A$ is bounded.  Suppose $N$ is bounded and disjoint from $A + B$; we will show $N$ has measure zero.  Then the result follows by taking $N = (A+B)^c \cap [-k,k]$, letting $k \to \infty$, and using countable additivity.
Set $f = 1_N$ and $g = 1_{-A}$ (i.e. $g(y) = 1$ if $-y \in A$, and 0 otherwise).  Now if $x \in B$, then $N$ and $x+A$ are disjoint, and so for every $y \in \mathbb{R}$, $f(x-y) g(y) = 0$.  (If $g(y) \ne 0$, then $-y \in A$, so $x-y \notin N$ and $f(x-y) = 0$.)  In particular, for $x \in B$, we have
$$(f * g)(x) := \int f(x-y) g(y)\,dy = 0$$
But now it follows from standard properties of convolution that $f * g$ is continuous.  (If $f$ were continuous and compactly supported, this would follow from dominated convergence.  Now approximate $f$ in $L^1$ norm by a sequence $\{f_n\}$ of continuous, compactly supported functions, and note that $\|f * g - f_n * g\|_{\infty} \le \|f-f_n\|_{1} \|g\|_\infty$)  Since $f*g$ vanishes on the dense set $B$, we have $f*g \equiv 0$.  Now integrating and using Tonelli's theorem,
$$\begin{align*} 0 &= \int (f*g)(x)\,dx \\ &=\int \int f(x-y) g(y)\,dy\,dx \\
&= \int \int f(x-y) \,dx\, g(y)\,dy \\
&= \|f\|_{1} \|g\|_1
\end{align*}$$
Hence either $\|f\|_1 = 0$ or $\|g\|_1=0$, i.e. either $m(N) = 0$ or $m(A) = 0$.  Since by assumption $m(A) \ne 0$, we must have $m(N) = 0$, completing the proof.

A: I wanted to add this as a comment, but I have not required reputation.

This follows from the following Steinhaus theorem: if $A,B$ are
  subsets of the real line of positive measure then $A-B$ contains an
  interval.

The Steinhaus theorem states that $A-A$ contains an open neighborhood of zero and the strong version states that $A+B$ contains an open set.
This desired result result, to my knowledge, was first proved  here.  It is not entirely obvious.


text:
Q: Tweepy + Twitter API v2: I want to extract the tweet.id for media_key only What if I want to take the Tweet ID and media_keys and only get the Tweet ID that has media_keys?
I was trying to do it with this sample but I got stuck:
https://docs.tweepy.org/en/stable/examples.html
client = tweepy.Client(consumer_key=API_KEY, consumer_secret=API_SECRET, access_token=ACCESS_TOKEN, access_token_secret=ACCESS_TOKEN_SECRET, bearer_token=Bearer_token)

counts = 10

search_result = client.get_list_tweets(id='list id', max_results=counts, expansions=["attachments.media_keys"])
tweets = search_result.data

includes = search_result.includes
medias = includes['media']

for tweetid in tweets:
    tid = tweetid.id

mediass = {media['media_key']: media for media in medias}
for tweet in tweets:
    print(tweet.id, mediass)

A: You can check the attachments field of Tweet objects to obtain media keys for media attached to the Tweet.


text:
Q: Having issue with substring in SQL Server I have to split the resolution something like below:
declare @t table (resolution nvarchar(100))

Insert into @t values ('1366 X 768 @ 60 Hz'),
('1024 X 768 @ 60 Hz'),
('640 X 480 @ 70 Hz')

I want the output as
Fst   |  Snd  | Thd
------+-------+-----------
1366  |  768  |  60 Hz
1024  |  768  |  60 Hz
640   |  480  |  70 HZ

I have tried this query
select
    *,
    substring(resolution, 1, charindex('X', resolution) - 1) as fst,
    substring(resolution, charindex('X', resolution) + 1, charindex('@', resolution) + 1) as snd
from
    @t

But it is not returning the correct output.
Can anyone please show me what is wrong in here?

A: You can also try PARSENAME() function if there are only 3 part every time, and data format always as you shown.
SELECT
PARSENAME(REPLACE(REPLACE(resolution,' X ','.'),' @ ','.') ,3) Fst,
PARSENAME(REPLACE(REPLACE(resolution,' X ','.'),' @ ','.') ,2) Snd,
PARSENAME(REPLACE(REPLACE(resolution,' X ','.'),' @ ','.') ,1) Thd
FROM @t

Output is-
Fst     Snd     Thd
1366    768     60 Hz
1024    768     60 Hz
640     480     70 Hz

If you wants to exlude ' Hz' from the Thd column, Just do it-
SELECT
PARSENAME(REPLACE(REPLACE(REPLACE(resolution,' X ','.'),' @ ','.'),' Hz','') ,3) Fst,
PARSENAME(REPLACE(REPLACE(REPLACE(resolution,' X ','.'),' @ ','.'),' Hz','')  ,2) Snd,
PARSENAME(REPLACE(REPLACE(REPLACE(resolution,' X ','.'),' @ ','.'),' Hz','')  ,1) Thd
FROM @t

A: Here you go
declare @t table (resolution nvarchar(100))

Insert into @t values ('1366 X 768 @ 60 Hz'),
('1024 X 768 @ 60 Hz'),
('640 X 480 @ 70 Hz');

SELECT LEFT(Resolution, CHARINDEX('X', Resolution) - 1) [1St],
       SUBSTRING(Resolution, CHARINDEX('X', Resolution)+1, CHARINDEX('@', Resolution)-
       CHARINDEX('X', Resolution)-2) [2nd],
       SUBSTRING(Resolution, CHARINDEX('@', Resolution)+1, CHARINDEX('H', Resolution)-
       CHARINDEX('@', Resolution)-2) [3rd]
FROM @t;

Online demo
Or more better(without white spaces)
SELECT LEFT(Resolution, CHARINDEX('X', Resolution) - 2) [1St],
       SUBSTRING(Resolution,
                 CHARINDEX('X', Resolution)+2,
                 CHARINDEX('@', Resolution)- CHARINDEX('X', Resolution)-3
                ) [2nd],
       SUBSTRING(Resolution,
                 CHARINDEX('@', Resolution)+2,
                 CHARINDEX('H', Resolution) - CHARINDEX('@', Resolution)-3
                ) [3rd]
FROM @t

If you want 'Hz' to be in the third column then
SELECT LEFT(Resolution, CHARINDEX('X', Resolution) - 2) [1St],
       SUBSTRING(Resolution,
                 CHARINDEX('X', Resolution)+2,
                 CHARINDEX('@', Resolution)- CHARINDEX('X', Resolution)-3
                ) [2nd],
       SUBSTRING(Resolution,
                 CHARINDEX('@', Resolution)+2,
                 LEN(Resolution)
                ) [3rd]
FROM @t;

Also, you could use PARSENMAE() function (as mkrabbani provide)to return both results as the following:

*

*With 'Hz'
SELECT Resolution,
       PARSENAME(Res, 3) Fst,
       PARSENAME(Res, 2) Snd,
       PARSENAME(Res, 1) Thd
FROM
(
  VALUES
  ('1366 X 768 @ 60 Hz'),
  ('1024 X 768 @ 60 Hz'),
  ('640 X 480 @ 70 Hz')
) T(Resolution)
CROSS APPLY
(
  SELECT REPLACE(REPLACE(T.Resolution, ' X ', '.'), ' @ ', '.') Res
) TT;

*Without 'Hz':
SELECT Resolution,
       PARSENAME(Res, 3) Fst,
       PARSENAME(Res, 2) Snd,
       PARSENAME(Res, 1) Thd
FROM
(
  VALUES
  ('1366 X 768 @ 60 Hz'),
  ('1024 X 768 @ 60 Hz'),
  ('640 X 480 @ 70 Hz')
) T(Resolution)
CROSS APPLY
(
  SELECT REPLACE(REPLACE(REPLACE(T.Resolution, ' X ', '.'), ' @ ', '.'), 'Hz', '') Res
) TT;

Demo for the last 3 queries.

A: You can use PARSENAME function to split :
SELECT *,
    PARSENAME(REPLACE(PARSENAME(REPLACE(resolution,'@','.'),2),'X','.'),2) 'Fst' ,
    PARSENAME(REPLACE(PARSENAME(REPLACE(resolution,'@','.'),2),'X','.'),1) 'Snd' ,
    PARSENAME(REPLACE(resolution,'@','.'),1) 'Thd'
FROM @t

A: You can use this :
select
    *,
    substring(resolution, 1, charindex('X', resolution) - 1) as fst,
    substring(resolution, charindex('X', resolution) + 1, charindex('@', resolution) - charindex('X', resolution)-1) as snd ,
    substring(resolution, charindex('@', resolution) + 1,len(resolution) -  charindex('@', resolution)  ) as thr
from
    @t

A: A bit cleaner code using APPLY
SELECT LEFT(Resolution, idx1 - 2) [1St],
       SUBSTRING(Resolution, idx1 + 2, idx2 - idx1 - 3) [2nd],
       SUBSTRING(Resolution, idx2 + 2, CHARINDEX('H', Resolution) - idx2 - 3) [3rd]
FROM @t
CROSS APPLY (
     SELECT CHARINDEX('X', Resolution) idx1
          , CHARINDEX('@', Resolution) idx2) i

A: And since no string parsing post would be complete without an XML based solution:
SELECT ResXml.value(N'/x[1]', 'nvarchar(100)') As Fst,
       ResXml.value(N'/x[2]', 'nvarchar(100)') As Snd,
       ResXml.value(N'/x[3]', 'nvarchar(100)') As Thd
FROM
(
    SELECT CAST('<x>'+ REPLACE(REPLACE(resolution, ' X ', '</x><x>'), ' @ ', '</x><x>') + '</x>' As Xml) As ResXml
    FROM @t
) As x


text:
Q: Flutter theme not applied to new screen Below is a simple screen with three buttons with different colored themes what I want is when any of each button pressed detail screen should use that theme.
also, I don't what to change the theme of MaterialAppWidget because it's used in other places just this details screen needs to be themed according to which button it opened.
import 'package:flutter/material.dart';

main() => runApp(const App());

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) => MaterialApp(
        home: const HomeScreen(),
        theme: ThemeData(
          primaryColor: Colors.orange,
          colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.orange),
        ),
      );
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Wrap(
          spacing: 20,
          direction: Axis.vertical,
          children: const [
            ThemedButton(
              materialColor: Colors.red,
            ),
            ThemedButton(
              materialColor: Colors.green,
            ),
            ThemedButton(
              materialColor: Colors.brown,
            ),
          ],
        ),
      ),
    );
  }
}

class ThemedButton extends StatelessWidget {
  final MaterialColor materialColor;

  const ThemedButton({
    Key? key,
    required this.materialColor,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(
        primaryColor: materialColor,
        colorScheme: ColorScheme.fromSwatch(primarySwatch: materialColor),
      ),
      child: ElevatedButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => const DetailScreen(),
            ),
          );
        },
        child: const Text('Go to Detail Screen'),
      ),
    );
  }
}

class DetailScreen extends StatelessWidget {
  const DetailScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
    );
  }
}

A: Would something like this work for you?
class ThemedButton extends StatelessWidget {

  final MaterialColor materialColor;
  const ThemedButton({Key? key, required this.materialColor}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        primary: materialColor
      ),
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => Theme(
              data: Theme.of(context).copyWith(
                primaryColor: materialColor,
                colorScheme: ColorScheme.fromSwatch(primarySwatch: materialColor),
              ),
              child: const DetailScreen()
            )
          ),
        );
      },
      child: const Text('Go to Detail Screen'),
    );
  }
}

I'm wrapping the Elevated Button in a Builder Widget to use the new BuildContext theme to pass down.


text:
Q: How to convert Integers to Strings that can be used as column names in postgresql? I am trying to use two loops to INSERT INTO new_table. The thing is the old_table is like this with strange "year-month" column names:
CREATE TABLE old_table
(
    regionname character varying(10),
    "1996-01" integer,
    "1996-02" integer,
    "1996-03" integer,
    ...
    "2014-11" integer,
    "2014-12" integer
)

And the empty new_table waiting for data has the schema like this:
CREATE TABLE new_table
(
  regionname character varying(10),
  year integer,
  month integer,
  value integer
)

And I would like to use the parameter y and m in the following function to create column names. For example when y = 1996 and m = 1 in the loops, NEEDTOFILL part should be "1996-01" that can be used as a column name.
CREATE FUNCTION insertLoop() RETURNS void AS $$
BEGIN
  FOR y IN 1996..2014 LOOP
      FOR m IN 1..12 LOOP
          INSERT INTO new_table(regionname, year, month, value)
          (
              SELECT regionname, y AS year, m AS month, **NEEDTOFILL** AS value
              FROM old_table
              WHERE **NEEDTOFILL** IS NOT NULL
          );
      END LOOP;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

What should be the NEETOFILL? Or is there a way to select the ith column instead of using the actual column name in SQL? Or other ways to do it?

A: You need to cast integer to varchar with :: and concatenate with || like...
y::varchar || '-' || m::varchar

EDIT
You right. this will generate value not column name
Then you must generate query in to variable then execute query. something like this
query = 'INSERT INTO new_table(regionname, year, month, value)
          SELECT regionname, y AS year, m AS month, ' || y::varchar || '-' || m::varchar || ' AS value
          FROM old_table
          WHERE ' || y::varchar || '-' || m::varchar || ' IS NOT NULL';
execute query;


text:
Q: How to get the name of input file in MRjob I'm writing a map function using mrjob.  My input will come from files in a directory on HDFS.  Names of the files contain a small but crucial piece information that is not present in the files.  Is there a way to learn (inside a map function) the name of the input file from which a given key-value pair comes?
I'm looking for an equivalent of this Java code:
FileSplit fileSplit = (FileSplit)reporter.getInputSplit();
String fileName = fileSplit.getPath().getName();

Thanks in advance!

A: map.input.file property will give the input file name.
According to the Hadoop - The Definitive Guide

The properties can be accessed from the job's configuration, obtained in the old MapReduce API by providing an implementation of the configure() method for Mapper or Reducer, where the configuration is passed in as an argument. In the new API, these properties can be accessed from the context object passed to all methods of the Mapper or Reducer.

A: If you are using HADOOP 2.x with Python:
file_name = os.environ['mapreduce_map_input_file']


text:
Q: mspaint problem "this is not a valid bitmap file" I have Vista Business on my laptop. I download JPG pictures from my Nikkon camera. I open them with mspaint and resize them. Then save them back as jpg (using the jpg option). When I try to open the saved file, I get "Paint cannot read this file. This is not a valid bitmap file". When I preview it with windows photo gallery, I can see the picture. Any ideas?

A: How are you saving them as .jpg ? Did you select JPEG in the file format options? (I believe paint defaults to .bmp, so you may have a .bmp save with a .jpg extension).
However, as people have already said in the comments, Paint is not a great program for any serious image editing tasks. A good free alternative is Paint.NET, it has most of Paint's ease of use, with a much larger feature set.

A: I came across this issue today and as far as I can tell it has to do with the resolution of the image. From my testing today, it seems that any image above 1200*1200dpi won't open in Paint, even if it is a BMP file or even if it is only 4MB in size It seems to be purely resolution related.
See this thread:
https://answers.microsoft.com/en-us/windows/forum/windows_10-files/paint-wont-open-valid-file-types-over-1200x1200/176a85c8-ac6a-4e1a-a6e2-6b7ce7190ea7
Until Microsoft fix it, I would suggest using Paint.net or GIMP. They're both completely free (and ad free) and easy to use with some more advanced features too if you need them.

A: It's a size issue. The Fujifilm GFX 100 S produces TIF that will neither open in Paint nor in Portrait Pro.
Solution: Crop the image slightly in Photoshop or Corel. Then it will behave normally.

A: If you want to check if the file is good anyways, you can install Image Magick and run in cmd:
identify imagename

replace imagename by the name of the actual file if there's and error thaty comand will clearly tell you.