text:
Q: CakePHP : complexe paginated query does not sort on columns I want to use a complexe query with paginate(). Here is my code :
// PhasesController.php
public function manage($id = null) {
    $this->loadModel('ProjectDomainPhasesUser');
    $this->ProjectDomainPhasesUser->recursive = 0;
    $this->paginate = array(
      'ProjectDomainPhasesUser' => array(
      'order' => array('Phase.label_'.$_SESSION['lang']),
      'joins' => array(
         array(
            'table' => 'users',
            'alias' => 'User',
            'type' => 'INNER',
            'foreignKey' => false,
            'conditions'=> array(
             'ProjectDomainPhasesUser.user_id = User.id AND User.id = '.$this->Auth->User('id')
            )
         ),
         array(
            'table' => 'project_domains_phases',
            'alias' => 'ProjectDomainsPhase',
            'type' => 'INNER',
            'foreignKey' => false,
            'conditions'=> array(
             'ProjectDomainsPhase.id = ProjectDomainPhasesUser.project_domain_phase_id'
            )
         ),
         array(
            'table' => 'processes_phases',
            'alias' => 'ProcessesPhase',
            'type' => 'LEFT',
            'foreignKey' => false,
            'conditions'=> array(
             'ProjectDomainsPhase.process_phase_id = ProcessesPhase.id'
            )
         ),
         array(
            'table' => 'phases',
            'alias' => 'Phase',
            'type' => 'LEFT',
            'foreignKey' => false,
            'conditions'=> array(
             'ProcessesPhase.phase_id = Phase.id'
            )
         ),
         array(
            'table' => 'projects_domains',
            'alias' => 'ProjectsDomain',
            'type' => 'LEFT',
            'foreignKey' => false,
            'conditions'=> array(
             'ProjectDomainsPhase.project_domain_id = ProjectsDomain.id'
            )
         ),
         array(
            'table' => 'domains',
            'alias' => 'Domain',
            'type' => 'LEFT',
            'foreignKey' => false,
            'conditions'=> array(
             'ProjectsDomain.domain_id = Domain.id'
            )
         ),
         array(
            'table' => 'projects',
            'alias' => 'Project',
            'type' => 'LEFT',
            'foreignKey' => false,
            'conditions'=> array(
             'ProjectsDomain.project_id = Project.id'
            )
         )
      ),
      'fields' => array('Project.title', 'Project.date_target', 'ProcessesPhase.step_number', 'Domain.label_fr AS domain_fr', 'Domain.label_es AS domain_es', 'Phase.label_fr AS phase_fr', 'Phase.label_es AS phase_es', 'ProjectDomainsPhase.date_notification', 'ProjectDomainsPhase.done', 'ProjectDomainsPhase.date_finished', 'ProjectDomainsPhase.id')
      )
    );
    $this->set('taches', $this->paginate());

I made this by following cakephp: using a join for search results
My view :
// manage.ctp

    <?php echo $this->Paginator->sort('Project.title','Projet'); ?>
    <?php echo $this->Paginator->sort('Project.date_target','Date cible du projet'); ?>
    <?php echo $this->Paginator->sort('ProcessesPhase.step_number','Etape'); ?>
    <?php echo $this->Paginator->sort('Domain.domain_'.$_SESSION['lang'],'Domaine'); ?>
    <?php echo $this->Paginator->sort('Phase.phase_'.$_SESSION['lang'],'Tâche'); ?>
    <?php echo $this->Paginator->sort('ProjectDomainsPhase.date_notification','Date notification'); ?>
    <?php echo __('Statut'); ?>
    <?php echo $this->Paginator->sort('ProjectDomainsPhase.date_finished','Date fin tâche'); ?>

<?php
foreach ($taches as $key => $tache){ ?>

    <?php echo $tache['Project']['title']; ?>
    <?php echo $this->Date->date_inv($tache['Project']['date_target']); ?>
    <?php echo $tache['ProcessesPhase']['step_number']; ?>
    <?php echo $tache['Domain']['domain_'.$_SESSION['lang']]; ?>
    <?php echo $tache['Phase']['phase_'.$_SESSION['lang']]; ?>
    <?php echo $this->Date->date_inv($tache['ProjectDomainsPhase']['date_notification']); ?>
    <?php
    echo '<input type="hidden" name="data['.$key.'][ProjectDomainsPhase][done]" value=0 />';
    echo '<input type="checkbox" name="data['.$key.'][ProjectDomainsPhase][done]" value="1"';
    if ($tache['ProjectDomainsPhase']['done']==1)
    echo ' checked';
    echo ' />';
    echo '<input type="hidden" name="data['.$key.'][ProjectDomainsPhase][id]" value='.$tache['ProjectDomainsPhase']['id'].' />';
    ?>
    <?php echo $this->Date->date_inv($tache['ProjectDomainsPhase']['date_finished']); ?>

<?php };
?>

My problem is that in my view, all the data are great but when i try to sort, by clicking a column, the page reload but nothing change.

A: I got a new solution for this..
Actually i too faced the same problem and finally got a trick to do this..
Here is my join query and functionality..
        $fields = array('SubjectCategory.name,Subject.name');
        $joins = array();
        $joins[] = array(
            'table' => 'subject_category_link',
            'foreignKey' => false,
            'conditions' => array('SubjectCategoryLink.subject_id = Subject.subject_id'
            ),
            'type' => 'INNER',
            'alias' => 'SubjectCategoryLink',
        );
        $joins[] = array(
            'table' => 'subject_category',
            'foreignKey' => false,
            'conditions' => 'SubjectCategory.subject_category_id = SubjectCategoryLink.subject_category_id',
            'type' => 'INNER',
            'alias' => 'SubjectCategory',
        );
        $conditions = array('SubjectCategory.parent_category_id' => NULL);
        $limit = 10;
        $group = 'Subject.name';
        $this->paginate = array('Subject' => compact('conditions', 'fields', 'order', 'limit', 'joins', 'group'));
        $order='';
       /* Here you should solution code provided bellow */

        $this->paginate('Subject');

The cakephp paginator component only sort the above records when i call the bellow code in my view file..
echo $this->Paginator->sort('Subject.name');

The problem i faced i cant able to sort the records by SubjectCategory.name by clicking the link generated in view file.
echo $this->Paginator->sort('SubjectCategory.name');

But it works only at initial load by defining $order in controller..
$order = 'SubjectCategory.name asc';

So i analyzed the paginator component (located in app/Cake/Controller/Component/PaginatorComponent.php) in cakephp and got a trick to sort the records..
1.Add this part before your paginate call ($this->paginate('Subject')) in controller..
    if (array_key_exists('sort', $this->params['named'])) {
        $order = $this->params['named']['sort'] . ' ' . $this->params['named']['direction'];
    } else {
        $order = 'Subject.name asc';
    }
    $this->Session->write('paginate_custom',1);
    $this->paginate = array('Subject' => compact('conditions', 'fields', 'order', 'limit', 'joins', 'group'));

    $this->set(compact('order'));// Dont forget to set this order variable to view

*

*Go and edit the cakephp paginator component.(app/Cake/Controller/Component/PaginatorComponent.php)

At line 141 you can see the bellow code in paginate() function.
 $options = $this->mergeOptions($object->alias);

After this line you add the bellow logic.
    if ($this->Controller->Session->read('paginate_custom')) {
        unset($options['sort']);
        unset($options['direction']);
        $this->Controller->Session->delete('paginate_custom');
    }

3.In your view replace the bellow code at each sort call ($this->Paginator->sort('SubjectCategory.name') )
    <?php
         $col_string = explode(' ', $order);
         $col = $col_string[0];
         if ($col == 'SubjectCategory.name') {
             $dir = ($col_string[1] == 'asc') ? 'desc' : 'asc';
         } else {
             $dir = 'asc';
         }
         echo $this->Paginator->sort('SubjectCategory.name', 'Name', array('direction' => $dir));?>

I think this may help you..
All the best..
Happy programming..


text:
Q: How to async load vuetify dropdown(v-select) items in Vue I have an issue to asynchronously fetch data for the v-select Vuetify Component. The thing is the v-select component does only except Arrayfor the :items attribute. What is the workaround to fetch data asynchronously :

Invalid prop: type check failed for prop "items". Expected Array, got
  Promise

template:
<template>
    <v-layout row wrap>
        <v-flex xs12 md6 v-for="(field, index) in fields" :key="index" v-show="!field.hidden">
            <v-text-field v-if="field.component === 'v-text-field'" :label="field.label"></v-text-field>
            <v-select
                v-else-if="field.component === 'v-select' "
                :label="field.label"
                :items="(typeof field.items === 'string') ? getLookups(field.items) : []"
            ></v-select>
            <v-checkbox v-else-if="field.component === 'v-checkbox'" :label="field.label"></v-checkbox>
        </v-flex>
    </v-layout>
</template>

async method:
async getLookups( api: string | string[]) {
    // Mock Async timeout
    var wait = (ms: any) => new Promise((r, j) => setTimeout(r, ms));
    wait(2000);
    return ["test1", "test2", "test3", "test4"];
}

A: The best solution/workaround I found is creating a local variable and return the local variable instance. I just pass through the index to create a unique object for my dynamic component
template:
<template>
    <v-layout row wrap>
        <v-flex xs12 md6 v-for="(field, index) in fields" :key="index" v-show="!field.hidden">
            <v-text-field v-if="field.component === 'v-text-field'" :label="field.label"></v-text-field>
            <v-select
                v-else-if="field.component === 'v-select' "
                :label="field.label"
                :items="(typeof field.items === 'string') ? getLookups(index, field.items) : field.items"
            ></v-select>
            <v-checkbox v-else-if="field.component === 'v-checkbox'" :label="field.label"></v-checkbox>
        </v-flex>
    </v-layout>
</template>

script:
private lookups: any = {};

getLookups(index: number, api: string | string[]) {
    // Mock Async timeout
    var wait = (ms: any) => new Promise((r, j) => setTimeout(r, ms));
    wait(2000).then(() => {
        this.lookups[index] = ["test1", "test2", "test3", "test4"];
    });
    return this.lookups[index];
}

So the v-select component will be listening to the local variable. As soon as it populated it would update the v-select items.

A: Another alternative could be using asyncComputed, it's an opensource project.
data: {
    userId: 1
},
asyncComputed: {
 async getLookups( api: string | string[]) {
   // Mock Async timeout
  var wait = (ms: any) => new Promise((r, j) => setTimeout(r, ms));
  wait(2000);
  return ["test1", "test2", "test3", "test4"];
 }
}

A: Thx @Ruslan, asyncComputed works great. Below is an extract from my code "GetClients" is the computed source for my select.

async created() {
    if (this.id) {
      this.action = "Update";
      this.getItem();
    }
  },
  asyncComputed:{
    async getClients(){
      const items = await API.graphql({
        query: listClients
      });
      return items.data.listClients.items;
    }
  },
  methods: {
    async getItem() {

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do method calls in derived classes count as virtual function calls? Say I have an abstract base class and a derived class like so,
class Base {
public:
    virtual void doSomething() = 0;
}

class Derived: public Base {
private:
    void doSomethingSpecificA();
    void doSomethingSpecificB();
public:
    void doSomething();
}

and I initialize my derived class with
Base *instance = new Derived;.

Now, say I call the derived version of doSomething like:
instance->doSomething();

and doSomething() calls the private methods doSomethingSpecificA() and doSomethingSpecificB(). Do these internal calls to the specific functions require the same amount of vtable work that the original call to doSomething() required? Or are they equivalent to just a standard method call?

A:
Do these internal calls to the specific functions require the same amount of vtable work that the original call to doSomething() required?

No. There is no lookup/dynamic dispatch involved in the calls to doSomethingSpecificA and doSomethingSpecificB since they are not virtual member functions.

Or are they equivalent to just a standard method call?

Yes.


text:
Q: Lots of "Query End" states in MySQL, all connections used in a matter of minutes This morning I noticed that our MySQL server load was going sky high. Max should be 8 but it hit over 100 at one point. When I checked the process list I found loads of update queries (simple ones, incrementing a "hitcounter") that were in query end state. We couldn't kill them (well, we could, but they remained in the killed state indefinitely) and our site ground to a halt.
We had loads of problems restarting the service and had to forcibly kill some processes. When we did we were able to get MySQLd to come back up but the processes started to build up again immediately. As far as we're aware, no configuration had been changed at this point.
So, we changed innodb_flush_log_at_trx_commit from 2 to 1 (note that we need ACID compliance) in the hope that this would resolve the problem, and set the connections in PHP/PDO to be persistent. This seemed to work for an hour or so, and then the connections started to run out again.
Fortunately, I set a slave server up a couple of months ago and was able to promote it and it's taking up the slack for now, but I need to understand why this has happened and how to stop it, since the slave server is significantly underpowered compared to the master, so I need to switch back soon.
Has anyone any ideas? Could it be that something needs clearing out? I don't know what, maybe the binary logs or something? Any ideas at all? It's extremely important that we can get this server back as the master ASAP but frankly I have no idea where to look and everything I have tried so far has only resulted in a temporary fix.
Help! :)

A: We've been having a very similar problem, where the mysql processlist showed that almost all of our connections were stuck in the "query end" state. Our problem was also related to replication and writing the binlog.
We changed the sync_binlog variable from 1 to 0, which means that instead of flushing binlog changes to disk on each commit, it allows the operating system to decide when to fsync() to the binlog. That entirely resolved the "query end" problem for us.
According to this post from Mats Kindahl, writing to the binlog won't be as much of a problem in the 5.6 release of MySQL.

A: I'll answer my own question here. I checked the partition sizes with a simple df command and there I could see that /var was 100% full. I found an archive that someone had left that was 10GB in size. Deleted that, started MySQL, ran a PURGE LOGS BEFORE '2012-10-01 00:00:00' query to clear out a load of space and reduced the /var/lib/mysql directory size from 346GB to 169GB. Changed back to master and everything is running great again.
From this I've learnt that our log files get VERY large, VERY quickly. So I'll be establishing a maintenance routine to not only keep the log files down, but also to alert me when we're nearing a full partition.
I hope that's some use to someone in the future who stumbles across this with the same problem. Check your drive space! :)

A: In my case, it was indicative of maxing out the I/O on disk. I had already reduced fsyncs to a minimum, so it wasn't that. Another symptoms is "log*.tokulog*" files start accumulating because the system can't catch up all the writes.

A: I had met this problem in my production use case . I was using replace into select in the table for archival and it has 10 lakhs records init . I interrupted the query in the middle and it went to killed state  .
i had set the innodb_flush_log_at_trx_commit to 1 as well as sync_binlog=1 and it completely recovered in my case . And i have triggered my archival script again without any issues .


text:
Q: Android Bluetooth Low Energy - How do I access previously paired device? I'm developing and Android app that connects to a device via Bluetooth Low Energy.
My problem is that I can't figure out a way to connect to a device I had previously connected do. In the phone's Bluetooth settings it shows the bluetooth device as "Paired" so I would like to connect to it from the app to 'talk' to it.
Anyone knows how to do this?
Thanks in advance!

A: You can get a list of bonded devices from BluetoothAdapter:
Set<BluetoothDevice> devices = myBluetoothAdapter.getBondedDevices();

Then identify the device you are interested in and connect:
myBluetoothGatt = myBluetoothDevice.connectGatt(context, false, myGattCallback);


text:
Q: what is causing this error message [Error]: "Client 'host' unknown - use 'client' command to create it."? Whenver I try to run p4 command p4 change -o or pythonically p4.fetch_change()
I get this error message !
[Error]: "Client 'hostname' unknown - use 'client' command to create it."
Does anyone know why am I getting this ?

A: You don't have a client workspace defined.  The changelist spec you get from p4 change -o is the spec for the default pending changelist associated with your current client.  If you don't have a client, you'll get that error.  You'll see the same behavior for any other command that depends on a client spec (which is most of them).
As the error says, use p4 client to define a new client specification.  If you already have a client for hostname, use p4 set to set P4CLIENT to the name of that client.


text:
Q: Debugging internet connectivity delay issue Problem
For quite some time now, I am experiencing hiccups in my network connection, although the speeds are on par with what ISP offers (tested with https://speed.cloudflare.com/). Specifically, when I go to a website (or even when pinging an IP), there is a delay that seems unrelated to actual speed.
Here are the speed test results:

Here's the result of pinging wikipedia:
$ time ping -c 5 wikipedia.org
PING wikipedia.org (91.198.174.192) 56(84) bytes of data.
64 bytes from 91.198.174.192: icmp_seq=1 ttl=57 time=46.1 ms
64 bytes from 91.198.174.192: icmp_seq=2 ttl=57 time=48.6 ms
64 bytes from text-lb.esams.wikimedia.org (91.198.174.192): icmp_seq=3 ttl=57 time=48.2 ms
64 bytes from text-lb.esams.wikimedia.org (91.198.174.192): icmp_seq=4 ttl=57 time=48.5 ms
64 bytes from 91.198.174.192: icmp_seq=5 ttl=57 time=46.3 ms

--- wikipedia.org ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 26204ms
rtt min/avg/max/mdev = 46.085/47.527/48.634/1.100 ms

ping -c 5 wikipedia.org  0.01s user 0.00s system 0% cpu 27.280 total
                                                         ^--- this is way too high

Notice that although the ping response time is on the order of ms (~48ms), the total time taken (as measured by time) is way higher (~27s).
I tried to debug this with Wireshark and observed a consistent pattern:
there are DHCP Discover packets with a lot of delay in-between, like so:
No. Time
13  1.741054670 0.0.0.0 255.255.255.255 DHCP    590 DHCP Discover - Transaction ID 0xdefe259a
14  4.813077659 0.0.0.0 255.255.255.255 DHCP    590 DHCP Discover - Transaction ID 0xdefe259a
# ~3s delay

Here's a larger context between 2 consecutive ping request/reply:
      10 1.115798068 192.168.0.107  91.198.174.192  ICMP 98  Echo (ping) request  id=0x0009, seq=2/512, ttl=64 (reply in 11)
/---> 11 1.163998347 91.198.174.192 192.168.0.107   ICMP 98  Echo (ping) reply    id=0x0009, seq=2/512, ttl=57 (request in 10)
|     12 1.164386243 192.168.0.107  192.168.0.1     DNS  87  Standard query 0x4e78 PTR 192.174.198.91.in-addr.arpa
|     13 1.741054670 0.0.0.0        255.255.255.255 DHCP 590 DHCP Discover - Transaction ID 0xdefe259a
5s    14 4.813077659 0.0.0.0        255.255.255.255 DHCP 590 DHCP Discover - Transaction ID 0xdefe259a
|     15 6.169712508 192.168.0.107  192.168.0.1     DNS  87  Standard query 0x4e78 PTR 192.174.198.91.in-addr.arpa
|     16 6.200238569 192.168.0.1    192.168.0.107   DNS  128 Standard query response 0x4e78 PTR 192.174.198.91.in-addr.arpa PTR text-lb.esams.wikimedia.org
\---> 17 6.200452771 192.168.0.107  91.198.174.192  ICMP 98  Echo (ping) request  id=0x0009, seq=3/768, ttl=64 (reply in 18)
      18 6.246764831 91.198.174.192 192.168.0.107   ICMP 98  Echo (ping) reply    id=0x0009, seq=3/768, ttl=57 (request in 17)

I noticed this delay due to DHCP Discover in many captures.

What I tried

*

*static IP (DHCP bypass on router)

*router & computer reset

*different browsers

*different kernels

*wired connection: same delay is experienced on PPPoE

*different devices: this problem is not present on any other device connected on this network, so it's very likely it's a Linux / laptop issue

System info
System:
  Kernel: 6.0.15-1-MANJARO arch: x86_64 bits: 64 compiler: gcc v: 12.2.0
    Desktop: GNOME v: 43.2 Distro: Manjaro Linux base: Arch Linux

Machine:
  Type: Laptop System: LENOVO product: 82K8 v: Legion S7 15ACH6
    serial: <filter>
  Mobo: LENOVO model: LNVNB161216 v: NO DPK serial: <filter> UEFI: LENOVO
    v: HACN31WW date: 11/19/2021

Network:
  Device-1: Intel Wi-Fi 6 AX200 vendor: Rivet Networks Killer™
    driver: iwlwifi v: kernel bus-ID: 02:00.0
  IF: wlp2s0 state: up mac: <filter>

What can I try to further debug this?

A: The DHCP Discover messages are probably a red herring, possibly other devices in your network trying to get a dhcp address at the same time you are doing the ping (these are broadcast messages to your network, so everything in the network sees them).
Is the 5s delay consistent between all pings? I would guess the ping is running with an "-i 5" option or something similar, can you check if e.g. you have an alias for ping or something similar?
You can try "ps axuw | grep ping" while your ping is running, and see if the ping command is exactly as you run it, or if it has additional arguments, like the "-i 5" I mentioned above.
UPDATE
After looking at your tcpdump in more detail, it seems to be more related to the DNS queries. Notice that there is no answer to the first query at 1.164386243 and after a 5s timeout your resolver retries the query at 6.169712508 to which it receives the reply and the ping can continue normally. You can probably reduce the delay with an option in /etc/resolv.conf, but better if you can debug why your dns server does not respond to the first query.
To verify it is the DNS causing the delay, you can try the ping with -n to avoid the name resolution in the ping (but this same dns 5s delay will be also causing the similar problems in other situations).


text:
Q: How can I connect pg-promise with RDS proxy? I currently have an AWS RDS instance setup with a Proxy that manages connections. I am trying to connect to that proxy with pg-promise but I am getting an Error: Task timed out after 3.00 seconds.
I have tried to initialize the pgp connection the way I normally would and simply switched the host parameter with the proxy endpoint. The following is all found in one lambda file but I'll split it up for clarity:
Here I initialize (this stuff is before the handler):
const initOptions = {

    // pg-promise initialization options...

    task(e) {
        if (e.ctx.finish) {
            // this is a task->finish event;
            console.log('Duration:', e.ctx.duration);
            if (e.ctx.success) {
                // e.ctx.result = resolved data;
            } else {
                // e.ctx.result = error/rejection reason;
            }
        } else {
            // this is a task->start event;
            console.log('Start Time:', e.ctx.start);
        }
    }
}

const pgp = require('pg-promise')(initOptions)

connect to db(also before the handler)
let connection = {
    host: process.env.proxyendpoint,
    port: process.env.DB_PORT,
    database: process.env.DB,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD
}

const db = pgp(connection)

the handler that is run when lambda is called
exports.handler = async (event) => {
     ...
     try {
        console.log('before insert')
        const res = await getInsertUser({...event.body, token, chatUsername})
        console.log('after insert') <------ this is never reached
        // if new user, create one direct channel with me
        ...
        return formatResponse(res)
    } catch (error) {
        console.error(error)
        return formatError(error)
    }

this is the insert user function (tried it with and without the await)
const getInsertUser = async (userData) => {
    return await db.task('getInsertUser', async t => {
        console.log('insert user callback fired') <---- this is never reached
        const user = await t.oneOrNone('SELECT * FROM users WHERE unique_id = ${profile.sub}', userData);
        if (user) {
            return { ...user, userAlreadyExists: true }
        } else {
            const newUser = await t.one('INSERT INTO users(unique_id, name, email, chat_token, chat_username) VALUES(${profile.sub}, ${profile.nickname}, ${profile.email}, ${token}, ${chatUsername}) RETURNING *', userData);
            return {...newUser, userAlreadyExists: false }
        }
    })
}


text:
Q: Selenium wait not solving error "Element is not currently visible" I got an error:

Element is not currently visible and so may not be interacted with
  Command duration or timeout: 63 milliseconds

So I added "wait" object to wait for the html obj to load:
   val wait: WebDriverWait  = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.elementToBeClickable(By.id("company_id")))

   val selectCompany = new Select(driver.findElement(By.id("company_id")))
    selectCompany.selectByValue("975")

but still i get the error:

Exception in thread "main" org.openqa.selenium.TimeoutException: Timed
  out after 10 seconds waiting for element to be clickable: By.id:
  company_id

and I dont get it since the html is:
<select class="upload_company_id jcf-hidden" id="company_id" name="company_id" size="2"><option value="">Select account...</option>
<option value="100">100</option>
<option value="101">101</option>
<option value="104">104</option>
<option value="975">105</option>

this is more of the html:

thanks

A: I am not sure that the expected condition you choosed is right.The class you are using is select class. Could you please try elementToBeSelected(WebElement element)?

A: What you need to check is the computed CSS values of the element you are clicking. (In Chrome web inspector select the Computed tab on the right).
Selenium thinks that an element is hidden and can't be interacted with if any of these CSS values are set for the element:

*

*display=none or

*visibility=hidden or

*visibility=collapse
If you can find any of these values on the computed tab, you will have to use JS to click on the element, or change the CSS value of the element on some way - Selenium will refuse interacting with the element regardless of the actual visibility of it. (I suspect the problem will be the "jcf-hidden" class)

When inspecting the element, switch to this tab in Chrome inspector on the right side:
 and look for any of the mentioned values in the list.


text:
Q: Can't get a token from the Google API I'm trying to exchange my authorization code for a token with the Google OAuth2 API for my Windows 8 app, but I keep getting HTTP 400 errors.
This is how I perform the request (simplified):
var url = "https://accounts.google.com/o/oauth2/token";
var body = "code=4/LEXF1iAVRZvfCfdQg9r1aFqoYDgV&client_id=904019870963.apps.googleusercontent.com&client_secret=[removed]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code";

HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(new Uri(url), new StringContent(body));

response.EnsureSuccessStatusCode();

Visual Studio usually simply gives me a HTTP 400 bad request error, when I try the same thing in Fiddler I also get an HTTP 400 error, but with this as content:
21
{
  "error" : "invalid_request"
}
0

I read all the documentation about Google OAuth, I searched on Google and StackOverflow for this issue, I tried changing all different sorts of things in my code (UrlEncode, etc.), I used the Google API Playground to see what kind of requests it performs and compared it with my own requests (couldn't find a difference except for the return URL, the auth code and the user-agent). No matter what I do, I just can't get this working, I've been stuck for hours already.
Can anyone help me out here?

A: Read the body content to get the error json you noticed in Fiddler.
HttpClient httpClient = new HttpClient();
var response = httpClient.PostAsync(new Uri(url), new StringContent(body)).Result;
var content = response.Content.ReadAsStringAsync().Result;

content now holds :
{
  "error" : "invalid_request"
}

You could project the error in an object, by specifing your error type like: response.Content.ReadAsAsync().Result
For the invalid request part, you should play with UrlEncode. I know you say you tried it, but applying it at the right spots really solves your problem.
var body = "code="+WebUtility.UrlEncode("4/LEXF1iAVRZvfCfdQg9r1aFqoYDgV")+
           "&redirect_uri="+WebUtility.UrlEncode("https://yoursite...")+
           "&client_id=904019870963.apps.googleusercontent.com" +
           "&scope=" +
           "&client_secret=********" +
           "&grant_type=authorization_code";

HttpClient httpClient = new HttpClient();
var response = httpClient.PostAsync(new Uri(endpoint),
    new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded")).Result;

This is the code that works for me. Should work for you also.


text:
Q: Menu bar scrolling not working in IE I have a flyover dropdown menu and when I scroll down the page this menu need to appear all the time. I have this below code which is working fine for FFox and chrome but IE8 and I hope IE9 its not working. Not sure whats causing the issue. Please suggest if any change need to be done to work with IE as well
var name = ".cssMenu";
//var menuYloc = null;
$(document).ready(function(){
    //menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")))
    $(window).scroll(function () {
    if($(this).scrollTop()>70){

        offset =$(document).scrollTop()-70+"px";
        }
        else
        {
        offset = $(document).scrollTop()+"px";
        }

        $(name).css("top",offset);
    });
});

A: i blind shoot suspect it being the order its executed. try wrapping it in () like:
`offset =($(document).scrollTop()-70)+"px";`


text:
Q: SQL query to select a word from 100 columns I have 100 columns in an Oracle table like this Sh. North Miladhunmadulu - Shaviyani Atoll . I need a query to select only Shaviyani from the above. Please help me. I need to select data after - and before Atoll word.

A: Assuming you are talking about rows and not column. You can achieve this using multiple comma separated CTE.
Below query has 3 cte table. Table t0 will pull the position of the '-' using charindex function. Then using the charindex function we can find the  next space which should be after the word Shaviyani. As you can see there is immediate space after '-'. Therefore we will have added +2 to t0.position to the table t1 which is used to find the position of the next space. The table t3 will get the final result using substring function.
declare @string nvarchar(50)='Sh. North Miladhunmadulu - Shaviyani Atoll';

with t0 AS (select charindex('-',@string) pos, @string name),
     t1 AS (select charindex(' ',@string,pos+2) pos,name from t0),
     t2 AS (select substring(@string,t0.pos+1,t1.pos - t0.pos) name
            from t0
            inner join t1 on t0.name = t1.name )

select * from t2

Output
name
--------------------------------------------------
 Shaviyani

A: Please use SUBSTR and INSTR as following
SELECT SUBSTR('Sh. North Miladhunmadulu - Shaviyani Atoll',instr ('Sh. North Miladhunmadulu - Shaviyani Atoll','-')+1,
        ((instr ('Sh. North Miladhunmadulu - Shaviyani Atoll','Atoll')-1) - instr ('Sh. North Miladhunmadulu - Shaviyani Atoll','-'))) as OUTPUT
    FROM dual;

Here is output at Fiddle
Replace the string by column name and dual with your table name.


text:
Q: Android splash Activity does not implement or extend Thread Class The splash screen activity works on thread class but it does not extend or implement Thread. then how does the Thread work inside the Activity?

A: Why Activity not extends Thread class.you can implements Runnable as in your Activity:
public class AndroidRunnable extends Activity implements Runnable{

Thread myThread;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
  }

  @Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}

@Override
public void run() {
// TODO Auto-generated method stub

}

}

See this Example for Creating Splashing Screen Activity Using Thread:
Android tutorial: How to make a basic splash screen


text:
Q: Why is my Modal Bottom Sheet not blocking the main screen? From documentation, I read that the Modal Bottom Sheet should block the main screen and place a tint over it. I thought all that needed to be done was to extend BottomSheetDialogFragment and it would work. Is there a property that is not being set?
Bottom sheet class:
class BottomTimeSheet: BottomSheetDialogFragment() {

    private lateinit var bottomSheetLayout: ConstraintLayout
    private lateinit var bottomSheetBehavior: BottomSheetBehavior<ConstraintLayout>
    private lateinit var bottomSheetCloseBtn: MaterialButton

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.bottom_sheet, container, false)

        bottomSheetCloseBtn = view.findViewById(R.id.bottom_sheet_btn1)
        bottomSheetLayout = view.findViewById(R.id.bottom_sheet_layout)
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetLayout)
        bottomSheetBehavior.setBottomSheetCallback(object: BottomSheetBehavior.BottomSheetCallback(){
            override fun onSlide(bottomSheet: View, slideOffset: Float) {
            }

            override fun onStateChanged(bottomSheet: View, newState: Int) {
                Log.d(TAG, "newState: $newState")
            }

        })

        bottomSheetCloseBtn.setOnClickListener {
            hideBottomTimeSheet()
        }

        return view
    }

    fun showBottomTimeSheet(){
        if(bottomSheetBehavior.state == BottomSheetBehavior.STATE_COLLAPSED){
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
        }
    }

    fun hideBottomTimeSheet(){
        if(bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED){
            bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
        }
    }

    companion object {
        val TAG = BottomTimeSheet::class.java.toString()
    }

}

bottom_sheet.xml:
<?xml version="1.0" encoding="utf-8"?>

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bottom_sheet_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="end">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/bottom_sheet_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        app:behavior_peekHeight="0dp"
        app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

        <com.google.android.material.textview.MaterialTextView
            android:id="@+id/bottom_sheet_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="This is a bottom sheet"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"/>

        <com.google.android.material.button.MaterialButton
            android:id="@+id/bottom_sheet_btn1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@id/bottom_sheet_text"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            style="@style/Widget.MaterialComponents.Button"
            />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/bottom_sheet_btn2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@id/bottom_sheet_btn1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            style="@style/Widget.MaterialComponents.Button"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

The bottom sheet slides up, but you can see there is not tint nor blocking on the main screen. The buttons on main screen are still clickable.
Edit:
I am instantiating and invoking the bottom sheet like this
private lateinit var bottomTimeSheet: BottomTimeSheet

bottomTimeSheet = BottomTimeSheet

bottomTimeSheet.showBottomTimeSheet()

element in main_activity.xml:
   <fragment
       android:id="@+id/bottom_sheet_view"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:name="com.ds.base.fragments.BottomTimeSheet"
       tools:layout="@layout/bottom_sheet"/>


text:
Q: How does comparison between defined object and dynamic object work using "is" keyword? I prepared code like this and I wonder how does "is" work here?
Why it just ignores null and how does field comparison work? Does it use reflection somewhere?
using System;
using System.Linq;

public class A
{
    public int x;
    public int y;

    public override string ToString()
    {
        return $"{x} {y}";
    }
}

public class Test
{
    private static Random rnd = new Random();

    public static void Main()
    {
        A[] a = new A[10];

        for(int i = 0; i < a.Length; ++i)
        {
            a[i] = new A();
            a[i].x = rnd.Next() % 2;
            a[i].y = rnd.Next() % 10;

            if(a[i].y < 5)
                a[i] = null;
        }

        //How the hell does it null-checks?
        //How does `is` work here?
        if(a.Any(obj => obj is { x: 1 })) {
            Console.WriteLine("There is object with x = 1");
        } else {
            Console.WriteLine("There is no object with x = 1");
        }

        Console.WriteLine("========DEBUG");
        Console.WriteLine(string.Join("\n", a.ToList()));
    }
}


text:
Q: Sorting of Arraylist by date only sorts day and not month and year? I'm attempting to SORT an ArrayList by (Type Date) MyObject.getDate()
My format is formatted by SimpleDateFormat by dd-mm-yyyy;
I'm using a custom comparator to sort my list.
I'm using Collections.sort(produuctList, new CustomComparator())
Problem my sorted list is only by dd and not dd-mm-yyyy.
Any ideas?
public class Product
{
    private String productName;
    private Date boughtOn;
    private Date useBy;
    private double boughtAt;
    private long quantity;
    private static DateFormat dateFormat;

    public Date getUseBy()
    {
        return useBy;
    }
    public void setUseBy(Date useBy)
    {
        this.useBy = useBy;
    }
}

public static Date rtnDate(String dateStr, int currentLineCount)
    {
        SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
        try
        {
            Date date = df.parse(dateStr);
            return date;
        }
        catch (ParseException e)
        {
            productParsingErrorMessages.add("Date parse exception: " + e + "on line " + currentLineCount);
            return null;
        }

//      DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
//      Date date2 = (Date)formatter.parse(dateStr);
    }

System.out.println("Product list - BEFORE sorting by UseBy");
printInventory(produuctList);

Collections.sort(produuctList, new CustomComparator());

System.out.println("Product list - AFTER sorting by UseBy");
printInventory(produuctList);

public class CustomComparator implements Comparator<Product>
{
    @Override
    public int compare(Product o1, Product o2)
    {
        return o1.getUseBy().compareTo(o2.getUseBy());
    }
}

Product list - BEFORE sorting by UseBy
Product name: sugar  UseBy : 12-12-2012
Product name: sugar  UseBy : 01-10-2012
Product name: sugar  UseBy : 16-04-2012
Product name: sugar  UseBy : 30-01-2012
Product name: sugar  UseBy : 25-04-2012
Product name: sugar  UseBy : 03-04-2012
Product name: sugar  UseBy : 08-04-2012
Product list - AFTER sorting by UseBy
Product name: sugar  UseBy : 01-10-2012
Product name: sugar  UseBy : 03-04-2012
Product name: sugar  UseBy : 08-04-2012
Product name: sugar  UseBy : 12-12-2012
Product name: sugar  UseBy : 16-04-2012
Product name: sugar  UseBy : 25-04-2012
Product name: sugar  UseBy : 30-01-2012

A: If your format String has been copied correctly, your SimpleDateFormat is wrong. It should be dd-MM-yyyy, not dd-mm-yyyy, since you're interested in months, not minutes.
You've got:
public static Date rtnDate(String dateStr, int currentLineCount)
{
    SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");

When you should be using:
public static Date rtnDate(String dateStr, int currentLineCount)
{
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");

This would explain everything.

A: I'm about 90% sure you're comparing java.lang.Strings and not java.util.Dates. Given the date format you mentioned, it'll obviously sort all the days together first. E.g. for a full year, your list would start off:
01-01-2012 (1 Jan)
01-02-2012 (1 Feb)
01-03-2012 (1 Mar)

Use the Date object to compare on, not a String representation of it.
P.S. a picture is not code. Put your code in your question.
Update: Proof that the code you've posted works as expected:
import java.text.DateFormat;
import java.util.*;

public class DateComparators {
    public static void main(String[] args) {
        List<Product> productList = Arrays.asList(
                new Product(new Date(2012 - 1900, 5, 1)), // 1 Jun 2012
                new Product(new Date(2012 - 1900, 1, 1)), // 1 Feb 2012
                new Product(new Date(2012 - 1900, 2, 15)), // 15 Mar 2012
                new Product(new Date(2012 - 1900, 0, 2)), // 2 Jan 2012
                new Product(new Date(2012 - 1900, 1, 2)), // 2 Feb 2012
                new Product(new Date(2012 - 1900, 0, 1)) // 1 Jan 2012
        );
        Collections.sort(productList, new CustomComparator());
        System.out.println(productList);
    }

    static class CustomComparator implements Comparator<Product> {
        @Override
        public int compare(Product o1, Product o2) {
            return o1.getUseBy().compareTo(o2.getUseBy());
        }
    }

    static class Product {
        private String productName; // sauce pan
        private Date boughtOn; // 4-5-2012
        private Date useBy; // 4-5-2012
        private double boughtAt; // $4.05
        private long quantity; // 9
        private static DateFormat dateFormat;

        Product(Date useBy) {
            this.useBy = useBy;
        }

        public Date getUseBy() {
            return useBy;
        }

        public void setUseBy(Date useBy) {
            this.useBy = useBy;
        }

        @Override
        public String toString() {
            return "\nuseBy=" + useBy;
        }
    }
}

Output:
[
useBy=Sun Jan 01 00:00:00 CST 2012,
useBy=Mon Jan 02 00:00:00 CST 2012,
useBy=Wed Feb 01 00:00:00 CST 2012,
useBy=Thu Feb 02 00:00:00 CST 2012,
useBy=Thu Mar 15 00:00:00 CDT 2012,
useBy=Fri Jun 01 00:00:00 CDT 2012]

Therefore, you haven't shown us everything. The problem is in something you left out.


text:
Q: what is the best way to find longest path between set of nodes(certain nodes) in neo4j? I have set of nodes which will be declared by user(I mean user enters some words and those which exist among my nodes will be included in my set of nodes),and I want to find the longest path which exists between just these nodes(does not have to include all of the nodes in set ,but should not include a node which is not exist in my set of nodes)in neo4j embedded java database.(I do not know what is the start node,all of them can be the start node.)
First I thought maybe I have to make a subgraph of these nodes and relations between them,and then find the longest path in that subgraph,but I don't know what is the right and best thing to do?
Then i thought,I can directly find longest path between the set of nodes(can that be done?).
Or if this can't be done,how about finding the relations of the certain nodes(set of nodes) and make a set of relations,and then find the longest path between set of relations?
I want the optimum and fastest way in performance,and I don't want cypher query,because I am using java core api(it is faster),so please tell me what is the best way?
Consider it as a large scale database,with so many nodes.
Thanks in advance.

A: i'm afraid this cannot be done by any standard algorithm except traversing the whole graph. thus, there is no optimum way in performance. neo4j has no build-in option for it.
this is an cypher query (sorry i don't know other input languages in neo4j):
start n1=node(*), n2=node(user)
match n1--n2    //filter only the just declared user nodes, or any other matching condition
with n1, n2
match p=n1-[r:..*]-m, m--n2    //all paths between declared user nodes
return p
order by length(r) desc
limit 1


text:
Q: How to add condition to EmberJS Input Helper How can I build a this input <input class="{{unless isEditing "hidden"}}" /> with the input helper of Ember.js?

A: You can use parenthesis to have another helper within a helper
{{input class=(unless isEditing "hidden")}}


text:
Q: Initializer for conditional binding must have Optional type, not 'String'? Unable to read FCM notification Userdata, I am trying this-
    let userInfo = response.notification.request.content.userInfo

             if let jsonResult = userInfo as? Dictionary<String, AnyObject> //**Getting error on this line**
{

             if let notifyType =
              jsonResult["gcm.notification.notification_type"] as? String ?? ""
              {

                print(notifyType)

              }
            }

A: In your code
replace:
  if let notifyType =
      jsonResult["gcm.notification.notification_type"] as? String ?? ""
      {

with:
  if let notifyType =
      jsonResult["gcm.notification.notification_type"] as? String {


text:
Q: Android: (De)Activating TapSpecs when a application successfully connected This is my first application with Android! ;-)
I have got a TabHost with 4 TabSpecs. The "Account" is for the Connection (it should always work) the others should only work if the Login was successful and there is a connection to the service (which uses a RESTful API).
http://i.stack.imgur.com/zp5DT.png
I thought it would be helpful to have a Handler in the TabAcivitiy to change the TabSpecs-Status:
      Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
            case NOTIFY_DATASET_CHANGED:
                if(ServiceFactory.connected()){
                    tabHost.getTabWidget().getChildTabViewAt(1).setEnabled(true);
                    tabHost.getTabWidget().getChildTabViewAt(2).setEnabled(true);
                    tabHost.getTabWidget().getChildTabViewAt(3).setEnabled(true);
                }else{
                    tabHost.getTabWidget().getChildTabViewAt(1).setEnabled(false);
                    tabHost.getTabWidget().getChildTabViewAt(2).setEnabled(false);
                    tabHost.getTabWidget().getChildTabViewAt(3).setEnabled(false);
                }
                break;
            default:
                break;
            }
        }
    };

The static function connected() tests the connection to the RESTful API.
But now I do not know how I should proceed because I don't know how to access this handler from a Activity (AccountActivity for example).
Any good ideas to solve the problem ?

A: Consider setting an OnTabChangedListener for the TabHost. This callback will allow you to switch back to your login tab if they have not authenticated yet. Then after they've logged in you can allow them to change tabs.


text:
Q: Why can't Windows find a file that's obviously there? Take a look at this picture. There is a file that's obviously there

Now, say I tried to find FileZilla or File, or Zilla

As you see from the same screen shot the file is obviously not there.
So why and how do I fix it? Is the index broken or what? No error message whatsoever.
I want to know I will always be able to find my files.


text:
Q: how to use array_push() I want to push new data in array which each value of them.
$array = array("menu1" => "101", "menu2" => "201");
array_push($array, "menu3" => "301");

But I got an error syntax.
And if I use like this :
$array = array("menu1" => "101", "menu2" => "201");
array_push($array, "menu3", "301");

result is : Array ( [menu1]=>101  [menu2]=>201   [0]=>menu3  [1]=>301 )

My hope the result is : Array ( [menu1]=>101  [menu2]=>201   [menu3]=>301 )

I want push new [menu3]=>'301' but I dont know how. Please help me, the answer will be appreciate

A: You can use
$array["menu3"] = "301"

as for array_push

array_push() treats array as a stack, and pushes the passed variables onto the end of array

so for associative arrays is a no match
another suitable function for what you want but it requires an array argument is array_merge
$result = array_merge(array("one" => "1"), array("two" => "2"));


text:
Q: Universal property of X//G? Given an operation of say a topological group on a topological space, one can form the quotient stack X//G:
the stack associated to the action groupoid.
Does this stack satisfy some kind of universal property?

A: Probably the simplest example is when the space $X$ is a single point. Then $pt//G$ classifies principal $G$-bundles. Here, the action groupoid is just $G$ considered as a one-object groupoid. The one object, $pt$ becomes an atlas for the stack, so we have a representable epimorphism $pt \to pt//G$. This is in fact the universal principal $G$-bundle! Given any map $X \to pt//G$, the 2-fibered product $X \times_{pt//G} pt\to X$ is a principal $G$-bundle. What we have in general is, given any topological groupoid $H$, its associated stack (stackification of $Hom(blank,H)$ ) is equivalent to $Bun_H:T \mapsto Bun_H(T)$, where $Bun_H(T)$ is the groupoid of principal $H$-bundles over $T$. So, by Yoneda, we have for all spaces $T$, an equivalence of groupoids $Hom(T,Bun_H) \cong Bun_H(T)$. Moreover, you can show that for any map $T \to Bun_H$, the principal bundle $P$ to which the map corresponds is the 2-fibered product $T \times_{Bun_H} H_0 \to T$. Applying this to the case when $H$ is the group $G$, we get what I claimed. Now, if instead $H$ is the action groupoid of $G$ on a space $X$, we get that $X//G$ classifies principal $G \ltimes X$-bundles. This answers the question as far as what maps INTO the stack yield.
As Chris suggested, for any topological groupoid, you can take its enriched-nerve to get a simplicial space. Applying Yoneda on each component, you get a simplicial stack. The weak 2-colimit of this, is equivalent to the stack associated to the groupoid. (In fact, you only need to consider the 2-truncation of this diagram). Spelling this out, you get Proposition 3.19 out of Noohi's Foundations of Topological Stacks I. This roughly says that maps from the stack associated to a groupoid $H$ into another stack $Y$ are the same as maps $f:H_0 \to Y$ (or by Yoneda elements $f \in Y(H_0)_0$) together with an isomorphism $f \circ s \to f \circ t$ satisfying some obvious coherencies, where $s$ and $t$ are the source and target map of the groupoid $H_1 \rightrightarrows H_0$. In the case where $H$ is the action groupoid $G \ltimes X$, you get maps $f:X \to Y$, together with isomorphisms $f \circ proj \to f \circ \rho$, where $\rho:G \times X \to X$ is the action. This becomes more concrete, if for example, $Y$ is not some arbitrary stack, but instead the stack of principal $K$-bundles for some group $K$. Then $Hom(X//G,Bun_K)$ is the groupoid with objects principal $G$-bundles $P$ over $X$ together with an isomorphism $proj^*P \cong \rho^*P$ (satisfying a cocycle condition), with the obvious arrows.
If you were wondering why $X//G$ was the "like the ordinary quotient but better", then the following heuristics should help. The 2-truncated guy whose colimit equals $X//G$ is "like the colimit expressing $X/G$ but with the action built in more". In fact, we we took the UNtruncated guy, so, the simplicial space associated to the action groupoid, then it "IS" the Borel construction (or rather its geometric realization). In particular, this implies the homotopy type of $X//G$ is the same as the homotopy quotient $EG \times_G X$. Now consider one more thing- if $G$ is acting on $X$ we have the commutative square with $G \times X$ on the upper left, $X$ on bottom left and on the upper right, and $X/G$ (the coarse quotient) on the bottom right, with map up top being the action, and the map down below being the projection, then this is a pullback diagram if and only if the action is faithful. If you replace $X/G$ with $X//G$, then this is ALWAYS a (2-)pullback diagram. Hence, going to stacks "makes all actions faithful up to homotopy" (more accurately, stacks allow us to encode the isotropy data that would otherwise be lost in such a way that any action becomes as good as a faithful one).

A: Yes. It is the (homotopy) colimit in stacks of the simplicial diagram:
$$\cdots X \times G^2 \Rightarrow X \times G \rightrightarrows X $$
(here $\Rightarrow$ is a substitute for three arrows). This simplicial object is built from the action of G on X.  Since stacks form a 2-category, the natural thing is a "weak" or "homotopy" colimit. See the n-lab pages. The inclusion from spaces into stacks doesn't preserve colimits, so even though this is a diagram of ordinary spaces, the colimit is an interesting stack.
Since it is a colimit, there is a clear associated universal property for maps out of this stack.
It is also the stackification of the presheaf of groupoids associated to the action groupoid, hence from this description it satisfies another additional universal property for maps out of it, and there is a concrete description for maps into it. It is a fun (but tedious) exercise to see that the two universal properties are in fact the same.


text:
Q: PHP script to extract specific href links
Possible Duplicate:
Grabbing the href attribute of an A element

I would like to make a php script that extracts all the href links from a webpage (mine) but only links with "/view/" in their string.
http://www.example.com/roger/that => not extracted
http://www.example.com/roger/view/that => extracted
And if possible all the links would be set in an array
So basically the script would be in my admin section and I would run it to get all the links containing the specific string '/view/'  in an array to use later in another script.
I've done my research and found this script but can't modify it to only include the specific links (with "/view/")
I know you guys are not my slaves so even if you have any tips for modifying the existing script I would be happy !
My script
http://pastebin.com/gYf9DZ8i
Thanks !

A: Fetch the page contents using file_get_contents.
$input = file_get_contents("http://www.yourpage.php");

Then do a preg_match to extract the set of links you want.
Regex:    /\<a href(.*?\/view\/.*?)<\/a>/
$pattern = '/\<a href(.*?\/view\/.*?)<\/a>/';
preg_match_all($pattern, $input, $matches);
print_r($matches);

(Example)

A: You just need to change this:
preg_match_all ("/a[\s]+[^>]*?href[\s]?=[\s\"\']+".
                "(.*?)[\"\']+.*?>"."([^<]+|.*?)?<\/a>/",
                $var, &$matches);

into this
preg_match_all ("/<a.*href=\"([^\"]*\/view\/[^"]*)\"/", $var, &$matches);

A: $var = file_get_contents("http://www.entendu.info");

preg_match_all ("/<a\s+[^>]*?\bhref\s*=\s*([\'\"])(?=[^\'\"]*\/view\/)(.*?)[\'\"]/",
  $var, &$matches);

$matches = $matches[2];

foreach($matches as $var)
{
  print($var . "<br>\n");
}


text:
Q: Matrix exponentiation problem I have a problem with figuring this out. I looked at wikipedia article, but I'm not understanding it obviously. I have a matrix
$$
A=\left(\begin{array}{cc}0&a\\a&0\end{array}\right)
$$
And I need to find matrix exponential of that matrix. The solution is given as:
$$
\exp\left(\begin{array}{cc}0&a\\a&0\end{array}\right)=\sum^\infty_{k=0}\frac{1}{k!}\left(\begin{array}{cc}0&a\\a&0\end{array}\right)^k=\left(\begin{array}{cc}1&0\\0&1\end{array}\right)+\left(\begin{array}{cc}0&a\\a&0\end{array}\right)+\frac{1}{2}\left(\begin{array}{cc}a^2&0\\0&a^2\end{array}\right)+\frac{1}{6}\left(\begin{array}{cc}0&a^3\\a^3&0\end{array}\right)+\ldots
$$
But how? Shouldn't it be just writing a Taylor expansion for exponential function with $A$ as exponent? Why are the terms alternating? Can someone clarify this a bit for me? Thanks.

A: Multiply out a few and you will see:
$$\left(\begin{array}{cc}0&a\\a&0\end{array}\right)\left(\begin{array}{cc}0&a\\a&0\end{array}\right)=\left(\begin{array}{cc}a^2&0\\0&a^2\end{array}\right),$$
$$\left(\begin{array}{cc}0&a\\a&0\end{array}\right)\left(\begin{array}{cc}a^2&0\\0&a^2\end{array}\right)=\left(\begin{array}{cc}0&a^3\\a^3&0\end{array}\right),$$
and so forth.

A: We have
$$
A^2=\left(\begin{array}{cc}0&a\\a&0\end{array}\right)\left(\begin{array}{cc}0&a\\a&0\end{array}\right)=\left(\begin{array}{cc}a^2&0\\0&a^2\end{array}\right)=a^2I_2
$$
so it's simple to see that
$$A^k=a^kI_2\;\text{if $k$ is even and}\; A^k=a^{k-1} A\;\text{if $k$ is odd}$$
so
$$\exp(A)=\sum_{k=0}^\infty\frac{A^k}{k!}=\sum_{p=0}^\infty\frac{A^{2p}}{(2p)!}+\sum_{p=0}^\infty\frac{A^{2p+1}}{(2p+1)!}= \left(\sum_{p=0}^\infty\frac{a^{2p}}{(2p)!}\right)I_2+\left(\sum_{p=0}^\infty\frac{a^{2p}}{(2p+1)!}\right)A\\=\cosh(a)I_2+\frac{1}{a}\sinh(a)A=\left(\begin{array}{cc}\cosh(a)&\sinh(a)\\\sinh(a)&\cosh(a)\end{array}\right)$$


text:
Q: Does gravity play a role in the Earth's equatorial bulge? I'm trying to understand why the Earth bulges at the equator. But before looking at the Earth, which introduces gravity, I wanted to make sure I understood the shape of some rotating objects and if/why they have a bulge.
A metal sphere: A very rigid object. If this is rotated then there is no bulge because it requires a lot of energy to deform the object.
A ball of sand: Nothing is connected. If this rotated then all the sand is simply thrown off due to inertia, leaving nothing behind after a time.
A ball of dirt: Somewhat rigid. The dirt wants to "fly off" due to inertia but tension keeps the object pulled together, as a result there is bulge at the equator - where the velocity is fastest and thus more "tension" (more bulge) is needed.
Does the "ball of dirt" situation accurately resemble Earth? If so, then does this not suffice to explain why the Earth bulges without even needing to mention gravity? Or is Earth more like the "ball of sand" which is can only be kept together (while rotating) under the force of gravity? Or is it something between or neither at all?
I'm afraid I'm terribly confused as to how the various effects come in to play and interact to create an equatorial bulge. Some sources have tried to explain in terms of an energy equilibrium but I'm not entirely satisfied with that as an explanation (actually that source even indicates the equilibrium approach is not so straightforward).

A:
Does gravity play a role in the Earth's equatorial bulge?

Absolutely.

A metal sphere: A very rigid object. If this is rotated then there is no bulge because it requires a lot of energy to deform the object.

Of your three models, this is the closest to the truth. Metal is not quite as rigid as you think. It compresses under pressure, bends under strain. Solid metal can be quite ductile and malleable, particularly when it's warm.
Most of the Earth is solid rock. It, too, is ductile and malleable.
That ductility and malleability, combined with gravitation, is all that is needed to explain the Earth's equatorial bulge. The Earth's self-gravitation forces the Earth to take on a shape whose surface is very close to an equipotential surface. The equipotential surface for a rotating object is not spherical. It is instead ellipsoidal. In other words, an object with an equatorial bulge.

A: The inside of the earth is still, partly liquid, source: Mantle  So, it's very viscous, slow moving under very high pressure, but it's still liquid enough and the Earth's crust is really quite thin and not nearly rigid enough to resist forces from below.
Taking the earth as a whole, I'm not sure there's a really good single single analogy.

A metal sphere: A very rigid object. If this is rotated then there is
  no bulge because it requires a lot of energy to deform the object.

OK, I can't do the math here, but in a nutshell, an Earth made of Iron and an earth made of water would have the same bulge - er, almost certainly.    Certainly a hot earth made of iron would have the same bulge as the earth does now, cause the inside would be liquid (and the formation of planets tends to get them very very hot).   The bulge has nothing to do with density or tension.  Just angular momentum vs gravity.  An earth made of fluffy marshmallow vs an earth made of iron would have very different gravity but the corresponding angular momentum would be equivalent to the ratio in gravity so the bulge would be the same no matter what the material.
Now, if you could construct an entire earth - cold and solid all the way through, made of Iron into a perfect sphere, maybe such an earth could resist the centrifugal forces that makes planets bulge. - MAYBE, but it would have to be artificially constructed and even then, I'm not sure it would hold and even if the strong metallic bonds did hold, there would still be stretching around the middle due to rotation anyway.   It's roughly the same principal of how high can you build.   At a certain point, even the strongest metals won't support themselves if you keep building bigger and bigger - so generally speaking, hardness isn't a factor at all in planetary bulges any more than mass is - at least at the size of a planet.   All that matters is the ratio between gravitation and rotation.   At the size of a large asteroid or small moon, then hardness matters, but not for an earth sized planet.

A ball of sand: Nothing is connected. If this rotated then all the
  sand is simply thrown off due to inertia, leaving nothing behind after
  a time.

You have to compare the gravitational force to the centrifugal force.   If the Earth spun some 18 times faster, sand could fly off the equator, effectively weightless.   The Earth spins much to slow for that to happen though when the moon formed, the Earth may have spun some 5 or 6 times faster than it does today - enough that, at that speed of rotation, you'd feel noticeably a little lighter on the equator, but not enough for stuff to fly off.   in other words, Gravity 42, Inertia 0.  It's not even close.
On Jupiter, which spins faster than any other planet, and assuming it had a hard surface you could stand on, you would notice a measurable difference in your weight at the pole vs on the equator.  Source:   Jupiter
Quote:

A day on Jupiter is only 9 hours and 48 minutes long. Such fast
  rotation causes Jupiter to be somewhat squashed due to centrifugal
  force: its polar radius is 4000 km less than its equatorial radius
  (the latter being 71,392 km). That means you'd weigh almost 25% more
  at Jupiter's poles than at its equator, that is, if you could find a
  place to stand! So a 100 pound person (on Earth) would weigh 230
  pounds at Jupiter's equator but 285 pounds at the pole!

Now, if you get small enough objects with very low gravity, what you suggest can happen.  There are comets and asteroids that spin fast where anything lose on their rotation flies off, or, effectively negative gravity.   That can't happen with a planet, it can only happen with small objects and even then, it's pretty rare.
Example:  negative gravity asteroid
OK, moving on:

A ball of dirt: Somewhat rigid. The dirt wants to "fly off" due to
  inertia but tension keeps the object pulled together, as a result
  there is bulge at the equator - where the velocity is fastest and thus
  more "tension" (more bulge) is needed.

As discussed above, inertia would need to be sufficient to effectively make gravity zero.   At the size of a water balloon, gravity makes no sense, and things like surface tension is what you can see.   Small things don't have gravity to speak of.   At the size of a planet, bulges happen, but nothing flies off.   The bulge and "flying off" is the same force, but Gravity wins and it's not even close.

I'm afraid I'm terribly confused as to how the various effects come in
  to play and interact to create an equatorial bulge. Some sources have
  tried to explain in terms of an energy equilibrium but I'm not
  entirely satisfied with that as an explanation (actually that source
  even indicates the equilibrium approach is not so straightforward).

Gravity and the inertia from spinning can seem counter intuitive.  I get that.  The idea that standing on the Earth's equator and knowing that you're spinning at over 1,000 MPH, you might think, moving that fast, maybe I should fly off the earth and for what it's worth, that confused Ptolemy too, that's why he rejected the rotating earth idea that Aristarchus of Samos had proposed.  (Aristarchus followed Aristotle and I sometimes wonder what might have been had Aristotle and Aristarchus met and had that discussion, but Aristarchus was born 12 years after Aristotle died, and by then Aristotle's writings, which were accepted as scientific gospel for nearly 1,800 years, had been finished.   And, I'm not trying to put down Ptolemy or Aristotle, that's probobly not fair.   I only bring up the example to point out that the idea that the Earth was rotating was sufficiently confusing that many of the brightest people on earth doubted it was possible for many centuries.
So lets use a real world example:
You're in a car and the car takes a turn, or banks, if you like and you feel yourself pulled in the opposite direction of the bank.   That's quite similar to the interaction between gravity and centrifugal force on the surface of the earth.   Now in a car, gravity pulls you down and when the car banks a hard turn - that pulls you sideways, the forces are at a 90 degree angle.   Gravity down stays constant but gravity sideways depends on the speed and tightness of the turn.
On earth, lets say the earth's equator - same thing, except Gravity is down and the centrifugal force, or inertia, or bank - whatever you want to call it, is effectively up, not sideways.
OK, back to the car.   The car is driving very fast, just over 1,000 MPH, but it banks the turn very slowly, in fact, the turn on the wheel is so slight, you barely even see it and it takes 6 hours and over 6,000 miles of driving to complete 1 90 degree turn.   Because the turn takes so long, the force you feel sideways in that car is very slight - about 3 OZ to a 200 lb person.
Same with the earth.  The Inertia, reduces your gravity less than 1/2 of 1 percent - so little, in fact, you don't even feel it.
hope that wasn't too long.  :-)


text:
Q: Excel - Random Numbers - and If statement In "A", rows 1-1000, I generate random numbers using RAND(). I want to pick numbers between say 1-100.
In "B" for 1000 rows I have =RAND()*(100-1)+1
In "C" for 1000 rows I use the numbers that I generated in "A", so =A1*(100-1)+1
The averages in B and C are the same, as expected.
I only want to use the values for 20% of the time, so for each of the 1000 rows:
For B, I use  =IF(A1<0.2,B1,0)
For C, I use  =IF(A1<0.2,C1,0)
If I do this, the averages for each of the two columns are vastly different.
Can anybody explain why?
Both approaches are using random numbers.  The first approach uses two different random numbers (from column "A" and the one used in the "B" column calculation).

A: Columns A and B have the same uniform distribution, aside from the linear transformation, but are independant. B's probability density function (PDF) for A<0,2 is the same as the PDF for any other selection of A.
Columns A and C are not independant. In fact, they are completely deterministic. If you select rows where A<0,2, you are only selecting rows where C<20,8. The probability of finding a value of C greater than 20,8 within that selection has dropped to zero. Clearly, the distribution has changed.
For a more obvious example of this, consider rolling two dice (A and B) and their total (C). I'd expect to see an average of 3,5 in columns A and B, and an average of 7 in column C. If from this table I only select rows where die A landed on 1, I'd still see an average of 3,5 in B (independant), but merely 4,5 instead of 7 in column C (dependant).

A: For your 1 in 5 sample from ColumnC, instead of choosing the C value based on the A value for the corresponding row (ie those A values less than 0.2) try choosing your 1 in 5 C sample from an adjacent row. Say use =IF(A1<0.2,C2,0). This should give you similar averages for the two columns (though =A1(100-1)+1 is not correct).
Then you should have a more-or-less representative 1 in 5 of ColumnC rather than merely (approximately) a scaled up version of values preselected to be the bottom 20%.
In other words, your ColumnB 'vastly different' (but probably anticipated ie around 50) average is probably about five times the ColumnC sample average. Choose 1 in 10 on the above basis and would be ~10 times.
Rather than scaling up, if you want to generate 1000 approximately random numbers in the range 1-100 then you could apply =RANDBETWEEN(1,100).


text:
Q: Why did the mailbox at the Lake House allow time travel? A simple enough question, and one that hopefully has a simple answer. In the Lake House, the magic mailbox at the eponymous Lake House serves as a portal through time, allowing Alex (in the past) to communicate with Kate (in the future) and vice versa.

In-universe, what made the mailbox special?

A: We don't know
Unfortunately, there is little to no information to point to a definitive answer.  The main characters worry about the possibilities of the mailbox, but don't really speculate as to how it works. Note that this is from the original script, so the characters' names are different:

LUCY (V.O.) Okay. One thing worries me. What if, in sending these letters, in communicating like this, we accidentally tamper with the course of time itself, altering human history forever in the process?

In Il Mare,  or  시월애, the Korean film that The Lake House was based on, there is no more indication of why the mailbox allows communication between times.  From the English subtitles, we learn nothing more than that the mailbox was responsible—which, of course, we already knew:

00:30:34,265 --> 00:30:37,166
It was a mail-box. The mail-box!
00:30:41,239 --> 00:30:43,799
Yes it was. It was because of the mail-box.

That said, both main characters have a connection to the Lake House in some way, which might be as close to an explanation as we have.

LUCY (V.O.):  So I did. I drove to the Lake House. And that was the day I got your first letter.
INT. ARCHITECTURE SCHOOL - LATER
After the reception, Henry and a few other STUDENTS help fold chairs, clean up.
CONTINUED; LUCY (V.O.):  It's a place we both love, and it's a place your father built, so I hope you can find some solace there.

In particular, since Alex's father built the Lake House, perhaps he (or his connection to Alex) is responsible in some way for its properties.
Elsewhere in the script, there is a not-so-subtle reference to the relationship between Alex and Kate vis-à-vis the Lake House:

HENRY My project is informed and inspired by a metaphor of the loop, or fugue -- interlocking, repeating patterns in time and/or space that generate meaning and structural complexity via their contrapuntal interweaving and mutual interdependence, as much as by paradox and apparent contradiction. Around the table -- generally approving looks. Henry pulls out a rolled-up poster.

Henry is speaking of creating an architectural project that embodies the temporal complexities of an Escher drawing, which seems a good description of the Lake House (though he did not construct the Lake House, of course). Of course, this brings us no closer to figuring out why the mailbox was a portal.

If we assume, though, that (as in many such romantic films), the mailbox served a purpose with regard to their relationship, it presumably was to prevent Alex from dying so that he and Kate could be together. Alex died before Kate ever had a chance to meet him:

HENRY: He died. Two years ago.
ON LUCY
Beat.
BACK TO SCENE
HENRY (realizing): Two years ago today, actually, There was an accident...
Lucy tries to take this in.

Without time travel, they would never have had an opportunity to be together. This might be the reason for the mailbox working as it did (though it says nothing about the mechanism).

A: There is deliberately no science between the temporal link of the mailbox.  At most, there is an emotional link between the two main characters and the lake house itself.  It's one of the things that a lot of people complain about with the movie.
This link complains most scientifically about it.
http://www.thebulletproofpatriot.com/2011/09/the-mailbox-inconsistency-a-scientific-criticism-of-the-lake-house-movie/
In short, there isn't an "in universe" explanation, because in forcing reality to warp enough for the concept to work, it would end up destroying universes. At the most stretchy explanation, its due to two people 'Needing' contact that badly at the same time that a link forms.
Even the most romantic of us turn our nose up at the idea and drag it out into the street to shoot it.
This is the most thorough review of the movie, its background, and the focus of the acting and directing in the movie.  http://www.whoaisnotme.net/articles/2006_xxxx_lak.htm  There really isn't an in world explanation of the effect.
In response to the comments:
It's a plot device.  The more romantic would say 'Because Love!'.  In this case, its a plot device that might as well hang a sign on it that says 'I'm a plot device.'  This is complained about often in reviews and comments on the movie.
To revisit:
Why did the mailbox at the Lake House allow time travel?  Because the writers wanted it to.

A: I guess the premise is that the house is a paradox, with different meanings for father, son and Kate... of course, there's no explaining it. There had to be some portal of communication past/future for the story to be possible.
The interesting thing is that the man died in the beginning in the bus accident, so was "dead" the whole time the romantic communication was taking place. By sending the note telling him not to come meet her, Kate would have changed reality that had already happened in her own time. Kinda hard to wrap one's head around that.
Stuff that bother me more than the mailbox includes the tree, which is both of their times. How can it be both a young tree and a full grown tree at the same time?
And the dog footprints... Kate lived there two years earlier, and apologized for the prints she said were already there when she moved in. But he already lived in the house when the dog made the prints. If they are exactly two years apart, she would have been there with him, right?
  Speaking of the dog, Jack is with both of them at exactly the same time, two years apart. Unless there were two dogs, that would be impossible.
  Also, if they are exactly two years apart, it can't be the same day of the week, as they movie says, the calendar doesn't work that way. Also, a Leap Year is not accounted for, so the closest they could be would be two days off from an exact year.


text:
Q: Exponential fit precision lost I have a data:
data = {{1504., 0.38623}, {1698.56, 1.70795}, {1855.34, 4.77922}, {1998.22,
  9.76965}, {1957.13, 7.34756}, {1924.72, 5.8017}, {1793.82,
  2.84449}, {1679.68, 1.14792}, {1604.06, 0.765434}, {1422.63,
  0.183902}, {1350.57, 0.078183}}

And I wanted to fit function
nlm = NonlinearModelFit[data, $\frac{c1}{Exp \left[\frac{c2 \left(\frac{3*10^8}{583.92*10^{-9}}\right)}{x+273.15}\right]-1}$, {c1, c2}, x]
I get warning: ...is too small to represent as a normalized machine number; precision may be lost.
How to fit this function?

A: I guess, there is simpliy a typo with 583.92 10^-9  Get good result with positive exponent
model[x_] = c1/(Exp[(c2 ((3 10^8)/(583.92 10^9)))/(x + 273.15)] - 1)

nlm = NonlinearModelFit[data, model[x], {c1, c2}, x]

Normal[nlm]

(*   1.50253*10^6/(-1 + E^(27202./(273.15+ x)))   *)

Plot[Normal[nlm], {x, 1300, 2000}, Epilog -> Point@data]


text:
Q: ASP.NET WebMethod holding threadpool thread on long running SQL procedure I have a reporting page which builds a report from a database table. The report is displayed in a tabular format. To handle user interactions I have built a JQuery table plugin which allows a user to customize their report with custom sorting, filtering and paging.
The JQuery plugin uses a set of ajax requests to populate the table with data. These ajax requests call asp.net (c#) webMethods which in-turn uses a set of classes to build SQL and execute the Query. The Queries built are run in the same thread as the WebMethod this causes a problem because the SQL can take in excess of 30 seconds to return. I have been reading about starting new threads and the asynchronous approach. My problem is I obviously don't want to hold a thread from the ASP.NET pool for the entire execution of the SQL as it is only waiting for I/O.
Is it possible to return the thread to the threadpool while waiting for the response from the SQL Server? Can this be achieved using the Begin and End ADO.net commands?
The reason I ask is at the moment this is not a problem but as the number of users using this system increases all the threadpool serving new users will be saturated running these long queries.

A:
Can this be achieved using the Begin and End ADO.net commands?

Exactly!


text:
Q: Number to HH24:MM conversion - SQL, Oracle We have number pairs like 810 1015 that mean the hour and minute. We have to calculate the minute difference of the pair. The example above would give 125 (minutes).
What solution would you give? I thought about converting to string and substringing then concatenating, but can't know if it is 3 or 4 long and using IF ELSE but would be too complicated (if no other solution exist I am left with this). Also thought about somehow converting to base 60 and subtracting, but also too complicated.
Thanks in advance.

A: Edit: This solution is based on Plirkee's comment to lpad numbers to get 4-character strings, and on Stefano Zanini's solution modified to allow for 0 hour, and 24-hour format.
If last two digits always represent minutes, and if hours are always in 24-hour format:
with t(time1, time2) as (
  select 810, 1015 from dual union all
  select 20, 1530 from dual
),
conv(time1, time2) as (
  select lpad(to_char(time1), 4, '0'),
         lpad(to_char(time2), 4, '0')
    from t
)
select time1,
       time2,
       24 * 60 * (to_date(time2, 'HH24MI') - to_date(time1, 'HH24MI')) diff_minutes
  from conv;

A: How about storing the data as a DATA datetype, using an standard date portion, such as 01-10-2000. So you data would be
    01-01-2000 8:10:00
    01-01-2000 10:15:00
etc

Then you can just do simple date math :)

A: Assuming 3 digits is the minimum length of your numbers (otherwise you'd have ambiguous cases), this following query should do the trick
select  (to_date(substr(t2, 1, length(t2)-2) || ':' || substr(t2, length(t2)-1, length(t2)), 'HH:MI') -
        to_date(substr(t1, 1, length(t1)-2) || ':' || substr(t1, length(t1)-1, length(t1)), 'HH:MI')) * 24 * 60 cc
from    (select 810 t1, 1015 t2 from dual)

The steps are:

*

*explode the numbers in two parts each: last two digits as the minutes and the remaining digits as the hour

*concatenate the two parts with a separator (in this example ':')

*convert that concatenations into dates

*multiply the difference between the two dates (which is in days) by 24 to get hours and by 60 to get minutes

A: Just an another tweak which can be used. Hope this helps.
SELECT
TO_CHAR(TO_DATE(LPAD(LPAD('1015',4,'0') - LPAD('810',4,'0'),4,'0'),'HH24MI'),'HH24')*60
+TO_CHAR(TO_DATE(lpad(lpad('1015',4,'0') - lpad('810',4,'0'),4,'0'),'HH24MI'),'MI') MINUTES
FROM dual;


text:
Q: SQL Server database project in VS. Order of sql script generation step in build process I have a SQL Server database project in my solution and several dependencies projects.
When I compiling (in VS) this database project I've get a SQL script and a .dacpac file as result.
But also I want to aggregate all my dependencies projects in one dll and make SQL script/.dacpac file only for this result dll.
I'm using ILMerge.MSBuild.Tasks.ILMerge to aggregate all dll on AfterBuild event in sqlproj. But this aggregation happens after generating SQL script.
How can I enforce SQL script generation in the end?
Build log:
2>------ Rebuild All started: Project: TestCLR, Configuration: Debug Any CPU ------
2>      D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Roslyn\csc.exe /noconfig /nowarn:1701,1702,2008 /fullpaths /nostdlib+ /errorreport:prompt /warn:4 /define:DEBUG;TRACE /errorendlocation /preferreduilang:en-US /highentropyva+ /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\mscorlib.dll" /reference:D:\Work\FF\Sql-Objects\Tools\TestCLR\bin\Debug\TestLogic.dll /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\System.Data.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\System.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\System.Xml.dll" /debug+ /debug:full /optimize- /out:obj\Debug\TestCLR.dll /subsystemversion:6.00 /target:library /warnaserror- /utf8output /langversion:7.3 TestProcedures.cs
2>      Loading project references...
2>      Loading project files...
2>      Building the project model and resolving object interdependencies...
2>      Validating the project model...
2>      Writing model to D:\Work\FF\Sql-Objects\Tools\TestCLR\obj\Debug\Model.xml...
2>      Writing create script to TestCLR_Create.sql...
2>      TestCLR -> D:\Work\FF\Sql-Objects\Tools\TestCLR\bin\Debug\TestCLR.dll
2>      TestCLR -> D:\Work\FF\Sql-Objects\Tools\TestCLR\bin\Debug\TestCLR.dacpac
2>      ILMerge bin\Debug\TestCLR.dll;bin\Debug\TestLogic.dll;bin\Debug\Sider.dll -> D:\Work\FF\Sql-Objects\Tools\TestCLR\bin\Debug\TestCLR.dll
========== Rebuild All: 2 succeeded, 0 failed, 0 skipped ==========

.sqlproj part with ILMerge (Right now it's on the last place. Right before /Project tag )
  <UsingTask TaskName="ILMerge.MSBuild.Tasks.ILMerge" AssemblyFile="$(SolutionDir)\packages\ILMerge.MSBuild.Tasks.1.0.0.3\tools\ILMerge.MSBuild.Tasks.dll" />
  <Target Name="AfterBuild">
    <ItemGroup>
      <MergeAsm Include="bin\Debug\*.dll" />
    </ItemGroup>
    <PropertyGroup>
      <MergedAssembly>$(ProjectDir)$(OutDir)RedisCLR.dll</MergedAssembly>
    </PropertyGroup>
    <Message Text="ILMerge @(MergeAsm) -> $(MergedAssembly)" Importance="high" />
    <ILMerge InputAssemblies="@(MergeAsm)" OutputFile="$(MergedAssembly)" TargetKind="SameAsPrimaryAssembly" />
  </Target>

Much appreciate Mr. Solomon Rutzky. This solution was wery helpful.
<PropertyGroup>
  <SqlBuildDependsOn>
    BeforeSqlBuild;
    $(SqlBuildDependsOn);
  </SqlBuildDependsOn>
</PropertyGroup>
<Target Name="BeforeSqlBuild">
  ILMerge things
</Target>

But there was one curious thing. Dll comes to Bin\debug in the end of flow (I think on PostBuildEvent step or near). And if I move ILMerge upper on the flow - it returns error, that there are no DLLs. Changed config to gater dll from obj folder and from dependant project.

A: Interesting question. I don't know of any easy way to do this, or if it's even possible in the first place. However, there are two options that I know of for altering the build process:
Option 1
Inject a build step / target. SSDT is missing at least two build steps/targets — "BeforeSqlBuild" and "BeforePublish" — because the "AfterBuild" target is too late in the process (as you have discovered).
To get around the "CLR strict security" debacle introduced in SQL Server 2017 (documented in the following post of mine: SQLCLR vs. SQL Server 2017, Part 3: "CLR strict security" – Solution 2), I updated the .sqlproj file by placing the following at the end, just before the closing </Project> tag (to sign the assembly with a certificate):
<PropertyGroup>
  <SqlBuildDependsOn>
    BeforeSqlBuild;
    $(SqlBuildDependsOn);
  </SqlBuildDependsOn>
</PropertyGroup>
<Target Name="BeforeSqlBuild">
  <Exec Command="{DOS / Windows commands}"/>
</Target>

You can keep the <Exec Command="..."/> and/or add the contents of your existing "AfterBuild" target. HOWEVER, even with this performing the action at the correct time, I'm not entirely certain that you will be able to change the assembly name that it will want to serialize and put in the "Create" script (i.e. switch from using "TestCLR.dll" to "RedisCLR.dll"). You can try re-assigning the build variable, but I've never tried that and am not sure it's allowed. In which case the next option might help.
(Please vote for my enhancement request to improve the SSDT build process:
Add MSBuild predefined Targets for "BeforeSqlBuild" and "BeforePublish" to SSDT SQL Server Database Projects)
Option 2
Use .NET to create a custom build task that has access to the objects, files, and overall process:

*

*Customize Database Build and Deployment by Using Build and Deployment Contributors

*BuildContributor Class

*BuildContributorContext Class

*Walkthrough: Extend Database Project Build to Generate Model Statistics


text:
Q: How to secure EC2 server with just MySQL on it? I have two servers. Let's call them EC2 A and EC2 B.
EC2 A = main server with PHP code
EC2 B = server with ONLY MySQL database. Right now, EC2 A is connecting to EC2 B.

What kind of security groups can I use to secure my EC2 A server for just the website access and EC2 B for just MySQL access from the EC2 A server?
Here is the security group I have for both EC2 servers:
HTTP 80
Custom TCP Rule 8080
SSH 22
SMTP 25
Custom TCP Rule 20-21
Custom TCP Rule 1024-1048
IMAP 143
MYSQL/Aurora 3306
HTTPS 443

Here is how I am connecting to the database in PHP PDO.
define ("DB_HOST", "ec2-**-***-*-***.us-west-1.compute.amazonaws.com");
define ("DB_USER", "dbuser");
define ("DB_PASS",'dbpassword');
define ("DB_NAME","dbname");
try {
    $dsn = "mysql:dbname=".DB_NAME.";host=".DB_HOST;
    $dbh = new PDO($dsn, DB_USER, DB_PASS);
    return $dbh;
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

Is there anything I can do to EC2 A or or EC2 B to make them more secure? is there anything I need to change to make it more secure or faster?

A: To secure the connection, you can specify the source (which is the EC2 A) in your security group's MySQL rule, i.e. only your EC2 A can connect to EC2 B via port 3306.


text:
Q: Background image transition with fadeIn fadeOut effects on page load without any bindings to events I would like to implement a background image transition effect using jquery. The images should change from one to the other with a fadeIn fadeOut effect. The image names are in the database but retrieved from a folder on my PC.I want the transition to take place automatically without listening to any events like click events.
This is my trial code from the php page to the js page.
This is getImages.php
<?php
error_reporting(E_ALL ^ E_NOTICE);

require_once("Connections/imageconn.php");

mysql_select_db($database_imageconn,$imageconn);
$sql1=mysql_query("SELECT * FROM images WHERE ImageID=1",$imageconn)or die(mysql_error());
$numofrows=mysql_num_rows($sql1);
$image_one=mysql_fetch_assoc($sql1);
$img1=$image_one['Image_name'];

$sql2=mysql_query("SELECT * FROM images WHERE ImageID=2",$imageconn)or die(mysql_error());
$numofrows=mysql_num_rows($sql2);
$image_two=mysql_fetch_assoc($sql2);
$img2=$image_two['Image_name'];

$sql3=mysql_query("SELECT * FROM images WHERE ImageID=3",$imageconn)or die(mysql_error());
$numofrows=mysql_num_rows($sql3);
$image_three=mysql_fetch_assoc($sql3);
$img3=$image_three['Image_name'];

$sql4=mysql_query("SELECT * FROM images WHERE ImageID=4",$imageconn)or die(mysql_error());
$numofrows=mysql_num_rows($sql4);
$image_four=mysql_fetch_assoc($sql4);
$img4=$image_four['Image_name'];

$data['imageone']=$img1;
$data['imagetwo']=$img2;
$data['imagethree']=$img3;
$data['imagefour']=$img4;

echo json_encode($data);
?>

This is images.php
$(document).ready(function(){
    $.post("getImage.php",{},function(data){

            $("#response").toggle(function(){
                  $(this).html("");
                },function()
                {
                  $(this).html("");
                },function()
                {
                  $(this).html("");
                },function()
                {
                  $(this).html("");
                });

        },"json");
});

Any help would be appreciated.

A: Given a DOM structure like:

var i = 0;
var number = $('.wrapper img').size();
var tabtimer = self.setInterval(function() {
  crossFade(i);
  i++;
  if (i == number + 1){ i = 0}
},
8000);

function crossFade(i){
  $('.wrapper img:visible').fadeOut();
  $('.wrapper img:nth-child('+i+')').fadeIn();
};

A: This will iterate over your JSON properties, create the 's in the DOM and then fade them in and out with a 1 second delay between each.
var idx = 0;
for (var i in data) {

    // Create the image DOM elements
    var img = $('');
    img.css({opacity: 0});

    // Add them to their container
    $('#response').append(img);

    // Set fadeIn/Out delays
    var delay = idx++ * 1000;
    img.delay(delay).fadeIn();
    img.delay(delay + 1000).fadeOut();
}


text:
Q: Why isn't my SysTick_Handler() being called in my LPCxpresso C++ Project? I have created a C++ project for an LPC1227 using LPCExpresso 6.1.0.  The project, up until now, builds and runs fine.  I have not made any changes to cr_startup_lpc12xx.cpp.
I would like to add a SysTick_Handler().  In my main.cpp I have added a method:
void SysTick_Handler(void)
{
    timerCounter++;  // these variables are all declared globally in main.cpp
    timer_10ms_tick = true;
    if ((timerCounter % 10) == 0)  //every 100ms
    {
        timer_100ms_tick = true;
    }
    if ((timerCounter % 100) == 0)  //every 1000ms
    {
        timer_1000ms_tick = true;
    }
}

I have also add the following line in my main() method:
SysTick_Config(12000000/100);

When I run my code via debug, the interrupt is firing, but it is getting stuck in the default SysTick_Handler() that is inside of cr_startup_lpc12xx.cpp (which is just an infinite while loop).   If I delete the default SysTick_Handler from cr_startup_lpc12xx.cpp, my program hard faults.
I have looked at the Blinky example (which is C, not C++) and it adds a new handler into main.cpp without deleting the handler from the startup file.
Can anyone suggest why my overriding handler is not being called?  Is this a C++ difference?

A: From https://rowley.zendesk.com/entries/20986562-LPC1114-IRQ-Handlers-in-C-work-in-C-do-not-work

You need to declare your interrupt handler as a C function otherwise
  the function will not override the default handler.
So for example you could do something like the following to make the
  declaration work in both C or C++:

#ifdef __cplusplus
extern "C" {
#endif

void irq_handler();

#ifdef __cplusplus
}
#endif

I assume changing irq_handler() in the code above to your SysTick_Handler code will then work. e.g.
extern "C" {
    void SysTick_Handler(void)
    {
        timerCounter++;  // these variables are all declared globally in main.cpp
        timer_10ms_tick = true;
        if ((timerCounter % 10) == 0)  //every 100ms
        {
            timer_100ms_tick = true;
        }
        if ((timerCounter % 100) == 0)  //every 1000ms
        {
            timer_1000ms_tick = true;
        }
    }
}

A: I don't know if this is true of C++, but in C the default handler must be declared as a weak function in the default declarations. This allows another declaration to override the original one, so your custom handler should not have the weak attribute.

A: I had exactly the same problem once. Yes it is C++ vs C difference. Looks like the maintainers of LPC support libraries did not care for C++ developers. Full answer is here Bug in Keil ARM compiler with interrupt handlers and C++?


text:
Q: Using enums with AJV's "select/selectCases" keyword Is it possible to give select a schema to match the case on?
The use case I have is that I want to select and match on a list of accepted values:
{
  "type": "object",
  "properties": {
    "addressCountry": {
      "type": ["string", "null"]
    }
  },
  "select": {
    "$data": "0/addressCountry"
  },
  "selectIf": {
    "type": "string",
    "enum": ["FR", "JP", "US", "NZ", "DE"]
  },
  "selectThen": {
    "addressCountry": {
      "type": "string"
    }
  }
}

EDIT: please note that selectIf and selectThen aren't keywords supported by AJV. It does support selectCases and selectDefault, however with selectCases you have to state each case individually. My question is more about if it's possible to match on multiple cases and use a single definition.

A: @Relequestual managed to help me solve this outside of SO. I didn't need to use select at all, could just use if/then/else like so:
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "properties": {
    "contactByPost": {
      "type": "boolean"
    },
    "streetAddress1": {
      "type": ["string", "null"]
    },
    "streetAddress2": {
      "type": ["string", "null"]
    },
    "streetAddress3": {
      "type": ["string", "null"]
    },
    "locality": {
      "type": ["string", "null"]
    },
    "region": {
      "type": ["string", "null"]
    },
    "postCode": {
      "type": ["string", "number", "null"]
    },
    "country": {
      "type": ["string", "null"]
    }
  },
  "if": {
    "type": "object",
    "properties": {
      "contactByPost": {
        "type": "boolean",
        "const": true
      }
    }
  },
  "then": {
    "if": {
      "type": "object",
      "properties": {
        "country": {
          "type": "string",
          "enum": ["JP", "US"]
        }
      }
    },
    "then": {
      "type": "object",
      "properties": {
        "contactByPost": { "type": "boolean" },
        "streetAddress1": { "type": "string" },
        "locality": { "type": "string" },
        "region": { "type": "string" },
        "postCode": { "type": ["string", "number"] },
        "country": { "type": "string" }
      },
      "required": ["streetAddress1", "locality", "region", "postCode", "country"]
    },
    "else": {
      "type": "object",
      "properties": {
        "contactByPost": { "type": "boolean" },
        "streetAddress1": { "type": "string" },
        "locality": { "type": "string" },
        "region": { "type": ["string", "null"] },
        "country": { "type": "string" }
      },
      "required": ["streetAddress1", "locality", "country"]
    }
  }
}

Would provide the following results:
// Valid
{
  "contactByPost": false
}

{
  "contactByPost": true,
  "streetAddress1": "123 Alphabet St",
  "streetAddress2": null,
  "streetAddress3": null,
  "locality": "City",
  "region": "State",
  "postCode": "12345",
  "country": "JP"
}

{
  "contactByPost": true,
  "streetAddress1": "123 Alphabet St",
  "streetAddress2": null,
  "streetAddress3": null,
  "locality": "City",
  "region": "State",
  "postCode": "12345",
  "country": "US"
}

{
  "contactByPost": true,
  "streetAddress1": "123 Alphabet St",
  "streetAddress2": null,
  "streetAddress3": null,
  "locality": "City",
  "region": "State",
  "postCode": "12345",
  "country": "NZ"
}

{
  "contactByPost": true,
  "streetAddress1": "123 Alphabet St",
  "streetAddress2": null,
  "streetAddress3": null,
  "locality": "City",
  "region": null,
  "postCode": null,
  "country": "NZ"
}

// Invalid
{
  "contactByPost": true
}

{
  "contactByPost": true,
  "streetAddress1": "123 Alphabet St",
  "streetAddress2": null,
  "streetAddress3": null,
  "locality": "City",
  "region": null,
  "postCode": null,
  "country": "JP"
}

{
  "contactByPost": true,
  "streetAddress1": "123 Alphabet St",
  "streetAddress2": null,
  "streetAddress3": null,
  "locality": "City",
  "region": null,
  "postCode": null,
  "country": "US"
}


text:
Q: How do I create shallow routes inside a nested resource? How can I setup my routes file to create the following routes:
/forums/1/posts           # GET  index
/forums/1/posts           # POST create
/forums/1/posts/new
# ... the other forum posts restful actions

/posts/1/votes            # POST create
/posts/1/votes/1/destroy

I tried this way:
resources :forums do
  resources :posts
end

resources :posts do
  resources :votes
end

This creates redundant /posts/1 and /posts/new urls, not scoped to the forum.
I also tried:
resources :forums do
  resources :posts do
    resources :votes, only: [:create, :destroy], shallow: true
  end
end

But this creates forums/1/posts/1/votes/create while I only want /posts/1/votes/create.
Basically, I don't want to nest the votes resource under the forums resource.
resources :posts do # would be nice to do resources :posts, none: true, do
  resources :votes
end

Any ideas?

A: Instead of :none => true you can use :only => []:
resources :forums do
  resources :posts
end

resources :posts, :only => [] do
  resources :votes, :only => [:create, :destroy]
end