text:
Q: picker in android with dynamic data. but it giving me a error " cannot read property of null" i am trying to render a picker with dynamic data from api. but it is giving error
    <Picker style={styles.pickerStyleClass}
                                           enabled={true} mode="dropdown"
                                           selectedValue={(this.state.selectedWeight) || "Status"} prompt="Transaction Type"
                                           onValueChange={(itemValue, itemIndex) => this.PickerDataSelection(itemIndex, itemValue)}
                                           itemStyle={{ color: Colors.textColor }}>
                                           {stockQty.map((data) => { <Picker.Item label={data} value={data} /> })}

                                       </Picker>

let stockQty = ["Test1","Test2"];

A: The only thing missing here that causes this error is return so replace the Picker.Item line to
{stockQty.map((data) => { return <Picker.Item label={data} value={data} /> })}

as nothing was being returned from the function and Picker is made in a way that you can't return anything other than Picker.Item with the required props. Even the following line gives the same error.
{ this.state.someCheck && <Picker.Item label='some' value='value' /> }

and key should also be added as prop in Picker.Item.


text:
Q: Using Selenium to return which page of the PDF is being displayed I have Selenium opening many pdfs for me from Google Search (using f"https://www.google.com/search?q=filetype:pdf {search_term}" and then clicking on the first link)
I want to know which pages contain my keyword WITHOUT downloading the pdf first. I believe I can use
Ctrl+F --> keyword --> {scrape page number} --> Tab (next keyword) --> {scrape page number} --> ... --> switch to next PDF
How can I accomplish the {scrape page number} part?
Context
For each PDF I need to grab these numbers as a list or in a Pandas DataFrame or anything I can use to feed in camelot.read_pdf() later
The idea is also once I have these page numbers, I can selectively download pages of these pdfs and save on storage, memory and network speeds rather than downloading and parsing the entire pdf
Using BeautifulSoup
PDFs have a small gray box at the top with the current page number and total pages number with the option to skip around the PDF.

<input data-element-focusable="true" id="pageselector" class="c0191 c0189" type="text" value="151" title="Page number (Ctrl+Alt+G)" aria-label="Go to any page between 1 and 216">

The value in this input tag contains the number I am looking for.
Other SO answers
I'm aware that reading PDFs programatically is challenging and I'm currently using this function (finding on which page a search string is located in a pdf document using python) to scrape the pdf pages having downloaded the whole PDF first. But Chrome searches PDFs pretty quickly with Ctrl+F which gives me inspiration I can use browser functionality to collect this data and I've already seen this data in the box at the top.
How do you keep the page numbers in a PDF where a keyword is present?

A: Your question is built on several misconceptions not helped by the way modern browsers obscure their workings.
Consider these points

*

*while viewing a 4096 page pdf I can disconnect from the web and still navigate end to end. (Only possible by the fact that a PDF must download ALL pages to start view search edit etc, yes there are those that display early but most need 100% download first)

*I can add annotation with the web address showing but clearly I am not writing on the server copy. The downloaded file is converted to text and pixels using my local resources, thus I have already paid the price of my own converted copy. Why would I want to keep repeating that cost over and over, simply save as my own, searchable copy, that's far easier to grep offline.

It does not matter which browser extension you are using they all hold the file somewhere in your file system, note the difference here the data says its on the web but the edit message show otherwise. In this case the field is secured outside the browser however Ctrl+D + C gives me
File: https://africau.edu/images/default/sample.pdf
Created: 3/1/2006 7:28:26 AM
Application: Rave (http://www.nevrona.com/rave)
PDF Producer: Nevrona Designs
PDF Version: 1.3
File Size: 2.96 KB (3,028 Bytes)
Number of Pages: 2
Page Size: 8.5 x 11.0 in (Letter)

Fonts: Helvetica (Type1; Ansi)

Mozilla PDF.js is a different beast, so may be more addressable, but as you found you can use a hybrid approach in the index.htm of Chrome/Edge you could equally do that offline.
So on the basis you have scraped a list of URLs the simplest solution should be
curl -O (or -o tmp.pdf) URL & pdftotext | find "Keyword"
you will need to adapt that a bit to show page and line number but that's a different question or two
https://stackoverflow.com/a/72440765/10802527
https://stackoverflow.com/a/72778117/10802527

redpajama_set_name: RedPajamaStackExchange


text:
Q: Upload image and change default image location everywhere I have an image in a div given below that appears on every page of my website and I have a URL link available to me that contains a profile picture. I would like to replace the image src attribute and update the profile picture and make sure that it updates on every other page. Any suggestions on how I can achieve this using javascript/jquery? Kindly let me know.
Test image URL: http://www.hdrspotting.com/images/default_profile.jpg


text:
Q: Retain authentication via JavaScript client? I have a WCF application where I make JavaScript calls to. I want to secure the web services so you have to be logged in to use it. This is easy if I have a server-side application making the requests to the WCF. If I am using a pure JavaScript / jQuery client-side app, I can authenticate fine by passing the credentials as JSON parameter, but how do I keep that client-side app logged in from that point on? Do I store a cookie? I do not want to store the credentials in the cookie of course because that is not secure. So how can I achieve this without introducing another server-side application to the mix? How do web apps achieve this?

A: OAuth is kind of the go to solution for JS API's.  Netflix, Yelp, Facebook etc. use this.
Here is an article on OAuth in WCF
And here is a pretty well known library for doing auth in .NET: DotNetOpenAuth

A: If you use or are using ASP.Net form authentication (WCF should be running in ASP.Net compatibility mode) then there is not much to do.
If you set the form authentication ticket\cookie after your initial authentication, the cookie would be attached to every subsequent request from the browser without you writing any code. All future calls to WCF service then can be authenticated on the server using the standard ASP.Net authentication pipeline.


text:
Q: Creating a Launcher and sending info to second program I have created a program that extracts data from a racing game and sends it to a speed gauge cluster. I call it the transfer program.
I need a simple user-friendly User Interface to start the transfer program, set some variables and choose a COM Port. At the moment I'm trying to do it with a C++ Windows Forms Application in a CLR Project on Microsoft Visual Studio 2015. When I tried to do it directly (creating the UI in the same project as the transfer program) I just get too many errors that I have no idea where they come from or why they are there.
So I've decided maybe I could try creating some sort of launcher, i.e. a completely different program that is only the UI to start the transfer program and send a few user-set variables to it on startup as well as choose a COM Port to communicate on.
Any idea on how to start on this? How do I execute the transfer program from the Launcher? How do I send variables and data to it?
Thank you very much!

A: There are basically two ways to pass information to your transfer program.

*

*For simple use cases, just pass the values along on the command line. If you're still using the CLR, this is done using System.Diagnostics.Process. A nice example can be found in this answer: https://stackoverflow.com/a/33633148/127826

*Use a shared configuration file. So the user interface loads the values from the config and also saves the file before executing the transfer program. The transfer program then reads the same configuration file to get the values it needs.

The second approach is far more flexible and is what I would use.


text:
Q: Python: Function hangs in child process I wrote this script which uses the exchangelib python API to log into my Microsoft exchange account and download sent messages that contain a particular subject.
I split it into two functions each running as a seperate process:
Function A fetches emails from my account and places the ones that match a specific subject in a Queue.
Function B takes these emails from the Queue and saves them to disk.
These functions work properly when run in a single process but when I decided to run function A in a child process while function B runs in main process, function A just hangs at the line that downloads the emails.
My code is below.
from exchangelib import Credentials, Account, Mailbox, HTMLBody, Message

import multiprocessing as mp
from multiprocessing import Process, Queue

def authenticate(user_id, passw):
    credentials = Credentials(user_id, passw)
    exchange = Account(account_id, credentials=credentials, autodiscover=True)
    return exchange

def fetch_bounces(exchange, output_q, progress):
    print('fetcher process started')
    while exchange.inbox.total_count != 0:
        exchange.inbox.refresh()
        inbox=exchange.inbox.all()
        for msg in inbox:
            if 'Undeliverable:' in msg.subject:
                output_q.put(msg.display_to)
        inbox.move_to_trash()
    progress.put('done')

def save_bounced(outputfile, output_q):
    bounces = []
    while output_q.empty() is False:
        lead = output_q.get()
        print('bounce: '+lead)
        bounces.append(lead)
    if len(bounces)>0:
        existing = []
        try:
            with open(outputfile, 'r+') as f:
                lines = f.readlines()
                existing = [line.strip().lower() for line in lines]
        except:
            pass
        with open(outputfile, 'a+') as f:
            for line in bounces:
                if line.strip().lower() in existing:
                    continue
                else:
                    f.write(line.strip().lower()+'\n')

if __name__ == '__main__':
    #credentials
    account_id =
    password =

    #set Queues to store bounces and progress
    bounced = Queue()
    progress = Queue()

    #login to exhcnage
    exchange = authenticate(account_id, password)
    print('logged in successfully')

    #spawn bounce fetching process and start it
    f_process = Process(target=fetch_bounces, args=(exchange, bounced, progress))
    f_process.start()

    #define file path where bounces will be stored
    output_f = 'bounces.txt'

    #while new bounce emails are being fetch, remain in loop and also specify flag to know when all emails have been fetched

    complete = False
    while not complete:
        save_bounced(output_f, bounced)
        try:
            msg = progress.get(block=False)
            if msg == 'done':
                complete =  True
        except:
            pass

    #terminate fetcher process

    f_process.join()

    print('bounces completely removed')

A: When you are using multiprocessing, all arguments must be serializable. But an Account instance cannot be safely serialized. You must create the Account instance within each process.


text:
Q: Preventing PHP scripts used in a iPhone app from being access via web browser I'm trying to get some more info on a question I posed on another thread
Basically, I am using this method to pass parameters to a php script which returns values from a server:
NSString *urlstr = [[NSString alloc] initWithFormat:@"http://www.yourserver.com/yourphp.php?param=%d", paramVal];
NSURL *url = [[NSURL alloc] initWithString:urlstr];
NSString *ans = [NSString stringWithContentsOfURL:url];
// here in ans you'll have what the PHP side returned. Do whatever you want
[urlstr release];
[url release];

I then pose the question. How do you secure 'http://www.yourserver.com/yourphp.php' ? You can easily navigate to the same script (if you know the path) and pass in any parameters that you want. Am I missing something?

A: $_SERVER['HTTP_USER_AGENT'];

Will show you accessors user agent, but user agents are certainly spoof-able, your only other option would be to lock down the param by checking for certain characters that you know will never be passed through it, perhaps add another (dummy) peram just for a little added security. Other than that there really is no other way to secure it down.

A: You could use a MAC of the outgoing data to send along.
This avoids using a full blow Auth framework (and sessions for that matter).
This is however vulnerable to a repeat attack, but would certainly verify that the message originated from your application.
http://en.wikipedia.org/wiki/Message_authentication_code

A: Nope, you're not missing anything. Well, other than an auth framework. :)
PHP isn't the best platform for securing a web application, but you might use Pear's Auth library.

A: Validate your input on the PHP side;  If any input is valid, then generate a password and pass that along with the parameter to be validated against before taking any action.
They password should be as temporary as possible, ideally based on a nonce from the server salted with some data the application generates (i.e. it's not stored) and the server knows beforehand.


text:
Q: Set value knowing the EObject and its EAttribute I want to set the value of an object EObject knowing it's EAttribute. Is that possible?
I can use reflections, build the method name and invoke it, but is there a better way to achieve that? Maybe some EMF Util classes?
public static Object invokeMethodBy(EObject object, EAttribute attribute, Object...inputParameters){
    String attrName = attribute.getName().substring(0, 1).toUpperCase() + attribute.getName().substring(1);
    Object returnValue = null;
    try {
        returnValue = object.getClass().getMethod("set"+attrName, boolean.class).invoke(object,inputParameters);
    } catch (IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoSuchMethodException
            | SecurityException e1) {
        e1.printStackTrace();
    }
    return returnValue;
}

A: EMF has already its own introspection mechanisms, that do not use Java Reflection but use static generated code.
What you need is this:
object.eSet(attribute, value);

If the attribute is a "many" relationship, such as a List, you need to retrieve the list before and then add the content to the list:
if (attribute.isMany()) {
    List<Object> list = (List<Object>) object.eGet(attribute);
    list.addAll(value);
}

In case you don't have the EAttribute but have the name of the attribute (as String) you can also retrieve the EStructuralFeature by name using the EClass metadata:
EStructuralFeature feature = object.eClass.getEStructuralFeature(attributeName);
object.eSet(feature, value);

You should look to the EObject API, in special the methods starting by "e". EcoreUtil class has also useful methods.


text:
Q: How can I get rid of this Heisenbug in my doubly-linked list data structure? I am implementing a modified doubly-linked data structure and while I was unit testing the functions, I encountered a Heisenbug that I can't get rid of.
Specific piece of code that I get the random segmentation fault is below:
     case CURSOR_LIST_COPY_CONSTRUCTOR:
      {
        // Test to construct a cursor list by using the copy constructor.
        if (verbose) {
          os << "\nCURSOR_LIST_COPY_CONSTRUCTOR:" << std::endl <<
            "Starting the construction operation:" <<
            std::endl;
        }
        anil::cursor_list my_cursor_list;
        my_cursor_list.append(1);
        anil::cursor_list my_copied_cursor_list = my_cursor_list;
        if (&my_copied_cursor_list == nullptr &&
            my_copied_cursor_list.index() != -1 &&
            my_copied_cursor_list.size() != 1 &&
            my_copied_cursor_list.front_data() != 1 &&
            my_copied_cursor_list.back_data() != 1) {
          if (verbose) {
            os << "Copy construction unsuccessful!" << std::endl;
          }
          return false;
        } else {
          if (verbose) {
            os << "Copy construction successful!" << std::endl;
          }
          return true;
        }
        return false;
        break;
      }

Two runs out of ten give me a segmentation fault at my_copied_cursor_list.front_data() != 1. Initially I couldn't get to replicate this bug inside gdb but after using the command set disable-randomization off, which I learned from an answer to the question segfault only when NOT using debugger, inside gdb, I was able to replicate the same bug.
The source code for the front data is as following:
int anil::cursor_list::front_data() {
  if (this != nullptr && this->is_empty() == false) {
    return this->front->data;
  }
}

I tried to put return this->front->data; into an if statement in order to test if this->front was somehow nullptr; however, even when I did it, it still somehow caused a segmentation fault. This was what I tried and failed:
int anil::cursor_list::front_data() {
  if (this != nullptr && this->is_empty() == false) {
    if (this->front != nullptr) {
      return this->front->data;
    }
  }
}

The code for the append() function is as following:
void anil::cursor_list::append(int new_data) {
  if (this != nullptr) {
    cursor_list_node* new_node = new cursor_list_node;
    new_node->data = new_data;
    new_node->next = nullptr;
    new_node->previous = this->back;
    if (this->is_empty() == false) {
      this->back->next = new_node;
    } else {
      this->front = new_node;
    }
    this->back = new_node;
    ++this->m_size;
  }
}

The code for the class declaration is as following:
#ifndef ANIL_CURSOR_LIST_H
#define ANIL_CURSOR_LIST_H

#include <cstddef>
#include <iostream>

namespace anil {
  class cursor_list_node {
    private:
      int data;
      cursor_list_node* next;
      cursor_list_node* previous;
      friend class cursor_list;
  };

  class cursor_list {
    private:

      // Data:
      int m_index;
      int m_size;
      cursor_list_node* front;
      cursor_list_node* back;
      cursor_list_node* cursor;

      // Functions:
      void delete_list();

    public:
      cursor_list() : m_index(-1), m_size(0), front(nullptr), back(nullptr),
        cursor(nullptr) {}
      cursor_list(cursor_list& copied_list);
      bool is_empty();
      int size();
      int index();
      int front_data();
      int back_data();
      int cursor_data();
      bool operator==(cursor_list& rhs); // rhs = right hand side
      cursor_list& operator= (cursor_list& rhs);  // rhs = right hand side
      friend std::ostream& operator<<(std::ostream& out, const cursor_list& rhs); // rhs = right hand side
      void clear();
      void move_cursor_front();
      void move_cursor_back();
      void move_cursor_prev();
      void move_cursor_next();
      void prepend(int new_data);
      void append(int new_data);
      void insert_before_cursor(int new_data);
      void insert_after_cursor(int new_data);
      void delete_front();
      void delete_back();
      void delete_cursor();
      ~cursor_list();
  };
}

#endif /* ANIL_CURSOR_LIST_H */

The segmentation fault message inside gdb is as following:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004018c8 in anil::cursor_list::front_data (this=0x7ffe055100c0)
    at anil_cursor_list.cpp:82
82      return this->front->data;

My operating system is as following:
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:        16.04
Codename:       xenial

Lastly, the entire source code for the data structure can be found at https://github.com/Karipso/Karipso-Public/blob/master/cpp_practice_codes/data_structures/cursor_list/anil_cursor_list.cpp and https://github.com/Karipso/Karipso-Public/blob/master/cpp_practice_codes/data_structures/cursor_list/anil_cursor_list.h.
Similarly, the source code for the unit tests can be found at: https://github.com/Karipso/Karipso-Public/blob/master/cpp_practice_codes/data_structures/cursor_list/main.cpp
Finally, the makefile is located at https://github.com/Karipso/Karipso-Public/blob/master/cpp_practice_codes/data_structures/cursor_list/Makefile
Can someone help me determine what this bug is caused by?
Update: I tried to run the program using gdb line by line using next and step and printed this and this->front before the seg fault. This is the result:
Breakpoint 1, run_tests (os=..., bst_test=1, verbose=false) at main.cpp:121
121         anil::cursor_list my_copied_cursor_list = my_cursor_list;
(gdb) next
138         if (my_copied_cursor_list.index() != -1) {}
(gdb)
139         if (my_copied_cursor_list.size() != 1) {}
(gdb)
140         if (my_copied_cursor_list.front_data() != 1) {}
(gdb) step
anil::cursor_list::front_data (this=0x7ffc683c4500) at anil_cursor_list.cpp:79
79    if (this != nullptr && this->is_empty() == false) {
(gdb) next
80      return this->front->data;
(gdb) print this
$7 = (anil::cursor_list * const) 0x7ffc683c4500
(gdb) print this->front
$8 = (anil::cursor_list_node *) 0xe92cb976bc5a2900
(gdb) next

Program received signal SIGSEGV, Segmentation fault.
0x0000000000401956 in anil::cursor_list::front_data (this=0x7ffc683c4500)
    at anil_cursor_list.cpp:80
80      return this->front->data;

Update-2: I think, I was able to get rid of the Heisenbug. After adding the initializations for all member variables of the cursor_list class, the program stopped giving seg-faults. So, I updated the copy constructor to be as following:
  this->m_index = -1;
  this->m_size = 0;
  this->front = nullptr;
  this->back = nullptr;
  this->cursor = nullptr;
  if (copied_cursor_list.is_empty() == false) {
    for (cursor_list_node* it = copied_cursor_list.front; it != nullptr;
         it = it->next) {
      this->append(it->data);
    }
  }

I will do some experimentation to figure out why append() function wasn't properly initializing the front pointer and update the post if I can figure out the exact cascade of events that lead to that faulty initialization or lack of initialization.

A:
if (this != nullptr)

You aren't allowed to check that.  Compilers can and will change this to if(true).
Calling nullptr->blah() is already UB, so within blah the compiler is free to assume nullptr is not null.

int anil::cursor_list::front_data

Not all return paths return a value.  Falling off the end is UB.
The compiler is free to remove your if checks guarding the return path, because segfaulting is allowed in UB.
Fixing this might not fix your crash, but with UB in your code, compilers are permitted to generate code that crashes in nonsense ways.
To fix your problem, you should make a much much simpler linked list with fewer operations.
Then unit test that.
Then wrap that simpler linked list in your rich API.  And unit test your rich API.
Then when you have a crash in your rich API unit tests, you can write up a minimal unit test in your simple API.


text:
Q: avoiding a possible null in android i have a situation where i may encounter a possible null, and i don't want my program to crash.  it is only happening for a small % of users and i'm not entirely sure why, but i know the section of code that is doing it.  basically the isAchieved() is a check that should return a boolean value, but in a few cases it is returning a null.  this is part of a scoreloop library and i have a suspicion the bug might be with their code.
rather than getting a force close and exiting the program is there a way to check if this value is going to return a null and simply skip over this section of code if that is the case?
if (_achievements[ltc].isAchieved()) {
   // Do stuff for 99.9% of users here, but skip if .isAchieved() would force close
}

A:         boolean checker=false;
        try{
            checker=_achievements[ltc].isAchieved();
        }
        catch(NullPointerException e){
        }
        if (checker) {
           //content
        }

Did you think about doing that?.


text:
Q: Type Promise is not assignable to type Promise I am new to angularJs2. I have created following service:
import { Injectable, OnInit } from '@angular/core';
import { customType } from '../models/currentJobs';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class JobService implements OnInit {

    constructor(private http: Http) { }

    ngOnInit(): void {
        this.getCurrentJobs();
    }

    private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
    private ordersUrl: string = 'http://localhost:35032/api/order/';

    public orders: customType[];

    getCurrentJobs(): Promise<customType[]> {
        var jobs =  this.http.get(this.ordersUrl)
            .toPromise()
            .then(response => {
                this.orders = response.json() as customType[];
            })
            .catch(this.handleError);
        return jobs;//this line throws error
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

Following are my Typescript compile configuration of Vs2017

When I compile the code using visual studio 2017 I get following error
**TS2322   Build:Type 'Promise<void>' is not assignable to type 'Promise<customType[]>'.**
Help me to fix this error.

A: You are not returning anything inside your then which makes jobs be of type Promise<void>. Return the array inside then:
getCurrentJobs(): Promise<customType[]> {
    var jobs = this.http.get(this.ordersUrl)
      .toPromise()
      .then(response => {
        this.orders = response.json() as customType[];
        return this.orders;
      })
      .catch(this.handleError);
    return jobs;
}

See the chaining behaviour of promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Chaining

A: I've added the 'catch' operator, and swapped your interface import for an interface definition in the code (as I don't obviously have access to yours). I can't really test this without the rest of your project code, but it looks right to me and doesn't throw any errors in VSC.
import { Injectable, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';

export interface customType{
}

@Injectable()
export class JobService implements OnInit {

    constructor(private http: Http) { }
    private jobs: Promise<customType[]>;

    ngOnInit(): void {
        this.jobs = this.getCurrentJobs();
    }

    private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
    private ordersUrl: string = 'http://localhost:35032/api/order/';

    public orders: customType[];

    getCurrentJobs(): Promise<customType[]> {
        return this.http.get(this.ordersUrl)
          .map(response => response.json())
          .catch(this.handleError)
          .toPromise();

    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}


text:
Q: MariaDB no longer shipping with auth_socket.so? MariaDB still has lots of documentation regarding unix socket authentication. Version 10.3 ships with auth_socket.so in the /usr/lib64/mysql/plugin/ directory.
But it's gone in version 10.4.26 and later. Was it renamed or deprecated? What is the upgrade path for people who had been using unix socket auth?

A: When socket authentication for unix sockets became default (in MariaDB 10.4) the plugin type changed from dynamic to static, which means the plugin is statically compiled into server.
If you need it as a shared plugin (e.g. if an application tries to install the plugin via INSTALL SONAME), you need to rebuild it from source:
cmake .. -DPLUGIN_AUTH_SOCKET=DYNAMIC


text:
Q: Opencv throwing dll error when trying to open image using cv::imshow c++ So i'm trying to make opencv open a image i have saved on my computer and display it in a window. But my visual studio compiler keeps throwing this excpetion:

Exception thrown at 0x00007FF80A2012DB (vcruntime140.dll) in Pixel_analisys.exe: 0xC0000005: Access violation reading location 0x0000021037BD4000.

I have tried to change the file location, double checked the linker if the libraries was linked.
However using the cv:haveImageReader() with the same file path it says it is not accesable/not permissions to access it, i have double checked the file location and checked if it is locked in any way and still cant figure this out.
#include <windows.h>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
cv::Mat a;

int main()
{
    a = cv::imread("C:\\Users\\simuls26\\Desktop\\dog.jpg");
    cv::imshow("dog", a);
    return 0;
}

This is my callstack:

vcruntime140.dll!memcpy_repmovs() Line 40   Unknown
[Inline Frame] msvcp140.dll!std::_Char_traits<char,int>::copy(char * const) Line 64 C++
msvcp140.dll!std::basic_streambuf<char,std::char_traits>::xsputn(const char * _Ptr, __int64 _Count) Line 345  C++
opencv_world455.dll!std::_Insert_string<char,struct std::char_traits,unsigned __int64>(class std::basic_ostream<char,struct std::char_traits > &,char const * const,unsigned __int64)   C++
opencv_world455.dll!std::allocator<struct cv::Ptr >::deallocate(struct cv::Ptr * const,unsigned __int64)    C++
opencv_world455.dll!cv::imread(class std::basic_string<char,struct std::char_traits,class std::allocator > const &,int) C++
opencv_world455.dll!cv::imread(class std::basic_string<char,struct std::char_traits,class std::allocator > const &,int) C++
Pixel_analisys.exe!main() Line 14   C++
[External Code]

EDIT: I have fixed the .dll compiler issue by using the visual studio 2015 toolset instead of the 2022 toolset. However now my program wont open my picture. My code is still the same and i have trippled checked my file path. the console output i'm getting are as following

[ WARN:0@0.056] global C:\build\master_winpack-build-win64-vc15\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('

failed to open img.jpg

A: MSVC is a compiler that Microsoft Visual Studio IDE uses.
Your output log clearly shows that there is a mismatch in the OpenCV library and MSVC version you are using. Make sure the library you have installed is compatible with your compiler. Microsoft Visual C++
As for OpenCV, if you don't build OpenCV yourself(It means, you'll use pre-built binaries), again, make sure that the libraries are inside the opencvdir/x64/vc16(vc16:The compiler packaged with Visual Studio 2019). If you are using a higher version of that library, the folder name will already lead you.


text:
Q: I am getting jquery error while adding custom field in payment method in magento 2? I am trying to add custom fields in magento 2 but it is not working. I am getting

JQMIGRATE: jQuery.browser is deprecated jquery-migrate.js:41:4
  console.trace() jquery-migrate.js:43:5 migrateWarn
  http://localhost/magento221100/pub/static/version1546515844/frontend/Magento/luma/en_US/jquery/jquery-migrate.js:43:5
  get
  http://localhost/magento221100/pub/static/version1546515844/frontend/Magento/luma/en_US/jquery/jquery-migrate.js:58:6
  f<
  http://localhost/magento221100/pub/static/version1546515844/frontend/Magento/luma/en_US/jquery/jquery.ba-hashchange.min.js:9:677
http://localhost/magento221100/pub/static/version1546515844/frontend/Magento/luma/en_US/jquery/jquery.ba-hashchange.min.js:9:389
http://localhost/magento221100/pub/static/version1546515844/frontend/Magento/luma/en_US/jquery/jquery.ba-hashchange.min.js:9:2
  TypeError: this.test1 is not a function

Here is my code,
method-renderer.js
define(
    [
        'uiComponent',
        'Magento_Checkout/js/model/payment/renderer-list'
    ],
    function (
        Component,
        rendererList
    ) {
        'use strict';
        rendererList.push(
            {
                type: 'testpayment',
                component: 'Test_Testpayment/js/view/payment/method-renderer/testpayment'
                }
            );
            return Component.extend({

                getData: function() {
                return {
                    'method': this.item.method,
                    'additional_data': {
                        'test1':  $('#' +this.getCode() +'_test1').val(),
                        'test': $('#' +this.getCode() +'_test').val()
                    }
                };
            }
            });
        }
    );

method-renderer/tetpayment.js
define(
    [
        'Magento_Checkout/js/view/payment/default'
    ],
    function (Component) {
        'use strict';

        return Component.extend({
            defaults: {
                template: 'Test_Testpayment/payment/testpayment'
            },

            getCode: function() {
                return 'testing';
            },

            isActive: function() {
                return true;
            },

            validate: function() {
                var $form = $('#' + this.getCode() + '-form');
                return $form.validation() && $form.validation('isValid');
            },
            getData: function()
            {
                return {
                    'method': this.item.method,
                    'additional_data': {
                        'test1': this.test1(),
                        'test': this.test()
                    }
                };
            }

        });
    }
);

testpayment.html

        <input type="radio"
               name="payment[method]"
               class="radio"
               data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/>

            <form class="form" data-bind="attr: {'id': getCode() + '-form'}">
        <fieldset data-bind="attr: {class: 'fieldset payment items ccard ' + getCode(), id: 'payment_form_' + getCode()}">
            <input type="text" name="payment[test]" data-bind="attr: {'id': getCode()+'_test'}">
            <input type="text" name="payment[test1]" data-bind="attr: {'id': getCode()+'_test1'}">

            </fieldset>
        </form>

                <button class="action primary checkout"
                        type="submit"
                        data-bind="
                        click: placeOrder,
                        attr: {title: $t('Place Order')},
                        css: {disabled: !isPlaceOrderActionAllowed()},
                        enable: (getCode() == isChecked())
                        "
                        disabled>

                </button>

Main problem is in js file. Could you please help me.


text:
Q: Silverlight module doesnt load with firefox (ASP.NET tag) I am using IE and firefox, this is the default statement that was created using a default asp.net tag.
This works perfectly fine with IE but with firefox, nothing is rendered.
<%@ Page Title="" Language="C#" MasterPageFile="~/Core.Master" AutoEventWireup="true"
    CodeBehind="photoalbum.aspx.cs" Inherits="mkuk.photoalbum" %>

<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
    TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentLeft" runat="server">
    <asp:Silverlight ID="Xaml1" runat="server" Source="~/Static/silverlight/PhotoAlbum.xap"
        MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentRight" runat="server">
</asp:Content>

A: change Width="100%" Height="100%" to Width=600px Height= 800px. FF and IE7/IE8 cause problem with 100% values.
check this out -

A: Any chance you installed FireFox after installing the Silverlight plugin?  Maybe you could uninstall Silverlight (plugin only) and reinstall.  You could also try loading this page in FireFox on multiple machines to see if its really a FireFox issue (shouldn't be).


text:
Q: Sequential Causal Inference Scenario I am working on a problem where I am trying to estimate the effect of whether event C will occur given the time to B. The following scenarios illustrate the possible paths my system may take.
A -> B -> C
A -> C - > B
A -> B
Easy enough; a logistic model:   $Logit(C) = b_0 + b_1time_{A->B}$ could explain probability of an event C given the time to B.
However in my system if event C occurs before event B it causes B to take longer to occur. How can I account for this effect? (There are likely other confounding effects that contribute to C occurring)


text:
Q: Android 13 + workprofile + TileService = IllegalArgumentException Currently I found out that our app crashes when tries to requestListeningState of TileService on Android 13 (both compile and targetSdk 33) while running in workProfile.
Caused by: java.lang.IllegalArgumentException: User 10 is not the current user.

Does anybody have similar issue, or any idea why it happens or how to fix that?

A: Since Android 13, requestListeningState throw IllegalArgumentException if the user of the context is not the current user. See https://developer.android.com/reference/android/service/quicksettings/TileService#requestListeningState(android.content.Context,%20android.content.ComponentName)
On Android, the work profile is considered like another user. Apps on work profile cannot interact with tiles from main profile anyway. The tile on Android 12 and below only interact with the app on main profile, and not with the app on work profile.
Currently, I don't think there is a way to support tiles on a work profile for an app.


text:
Q: Why is 1200 being recognized as a valid date with moment? Hi I am looping through an array of objects and trying to change the values to true if the value is validated as a date but some values are being hit as well. I put examples of some values below.
const data1 = 1200;
const date = '2022-05-24T14:52:30.250Z';
console.log(moment(data1, moment.ISO_8601, true).isValid()); < --- expected to be false but returns true
console.log(moment(date, moment.ISO_8601, true).isValid()); < --- returns true

why is this? Thank you for the help.

A: When the first value passed to moment is a number, it's treated as a time value, the format argument is ignored. Any number in the range ±8.64e15 will be treated as representing a valid date.
The number 1200 will be treated as 1200 milliseconds after the ECMAScript epoch of 1 Jan 1970 UTC, so 1970-01-01T00:00:01.200Z, which is a valid date.

console.log(moment(1200).utc().format('YYYY-MM-DD HH:mm:ss.SSS'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>


text:
Q: Restkit Response with UTF8 chars I successfully post and receive data by using RestKit.
For example, I can easily decode this response (it is the debug output from RestLog):
 response.body={
    "response":
      {"fields":{"name":"test"}}
    }

But when the data contains accents, the response is encoded weardly:
response.body={
"response":
  {"fields":{"name":"\u00c3\u00a8\u00c3\u00a8"}}
}

and then my mapping is wrong.
The mapping is done as usual:
@property (nonatomic, copy) NSDictionary *fields;

I extract the fields from the response and then do the mapping.
 mappingDict = @{  @"fields"       :@"fields" };
 responseMapping = [RKObjectMapping mappingForClass:[SynchObj class]];
 [responseMapping addAttributeMappingsFromDictionary:mappingDict];

How to handle accents?


text:
Q: What is the best set of javascript tools to develop a multiplatform app, if I want to connect in real-time and offline-first approach? I've started using Firebase + Ionic + Electron for such a task, but I want to be sure it's the right approach.
Also, I read that you can use CouchDB + PouchDB to solve the offline-first part, but they always name the disadvantage that it does not provide authentication.
The system that I need to develop will be used by the government of my city. First, it will have information on the social development of citizens in need of social assistance. Then, a module will be developed for small health care centers, and more modules are planned in each department.
There are certain public data, which would be shared by the different applications to be developed.
I understand that it is not a trivial task, and that is why I want to hear your opinions.
Thank you very much in advance!


text:
Q: What's the keyboard shortcut of next option in completion list of Jupyter Notebook? For example, input the following codes in the first cell of a Jupyter Notebook in a browser:

aaa = 1
aab = 2

In the second cell, after inputing aa<TAB>, a completion list containing aaa and aab appears.
I want to select aab with keyboard. But after tried TAB, Up/Down key and Ctrl-p, no one works. I have to use the mouse to select aab.
And I've not found documents on Internet about this shortcut.
Question: how to choose aab with keyboard shortcuts?
Thanks.


text:
Q: Flash Transparency: Does it work reliably in anything other than IE? Are there workarounds? I've been given a site layout and a flash navigation to incorporate which requires transparency. However, using wmode='transparent' the results are highly inconsistent across browsers using the latest Flash 10.
In IE7 the sample page works perfectly fine.
In FireFox3 (Win) the colors are incorrect in the flash.
In Safari/FF3 (Mac) the Flash is not transparent at all.
I can use z-index to send it behind everything for the same effect, but then the divs on top do not allow the menu to be clicked.
I made a test page to demonstrate: http://quietmind.biofeedback.net/test/so.html

A: wmode has been a pain in the ass as far as I can remember. Has never worked correctly crossbrowser although I have to admit I haven't run the test in FP10.
Known issues with wmode transparent have been:

*

*Entering "@" sign in non- English keyboards.

*Tab Index craziness.

*Overall lost of performance.

*Printing problems (for example here).

*Ask Google and help yourself.

So, no, it's not reliable. Actually, for me any design that requires wmode is just not a valid design.
You can read more about wmode internals at What does GPU acceleration mean?.
Good luck.
Juan

A: Setting wmode to transparent can cause some strange problems, but this one is new to me. I would suspect that you're doing something a bit odd with the transparency in the swf itself which causes the plugin to mess up the calculations. Start by looking into that.
However, try to avoid wmode transparent if possible, it's a performance hog at best and can cause a whole bunch of strange behaviours (although the messed up colors can likely be avoided)

A: Both of the answers were helpful, but as it turns out the original SWF had a jpg for one of the images. For some reason the Windows implementation of Flash handled this just fine, but the Mac version didn't attempt to make it transparent.
There's still the issue of Windows FF3 mangling the colors on Flash with transparent set though, but that's a separate issue.


text:
Q: Dalzel's integral for $\pi$ and the lemniscate constant $\pi=\varpi_2$ can be considered as a member of the sequence of real numbers
$$\varpi_m=2\int\limits_0^1\frac{dt}{\sqrt{1-t^m}},$$
and, for example, the Wallis product formula $$\pi=4\prod_{n=1}^\infty{\frac{2n(2n+2)}{(2n+1)^2}}$$
can be generalized to all these m-clover constants (http://arxiv.org/abs/1212.4178 A Wallis Product on Clovers, by Trevor Hyde):
$$\varpi_m = \frac{2(m+2)}{m}\prod_{n=1}^\infty{\frac{2n(2mn+ m +2)}
{(2n+1)(2mn+2)}}.$$
On the other hand, for $\pi$ there exists the well known Dalzel's nice integral formula $$\frac{22}{7} - \pi = \int_0^1 (x-x^2)^4 \frac{dx}{1+x^2},$$
(see the discussion: Source and context of $\frac{22}{7} - \pi = \int_0^1 (x-x^2)^4 dx/(1+x^2)$? ).
I'm curious whether something like the Dalzel's formula exists, for example, for the lemniscate constant $\varpi_4$.


text:
Q: Writing Hex data to a file i am trying a piece of code.
<?php
$tmp = ord('F'); //gives the decimal value of character F (equals 70)
$tmp = $tmp - 55; //gives 15 - decimal equivalent of 0x0F
$tmp = dechex($tmp); // converts 15 to 0x0F
$fp = fopen("testing.data","wb+");
fwrite($fp,$tmp);
fclose($fp);
?>

When i open the file called testing.data in a hex editor, i see 2 bytes written. The 2 bytes are 0x36 and 0x33.
I am expecting that only 1 byte i.e. 0x0f will be written to the file. This doesn't happen.
Please help me out with this.

A: You are writing the string representation of the number 0x0F to the file (which will use 1 byte per character).
In PHP you would use the pack function to create binary strings.
$bindata = pack('n', 0x0F);
file_put_contents('testing.data', $bindata);

A: If you want to write the byte 0x0f to the file, simply write the character with that ASCII code. You effectively want to undo ord, and the reverse function is chr:
<?php
$tmp = ord('F'); //gives the decimal value of character F (equals 70)
$tmp = $tmp - 55; //gives 15 - decimal equivalent of 0x0F
$tmp = chr($tmp); // converts 15 to a character
$fp = fopen("testing.data","wb+");
fwrite($fp,$tmp);
fclose($fp);
?>


text:
Q: "ALTER" syntax error while doing migration with alembic for new added non-nullable column in flask_sqlalchemy When I add a new column (nullable=False) to an existing table, I will need to update the migration revision file by manually to first add the column with nullable=True, and then update all existing records to set the column, after that alter the column to nullable=False. But I encountered an error of "ALTER": syntax error.
Here is the test script (test.py):
#!/usr/bin/env python
import os

import flask_migrate
from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =\
    'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

manager = Manager(app)
db = SQLAlchemy(app)

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)

migrate = flask_migrate.Migrate(app, db)
manager.add_command('db', flask_migrate.MigrateCommand)

if __name__ == '__main__':
    manager.run()

First I initialized the db and upgrade it to latest:
$ python test.py db init && python test.py db migrate && python test.py db upgrade
  Creating directory /tmp/test/migrations ... done
  Creating directory /tmp/test/migrations/versions ... done
  Generating /tmp/test/migrations/env.pyc ... done
  Generating /tmp/test/migrations/script.py.mako ... done
  Generating /tmp/test/migrations/env.py ... done
  Generating /tmp/test/migrations/alembic.ini ... done
  Generating /tmp/test/migrations/README ... done
  Please edit configuration/connection/logging settings in '/tmp/test/migrations/alembic.ini' before proceeding.
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate.compare] Detected added table 'users'
  Generating /tmp/test/migrations/versions/86805d015930_.py ... done
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade  -> 86805d015930, empty message

Then I updated the model to add the new column 'email' which is nullable=False:
<snip>
...
class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)  # this is the new column

Then generate the migration revision file:
$ python test.py db migrate -m "add name"
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.autogenerate.compare] Detected added column 'users.name'
  Generating /tmp/test/migrations/versions/c89371227a53_add_name.py ... done

Since the name column is non-nullable, need to update the migration file by manual, update it as bellow:
$ cat /tmp/test/migrations/versions/c89371227a53_add_name.py

from alembic import op
import sqlalchemy as sa

revision = 'c89371227a53'
down_revision = '45a51b6df68c'
branch_labels = None
depends_on = None

def upgrade():
    op.add_column('users', sa.Column('name', sa.String(length=64), nullable=True))
    op.execute("""
    UPDATE users SET name="foobar"
    """)
    op.alter_column('users', 'name', nullable=False)

def downgrade():
    op.drop_column('users', 'name')

Now run the migration:
$ python test.py db upgrade

I got an error as below:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near "ALTER": syntax error [SQL: u'ALTER TABLE users ALTER COLUMN name SET NOT NULL']

How can I fix this or how should I do the migration for such cases?
My env is:
Flask==0.12.1
Flask-Migrate==2.0.3
Flask-Script==2.0.5
Flask-SQLAlchemy==2.2
SQLAlchemy==1.1.9
alembic==0.9.1

A: Just figured out the reason, it's because I'm using sqlite and sqlite lacks of ALTER support, a workaround for this is using the batch operation migrations http://alembic.zzzcomputing.com/en/latest/batch.html


text:
Q: Greendroid GDExpandableListActivity example needed I'm searching for any simple implementation of that activity class.

A: I will answer myself here my solution
import greendroid.app.GDExpandableListActivity;
import greendroid.widget.ActionBarItem.Type;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.widget.ExpandableListAdapter;
import android.widget.SimpleExpandableListAdapter;

public class ExpListViewActivity extends GDExpandableListActivity {
    private static final String NAME = "NAME";
    private static final String IS_EVEN = "IS_EVEN";

    DataBaseHelper dbHelper;

    private ExpandableListAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addActionBarItem(Type.Add);
    List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
    List<List<Map<String, String>>> childData = new ArrayList<List<Map<String, String>>>();

    for (int i = 0; i < 20; i++) {
        Map<String, String> curGroupMap = new HashMap<String, String>();
        groupData.add(curGroupMap);
        curGroupMap.put(NAME, "Item " + i);
        curGroupMap.put(IS_EVEN, (i % 2 == 0) ? "This group is even" : "This group is odd");

        List<Map<String, String>> children = new ArrayList<Map<String, String>>();
        for (int j = 0; j < 5; j++) {
            Map<String, String> curChildMap = new HashMap<String, String>();
            children.add(curChildMap);
           // curChildMap.put(NAME, "Child " + j);
            curChildMap.put(IS_EVEN, (j % 2 == 0) ? "Hello " + j: "Good Morning "+ j);
        }
        childData.add(children);
    }

    // Set up our adapter
    mAdapter = new SimpleExpandableListAdapter(
            this,
            groupData,
            android.R.layout.simple_expandable_list_item_1,
            new String[] { NAME, IS_EVEN },
            new int[] { android.R.id.text1, android.R.id.text2 },
            childData,
            android.R.layout.simple_expandable_list_item_2,
            new String[] { NAME, IS_EVEN },
            new int[] { android.R.id.text1, android.R.id.text2 }
            );
    setListAdapter(mAdapter);

    }

}


text:
Q: @media screen and (min-width: 320px) being overwritten I am tring to work with a small from, just 3 elements.
This is the i'm using, can someone please let me know where i am going wrong?
I have tried working with both min-width and max-width, nothing seems to be working.
<style type="text/css">

html,body{margin:0px; padding:0px; font-family:arial;}

form.form { margin:0px;}

p span strong{ color:#505050;}

form.form span.error {clear: left;display: block;font-weight: normal;margin-top: 2px;padding-left: 166px;}

/*form.form span.error {clear: left;display: block;font-weight: normal;margin-top: 2px;padding-left: 172px;}*/

form.form p.required, form.form span.required, form.form label.required
{font-weight: normal;}

form.form p {clear: left;margin: 0px;padding: 0px;width:544px;}

.btn_subscribe {
float: left;
margin: 0 0 11px 0;
width: 174px;
height: 41px;
background: url("http://www.vuesoftware.com/assets/btn_subscribenow.png") no-repeat;
background-size:170px 40px;
border: none;
cursor: pointer;
}

form.form div.submit{padding-top:7px;}
.text{ border: none; background:url("http://www.vuesoftware.com/assets/input_subscribe.jpg") no-repeat top left; width: 184px; height:32px; font-size:12px;
    padding-left:11px;}

form.form div.no-label{font-size:11px; margin-left:0px !important;color: rgb(226, 140, 36); }

form.form div label {display: block; float: left; margin: 0; padding: 0 13px 0 0; text-align: right; width: 160px; font-size:13px;}

.required{ padding:10px 0px 0px !important;  }
div span span {display: block; padding-left:174px; }
div span span label{ float:none !important;}

@media screen and (max-width: 320px)
{
    form.form div.no-label{
        float:none;
        width:200px;
        }
    .text{
        border:none;
        background:url("http://www.vuesoftware.com/assets/input_subscribe.jpg") no-repeat top left;
        width:184px;
        height:32px;
        }
    .btn_subscribe{
        background:url("http://www.vuesoftware.com/assets/btn_subscribenow@2x.png") no-repeat;
        background-size:170px 40px;
        }
      p span strong{
          display:none;
        }
}

@media screen and (min-width: 320px)
{
    form.form div.no-label{
        float:left;
        width:350px;
        }
    .text{
        border:none;
        background:url("http://www.vuesoftware.com/assets/input_subscribe_big.png") no-repeat top left;
        width:300px;
        height:32px;
        font-size:12px;
        padding-left:11px;
        }
    .btn_subscribe {
        width:250px;
        height:40px;
        background: url("http://www.vuesoftware.com/assets/btn_subscribefornewsletter@2x.png") no-repeat;
        background-size:250px 40px;
        border:none;
        cursor:pointer;
        }
}

@media screen and (min-width: 960px)
{
    form.form div.no-label{
        float:none;
        width:200px;
        }
    .text{
        border:none;
        background:url("http://www.vuesoftware.com/assets/input_subscribe.jpg") no-repeat top left;
        width:184px;
        height:32px;
        }
    .btn_subscribe{
        background:url("http://www.vuesoftware.com/assets/btn_subscribenow@2x.png") no-repeat;
        background-size:170px 40px;
        }
    p span strong{
        display:block;
        }
}

A: you are using wrong order of media quires use @media screen and (min-width: 960px) css first then add css of @media screen and (min-width: 320px) simple :)

A: Let's go through your media queries with imaginary DeviceX, which is 360px wide.
@media screen and (max-width: 320px) {
    // no match:  360px > 320px
}

@media screen and (min-width: 320px) {
    // match:  360px >= 320px
}

@media screen and (min-width: 960px) {
    // no match: 360px < 960px
}

/* media query found in your fiddle that's not listed in the OP */
@media only screen and (max-width:960px){
    // match:  360px <= 960px
}

Basically, your device is matching multiple media queries.  Later media queries are overwriting properties found in earlier media queries.
It may be that what you're looking for is to have a media query with both a min-width and a max-width:
@media screen and (min-width: 600px) and (max-width: 960px) {
    // no match: 360px < 600px
}


text:
Q: Explode variable from space and append basedir in ansible playbook In my use case I am reading directories from conf and source path is space separated. Number of space separated source may increase or decrease. My product.conf look like below
product.conf
{
    "directories": [{
        "source": "src/main/php/en/path1 src/main/php/en/path2 src/main/php/en/path3",
        "lang": "en"
    }, {
        "source": "src/main/php/jp/path1 src/main/php/jp/path2",
        "lang": "jp"
    }]
}

Playbook to read conf and assign source into separate variable.
playbook.yml
---

 - hosts: 127.0.0.1
   connection: local

   vars:
     BASE_DIR: /home/roop

   tasks:
     - include_vars: product.conf

     - set_fact:
         en_source="{{ item.source }}"
       with_items: directories
       when: item.lang == "en"

     - set_fact:
         jp_source="{{ item.source }}"
       with_items: directories
       when: item.lang == "jp"

     - debug: var=en_source
     - debug: var=jp_source

I am getting BASE_DIR dynamically. I need to add this BASE_DIR with every source. like
"en_source" = "/home/roop/src/main/php/en/path1 /home/roop/src/main/php/en/path2"

Any suggestion?

A: A little hacky:
- set_fact:
    en_source="{{ BASE_DIR + '/' + item.source | regex_replace('(\s)', '\\1' + BASE_DIR + '/') }}"

regex_replace is a filter from Ansible.
For a cleaner solution you can create a custom filter plugin.


text:
Q: Is there an Apache-like Websocket server solution that handles php scripts? There are a lot of examples of implementing a TCP/IP-WS stack in all kinds of languages, also in PHP/CLI. But that is not what I'm looking for.
For http protocol there is Apache webserver software. It listens on default http port 80 for incoming requests. On shared hosting servers it can host an array of domain names and the incoming request url is mapped to the right served directory/file in the "hostAccountDir/domainName/docRoot/".
In this model each PHP script is a "specialized HTTP/application level" server; and does not need to invent/implement the TCP/IP-HTTP stack. Fortunately Apache does that for all PHP scripts.
Is there such a thing for Websockets, listening on port 9000(?), forking to the served directory/file... etc?

A: Apache powers more than 70% of websites today, but new alternatives are gaining market share. Apache is a reliable server, but it takes considerable memory to run. In some situations other web servers can perform better. The best-known alternative open source HTTP servers are lighttpd, nginx, and Cherokee.
PHP-FPM can listen on multiple sockets. It also listen on Unix sockets, or TCP sockets.
nginx is an HTTP server and mail proxy server. It has been running for more than two years on many heavily loaded Russian sites, and it has become more popular in the rest of the world, to the point where today it's used by 6.5% of all websites.
For more details refer to the links below.
https://serversforhackers.com/video/php-fpm-configuration-the-listen-directive
https://linuxaria.com/article/apache-alternatives-for-serving-php


text:
Q: Usage of Bitwise OR in the following DOS command I use the following line of code to execute two commands simultaneously:
C:\Users\Me\CLAP.txt | %SystemRoot%\explorer.exe F:\Software
Can't help but wonder how the bitwise OR is used to perform the above.
C:\Users\Me\CLAP.txt && %SystemRoot%\explorer.exe F:\Software
seems to work fine too.

A: In this context, the | is the pipe symbol, not a bitwise or.  The output of the first command is sent to the input of the next command.


text:
Q: How to include automatically xmlbeans generated code into maven jar? I have a project which uses Apache Xmlbeans for databinding. Currently it is very simple it only has some Schema-Files in src/main/xsd and xsdconfig in src/main/xsdconfig.
I want to include the generated Classes into the generated jar-File. It works if I specify the xmlbeans goal:
"mvn xmlbeans:xmlbeans package" --> Creates a Jar with the xmlbeans classes
But I want to do this within the normal build cycle: "mvn package" --> should create a jar with the xmlbeans classes, but won't.
The pom is the following:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.test</groupId>
  <artifactId>xmlbeans-maven-test</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <build>
   <pluginManagement>
    <plugins>
     <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>maven-xmlbeans-plugin</artifactId>
          <version>2.3.3</version>
     </plugin>
    </plugins>
   </pluginManagement>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.apache.xmlbeans</groupId>
      <artifactId>xmlbeans</artifactId>
      <version>2.4.0</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>

I tried to bind it manually to the "generate-sources" (And to the "compile" phase, too) phase, but it does not work.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>de.leradon</groupId>
  <artifactId>xmlbeans-maven</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <build>
   <pluginManagement>
    <plugins>
     <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>maven-xmlbeans-plugin</artifactId>
          <version>2.3.3</version>
          <executions>
             <execution>
                <phase>generate-sources</phase>
                <goals>
                  <goal>xmlbeans</goal>
                </goals>
             </execution>
          </executions>
     </plugin>

    </plugins>
   </pluginManagement>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.apache.xmlbeans</groupId>
      <artifactId>xmlbeans</artifactId>
      <version>2.4.0</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
</project>

How can I configure the plugin, so that when I run "mvn package" all the generated classes are packaged into the jar?
Greetings,
lerad

A: If you configure the plugin under pluginManagement, you still need to declare it under plugins. To simplify, I'm not using the pluginManagement in the pom.xml below:
<project>
  ...
  <dependencies>
    ...
    <dependency>
      <groupId>org.apache.xmlbeans</groupId>
      <artifactId>xmlbeans</artifactId>
      <version>2.4.0</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      ...
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>xmlbeans-maven-plugin</artifactId>
        <version>2.3.3</version>
        <executions>
          <execution>
            <phase>generate-sources</phase>
            <goals>
              <goal>xmlbeans</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

With this POM (and some XSD in src/main/xsd which is the default location), running mvn clean package just works (i.e. sources are generated from the XSD, compiled and packaged as part of the build).

A: Try this.
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>xmlbeans-maven-plugin</artifactId>
    <version>2.3.2</version>
    <executions>
        <execution>
            <id />
            <phase>generate-sources</phase>
            <goals>
                <goal>xmlbeans</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <schemaDirectory>src/main/xsd</schemaDirectory>
        <staleFile>${project.build.directory}/generated-sources/xmlbeans/.staleFlag</staleFile>
        <verbose>false</verbose>
        <quiet>false</quiet>
        <javaSource>1.6</javaSource>
    </configuration>
</plugin>


text:
Q: Probability Discrete Math Bag A bag contains 15 different objects, 5 red object, 5 blue objects, and 5 white objects. If 3 objects are chosen at random
a) What is the probability that 3 objects of the same color are chosen?
b) What is the probability that 3 objects, one of each color are chosen?
For a the answer that I was given is 3$\lgroup\frac{5\choose3}{15\choose3}\rgroup$
But that doesn't make sense.  Another way was 15(2)(1)/$15\choose3$  but yet again it doesn't make sense.

A: For part a), examine the situation where you want to pick, say, exactly 3 red objects.
There are ${5\choose3}$ ways that you can pick 3 red objects. There are ${15\choose3}$ ways to pick any object at all. So you take the number of desired outcomes and divide by the number of all possible outcomes. This gives you $\frac{5\choose3}{15\choose3}$.
But the goal isn't to get 3 red objects, it's to get 3 of the same colour. Since there are 3 colours you triple the number of desired outcomes. This gives you $3\lgroup\frac{5\choose3}{15\choose3}\rgroup$.
For $\frac{15(2)(1)}{15\choose3}$. The bottom term of $15\choose3$ follows the same logic as the above answer (all possible ways to choose the objects).
For the numerator you need to pick an object. There are 15. Now your desired colour is locked in. You pick another object, of which there are 4 remaining that you want. Then another when 3 remain. This gives $(15)(4)(3)$. But the order doesn't matter, and there are $3!$ ways to arrange them. So that gives $\frac{(15)(4)(3)}{3!}$. If you eliminate the $3!$  by cancelling out a 3, then a 2, you get $(15)(2)(1)$.
For the sake of interest, here's a different way to solve the problem.
You're picking 3 objects. You pick your first object. It doesn't matter what it is. This just happens. This is now your desired object colour. You now have 4 desired objects out of 14 possible objects to choose from, which is a $\frac{4}{14}$ chance.
Then you have 3 desired objects out of 13, or a $\frac{3}{13}$ chance.
This results in $(\frac{4}{14})(\frac{3}{13}) = \frac{12}{182} = \frac{6}{91}$, which matches the answer above.
You posted a b) part but didn't make any specific mention of it. Is there something with b) that needs clarification?


text:
Q: TypeError: 'MediaDefiningClass' object is not iterable I'm attempting to implement django-progressbarupload.
https://github.com/ouhouhsami/django-progressbarupload
I'm getting the following error:
for model in model_or_iterable:
TypeError: 'MediaDefiningClass' object is not iterable
admin.py
from django.contrib import admin
from accounts.models import UserProfile

class UserProfile(admin.ModelAdmin):
    change_form_template = 'progressbarupload/change_form.html'
    add_form_template = 'progressbarupload/change_form.html'

admin.site.register(UserProfile)

This is the traceback
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 347, in execute
    django.setup()
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\registry.py", line 120, in populate
    app_config.ready()
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
    self.module.autodiscover()
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\jason\Desktop\jason3\accounts\admin.py", line 18, in <module>
    admin.site.register(UserProfile)
  File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 102, in register
    for model in model_or_iterable:
TypeError: 'MediaDefiningClass' object is not iterable

Thanks for the help!

A: The first parameter to register is the model class itself. You have used the same name for your model class as your admin class. Give them separate names and pass them both to register.
class UserProfileAdmin(admin.ModelAdmin):
    change_form_template = 'progressbarupload/change_form.html'
    add_form_template = 'progressbarupload/change_form.html'

admin.site.register(UserProfile, UserProfileAdmin)


text:
Q: CSS Error with a span I'm trying to use a span to show a small icon next to some text inside a table. Here's the html code:

    Bob Smith

CSS code:
.icon
{
    cursor: pointer;
    background-position: left top;
    background-repeat: no-repeat;
    display: block;
    float:left;
    padding-left: 15px;
    background-image: url(../images/icon.png);
}

All I want is a small checkbox icon (15x15px) to be showed right next to the name, in this format:
[icon]Bob Smith

However, right now its showing as:
[icon]           Bob Smith

(I.e there's a lot of whitespace between the icon and the text)
Any ideas how to fix this?

A: Try explicity setting a width on the icon class, such as this:
.icon
{
    cursor: pointer;
    background-position: left top;
    background-repeat: no-repeat;
    float:left;
    width: 15px;
    height: 15px;
    background-image: url(../images/icon.png);
}

A: Html

         Bob Smith

CSS code:
.icon {
    cursor: pointer;
    background: url(../images/icon.png) 0 0 no-repeat;
    display: block;
    float:left;
    width: 15px;
    height:15px;
    margin-right:4px;/*to put a slight buffer between icon and text*/
}


text:
Q: Updating multiple columns using Case I have a query that looks like below:
UPDATE some_table
SET column_x = CASE WHEN x_specific_condition THEN new_value_for_x ELSE column_x END,
    column_y = CASE WHEN y_specific_condition THEN new_value_for_y ELSE column_y END,
WHERE some_more_conditions

Problem with above is, each column (x, y) still gets updated with their own value if some_more_conditions return true irrespective of their specific conditions returning true. I tried removing ELSE from above, but no luck
I am combining as some_more_conditions are same for both cases, I think its better to perform all in 1 update (suggestions welcome)
Do you know if there is a way that I can perform the above update in 1 query by skipping the individual columns where the specific conditions do not match (basically avoid overwriting of same values)

A: To do this in one update, you would need to expand the where clause:
UPDATE some_table
    SET column_x = CASE WHEN x_specific_condition THEN new_value_for_x ELSE column_x END,
        column_y = CASE WHEN y_specific_condition THEN new_value_for_y ELSE column_y END,
    WHERE some_more_conditions AND
          (x_specific_condition OR
           y_specific_condition
          );

An alternative is to use multiple updates, but that could be more expensive:
UPDATE some_table
    SET column_x = new_value_for_x
    WHERE some_more_conditions AND x_specific_condition;

UPDATE some_table
    SET column_y = new_value_for_y
    WHERE some_more_conditions AND y_specific_condition;

A: update [table_name]
set [column_name_1] = case when [column_name_1] = [condition_1] then [condition_2]
else [column_name_1]
end,
[column_name_2] = case when [column_name_2] = [condition_1] then [condition_2]
else [column_name_2]
end,
where condition;
Note: [table_name] is your table name, [column_name] is your column name in which you want to update values.
you can update values without where condition as well.
find screenshot


text:
Q: Upload every photo present in specific folder, without duplicates I need help. After obtaining a list of photo names (.jpg) in a specific folder (chosen randomly from various folders), is there a way to upload every photo in that folder to a site, until they are finished? I would also like to avoid uploading duplicates.
So far, I have only managed to get a list of photos in a folder:
current_dir = os.getcwd()

folder = random.randint(1, 27)
img_path = current_dir + '\\' + 'Photo' + '\\' + str(folder)
img_dir = os.listdir(img_path)
img_list = []
for N in img_dir:
    img_list.append(N)

At this point, I wanted to upload every single photo in the randomly selected folder using the send_keys() command, for example: driver.find_element(By.XPATH, "//input[@type='file']").send_keys(). But how can I do that? Thank you in advance for your help.


text:
Q: How to get common objects from 2 querysets in Django? I have 2 querysets of same model (obtained from different functions). Now I want to see common elements in them on the basis of some fields like:
first_name, last_name, date_of_birth, abc_field(boolean field)
They will have different primary keys, and unique ids. The only difference in them should be that abc_field should be True in one object and False in another object. How do I achieve this?
I read online about annotate(Count()), but I think this would make the code look a bit naive, with all those Count() on every field.

A: I will suggest you custom-define a function that compares two objects. Something like:
def compare(obj1, obj2):
    if (obj1.first_name == obj2.first_name && obj1.last_name == obj2.last_name ...):
        return true
    return false

Even if there are default methods to compare two objects, I don't think they will work in your case as you said specifically to exclude the primary key fields. The rest is simple: you loop through a double loop between your two lists and check whether the two objects are equal. Like:
for item1 in list1:
    for item2 in list2:
        if compare(item1, item2):
            # ... do something

Pretty naive, but should work.


text:
Q: Using segmented linear regression as evidence for the limit of human lifespan Nature published this year the following paper: Evidence for a limit to human lifespan1, in which the authors argue their "results strongly suggest that the maximum lifespan of humans is fixed and subject to natural constraints."
One of this paper's statistical analysis has been panned at some sites already, including Nature article is wrong about 115 year limit on human lifespan and Evidence for a limit to effective peer review, since it turned up in some popular media.
The study is based, among several things, on data from databases detailing the yearly maximum age of death. Among their analyses, the following figure is included:

Basically the authors argue there's a breakpoint, and so they performed a segmented regression before circa 1995 and after that point onward. The regression is used as evidence for the limit of human lifespan.
Does it make sense though? If not, what method could better be employed to study these data?
[1] Dong, Xiao, Brandon Milholland, and Jan Vijg. "Evidence for a limit to human lifespan." Nature 538.7624 (2016): 257-259.

A: I think the nature of the conclusions are totally bunk. We see between 1950 and 2015 an increasing trend followed by a decreasing trend. It is a classic fallacy of applying data which are suggestive of a hypothesis different than the one tested and presenting them as such. With these data, a segmented regression can interpolate and predict that in 1995 a local maxima of lifespan was about 115 years $\pm$ whatever error they estimate from segmented regression. This does not preclude 2020 or 2030 trends superseding that value.

*

*The concept of natural lifespan conflicts with the preponderance of research in aging, genetics, and telomeres.

*An experimental design to address natural human lifespan is needed using "body on a chip" technology.

*50 years is utterly trivial in the course of human history. There have been many points in the past where an upward trend in lifespan was followed by a downward one.

*Data such as those presented could have been simulated from a non-linear model having discontinuities and/or asymptotes which are unmeasurable.

*Since the model's goal is prediction, distributional assumptions, and mean-model correctness are needed, and neither (it seems) were these checked nor are they met.

A: First of all, let's manually extract the values from their original Figure 2 and plot the data without any colors or regression lines biasing our first visual inspection of the raw data.
year <- c(1968, 1970, 1973, 1975, 1978, 1979, 1980, 1981, 1982,
          1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991,
          1992, 1994, 1993, 1995, 1996, 1998, 1997, 1999, 2000,
          2001, 2002, 2003, 2004, 2005, 2006)
age <- c(111, 111, 112, 111, 111, 110, 111, 113, 113, 113, 111,
         114, 113, 114, 114, 112, 112, 112, 114, 115, 117, 112,
         114, 115, 121, 119, 114, 115, 115, 114, 113, 114, 112)

plot(year,age,xlab="Year",
     ylab="Yearly maximum reported age at death (years)",
     pch=20,cex=2,ylim=c(108,124),xlim=c(1960,2010))

We obtain:

And, let's do the same for the data in Figure 6 (as presented in the question above):
age <- c(113, 109, 109, 110, 113, 109, 110, 111, 111, 111,
         112, 112, 113, 111, 111, 113, 113, 113, 114, 115,
         113, 114, 122, 119, 117, 114, 115, 115, 114, 114,
         115, 116, 115, 115, 114, 114, 116, 116, 117)
year <- c(1954, 1957, 1958, 1958, 1963, 1964, 1965, 1967,
          1968, 1970, 1975, 1972, 1976, 1976, 1977, 1980,
          1981, 1982, 1984, 1985, 1986, 1987, 1997, 1998,
          1998, 1999, 2001, 2001, 2002, 2003, 2006, 2006,
          2008, 2007, 2010, 2011, 2011, 2012, 2015)

plot(year,age,xlab="Year",
     ylab="MRAD from GRG",
     pch=20,cex=2,ylim=c(108,124),xlim=c(1950,2020))

It seems that a simple linear regression model would be the natural candidate challenging the less parsimonious change-point model the authors proposed.
Indeed, Philipp Berens and Tom Wallis have done so and published their re-analysis on github: https://github.com/philippberens/lifespan


text:
Q: What is this Textmate keyboard shortcut doing (Control+Shift+.) It's inserting <%=  %> into my HTML, but what is that for?

A: ASP-style short form tags for PHP scripts.

A: It's also used in ERB which is the ruby template engine and is used as the default template engine in Ruby on Rails.
ERB docs: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB.html
Rails use of ERB: http://api.rubyonrails.org/classes/ActionView/Base.html


text:
Q: Solving cubic equation modulo prime I'm trying to an algorithm that can solve an elliptic curve equation for constant y:
$y^2 = x^3 + ax + b  \text{ mod } p$
p is 57 digits long
I've tried to solve it using like a regular cubic equation, but it's only return good results when the square root inside the formula for cubic equations has a solution mod p.
Thank you very much in advance.


text:
Q: MySQL group by day display empty days +-------------+---------------------+
| uid         | date                |
+-------------+---------------------+
|          35 | 01-11-2009 19:32:44 |
|          35 | 01-13-2009 22:33:49 |
|          42 | 01-23-2009 22:08:24 |
|          42 | 02-01-2009 22:33:57 |
|          35 | 02-01-2009 22:37:34 |
|          35 | 04-20-2009 15:23:49 |
+-------------+---------------------+

I want to get a count for each day for a specific uid like and display the empty days (within a range):
User 35 (21 days)
01-11-2009 -> 1
01-12-2009 -> 0
01-13-2009 -> 1
01-14-2009 -> 0
01-15-2009 -> 0
01-16-2009 -> 0
01-17-2009 -> 0
01-18-2009 -> 0
01-19-2009 -> 0
01-20-2009 -> 0
01-21-2009 -> 0
01-22-2009 -> 0
01-23-2009 -> 0
01-24-2009 -> 0
01-25-2009 -> 0
01-26-2009 -> 0
01-27-2009 -> 0
01-28-2009 -> 0
01-29-2009 -> 0
01-30-2009 -> 0
01-31-2009 -> 0
02-01-2009 -> 1

So far I got
SELECT MONTHNAME(date), COUNT(uid) FROM cliques_referidos WHERE uid = 35 GROUP BY YEAR(date), MONTH(date), DAY(date)

How to get the 0 count for the days in between?

A: Assuming it's an option, consider creating a Dates Lookup table.  Then you can easily use an OUTER JOIN to create your list.  Here is an SO post about it.
Calling the lookup table datelookup with a date field called datevalue, then this should work:
SELECT MONTHNAME(d.datevalue), COUNT(cr.uid)
FROM datelookup d LEFT JOIN
    cliques_referidos cr ON d.datevalue = DATE(cr.date)
        and cr.uid = 35
GROUP BY YEAR(d.datevalue), MONTH(d.datevalue), DAY(d.datevalue)

Since you're date field is a datetime, use DATE() in your join.
If you can't create a lookup table, look into using a stored procedure or a function since MySQL doesn't support Recursive CTEs.  Search SO for some examples.


text:
Q: TIF Converted to PDF with PDFSharp and System.Drawing Loads in Chrome and Edge But Blank in Firefox/pdf.js/react-pdf I have converted a TIF into a PDF with System.Drawing and PDFsharp-gdi (version 1.50.5147) in my .NET 6 API. I am sending the file as a base64-encoded string to my react frontend that uses wojtekmaj/react-pdf as the PDF viewer. However, the TIF needed to be resized due to being larger than the max allowed size for PDFs (200in x 200in) in the API which I did with the following:
System.Drawing.Image MyImg = System.Drawing.Image.FromStream(inStrm);
XImage img = XImage.FromGdiPlusImage(MyImg);
var p = new PdfPage();

double maxRez = 14400.0;
if (MyImg.Width > maxRez || MyImg.Height > maxRez)
{
    double factor = 0.0;
    if(MyImg.Width > MyImg.Height)
    {
      factor = (double)(MyImg.Width) / maxRez;
    }
    else{
      factor = (double)(MyImage.Height) / maxRez;
    }

    p.Width = MyImg.Width / factor;
    p.Height = MyImg.Height / factor;
}

doc.Pages.Add(p);
XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[PageIndex]);
xgr.DrawImage(img, 0, 0, p.Width, p.Height);

Normally sized images (not beyond 200inx200in are converted and displayed fine). Why would PDFs generated after being resized not load correctly? This issue also occurs if I download the file and load it as a PDF in Firefox, which uses PDF.js under the hood I believe.
In Firefox, the error is An error occurred while rendering the page. PDF.js v2.4.152 (build 827eb64b) Message: Stack: putBinaryImageData@resource://pdf..., which I have tried looking up but no solutions have been suggested.

A: The solution was to resize the image being embedded first, then adding it to the PDF page after it has already been resized. I was previously trying to resize the PDF which would allow the PDF to be loaded but none of the images because their resolution was greater than what is supported in PDF files. Refer to this article for how to resize images.
If you are working with multi-page images, scale each one iteratively with MyImg.GetFrameCount(FrameDimension.Page) and select active frame with MyImg.SelectActiveFrame(FrameDimension.Page, PageNum).


text:
Q: apscheduler ValueError: The following arguments have not been supplied: self when decorating function First of all, I checked this question in order to make sure that I have no duplicates.
I have a singleton class that has 2 internal methods that I want to trigger via a public method.
Each method should be run in a background job scheduled by a BackgroundScheduler.
Each method has a different interval.
Here is the code:
import inspect
import threading
import structlog
from apscheduler.schedulers.background import BackgroundScheduler
from typing import Optional, Iterator, Callable

SCAN_A_INTERVAL: int = 30
SCAN_B_INTERVAL: int = 10
scheduler = BackgroundScheduler()

class Scanner:
    __instance: Optional["Scanner"] = None

    def __init__(self):
        self.__logger = structlog.get_logger()

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super(Scanner, cls).__new__(cls)

        return cls.__instance

    @scheduler.scheduled_job("interval", seconds=SCAN_A_INTERVAL)
    def _scan_a(self):
        print("I'm in a")

    @scheduler.scheduled_job("interval", seconds=SCAN_B_INTERVAL)
    def _scan_b(self):
        print("I'm in b")

    def scan_all(self):
        scan_methods: Iterator[Callable] = (
            tup[1] for tup in inspect.getmembers(self, inspect.ismethod)
            if tup[0].startswith("_scan_")
        )

        for method in scan_methods:
            threading.Thread(target=method, daemon=True).start()  # We want the method to starts manually the first time

        scheduler.start()

if __name__ == '__main__':
    Scanner().scan_all()
    #  Flask application running so the main thread doesn't die

When running this I get the following error:
File "full_path/scanner/scanner.py", line 44, in <module>
    class Scanner:
  File "full_path/scanner/scanner.py", line 64, in Scanner
    def _scan_a(self):
  File "full_path/virtualenvs/repo/lib/python3.8/site-packages/apscheduler/schedulers/base.py", line 470, in inner
    self.add_job(func, trigger, args, kwargs, id, name, misfire_grace_time, coalesce,
  File "full_path/virtualenvs/repo/lib/python3.8/site-packages/apscheduler/schedulers/base.py", line 438, in add_job
    job = Job(self, **job_kwargs)
  File "full_path/virtualenvs/repo/lib/python3.8/site-packages/apscheduler/job.py", line 49, in __init__
    self._modify(id=id or uuid4().hex, **kwargs)
  File "full_path/virtualenvs/repo/lib/python3.8/site-packages/apscheduler/job.py", line 180, in _modify
    check_callable_args(func, args, kwargs)
  File "full_path/virtualenvs/repo/lib/python3.8/site-packages/apscheduler/util.py", line 399, in check_callable_args
    raise ValueError('The following arguments have not been supplied: %s' %
ValueError: The following arguments have not been supplied: self

What I tried:
When adding the jobs manually in a loop (
for method in scan_methods:
   scheduler.add_job(method, "interval", seconds=<accordingly>)

), The code runs perfectly.
I want to use the decorated function and not add the job manually.
Thank you!


text:
Q: The quantum hall effect and Hofstadter's butterfly spectrum What is the connection between the quantum Hall effect and the Hofstadter's butterfly spectrum? I mean, can I understand something about the quantum Hall effect in the Hofstadter's butterfly spectrum?

A: When you study the Quantum Hall effect and more precisely the Hall conductivity you learn that the latter is related to certain quantity called the Chern Number $\; \sigma_{xy}= \frac{-e^{2}}{2\pi\hbar} C \; $   which is also related to Berry Phase.
When you consider particles on a lattice in a magnetic field, the resulting Schrodinger equation (under certain conditions) yields to the Harper equation which gives the Hofstadter's spectrum (for rational values of the flux). For this lattice model we can compute the Chern Number which leads to the Hall Conductivity as mentioned above. This is the only link that I see, hope it helps you a little bit.


text:
Q: How do I set the BillingTier in the BigQuery Ruby API? Some of my queries are returning billingTierLimitExceeded error and troubleshooting it lead me to documents telling me to change the configuration for my query job.
I found the configuration.query.maximumBillingTier in the REST API but not for Ruby client library.
How do I set configuration.query.maximumBillingTier using the Ruby SDK?

A: To run the query at a higher pricing tier, pass a new value for maximumBillingTier as part of the query request, the same way as you pass other properties. See reference here.
For example, you could do something like configuration.query.createDisposition or configuration.query.allowLargeResults
It should be noted that the maximumBillingTier is a positive integer that serves as a multiplier of the basic price of $5 per TB. See reference and more detailed info here.
You could also achieve this from within bq command line:
USAGE: bq.py [--global_flags] <command> [--command_flags] [args]

Alter the job_property global flag as needed:

--job_property: Additional key-value pairs to include in the properties field of the job configuration; repeat this option to
  specify a list of values


text:
Q: Unsure solution of ODE with DiracDelta function Could the following solution be treated as reliable?
DSolve[{D[x[t], t] == x[t]^3*DiracDelta[t - 2], x[1] == 1}, x[t], t]

DSolve::bvnul: For some branches of the general solution, the given boundary conditions lead to an empty solution.
{{x[t] -> 1/Sqrt[1 - 2 HeavisideTheta[-2 + t]]}}

I have in mind that the function x[t] takes complex values for $ t>2.$
The general solution is produced with no warning:
DSolve[D[x[t], t] == x[t]^3*DiracDelta[t - 2], x[t], t]

{{x[t] -> -(1/(Sqrt[2] Sqrt[-C1 - HeavisideTheta[-2 + t]]))},                {x[t] -> 1/(Sqrt[2] Sqrt[-C1 - HeavisideTheta[-2 + t]])}}

Addition. Its numeric solution is quite different:
s = NDSolve[{D[x[t], t] == x[t]^3*DiracDelta[t - 2], x[1] == 1},x[t], {t, 1, 3}];
Plot[Evaluate[x[t] /. s], {t, 1, 3}, PlotRange -> All]

Which one of these solutions is more true?

A: Converting DiracDelta[t-2] to Piecewise[{{DiracDelta[0], t == 2}}] helps.
DSolve[{D[x[t], t] == x[t]^3*Piecewise[{{DiracDelta[0], t == 2}}], x[1] == 1}, x[t], t]

(* {{x[t] -> 1}} *)

A: Okay so let me begin.
Mathematica itself does a semi-good job here. It find 2 solutions where one is not applicable for your startingcondition. So it finds the only solution which is
1/Sqrt[1 - 2 HeavisideTheta[-2 + t]]

But this only seems to work for $t<2$ and this is indeed right (we'll see later).
If we apply the Fourier- or Laplactransform we get what we deserve. (nothing we can work with because the $\delta$-function forces us to know $x(2)$)
$$x(t)=\theta(t-2)\cdot x(2)+C$$
Since 2 is a exact discontinuity we cannot use this.
But we can use the good old approach of seperation of variables so we solve it by hand:
$$\frac{\text{d}x(t)}{\text{d}t}=x^3(t)\cdot\delta(t-2)$$
$$\int\frac{1}{x^3(t)}\text{d}x(t)=\int\delta(t-2)\text{d}t$$
$$-\frac{1}{2x^2(t)}=\theta(t-2)+C$$
Now we would like to use $(...)^{-1}$ but this will limit us to the domain of $t>2$ but this is okay, Mathematica solved it already for $t<2$.
We get:
$$x(t)=\pm\sqrt{C-\frac{\theta(t-2)}{2}}$$
with your condition:
$$x(t)=\pm\sqrt{1-\frac{\theta(t-2)}{2}}=const((2<t)\wedge(2>t))$$
So we look into the visualization:
Plot[{1/Sqrt[1-2 HeavisideTheta[-2+t]],Sqrt[1-HeavisideTheta[t-2]/2]},{t,-3,3},PlotRange->{{-3,3},{-5,5}},PlotStyle->{{Red},{Blue,Dashed}},PlotLegends->"Expressions"]

Oh look we have won! Our derived expression suprisingly also describes $t<2$.
Let's confirm that:
equ=x'[t]==x[t]^3*DiracDelta[t-2];
form=Sqrt[1-HeavisideTheta[t-2]/2];
FullSimplify[equ/.{x[t]->form,x'[t]->D[form,t]},{t\[Element]Reals,t<2}]
FullSimplify[equ/.{x[t]->form,x'[t]->D[form,t]},{t\[Element]Reals,t>2}]
FullSimplify[equ/.{x[t]->form,x'[t]->D[form,t]},{t\[Element]Reals,t==2}]

True
True
-(DiracDelta[0]/(2 Sqrt[4-2 HeavisideTheta[0]]))==DiracDelta[0] (1-HeavisideTheta[0]/2)^(3/2)

Year. Exactly what we expected. Our formula desribes it perfectly EXCEPT in $t=2$.

A: Both the Mathematica answers in my question are not correct and should be treated as bugs. Here are arguments. Up to Rudin W. Functional Analysis, McGraw-Hill Book Company, NY,…,Toronto, 1973, Part 2, Ch. 6, Par. 6.15, the multiplication  $ f(t)\delta(t)$ is defined if the function $f(t)$ is infinitely differentiable. This implies the solution $x(t)$ must be continuous at $t=2$. Therefore, the only true solution of the ODE with the initial condition under consideration is a constant function $x(t)=1$. This is not only my personal opinion: I consulted my colleagues about this topic. In particular, one may contact Dr. Yu. Golovatyj at yu_holovaty@franko.lviv.ua (with his kind permission) for more details concerning this complex matter under consideration. Wolfram staff also obtained my report [CASE:3789146].

A: Mathematica's first (analytic) solution is dead on correct.  It satisfies the differential equation and the boundary condition.  When that is the case, you have the solution.
ode = D[x[t], t] == x[t]^3*DiracDelta[t - 2];

DSolve[{ode, x[1] == 1}, x[t], t] // Flatten
(*{x[t] -> 1/Sqrt[1 - 2*HeavisideTheta[t - 2]]}*)

x[t_] = x[t] /. %;

MMa thinks it satisfies the ode.
ode
(*True*)

and the bc
x[1]
(*1*)

Take the derivative by hand as a check.  write x as
(1 - 2 HeavisideTheta[t - 2])^(-1/2)

and the derivative
(-1/2) (1 - 2 HeavisideTheta[t - 2])^(-3/2) (-2 DiracDelta[t - 2])
(*DiracDelta[t - 2]/(1 - 2*HeavisideTheta[t - 2])^(3/2)*)

We used the fact the derivative of the HeavisideTheta is the DiracDelta.
Look at
x[t]^3 DiracDelta[t - 2]
(*DiracDelta[t - 2]/(1 - 2 HeavisideTheta[t - 2])^(3/2)*)

%%==%
(*True*)

Plot both real and imaginary parts of the solution

Looking at the ode, in this case the slope is 0 everywhere except at x = 2 and the solution matches that, but it does jump from pure real for x < 2 to pure imaginary for x > 2.
And no, x will not be continuous across the delta function.  f[t] being continuous does not mean f[t] δ[t] is continuous.
The second (numerical) solution appears to be incorrect for values > 2.  Even though numerical, the solution is evidently:
xnum[t_] = 1 + HeavisideTheta[t - 2]

check
ode /. x -> xnum
(*DiracDelta[t - 2] == DiracDelta[t - 2] (HeavisideTheta[t - 2] + 1)^3*)

Which in general is not true for all t.


text:
Q: git fork a repo content into branch of another repo Say there is a repo A with just a branch master.There is another repo which is fork of repo A.This repo is called B.
B's master branch has certain new commits but is far behind the repo A.
I have to make a new branch in repo B with the contents of master branch of A.
I will have to pull in latest changes from repo A from time to time into this new branch.
I have cloned repo A to my computer, made some changes.Now this has to go to the new branch of B over github.
How do I do this ?
I tried looking at other questions but couldn't grasp it being a git newbie.

A: git branch master-of-a
git fetch upstream master:master-of-a

I would not do it like that if I were you, though. I would work, in B, in branches only. And I would synchronize A's master branch to B's master branch. It's much more traditional, and less confusing, to have the two master branches contain the same thing.
If you submit the changes made in one of B's branches and it ends up being accepted in repo A, then it will be merged to A's master branch, and you can then just synchronize B's master branch with A's, and delete the accepted branch.