text:
Q: Merge two query when using hibernate I am using hibernate to map the data from mysql database.
This is my queries :
long id = (Long) session.createQuery("Select category.id from Project as p where p.id =:projectId").setLong("projectId", projectId).uniqueResult();

activities = session.createQuery("Select name from Activity as a where a.parent.id =:activityId").setLong("activityId", id).list();

It works fine. How can I merge these two queries to one query?

addenda
Activity class:
@Entity
public class Activity implements BaseEntry, Comparable<Activity> {

    private static final long serialVersionUID = 4937176332500551910L;

    @Id
    @GeneratedValue
    private long id;

    @Column(name = "short", unique = true, nullable = false)
    private String key;

    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private Activity parent;

    @OneToMany(targetEntity = Activity.class, mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JsonIgnore
    private Collection<Activity> children;

    @OneToMany(targetEntity = Project.class, mappedBy = "category", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JsonIgnore
    private Collection<Project> projects;

Project class:
@Entity
public class Project implements BaseEntry, Comparable<Project> {

    private static final long serialVersionUID = 1911160043392595450L;

    @Id
    @GeneratedValue
    private long id;

    @Column(name = "short", unique = true, nullable = false)
    private String key;

    @Column(nullable = false)
    private String name;

    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    private Activity category;

I used:
activities = session.createQuery("Select a.name from Activity as a where a.parent.id = (Select p.category.id from Project as p where p.id =:projectId)")
                    .setLong("projectId", projectId).list();

And got an Error:
Apache Tomcat/7.0.23 - Error report HTTP Status 500 - type Exception reportmessage description The server encountered an internal error () that prevented it from fulfilling this request.exception org.codehaus.jackson.map.JsonMappingException: could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->se.softwerk.timelog.model.Activity["parent"]->se.softwerk.timelog.model.Activity_$$_javassist_3["id"])
    org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:218)
    org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:183)
    org.codehaus.jackson.map.ser.std.SerializerBase.wrapAndThrow(SerializerBase.java:140)
    org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:158)
    org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
    org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
    org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
    org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
    org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:122)
    org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:71)
    org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
    org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
    org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
    org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1604)
    org.codehaus.jackson.jaxrs.JacksonJsonProvider.writeTo(JacksonJsonProvider.java:558)
    com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.writeTo(JacksonProviderProxy.java:160)
    com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1437)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:149)
    org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:195)
    org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    se.softwerk.timelog.model.Activity$$_javassist_3.getId(Activity_$$_javassist_3.java)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.codehaus.jackson.map.ser.BeanPropertyWriter.get(BeanPropertyWriter.java:483)
    org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:418)
    org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
    org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
    org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
    org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
    org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112)
    org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:122)
    org.codehaus.jackson.map.ser.std.StdContainerSerializers$IndexedListSerializer.serializeContents(StdContainerSerializers.java:71)
    org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
    org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
    org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
    org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:1604)
    org.codehaus.jackson.jaxrs.JacksonJsonProvider.writeTo(JacksonJsonProvider.java:558)
    com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy.writeTo(JacksonProviderProxy.java:160)
    com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1437)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:708)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available

A: The simpliest way to merge these queries is to use a subquery:
Select a.name from Activity as a where a.parent.id =
    (Select p.category.id from Project as p where p.id =:projectId)


text:
Q: Where does gravity get the energy to pull the ball? I have read many answers here about gravitational potential energy.
Suppose that I am holding a ball 5 meters from the ground and I release it and it falls to the ground. Now i get that it falls because I did work against gravity to lift that ball to the height of 5 meters. But my question is that why did I have to do work against gravity? I mean where does gravity get the energy to pull the ball so that I have to do work to lift it? I hope you get my question.

A: Think of gravity as a sort of spring, trying to pull two objects together: the ball, and the earth. You are standing between them, trying to push them apart. In doing so, you stretch that spring a bit- putting energy into it- and when you let go, the energy you put into the spring is returned as the spring snaps back (that is, as the ball falls down). the farther apart you move them, the more energy you store in that "spring", and the harder it snaps back when you let go (which means the faster the ball is going when it hits the ground). in this sense and in this particular example, there is no energy that the gravitational field has all by itself; energy is stored in and released from the field when we reposition masses within that field.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ Temperature Conversion I know this is very simple.  But I am new to C++.
I need to write a program that converts Centigrade temperatures to Fahrenheit and displays it. The formula provided by my professor is: Fahrenheit = (5/9) * Centigrade + 32.
#include <iostream>

using namespace std;

int main(){

float ctemp;

cout << "What is the temperature out in Centigrade? ";
cin >> ctemp;

float ftemp = (5/9) * ctemp + 32;

cout << "That is " << ftemp << " in Fahrenheit" << endl;

cin.get();
cin.get();
return 0;
}

No matter what temperature i enter for cin ctemp, i get 32.  Something is wrong with my order of operations?  Any help appreciated.  I know this most likely simple, so please dont bag on this question.

A: float ftemp = (5/9) * ctemp + 32;

This line contains a minor bug. You should cast the ints to floats since that is the type you want to get. Something like this should do the trick:
float ftemp = (5.0f/9.0f) * ctemp + 32.0f;

A: Added to Drew Dormann's answer: it's (9.0f/5.0f) for the proper conversion from C to F.


text:
Q: Ordering in VAR models In Enders' 'Applied Econometric Time Series', I repeatedly stumbled upon the notion of the "ordering of a VAR model" and I am not sure I understand the concept right. As far as I understand it, the concept relates to the problem of recovering the true $\epsilon$ of the underlying structural equations.
Looking e.g. at the following VAR in standard form:
$y_t = a_{10} + a_{11}y_{t-1} + a_{12}z_{t-1} + e_{1t}$
$z_t = a_{20} + a_{21}y_{t-1} + a_{22}z_{t-1} + e_{2t}$
The problem is that the two errors are actually composites of the underlying shocks $\epsilon_{yt}$ and $\epsilon_{zt}$ of the structural equations, which we do not know. Here, Enders mentions that "(...) if the correlation coefficient between the $e_{1t}$ and $e_{2t}$ is low, the ordering is not likely to be important", and vice versa.
My problem is that I do not grasp the concept of ordering and how it would affect the identification problem of the disturbances in the structural model. Does ordering refer to the order of the independent variables in the VAR?

A: I will try to answer your second part of the question. If you understand this, I hope you will be able to answer the first part.
Ordering means placing the variables (all) in the decreasing order of exogenity . For example, if y1,y2, and y3 are three variables in the system and if we have from economic theory (or previous empirical findings) that y2 is relatively more exogeneous than y1 and y3 and y1 is relatively more exogeneous than y3 but less exogenous than y2, then we have the order as y2 y1 y3. To put in simple words, y2 (say weather) is more likely to influence y1 (GDP) and y3 (traveling) but the reverse is not true and y1 (GDP) is more likely to influence y3 (traveling) but the reverse is not true.Note that we are talking here of relative exogenity not the absolute one.


text:
Q: Get-EventLog -After query When I run the below command on powershell one by one, then I am getting the expected result. However when I run it as a PS script, I am not getting any output.
$StartDate = Get-Date

Write-EventLog -LogName Application -Source "MsiInstaller" -EventId 11707 -Message "Product: Installation operation completed successfully."

Get-EventLog Application -After "$StartDate" -Source "MsiInstaller"

What is missing?

A: It's the accuracy of the event log, when you run it in a script, it all happens in the same second.
try this:
$StartDate = Get-Date

Write-EventLog -LogName Application -Source "MsiInstaller" -EventId 11707 -Message "Product: Installation operation completed successfully."

start-sleep(1)

Get-EventLog Application -After "$StartDate" -Source "MsiInstaller"


text:
Q: C++ getting error C2440 Hello I'm using Visual Studio c++ 2010
I'm having a problem with this code ( it's taken from C language code ) :
MEMBLOCK* create_memblock (HANDLE hProc,  MEMORY_BASIC_INFORMATION *meminfo)
{

    MEMBLOCK *mb = malloc(sizeof(MEMBLOCK));

    if (mb)
    {
        mb->hProc = hProc;
        mb->addr = meminfo->BaseAddress;
        mb->size = meminfo->RegionSize;
        mb->buffer = malloc(meminfo->RegionSize);
        mb->next = NULL;

    }
    return mb;
}

I'm having these errors :

error C2440: 'initializing' : cannot convert from 'void *' to 'MEMBLOCK *'
error C2440: '=' : cannot convert from 'PVOID' to 'unsigned char *'
error C2440: '=' : cannot convert from 'void *' to 'unsigned char *'

I'm kinda newbie. Can you please provide a converted code for this that actually works with c++.
Thank you

A: Since you're programming in C++, you should not use the old C function malloc. Instead I would recommend that you use the C++ new construct:
MEMBLOCK *mb = new MEMBLOCK;

A: In C++ You may not assign a pointer of type void * to a pointer of some other type. So for example instead of writing
MEMBLOCK *mb = malloc(sizeof(MEMBLOCK));

You have to write
MEMBLOCK *mb = ( MEMBLOCK * )malloc(sizeof(MEMBLOCK));

Also you have to change other statements where there is the same problem. It seems these statements are
mb->addr = ( unsigned char * )meminfo->BaseAddress;
mb->buffer = ( unsigned char * )malloc(meminfo->RegionSize);

It is a good example of that you always should use an explicit casting even in C. That makes the code more safe and clear.

A: malloc() returns void*, and C++ does not automatically cast void* to a different pointer type. So you have to cast the return value:
MEMBLOCK *mb = (MEMBLOCK*) malloc(sizeof(MEMBLOCK));

Try:
MEMBLOCK* create_memblock (HANDLE hProc,  MEMORY_BASIC_INFORMATION *meminfo)
{
    MEMBLOCK *mb = (MEMBLOCK*)malloc(sizeof(MEMBLOCK));

    if (mb)
    {
        mb->hProc = hProc;
        mb->addr = meminfo->BaseAddress;
        mb->size = meminfo->RegionSize;
        mb->buffer = malloc(meminfo->RegionSize);
        mb->next = NULL;

    }
    return mb;
}


text:
Q: store the temporary data in couchbase or redis I have a nodejs project that using couchbase as database.
Just wonder if I store the temporary data in
1.redis
or in
2.couchbase directly.
As I know there is socket delay for couchbase, I think store temporary data in redis while store the permanent data in couchbase is better.
Is there any person has the experience on this?
Your comment welcome

A: I'm a big Redis fan, but in this situation I would use Couchbase only.
Couchbase is rather efficient, and comparable to the performance of memcached when the working set of your data fits in memory. Most of the time, an extra caching layer on top of Couchbase is not useful.
That said, if you really need a caching layer, or simply some storage for temporary data, you can simply create a memcached bucket hosted in the Couchbase cluster. So you would have an "eventually persistent" bucket for your persistent data, and a memcached bucket for the temporary data.
The bucket types are described here:
http://docs.couchbase.com/couchbase-manual-2.5/cb-admin/#data-storage
In that context, adding Redis as a extra storage layer does not really make sense.

A: Couchbase has a managed cache built into it, even for Couchbase buckets. So it already has a caching layer and adding another one on top just sounds superfluous.
I am not sure what you mean by a socket delay in Couchbase. Can you perhaps explain more about that? That is not something I have ever seen before and sticks out as suspect to me. I would try and troubleshoot this and figure out what that is before looking to add redis to the mix and have yet another layer to manage and code against. Without know more about the socket delay, it is difficult to make more recommendations.

A: It's an old question, but I'll have my take at it as well, if nothing else then for the people coming across it via google, just as I did.
I agree with he accepted answer, in that CouchBase has the most recently used Documents in RAM. In that aspect, it does the same as Redis. The advantage of CouchBase is of course that the data can reliably spill over the RAM limit, and the server disk limit, automatically, by adding more nodes.
However, I have a project where I am considering using Redis along side CouchBase. It's basically thought as a caching server, but for the "calculated" items. Such as html-snippets or other things. CouchBase is a fantastic document store, but making lists and other structures, doesn't come that easy, especially not without a lot of views. So I'm thinking to use Redis as a temporary datastore for the ad-hoc data manipulation needed, and CouchBase as the main datastore.


text:
Q: I need to create a custom print invoice.It should generate Xlsx I need to create a custom print invoice.So i created a file Export.php in module_sales->controller->adminhtml->invoice->Export.php. Excel is generating but how to put the data into different cells where ever i want.Now i am getting the data in top column only (like A1,B1,C1,D1)Please help.
namespace Magento\Sales\Controller\Adminhtml\Invoice;

use Magento\Backend\Block\Widget\Grid\ExportInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use \Magento\Sales\Model\SalesInvoiceFactory;
use \Magento\Sales\Model\SalesOrderFactory;
use \Magento\Sales\Model\SalesInvoiceGridFactory;
use \Magento\Backend\App\Action;

class Export extends Action {

    protected $_salesinvoiceFactory;
    protected $_salesorderFactory;
    protected $_salesinvoicegridFactory;

    public function __construct(
    \Magento\Backend\App\Action\Context $context, \Magento\Sales\Model\SalesInvoiceFactory $SalesInvoiceFactory, \Magento\Sales\Model\SalesOrderFactory $SalesOrderFactory, \Magento\Sales\Model\SalesInvoiceGridFactory $SalesInvoiceGridFactory
    ) {
        parent::__construct($context);

        $this->_salesinvoiceFactory = $SalesInvoiceFactory;
        $this->_salesorderFactory = $SalesOrderFactory;
        $this->_salesinvoicegridFactory = $SalesInvoiceGridFactory;
    }

    public function execute() {
        $rows = array();
        $invoiceId = $this->getRequest()->getParam('invoice_id');
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $invoicemodel = $this->_salesinvoiceFactory->create()->getCollection()->addFieldToFilter('entity_id', $invoiceId);
        foreach ($invoicemodel as $invoice) {

            $invoiceno = $invoice['increment_id'];
        }

        $ordermodel = $this->_salesorderFactory->create()->getCollection()->addFieldToFilter('entity_id', $invoiceId);

        foreach ($ordermodel as $order) {
            $invoiceno = $order['invoice_number'];

            $issueofinvoice = $order['created_at'];
            array_push($rows, $issueofinvoice);
            $timeofinvoice = $order['created_at'];
            array_push($rows, $timeofinvoice);
            $dispatchmethod = $order['dispatch_method'];
            array_push($rows, $dispatchmethod);
            $grandtotal = $order['grand_total'];
            array_push($rows, $grandtotal);
        }

        $gridmodel = $this->_salesinvoicegridFactory->create()->getCollection()->addFieldToFilter('entity_id', $invoiceId);
        foreach ($gridmodel as $grid) {

            $nameandaddress = $grid['billing_address'];
            array_push($rows, $nameandaddress);
        }

        header('Content-Type: text/xls; charset=utf-8');
        header('Content-Disposition: attachment; filename=klauz.xls');

        // create a file pointer connected to the output stream
        $output = fopen('php://output', 'w');
        fputcsv($output, $rows);
    }
}


text:
Q: PHP Login Script Not working in IE on a specific computer I have a perplexing problem. I am building a login system for a website, and on one user's computer only in IE 9, the sign in script fails. I have checked using Fiddler that the proper POST data is being sent. I would work with that computer more, but I don't have that oppurtunity.
I know the correct login details are being sent; the correct errors are sent out by the PHP script when incorrect login details are sent, and the login fails for all accounts. The sign in system uses PHP sessions. I am completely baffled by this, and have never seen anything like it.
The site located at gatewaymma.com I have setup a test account that does not have any special access:
username: testAcc
pwd: test22
Again this only occurs in IE 9, no other browser, and only on the one machine (win 7), so I have not been able replicate it, and as far as I can tell, the correct $_POST data is recieved.
If someone could replicate this or give a possible area that they have seen that may be causing this it would be much appreciated.
I had thought that cookie security might be causing the problem, but after adding a check for cookies, no errors were produced.
Here is a portion of the login script:
            if(/* the password was correct, there is def no problem here*/){

                session_regenerate_id(true);

                $_SESSION['logged'] = true;
                /*set other session vars*/

                DB::query("UPDATE fa_logged_ips SET tries = 0, next_try = 0 WHERE ip = %s LIMIT 1", $_SESSION['ip']);

                DB::query("UPDATE fa_users SET last_login = $_SESSION[last_activity] WHERE ID = %s LIMIT 1", $_SESSION['uid']);
            }
        }
        //If the login was not successful (this error message is not fired, so I don't believe the session is being lost somewhere after this point
        if($_SESSION['logged'] !== TRUE){
            $fArray['loginErr'] = "The username and password combination you entered is not valid.";
            check_ip();
        }

Notice that the last section of the script checks that the user is logged in, meaning that the session was successfully created, but that it is somehow being lost when the user is redirected to the home page.
EDIT: One more thing, this login system is derived from one that I launched on another section of the site (on a subdomain) that works fine on the same computer, and has so for the last 5 months.
EDIT:
if(!isset($_SESSION['logged'])){

formatSession();
setcookie('cookieTest', '1', time()+3600*24*30); //set a cookie that will be checked for later
$ip = $_SERVER['REMOTE_ADDR'];  //Get the user's ip address

//Check if the IP is logged in the system
$logged_ip = DB::queryFirstRow("SELECT * FROM fa_logged_ips WHERE ip = %s", $ip);

//if so
if(!empty($logged_ip)){

    //if ip has too many failed logins
    if ($logged_ip["tries"] < $login_attempt_limit) {
        $_SESSION['next_try'] = $logged_ip["next_try"]; //store when their lockout ends
    }
    else {
        $_SESSION['next_try'] = 0; //otherwise they may try to log in at their discretion
    }

    $_SESSION['tries'] = intval($logged_ip["tries"]); //store how many login tries the ip has
}
}

The session format funciton

 function formatSession(){
global $sysEnable;

$_SESSION['logged'] = false;        //The user is not logged in
$_SESSION['sysEnable'] = $sysEnable;//Store wether or not the system is accessible
}

EDIT
I strongly feel this is related to some kind of security setting in IE, because I have only seen it occur on the one computer, and have not been able to replicate it on any other machine. In addition I was able to produce a similar effect by turning up the cookie security, but as stated before, the cookie check was successful on the computer
EDIT 9/1
I think that IE may be failing to maintain the session; IE isn't saving the session id. Again I haven't been able replicate this behavior, so can't be 100% positive until I can work with that computer.

A: Oh, I have stumbled upon this recently! I couldn't believe my eyes that it was happening - because the post data was passed correctly! I have built precise login script and only in IE I had kind of the same problem!
What I had was that when you hit enter after login and password is entered in the fields, and when in all other browsers login happened just fine, in IE I just had the page kind of refreshed. BUT if I clicked signin button under the password field than everything went just fine!
There was no logical explanation to that and now I must say it's just IE unnoticed bug!
What I did is detected the users browser and if it's IE I canceled enter key and forced user to click signin button.
Here is my code to solve this crazy problem:
function browserIE(){
 if($.browser.msie){
     return true;
 }
 return false;
}

$(document).keypress(function(event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13' && browserIE()){
            event.preventDefault();
            event.stopPropagation();
        }
});

That was the only way to force IE user to click singin button to make proper signin because as I said before hitting enter being on fields just failed in my case too!
Edited:
Another Solution 1
The other solution could be but it didn't work in my case is to add additional hidden input field:
<!-- Fix for Internet Explorer bug (One text input and submit, disables submit on pressing "Enter") -->
  <div style="display:none">
    <input type="text" name="hiddenText"/>
  </div>

Another Solution 2
It appears that Internet Explorer scans the page at load time and figures out which submit buttons are visible, then attaches the enter-to-submit functionality to those forms.
To fix this scenario, you can use the following jQuery code:
$(document).ready(function() {
   $('input').keydown(function(e){
     if (e.keyCode == 13) {
        $(this).parents('form').submit();
        return false;
     }
   });
});

The return false is rather important in Internet Explorer, because it prevents that beep that you might hear if you hit return. The beep is saying "you can't hit enter here!", but return false cancels the key press and therefore the browser won't warn.
Read more about this and what people comment: Submit a Form in IE with Enter

Also Recommend reading: Button versus Input[type="submit"] in Internet Explorer and beyond


text:
Q: How to make a sort from a fits table python I own a table in fits format. I am using the astropy.io.fits library in Python.
I'm reading the file and I would like to print my array with conditions.
For exemple, I want to print all rows where the column "CHI" > value
#!/usr/bin/python
# coding: utf-8

from astropy.io import fits
import numpy as np

        ##################################
        # Fichier contenant le champ 169 #
        ##################################

file = '/astromaster/home/xxxx/Bureau/Stage/Champs/Field_169/Field169_combined_final_roughcal.fits'

field169 = fits.open(file)          # Ouverture du fichier à l'aide d'astropy

tbdata = field169[1].data           # Lecture des données fits

#print tbdata['CHI']
#print tbdata[tbdata['CHI'] < 1.0]

for row in tbdata :
    if tbdata['CHI'] < 1.0 :
        print row

And, how is it possible to add one or two more conditions in the new printed array ?
Thanks !

A: Astropy's fits interface functionality is best for working with image data, rather than tabular.
The Astropy tables library will be helpful to you. Using t = astropy.table.Table.read(fname) (aside: file is reserved in Python, so you should avoid using it as a variable name) will allow you to read in a FITS table as an Astropy table, which works a lot like a numpy record array.
You can then filter based on column values, e.g.: print t[t['CHI'] < 1.] (If you aren't familiar with numpy, you might do some more reading on masking and element selection, since this is essentially identical to numpy's functionality--if you aren't familiar, I think of reading the above statement "t such that t['CHI'] less than 1.")
You can combine conditions, as well: print t[(t['A'] < 1) & (t['B'] > 2)]. And when you're done, you can write out using t.write(fname2)

A: Well first of all and that's unrelated to your question: If you open any file you should either close it again afterwards or use it as context manager. I usually prefer the context manager:
filename = '...'
with fits.open(filename) as field169:
    tbdata = field169[1].data
... continue without indentation after you have finished with the file.

Afterwards you have a record numpy array, you can use it but since structured numpy arrays are more tables a true table program like pandas or astropy.table might be very convenient.
But if you really want to confine yourself to the table you get from fits.open (you shouldn't though because the recarray and structured array behave a bit different than normal table operations) you can use what is given in the documentation:
mask = tbdata['CHI'] < 1.0
tbdata[mask]

or if you want to have multiple conditions just add them with the & (if both should apply) or | (if at least one of the conditions should apply):
mask = tbdata['CHI'] < 1.0 & tbdata['CHI'] > 0.5
tbdata[mask]

mask = tbdata['CHI'] < 1.0 | tbdata['OTHER'] > 0.5
tbdata[mask]

I hope this helps you. But probably you are better off using @DathosPachy answer with tables.


text:
Q: Why does intramolecular hydrogen bonding cause molecules to separate? Today I learned about intramolecular hydrogen bonding, which occurs in molecules such as ortho-nitro-phenol.
What I was told is that, in case of intramolecular bonding, the molecules separate from each other, opposite of what happens during intermolecular hydrogen bonding. I don't understand why this is. Why would attraction within a molecule cause separation of the molecules?
There is obviously some intermolecular hydrogen bonding present in this case, but I understand that this might be negligible. Still, why should the molecules spread away from each other?

A: Hydrogen bonding arises when a chemical bond is polarised to one end of it has a slight positive charge and the other has a slight negative charge. In the case of o-nitrophenol it's mainly the OH bond that is polarised - the H atom has a slight positive charge and the O atom has a slight negative charge. The charge separation means the OH bond has an electric dipole.
Electric dipoles interact with each other, so the dipole on one o-nitrophenol molecule can attract the dipole on a neighbouring o-nitrophenol molecule. This creates the attractive force between the molecules known as a hydrogen bond. There is an extended description of this on this web site.
Just to complicate matters o-nitrophenol can also exhibit intra-molecular hydrogen bonding. This is because the OH and NO$_2$ groups are next door to each other, and the H on the OH group can interact with the O on the NO$_2$ group.
Response to comment:
Intramolecular hydrogen bonding will not cause molecules to repel each other, but it will reduce the attractive interactions between molecules. This is simply because in o-nitrophenol the OH group forms a hydrogen bond with the adjacent nitro group and that reduces its ability to form hydrogen bonds with other molecules. In p-nitrophenol the OH and nitro groups are on opposite sides of the molecule so there can't be any intramolecular hydrogen bonding and therefore the intermolecular hydrogen bonding is stronger. So o-nitrophenol has a melting point of 44ºC while p-nitro[henol has a melting point of 113ºC.
So intramolecular hydrogen bonding won't cause the molecules to separate, but it will make them bind together less strongly.


text:
Q: A code or some code? When talking about the source code of a program, my Computer Science teacher sometimes refers to single pieces of code as 'a code'. For example:

For today's task, you need to write a code which outputs "Hello World".

I feel that this is terribly wrong as I would say 'some code' or 'a piece of code'. E.g.:

For today's task, you need to write some code which outputs "Hello World".

Who is right, me, my teacher or both of us?

A: "Code" as usually used in the field of IT refers to source code of computer programs. My own intuition is that this is clearly uncountable, so you can speak of "some code" but not "a code". You can also speak of "the source code of a program", which means "the [representation of the program] as source code". However, "code" alone remains uncountable. You could speak of "a code" when used in a different meaning, such as: "he gave me a code with which I could open the locked door" (here "code" is a "hard-to-guess combination of letters/digits").
While Merriam Webster doesn't state anything about the countability of "code" used as shorthand for "source code", Wiktionary gives one of the meanings as synonymous with source code, machine code or bytecode, and these are described as uncountable.
Bytecode is described as countable and uncountable, and while it is not explicitly stated, it seems logical for bytecode (the byte representing a single instruction) to be countable and bytecode (a series of instructions represented as bytecodes) to be uncountable. I wouldn't object to using "a bytecode" in context such as: "this function consistes of a single bytecode", but "bytecode" in the latter meaning would behave like "source code" or "machine code" and be uncountable.

A: In American or British English, using "code" as a countable noun to refer to source code is wrong.
For an American source, see Merriam Webster's entry for the word "code", which gives the following definition...

instructions for a computer (as within a piece of software)

... with the following example usage, as a mass noun:

writing code for a new app

For a British source, see the entry in Collins which says:

uncountable noun
  Computer code is a system or language for expressing information and instructions in a form which can be understood by a computer.

However, in Indian English, "code" is typically used as a countable noun. I have observed this usage from reading posts by Indians on Stack Overflow, from teaching in India, from being offered programming jobs by Indian companies, and from working with Indian colleagues. Indians will talk about writing "codes" (incorrect in British or American English) or even writing "a code", as in the example in the question here. For an example in the wild, see this page on an outsourcing website called Outsource2india which uses the word "codes" in this way five times.
This is one of the many ways that Indian English differs from the English that Americans or Brits like me are used to. Of course, whether Indian English is proper English in the first place is subjective; attitudes vary, among both Indians and non-Indians, on the question of whether Indian English is a legitimate dialect in its own right like British and American English are, or merely a collection of erroneous (and perhaps even mildly embarrassing) deviations from correct English, as spoken by the Queen. As such, I leave the judgement of whether this usage is "wrong" as a matter for you to decide according to your own beliefs.

A: "code" is short for "source code"
Your version is correct. The teacher is wrong.
In this particular usage, however, using "source code" is not really ideal at all. The right expression is,

For today's task, you need to write a program which outputs "Hello
  World".

You write programs, you compile source code. In proper usage the term "source code" should only be used in the context of compiling. In other words, you have "source code" which compiles into "object code" which is linked into an "executable". Talking about "writing" source code is not really a correct usage, even though many laypersons who are trying to sound technical say it.


text:
Q: Как собрать все файлы js в один на gulp? Хочу собрать мои скрипты и подключаемые библиотеки в один js файл с помощью gulp. Подскажите

A: Используй gulp-concat (https://www.npmjs.com/package/gulp-concat)
Пример использования:
var concat = require('gulp-concat');

gulp.task('scripts', function() {
  return gulp.src('./lib/*.js') // путь к папке со скриптами
   .pipe(concat('all.js')) // в какой файл объединить
   .pipe(gulp.dest('./dist/'));
});

По ссылке, которую указал, есть больше примеров.


text:
Q: Gnuplot: logarithmic axes and dgrid3d not working together I have a sparse grid of data that I would like to plot with a log scale in the x and y axes, with colours and contours defining the z axis.
Using logscale xy results in a very different looking plot to when I plot a linear plot of the log of each axis.

I want the nice logarithmic axes and positioning of the contour legend of the first plot, with the nice central portion and colour scale of the second plot.
My current script is
set dgrid3d 50,50 splines
set pm3d
set pm3d map

set cntrparam levels auto
set contour surface

#set logscale xy
#splot "test_data.dat" using 1:2:3 with l nosurf lw 3
splot "test_data.dat" using (log10($1)):(log10($2)):3 with lines nosurf lw 3

where I change the comments to change which plots I make.
What am I doing wrong?
All suggestions will be gladly accepted.
edit: Through some more research, I think that the data is being gridded by dgrid3d in linear space, and then plotted in log space by logscale xy. I want the data to be gridded and plotted in log space.
Is there a gnuplot-only solution?

A: Two-fold solution. 1) the difference in the look of the plots was due to a bug in 5.2.2. Upgrade to 5.2.3 fixed it.
2) Solved the gridding issue by plotting the log of the data on linear axes and then bodging the axes to look logarithmic.
The plot needs to be improved by making the minor tics smaller than the major.

set pm3d
set pm3d map
set cntrparam levels auto
set contour surface

#set xrange [2:6] #setting this makes the image finish at the y2 tics, without changing the xtics
set xtics 2,1,6
unset xtics

# "major" tics
set xtics ("100" 2, "1000" 3, "10000" 4, "100000" 5, "1e6" 6)
# "minor" ticks
set for [i=2:6:1] xtics add ("" log10(2*10**i),"" log10(3*10**i),"" log10(4*10**i),"" log10(5*10**i), "" log10(6*10**i),"" log10(7*10**i),"" log10(8*10**i),"" log10(9*10**i))

set ytics -2,1,-1
unset ytics
set ytics ("0.01" -2, "0.1" -1)
set for [i=-3:0:1] ytics add ("" log10(2*10**i),"" log10(3*10**i),"" log10(4*10**i),"" log10(5*10**i), "" log10(6*10**i),"" log10(7*10**i),"" log10(8*10**i),"" log10(9*10**i))

splot "test_data.dat" using (log10($1)):(log10($2)):3


text:
Q: How to work with BlackList? I am new to asterisk. i am working under ubuntu 9.10. I use asterisk 1.8. I want to create a conference room.
in meetme.conf
conf => 1234,1234

in extensions.conf
exten =>1234,1,MeetMe(1234)

Is the pin number a secure one? How to create a secure pin number (do i have to use numbers and characters too)? Secondly how to create a blacklist? If a person tries to register 3 times..and the passed is incorrect how can I put him/her on the blacklist?

A: Passwords are numbers, however,  '1234' is not a good password choice.
Asterisk's dialplan is extremely dynamic; there is no single definition of 'Blacklist'.  However, try something like this:
== meetme.conf
conf => 1234

== extensions.conf
exten => 1234,1,GotoIf(${BLACKLIST()}?hangup)
exten => 1234,n(loop),Set(TRIES=$[0${TRIES} + 1]);
exten => 1234,n,GotoIf($["$TRIES" = "3"]?blacklist)
exten => 1234,n,Read(PIN,enter-conf-pin-number,4)
exten => 1234,n,GotoIf($["$PIN" = "9999"]?meetme)
exten => 1234,n,Goto(loop)
exten => 1234,n(meetme),MeetMe(1234)
exten => 1234,n,Hangup
exten => 1234,n(blacklist),Set(CALLERID(num)=${FILTER(0-9\-,${CALLERID(num):-10})})
exten => 1234,n,Set(DB(blacklist/${CALLERID(num)})="Some Comment")
exten => 1234,n(hangup),Hangup

there are all sorts of other ways.  this particular setup will only keep the caller from trying to authenticate into that one conference room.  if you'd rather ban him from ever touching your automated attendant, you can move the first line to your incoming context.
If you're already sanitizing your callerid (you should be) you can remove the FILTER line and bump the (blacklist) to the next line.


text:
Q: how to left join a table with a query? I have three tables
usertbl
id | fname | lname
---|-------|------
1  |  ali  | rahimi
2  | reza  | miri

citytbl
id | cityname
---|-------
1  |  ahvaz
2  | shiraz
3  | mashad

TBl3
Cityid| userid| Value
------|-------|------
1     |  1    | 10
2     |  1    | 30

Result that i want is:
Cityid| userid| Value
------|-------|------
1     |  1    | 10
2     |  1    | 30
3     |  1    | 0
1     |  2    | 0
2     |  2    | 0
3     |  2    | 0

I try this:
SELECT *
FROM usertbl, citytbl
LEFT OUTER JOIN tbl3 ON
    (tbl3.cityid=citytbl.id AND
     tb.l3.userid=usertbl.id)

but it did not worked.

A: My approach would be:
If you really want to have every user with every city, you can use a CROSS JOIN.
As you finally want to add the value use the LEFT JOIN.
To get a 0 instead of NULL (if there is no match in the Tbl3), use the COALESCE.
         SELECT c.id as Cityid
               ,u.id as userID
               ,COALESCE(t3.value,0) as value
           FROM usertbl u
     CROSS JOIN citytbl c
LEFT OUTER JOIN TBl3 t3
             ON t3.userid = u.id
            AND t3.cityid = c.id

I've also added a rextester to reproduce it herer: http://rextester.com/QBRSS10238
Attention!
I do not recommend you to use a CROSS JOIN here. Do you really need every user with every city? Even if they don't have a record in TBl3? You will have a lot of records with "value = 0" and the amount of records returned will increase massively if there are a few more users and cities.
Just imagine you have a table with 1500 users and 80 cities. Your CROSS JOIN will return 120.000 records. Even if just a very few have a match in table Tbl3.
If you just need users and cities, which have an entry in Tbl3. Start the select with Tbl3 and just join the tables user and cities like:
SELECT c.id as Cityid
      ,u.id as userId
      ,T3.value
  FROM TBl3 T3
 INNER JOIN usertbl u
    ON T3.userid = u.id
 INNER JOIN citytbl c
    ON T3.Cityid = c.id


text:
Q: Override Wagtail Admin login with AllAuth I am trying to override the Django Wagtail admin login with my AllAuth Login page.
I've tried adding the following line from the Documentation to my settings.py

WAGTAIL_FRONTEND_LOGIN_URL = '/accounts/login/'
  WAGTAILADMIN_USER_LOGIN_FORM = 'admin.site.login'

But I receive this error when I try to visit /admin url that renders the wagtail admin login view.
Exception Type: ImproperlyConfigured
Exception Value:
WAGTAILADMIN_USER_LOGIN_FORM refers to a form 'admin.site.login' that is not available


text:
Q: How to make a call for 10 digit number in FreeSwitch? FreeSwitch has 20 sample phone number between 1000-1019. It is okay to make a call with these numbers.
I've put 5168880000 number in directory folder. It is okay to call 1000 phone number from 5168880000 phone number. However, calling from 5168880000 to 1000 number has failed. All of variation for 5168880000 directory is same as 1000 number.
I believe that I need to change dialplan config file.. Is there way to make a call for 10 digit number? Thank you.

A: Jake, you really need to read the freeswitch book. It will take you a couple of days and will answer most of your questions.

A: In the default FreeSWITCH configuration ("vanilla"), dialplan/default.xml contains <extension name="Local_Extension"> which matches 4-digit numbers starting with 10. That's why your 516... numbers do not match.
I would advise to start with the minimal configuration (https://github.com/xlab1/freeswitch_conf_minimal) and build your dialplan as required. The default configuration has too much stuff which needs to be removed.

A: 2 simple options come to mind:

*

*add the configuration to an existing configuration
for instance, find "Local_Extension" in the default dialplan, and change the condition to:

<condition field="destination_number" expression="^(10[01][0-9]**|\d{10}**)$">

*

*add another configuration
in the default configuration, add the following

<extension name="10digits">
  <condition field="destination_number" expression="^(\d{10})$">
    <action application="set" data="dialed_extension=$1"/>
    <action application="bridge" data="user/${dialed_extension}@${domain_name}"/>
  </condition>
</extension>


text:
Q: NtCurrentTeb() on C++ Rad Studio 10 I've made this declaration in my include file:
 __inline struct _PEB * NtCurrentPeb() { return NtCurrentTeb()->ProcessEnvironmentBlock; }

Leading the file also includes these values:
  #include <stdio.h>
  #include <windows.h>
  #include <WinNT.h>
  #pragma comment(lib, "ntdll.lib")

But the compiler (Rad Studio XE 10) gives me this error:

Use of undeclared identifier 'NtCurrentTeb'

Where am I wrong? What is missing?


text:
Q: TextMate 2: can the file browser [project drawer] be put on the right side? in TextMate 2, can the file browser be put on the right side?
the old textmate solution does not seem to work.

A: Use the following command in Terminal:
defaults write com.macromates.TextMate.preview fileBrowserPlacement right

A: *

*Close the project drawer (view->hide project drawer)

*Move the application to the left of screen leaving little or no gap on the left but plenty on the right

*Open the project drawer - it should open on the right


text:
Q: ReactJS: render with ReactJSX syntax on javascript file? I want to use JSX syntax on render, but it is not recognized if I try to use it on .js file.
It does render using object notation though.
Using this:
html:
<!DOCTYPE html>

    <meta charset="UTF-8">

Now react-demo.js file:
(function(){
"use strict";
/* global React ReactDOM*/
const render = () => {
const jsContainer = document.getElementById("js");
jsContainer.innerHTML = `

    Hello JS
    <input>

${new Date()}

`;
const reactContainer = document.getElementById("react");
ReactDOM.render(
    React.createElement(
        "div",
        { className: "demo" },
        "Hello React",
        React.createElement('input'),
        React.createElement('p', null, new Date().toString())
    ),
    reactContainer
  );
  ReactDOM.render(
Hello Here
, document.getElementById('react2'))
}
setInterval(render, 1000)

})();

When I run it, I get this error:
Uncaught SyntaxError: Unexpected token <
And it points to this line: ReactDOM.render(
Hello Here
, document.getElementById('react2'))
Now I read I need to change script type to text/babel. But doing that gives me this error:
XMLHttpRequest cannot load file:///home/oerp/js-programs/react-demo/react-demo.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

But I'm merely loading local file. Why does it work that way with babel type?
Though I was able to use JSX syntax directly on html like:

But I do want to put rendering on js file, not on html file.

A: So the issue with babel type is that it can't be used locally using file type. It has to be from allowed types only, like http, https, data etc.
So the simplest approach would be to create local http server (to serve related html and js files). Like:
python -m SimpleHTTPServer
And then this works:

Then I can use text/babel using specified file instead of just using it directly on html.
P.S. How to launch html using Chrome at "--allow-file-access-from-files" mode? answer by orszaczky helped me solve this.

A: Use type babel for react script.
 - native javascript

 - it`s react js


text:
Q: Why is the same loop used twice & Why is the value of of a array decreased? I am following the offical java tutorial and i want to know why the for loop is repeated in both classes.
public class Deck {

    public static int numSuits = 4;
    public static int numRanks = 13;
    public static int numCards = numSuits * numRanks;

    private Card[][] cards;

    public Deck() {
        cards = new Card[numSuits][numRanks];
        for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
            for (int rank = Card.ACE; rank <= Card.KING; rank++) {
                //Don't understand why rank is decreased by one
                cards[suit-1][rank-1] = new Card(rank, suit);
            }
        }
    }

    public Card getCard(int suit, int rank) {
        return cards[suit-1][rank-1];
    }
}

      public class DisplayDeck {
    public static void main(String[] args) {
        Deck deck = new Deck();
        for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
            for (int rank = Card.ACE; rank <= Card.KING; rank++) {
                Card card = deck.getCard(suit, rank);
                System.out.format("%s of %s%n",
                    card.rankToString(card.getRank()),
                    card.suitToString(card.getSuit()));
            }
        }
    }
}

also the code for the cards class can be found here also can anyone tell me why the array values in the deck constructor is decreased by one?, since the intial value is one wouldn't this just cause and error?. thanks.

A: The loops are repeated twice because their bodies are different:

*

*The loop inside the Deck() constructor initializes the cards

*The loop inside main prints the cards.

The two methods do it in the same order, that's why the headers of the loops are identical.
The numbers are adjusted by one because in Java (as well as in C, C++, C#, and many other languages) array indexes are numbered from zero, rather than being numbered from one. The constants in the cards program, on the other hand, are one-based, so you must subtract one from them to get the numbers aligned with the way the arrays are indexed.

A: I don't know what pair of loops you're talking about, but i'll address what I can.
The first loop group
    for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
        for (int rank = Card.ACE; rank <= Card.KING; rank++) {
            //Don't understand why rank is decreased by one
            cards[suit-1][rank-1] = new Card(rank, suit);
        }
    }

builds the deck.  the outer loop iterates over the suits, and the inner loop iterates over values.  the result is the full 52 card deck.  13 values per suit.

the second loop group:
    for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++) {
        for (int rank = Card.ACE; rank <= Card.KING; rank++) {
            Card card = deck.getCard(suit, rank);
            System.out.format("%s of %s%n",
                card.rankToString(card.getRank()),
                card.suitToString(card.getSuit()));
        }
    }

iterates in the same manner as the first.  suits in the outer-loop and values in the inner-loop. But this time, it's not actually building the deck, rather, it's printing the results of what's in the deck.

A: in both cases, the reason is because you have a 2 dimensional array. the outer array is the suits, the inner array is the ranks. using arrays, you have to use different counting variables to go through them. for example, you want the outer loop to run 4 times, but you want the inner loop to run 13 times.


text:
Q: AppleScript clipboard race condition I want to use AppleScript to paste some text into the current application while preserving the preexisting contents of the clipboard.
on writeFromClipboard(someText)
    set oldClipboard to the clipboard
    log oldClipboard
    set the clipboard to someText
    log (the clipboard)
    tell application "System Events"
        keystroke "v" using {command down}
    end tell
    log (the clipboard)
    set the clipboard to oldClipboard
end writeFromClipboard

writeFromClipboard("new text")

When I have old text on the clipboard when this script is run, I get the following event log and old text is pasted. I can only conclude that the text is actually pasted after the clipboard contents have been changed back.
tell application "AppleScript Editor"
    the clipboard
        --> "old text"
end tell
(*old text*)
tell application "AppleScript Editor"
    set the clipboard to "new text"
    the clipboard
        --> "new text"
end tell
(*new text*)
tell application "System Events"
    keystroke "v" using {command down}
end tell
tell application "AppleScript Editor"
    the clipboard
        --> "new text"
end tell
(*new text*)
tell application "AppleScript Editor"
    set the clipboard to "old text"
end tell

Short of adding a pause after the paste keystroke, is there a way to get this working?

A: The Standard Additions Dictionary says:
set the clipboard to v : Place data on an application's clipboard. Use inside a 'tell' block and activate the application first. (Link to AppleScript Wiki)
Try it this way:
on writeFromClipboard(someText)
    tell application "TextEdit"
        activate
        set oldClipboard to the clipboard
        set the clipboard to someText
        --delay 0.2
        tell application "System Events" to tell process "TextEdit"
            keystroke "v" using {command down}
        end tell
        set the clipboard to oldClipboard
    end tell
end writeFromClipboard

writeFromClipboard("new text")

For safety, I would still add a little delay.


text:
Q: System.DllNotFoundExeption has been thrown (Xamarin,MonoGame,and XNA) I installed XNA 4.0, the latest version of Xamarin, and the latest version of MonoGame. I loaded up a brand new Open GL solution and got this error.
System.DllNotFoundException: Unable to load DLL 'openal32.dll': The specified module
could not be found. (Exception from HRESULT: 0x8007007E) ---> System.Exception:

at at OpenTK.Audio.OpenAL.Alc.OpenDevice(String devicename)

at at Microsoft.Xna.Framework.Audio.OpenALSoundController..ctor()

at at Microsoft.Xna.Framework.Audio.OpenALSoundController.get_GetInstance()

at at Microsoft.Xna.Framework.OpenTKGamePlatform..ctor(Game game)

at at Microsoft.Xna.Framework.GamePlatform.Create(Game game)

at at Microsoft.Xna.Framework.Game..ctor()

at dgsdgsdgdsg.Game1..ctor() in
c:\Users\Josh\Documents\Projects\dgsdgsdgdsg\dgsdgsdgdsg\Game1.cs:0

at dgsdgsdgdsg.Program.Main() in
c:\Users\Josh\Documents\Projects\dgsdgsdgdsg\dgsdgsdgdsg\Program.cs:0

A: Try installing OpenAL...
The link points to the the installer for OpenAL.

A: Upgrade your video drivers.
MonoGame is pretty picky about what OpenGL version you have installed. I don't know exact version required (it has changed over time) but refer to this discussion for more information.
You can also download the OpenGL caps viewer to determine which version you are currently running.


text:
Q: Opinions and facts on multiplexer select in implemented VHDL code. Ok, So in my digital design class last year we were told repeatedly how the compiler would realize or produce the same structure when given many different codes that did the same thing structurally. Now in my computer organization class this year I have came upon a situation and would like to gauge others opinion and knowledge.
As I understand a multiplexer to work you get x number of inputs and depending on a selector signal/s you output one of those inputs. I under stand that for say 8 inputs you want N number of selector bits so that 2^N=8.
My big question is, is there any difference or advantage of having the selector be say
entity myMultiplexer is
    Port ( S0 : in  STD_LOGIC_vector(0 to 1);

           Sum : in  STD_LOGIC;

           myAnd : in  STD_LOGIC;
           myOr : in  STD_LOGIC;
           OpOut : out  STD_LOGIC);

end myMultiplexer;

Where S0 is the selector as opposed to haveing the selector be like this
entity myMultiplexer is
    Port (
       S0 : in  STD_LOGIC;
       S1 : in STD_LOGIC;

       Sum : in  STD_LOGIC;

       myAnd : in  STD_LOGIC;
       myOr : in  STD_LOGIC;
       OpOut : out  STD_LOGIC);

end myMultiplexer;
So in the first one it would seem to me that the signal or electrical current would be coming in on the same wire where as with the second one you could have the source come from 2 separate things. Maybe also, i was just thinking; You could take 2 separate inputs and construct a signal telling one that it is vector bit 1 and the other it is vector bit 0 and then send that to the mux S0.
Anyones perspective on this would be appreciated.

A: No difference.  The first one defines a single signal with two bits in it.  In the terms of your question, this is still two "wires".
You first style is more conventional (as I see it) - as it is easier to extend to more bits if required.


text:
Q: Controlling a ring oscillator with a signal So for example if you have a very simple oscillator such as:
How could I control this so that the oscillator is only in operation when a signal (x) is high. And not in operation when it is low?

A: I assume you've had enough time to think about this (and I also don't have enough karma to make comments) so I'll give you one possible solution, though it's definitely not the only one. Replace the 3rd inverter with a NAND gate, where one of the inputs is x and the other input is the output from the second inverter. When x is 0, the output is forced to 1 and the whole thing stops oscillating. When x is 1, the output of the NAND gate is the opposite of the output of the second oscillator.
You can see the truth table for a NAND gate here in case you don't get it. http://hyperphysics.phy-astr.gsu.edu/hbase/Electronic/nand.html


text:
Q: Are assemblies compiled with MsBuild 4.0 compatible with computers which have only .NET 3.5? In a project which target framework is 3.5 the following line compiles with MsBuild 4.0:
 aEnumerable.Select(aMethod);

But MsBuild 3.5 requires me to write:
 aEnumerable.Select(item => aMethod(item));

Will both binaries will run a machine without .NET Framework 4.0, but with .NET 3.5?
PS: While i showed an example using "method overload inference" the same happens with other "4.0" features (eg. "named parameters").
another title for this question could be: What C# 4.0/Visual Studio 2010 features are .NET 3.5 compatible?

A: You are confusing Msbuild and the .NET framework.
Msbuild is just a tool to build .NET projects.  Version 4.0 is required to build .NET 4 projects, but it can also do .NET 1.1, 2.0, 3.0, 3.5, 3.5 SP1.  Its just like using Word 2010 to open a Word 2003 file.  2010 will open both, but 2003 will crash if you give it a 2010 file
Your code examples are showing differenecs added to the framework in version 4.0.  You cannot execute .NET 4 code on a machine that doesn't haven't the .NET 4.0 framework installed.  Doesn't matter what builds it, the runtime will not be able to  understand the CLR and it won't run
As for msBuild itself:
MsBuild 4.0 is a new version, largely updated to support .NET 4, but also with its own features.  Consult the release notes for msbuild4 if you need those details.
That said, MsBuild 4 is fully capable of producing .NET 3.5 output so long as the targetFramework is properly configured.  (We moved all our builds to MsBuild 4.0 long before we upgraded all projects to the .NET 4 framework)

A: If you target the installation to .NET 3.5 SP 1 and it works then it will work on a machine with just .NET 3.5 Service Pack 1.  If your not targeting 3.5 SP1 you should.

Version 3.5 of MSBuild, which is
  bundled together with .NET 3.5 (and
  Visual Studio 2008), allows .NET
  projects to be built for either 2.0,
  3.0 or 3.5 .NET version support (also known as"multi-targeting").

Source
I would extrapulate that MSBuild 4 would be updated to also support .NET Framework 4.0.  You should of course test your installations yourself a virtual machine and make sure everything works.
I just wanted to clarify that you should be using the MsBuild 3.5 method if you want to remove any compability issues that might arise otherwise.  I suspect that MSBuild 4.0 would keep support for the older method but was just updated to support changes that happen in the 4.0 .NET Framework.

A command similar to the following
  should work
msbuild YourSolution.sln /tv:3.5
  /p:TargetFrameworkVersion=v3.5 or
msbuild YourSolution.sln
  /p:TargetFrameworkVersion=v3.5 /tv (or
  /toolsversion) Indicates which version
  of the MSBuild tools you want to use,
  and the property
  TargetFrameworkVersion indicates the
  target framework. In your case just
  specifying that property should be
  fine, but if you want to use the 3.5
  MSBuild toolset you can sepcify it
  with /tv as I did in the first
  command.

Source


text:
Q: Routing to non-Angular pages within Angular I am converting a large server rendered app to use Angular. Because of the size, we are doing it a bit at a time. During this conversion period, part of the app will use Angular and part will not. This means that routing sometimes will route within the Angular app and sometimes it will need to transition from old world to new world (easy) or new world to old world (harder).
Ideally, I would like to specifically route some page transitions within the Angular app (new world) to the proper controllers but then any other page transitions should just fetch new HTML pages (old world).
I can't seem to figure out how to do this. I think I need to use the routeProvider and when / otherwise, but there isn't a lot of documentation that I found which is helpful.

A: You can't use routeProvider for the old world, since angular routes only direct you within the actual same page.
You could make a placeholder angular route for each legacy route, then in the controller, inject $window and do something like:
$window.location.href = destinationUrl;

Something like: (go to the old world on logout)
app.controller('LogoutCtrl', function ($scope, $window) {
    var destinationUrl = 'https://mywebsite.com/';
    $window.location.href = destinationUrl;

});

Vice versa, to go back to the angular world, just use a normal link to your angular route:
Link

If you want a catch-all route to redirect to the outside, you can do the following:
otherwise({
   controller: 'NotFoundCtrl'
  });
...
app.controller('NotFoundCtrl', function($scope, $location, $window) {
   var path = $location.path();
   $window.location.href="http://test.com" + path;
 })

A: As triggerNZ said, you can always have a controller redirect unhandled routes to the outside. Here is the HTML and Javascript showing how to do it.
HTML

This

That

Other

        <ng-view></ng-view>

Javascript
var app = angular.module("myApp", ['ngRoute']);

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider.when('/this', {
        templateUrl: 'this.html'
    }).when('/that', {
        templateUrl: 'that.html'
    }).otherwise({
        template: "

",
        controller: function ($window, $location, $rootScope) {
            if (!$rootScope.isInitialLoad) {
                $window.location.href = $location.absUrl();
            }
        }
    });

    $locationProvider.html5Mode(true);
});

app.run(function ($rootScope) {
    $rootScope.$on('$routeChangeSuccess', function() {
        $rootScope.isInitialLoad = (typeof $rootScope.isInitialLoad === "undefined");
    });
});


text:
Q: Only able to access SQLite3 database through Terminal I wrote a Node script to access Safari's iCloud Tabs database, found here on a Mac: ~/Library/Containers/com.apple.Safari/Data/Library/Safari/CloudTabs.db.
When I run the script through Terminal, it's able to access the database just fine. Or when I'm in Terminal, and I open the database with sqlite3 CloudTabs.db, I can view the tables just fine with .tables.
However, if I run the Node script through another program, such as Alfred, I get the following error:
[Error: SQLITE_CANTOPEN: unable to open database file] {
  errno: 14,
  code: 'SQLITE_CANTOPEN'
}

And if I open the database file directly from the Mac Finder with DB Browser for SQLite, then it says "Could not open database file." (I've read that perhaps this is because the file is located in a hidden directory?)
Through both Terminal and Alfred, USER is set to gary, and even if I try source ~/.bash_profile before running my Node script through Alfred, I get the same error.
Why am I only able to open this particular SQLite database in some ways, but can't open it in other ways? How is SQLite able to restrict access to its database selectively like this?
My primary question is, how can I make it possible to access this SQLite database by running the script through Alfred?

A: To fix the problem on a Mac to access restricted database files, I resolved the issue by going to "System Preferences > Security & Privacy > Privacy > Full Disk Access" and adding and checkmarking the relevant apps, which would be Alfred and SQLite DB Browser, in my case.


text:
Q: Signing electron-builder generated package on windows fails when using self signed certificate I have js project that ive packaged with electron-builder.
I want to sign windows package with self signed certificate.
My build machine is Windows Server 2019 64 bit.
Node version 12.18.2
I use electron-builder 22.7.0.
Ive generated pfx file on the different windows machine using following power shell commands
New-SelfSignedCertificate -DnsName www.github.com -CertStoreLocation cert:\LocalMachine\My -type CodeSigning
$pw = ConvertTo-SecureString -String sillypassword -Force –AsPlainText
Export-PfxCertificate -cert cert:\localMachine\my\SOMELONGNUMBERFROMFIRST COMMAND -FilePath $env:USERPROFILE\Desktop\Cert.pfx -Password $pw

Ive exported CSC_LINK and CSC_KEY_PASSWORD with proper values and im running electron-builder -p always --win to publish the package.
And i got following error
Exit code: 1. Command failed: C:\Users\travis\.cache\electron-builder\winCodeSign\winCodeSign-2.6.0\windows-10\x64\signtool.exe sign /t http://timestamp.digicert.com /f C:\Users\travis\certificate_win.pfx /d My project /du https://github.com/org/myrepo /p 434b9bda7dbaf509beaef9779192a67fbe263d70af93716804959aa49662adb6 (sha256 hash) /debug C:\Users\travis\build\org\myrepo\build\win-unpacked\My project.exe
232
SignTool Error: An unexpected internal error has occurred.
233
234
Error information: "Error: Store::ImportCertObject() failed." (-2146893808/0x80090010)
235
236
SignTool Error: An unexpected internal error has occurred.
237
  stackTrace=
238
                                                                                Error: Exit code: 1. Command failed: C:\Users\travis\.cache\electron-builder\winCodeSign\winCodeSign-2.6.0\windows-10\x64\signtool.exe sign /t http://timestamp.digicert.com /f C:\Users\travis\certificate_win.pfx /d My project /du https://github.com/org/myrepo /p 434b9bda7dbaf509beaef9779192a67fbe263d70af93716804959aa49662adb6 (sha256 hash) /debug C:\Users\travis\build\org\myrepo\build\win-unpacked\My project.exe
239
                                                                                SignTool Error: An unexpected internal error has occurred.
240

226
                                                                                Error information: "Error: Store::ImportCertObject() failed." (-2146893808/0x80090010)
227

228
                                                                                SignTool Error: An unexpected internal error has occurred.
247

248
                                                                                at C:\Users\travis\build\org\myrepo\node_modules\builder-util\src\util.ts:129:16
229
                                                                                at ChildProcess.exithandler (child_process.js:310:5)
230
                                                                                at ChildProcess.emit (events.js:315:20)
245
                                                                                at maybeClose (internal/child_process.js:1021:16)
246
                                                                                at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
249
                                                                                From previous event:
250
                                                                                at processImmediate (internal/timers.js:456:21)
251
                                                                                From previous event:
258
                                                                                at WinPackager.signApp (C:\Users\travis\build\org\myrepo\node_modules\app-builder-lib\src\winPackager.ts:357:27)
259
                                                                                at WinPackager.doPack (C:\Users\travis\build\org\myrepo\node_modules\app-builder-lib\src\platformPackager.ts:244:16)
243
                                                                                at WinPackager.pack (C:\Users\travis\build\org\myrepo\node_modules\app-builder-lib\src\platformPackager.ts:115:5)
244
                                                                                at Packager.doBuild (C:\Users\travis\build\org\myrepo\node_modules\app-builder-lib\src\packager.ts:444:9)
241
                                                                                at executeFinally (C:\Users\travis\build\org\myrepo\node_modules\builder-util\src\promise.ts:12:14)
242
                                                                                at Packager._build (C:\Users\travis\build\org\myrepo\node_modules\app-builder-lib\src\packager.ts:373:31)
252
                                                                                at Packager.build (C:\Users\travis\build\org\myrepo\node_modules\app-builder-lib\src\packager.ts:337:12)
253
                                                                                at executeFinally (C:\Users\travis\build\org\myrepo\node_modules\builder-util\src\promise.ts:12:14)
254
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I can sign it on my test machine that ive created specifically to test this behaviour, but it fails in Travis. How can i debug this situation to know what im doing wrong.
Thanks

A: For self-signed certificate, you'll probably need to first check if this cert was imported to your cert store. Then verify if the subject name was set properly. electron-builder (v22.6.0 - v22.8.1) has a bug signing windows store apps: https://github.com/electron-userland/electron-builder/issues/4931, but it may or may not have any relation to your windows .exe signing.


text:
Q: Cannot connect to Go GRPC server running in local Docker container I have a go grpc service. I'm developing on a mac, sierra. When running a grpc client against the service locally, all is well, but when running same client against same service in the docker container I get this error:
transport: http2Client.notifyError got notified that the client transport was broken EOF.
FATA[0000] rpc error: code = Internal desc = transport is closing

this is my docker file:
FROM golang:1.7.5

RUN mkdir -p /go/src/github.com/foo/bar
WORKDIR /go/src/github.com/foo/bar

COPY . /go/src/github.com/foo/bar
# ONBUILD RUN go-wrapper download
RUN go install

ENTRYPOINT /go/bin/bar

EXPOSE 51672

my command to build the image:
docker build -t bar .

my command to launch the docker container:
docker run -p 51672:51672 --name bar-container bar

Other info:

*

*client program runs fine from within the docker container

*connecting to a regular rest endpoint works fine (http2, grpc related?)

*running the lsof command in OS X yields these results
$lsof -i | grep 51672
com.docke   984 oldDave   21u  IPv4 0x72779547e3a32c89      0t0  TCP *:51672 (LISTEN)
com.docke   984 oldDave   22u  IPv6 0x72779547cc0fd161      0t0  TCP localhost:51672 (LISTEN)

*here's a snippet of my server code:
server := &Server{}
endpoint := "localhost:51672"
lis, err := net.Listen("tcp", endpoint)
if err != nil {
    log.Fatalf("failed to listen: %v", err)
}

s := grpc.NewServer(grpc.Creds(creds))

pb.RegisterExpServiceServer(s, server)

// Register reflection service on gRPC server.
reflection.Register(s)

log.Info("Starting Exp server: ", endpoint)

if err := s.Serve(lis); err != nil {
    log.Fatalf("failed to serve: %v", err)
}

A: When you specify a hostname or IP address to listen on (in this case localhost which resolves to 127.0.0.1), then your server will only listen on that IP address.
Listening on localhost isn't a problem when you are outside of a Docker container.  If your server only listens on 127.0.0.1:51672, then your client can easily connect to it since the connection is also made from 127.0.0.1.
When you run your server inside a Docker container, it'll only listen on 127.0.0.1:51672 as before. The 127.0.0.1 is a local loopback address and it not accessible outside the container.
When you fire up the docker container with "-p 51672:51672", it'll forward traffic heading to 127.0.0.1:51672 to the container's IP address, which in my case is 172.17.0.2.
The container gets an IP addresses within the docker0 network interface (which you can see with the "ip addr ls" command)
So, when your traffic gets forwarded to the container on 172.17.0.2:51672, there's nothing listening there and the connection attempt fails.
The fix:
The problem is with the listen endpoint:
endpoint := "localhost:51672"

To fix your problem, change it to
endpoint := ":51672"

That'll make your server listen on all it container's IP addresses.
Additional info:
When you expose ports in a Docker container, Docker will create iptables rules to do the actual forwarding.  See this.  You can view these rules
with:
iptables -n -L
iptables -t nat -n -L

A: If you use docker container to run grpc service,you should make sure grpc service and grpc client on ths same bridge

A: if you are using docker container, u can define network by IP and give this IP to your IP address(like: 178.20.0.5).


text:
Q: Detecting changes in SQL Azure, and publishing events My company is currently using event sourcing pattern in our system. The system usually publishes events from applications, and then stores them in event store and at the same time update database (for query) via event handler. However, there are exceptional cases where database (which is SQL Azure) is updated without publishing events and updating the event store. To keep integrity of event store, I would like to detect changes (from the aforementioned cases) in SQL Azure and send events to event store for backfilling.
I checked there are couple of ways in .NET to achieve it using SQLTableDependency or websocket to detect SQL CDC (Change Data Capture). I found SQLTableDependency doesn't support SQL Azure.
I wonder if someone has experience in the similar technical challenge.


text:
Q: I'm using MUI-Data-Tables and I would like to change the header text color after I click to sort the Column? I need to override the default black text color when sorting a column, I'm not sure how to do it. The closest I got was to change the arrow icon color using the snippet below.
 MUIDataTableHeadCell: {
        sortAction: {
            '& path': {
              color: "teal " // or whatever you need
            },
            },
      },

Does anyone have an idea how can I change the text color too? :)

A: This should do the trick!
 MUIDataTableHeadCell: {
    sortAction: {
        '& path': {
          color: "teal " // or whatever you need
        },
     },
    sortActive: {
      color: ""  // whatever you need
    }
  },

sortActive = Header Text Color


text:
Q: How do I output line breaks from xsl:value of I have this statement
xsl:value-of select="metadata/line1"/

where line1 is in the souce xml is:
Microsoft Windows 7 is installed<br/&gt

The HTML output turns out to be:
Microsoft Windows 7 is installed

I want it to actually insert the break after the word installed instead of outputting the literal

A: Instead of xsl:select, use xsl:copy-of
It will render the HTML as well
See http://www.w3schools.com/xsl/el_copy-of.asp
You can even try <xsl:value-of select="  " disable-output-escaping="yes" />

A: Seems that what you like to do is "unescape" some xml content. If I'm right disable-output-escaping should help. Try:
<xsl:value-of select="metadata/line1" disable-output-escaping="yes" />

E.g.: How to unescape XML characters with help of XSLT?


text:
Q: How to create microsoft teams meet link using nodejs in web app Problem statement : I am trying to create Microsoft teams meeting link using NodeJS without passing any tokens or granting permission. ( Or way to get token by asking the user to login to Microsoft account). But currently I am only getting ways which includes granting access in dashboard.
I am able to get token when I pass application id , tenant id etc. Which again give 403 forbidden may be because I am using my personal account. All I want a way to create meeting link without forcing to grant permission.

A: Looks like you are using this document to create onlinemeeting and this is not supported for Personal Accounts. Give a try by creating event which supports user calendar with personal accounts and use the onlinemeetingurl property.
Yes, you need to give permission to let app pull your data for Microsoft Graph API. See this document.


text:
Q: How does StackExchange load data from the server without making an XHR request? When viewing the questions for a tag on SE networks, every now and then you will get a message at the top:

n questions with new activity.

However the weird thing (to me) is that I don't see any network requests made. How exactly is this accomplished?

A: You're not seeing requests because it's not making any; the page is maintaining an open Web Socket connection to the server, and the updates are being pushed from the server to your browser, rather than downloaded at your browser's request.


text:
Q: Conceptual problem with surfaces of revolution
When calculating the surface area of a surface of revolution, we derive the formula $$S = \int_a^b 2\pi f(x) ds$$ by approximating the surface by a set conical loops (for lack of a better term).  Then we take the limit as the width of those loops goes to zero and get the surface area.  That makes perfect sense.
But why couldn't we approximate the surface by cylindrical loops (I hope you guys understand what I mean by that)?  To me this seems like the more Riemann style way to do it -- where the usual method looks a lot like the trapezoidal method for evaluating integrals.  But in the limit as $\Delta x \to 0$, shouldn't the error of either way also go to zero?

Why would $\int_a^b 2\pi f(x) dx$ get you the wrong answer?

A: This is a lot like trying to approximate the length of a hypotenuse of a right triangle by just adding up only the horizontal legs of small right triangles which fit together to make the larger right triangle. One clearly needs to add up the hypotenuses of the small right triangles in this case, not just the horizontal legs.

A: You can think $ds$ as:
\begin{equation}
ds=\sqrt{(dx)^2+(dy)^2)}\\
ds=\sqrt{(dx)^2(1+(\frac{dy}{dx})^2)}\\
ds=dx\sqrt{1+(\frac{dy}{dx})^2}\\
ds=dx\sqrt{1+(\frac{df}{dx})^2}
\end{equation}
just applying Pythagoras's theorem.
The term inside the square root takes into account the slope of the curve; in the case $\frac{df}{dx}=0$, $ds$=$dx$ (it could be the case of a cylinder along x-axis).


text:
Q: Bootstrap styling breaks when I add own stylesheets This is what I have on my application.html.erb file.
<head>
   <title>Software & Cia.</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
   <%= javascript_include_tag 'application', 'data-turbolineks-track': 'reload' %>
   <%= csrf_meta_tags %>
</head>

If I delete the application stylesheet_link_tag, bootstrap works just fine, but I want to add my own styling to some parts. Sorry for the noobish question, but tried to find a solution and can't get it working.
My application.scss is
@import "bootstrap-sprockets";
@import "boostrap";

My application.js is
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree . here

A: If you want to use Bootstrap in rails, it's a good way to use the bootstrap gem (same for jquery)
gem 'turbolinks', '~> 5'
gem 'bootstrap', '~> 4.1.1'
gem 'jquery-rails'

This way you keep your application <head> clean:
<head>
  <title>Software & Cia.</title>
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>

  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>

Now your assets/stylesheets folder can be organize like that:
stylesheets
  |_ custom_folder
  |   |_ custom1.scss
  |   |_ custom2.scss
  |
  |_ application.scss
  |_ another_custom.scss

And you import all these files, bootstrap included, in your application.scss:
@import "bootstrap";
@import "custom_folder/custom1";
@import "custom_folder/custom2";
@import "another_custom";

*

*If you have multiple files inside a custom folder, you can even
create an index.scss where you import all your files and just import
"custom_folder/index" in application.scss

*If you override some boostrap variables in a file, import this one before bootstrap


text:
Q: PDO MySQL get records with previous date I've got a table with some columns. I want to filter some records using two of them, the one with INT type and second with DATETIME type. I'm using PHP PDO extension to connect with database and make some queries.
I'm trying to get the records from my table where datetime field is lower then given date, f.e.
<?php
    $date = date("Y-m-d");
    $this->db->query("SELECT * FROM `" . DB_PREFIX . "fanpage` WHERE `flag_warning` = ? AND DATE(`update_date`) < ?", array(1, $date));
?>

This returns NULL, but when I paste the same query into the phpMyAdmin window it shows me proper records. What is the problem?
Edit:
Fragment from query function:
public function query($sql, $params = array())
{
    $result = array();
    $result['query'] = $this->pdo->prepare($sql);
    $result['query']->execute($params);
    $this->lastResult = $result['query'];
    unset($result['query']);
}

A: No need for the prepared statements at all
WHERE flag_warning = 1 AND update_date < CURDATE()

A: Use
$sqlStatement = $this->db->prepare("SELECT * FROM `" . DB_PREFIX . "fanpage` WHERE `flag_warning` = ? AND `update_date` < CURDATE()");
$this->db->execute(array(1));
$result = $sqlStatement->fetchAll(PDO::FETCH_ASSOC);

Now $result has what you need.

A: I've changed the column name to date_time_upd and it works right now, I think it's bug or something, maybe someone can explain that?
Edit:
Okay, I've figured it out. There was a fragment of code that checked for occurrence of the "UPDATE, DELETE OR INSERT" word in the query, and if there was a word like that the query result was not fetched. I've changed that to search for SELECT word, now everything is okay.


text:
Q: squid as reverse proxy (newbie)
I would like to setup a reverse proxy in front of my virtual machines. All DNS records would point to the public IP where squid3 lives and squid would redirect the traffic according to the squid.conf. According to http://wiki.squid-cache.org/ConfigExamples/Reverse/MultipleWebservers seemed easy...
However, I am stuck on browser message "The connection was reset" in FF and ERR_EMPTY_RESPONSE in Chrome.
I added these lines on the beginning on my squid.conf:
http_port 80
http_access allow all
cache_peer 192.168.0.50 parent 80 0 no-query originserver name=server_1
cache_peer_domain server_1 subdomain1.domain.tld
cache_peer 192.168.0.56 parent 80 0 no-query originserver name=server_2
cache_peer_domain server_2  subdomain2.domain.tld  domain2.tld
cache deny all
acl all src all

The proxy machine has access to the other machines (verified with links)
I don't see anything in squid logs that could help.
Thanks for any suggestions!

A: Got it.
The squid was not running.... It is a fresh ubuntu server 12.04 install with a official squid3 package, but the upstart script is somehow not starting the squid3.
If I type sudo squid3 manually, eveyrthing works as expected.


text:
Q: How to set custom format of cell with trailing text as hr/hrs.? Is it possible to set the custom format of cell if the number is 1.0 as "1.0 hr " and if the cell is having number greater than 1 the format display as "hrs" instead of "hr"?
Thank you

A: You could use:
[=1]#.0 "hr";[>1]#.0 "hrs"


text:
Q: How to cancel an Rsync mirror on Ubuntu? I mistakenly synced two folders, one on my Ubuntu 18.04 server and one on a NAS.
I did some research on Google but I couldn't find anything conclusive.
I would like to know how to cancel the mirror synchronization of Rsync.


text:
Q: What are fish shell command-line ui patterns? I want to construct an ui similar to what git have git <command> [<param1> ...]. What I came up with so far is:
function git -d "Description"
    switch $argv[1]
        case branch
            git_branch $argv[2]
        case reset
            git_reset
    end
end

function git_branch -d "Description for branch"
    do_something $argv[1]
end

function git_reset -d "Description for reset"
    do_something_else
end

It works, but there are couple problems:
1. Fish doesn't pick up available commands for auto-completion;
2. If I run git with no arguments it wouldn't print out list of command, neither it would pick up descriptions for them.
It appears to me that what I'm doing is not the "right" way to construct command-line utilities with fish. So, what is the right way?

A: Maybe your problems occur because you don't have a default branch if your switch statement, so you never call out to the actual git command. Try:
function git -d "Description"
    switch $argv[1]
        case branch
            git_branch $argv[2]
        case reset
            git_reset
        case '*'
            command git $argv
    end
end

To protect against the case where zero arguments are provided, I do this:
function git -d "Description"
    set -q argv[1]
    and switch $argv[1]
        case branch
            git_branch $argv[2]
            return
        case reset
            git_reset
            return
    end
    command git $argv
end


text:
Q: How do I differentiate between server errors and no network with ApolloGraphQl? I am using the ApolloGraphQl library to fetch data from my backend. https://www.apollographql.com/docs/react/data/error-handling
In my React app, I want to show a 'you are offline' page when the network was disrupted.
const {
    data
    loading,
    error,
} = useQuery('my query', 'cache-and-network');

I can destructure the result to get the ApolloError. However, how can I know if the error is caused by no network?
I see that I can get a networkError (https://www.apollographql.com/docs/react/data/error-handling#network-errors) but it's usually a 4xx or 5xx error and not HTTP error code -1.
How will I know that I am getting an error due to no network?

A: You can look at the networkError key of Apollo's error object.
Here's a function that you might find useful in interpreting Apollo errors:
import { ApolloError } from '@apollo/client/errors';

export const apolloErrorToStrings = (apolloError: ApolloError) => {
  const errorArray: Array<string> = [];
  let isNetworkError = false,
    isAuthenticationError = false;

  if (apolloError.graphQLErrors) {
    apolloError.graphQLErrors.forEach((error) => {
      errorArray.push(
        `${error.extensions?.code || 'unknown'}: ${error.message}`
      );
      if (error.extensions?.code === 'UNAUTHENTICATED')
        isAuthenticationError = true;
    });
  }
  if (apolloError.networkError) {
    errorArray.push('CONNECTION FAILED: Are you connected to the internet?');
    isNetworkError = true;
  }
  return { errorArray, isNetworkError, isAuthenticationError };
};


text:
Q: JSP is not running in IE8 My webapp works fine with most of the browsers even with latest IE, but it won't load any jsp script (Such as drawing charts, submitting forms, etc) in IE8.
Is there any work-around to enable jsp in IE8?
General Information about the app:
Backend: JAVA
Frontend: Javascript
Web Server: Tomcat 8.0

A: Try to insert this in your jsp page
<head>
   <meta http-equiv="X-UA-Compatible" content="IE=8">
</head>

Otherwise check if the elements you are using are compatible with IE8.
http://www.w3schools.com/cssref/css3_browsersupport.asp
EDIT:
The <meta> tag should be added above the links to the css files.
 <head>
       <title>Page Title</title>
       <meta http-equiv="X-UA-Compatible" content="IE=8">
       <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
       <...>
 </head>


text:
Q: A circle with radius $r$ has $k$ points within its radius. What is the min number of points a square with side $2r$ need to maintain this? Consider that I have a circumference $c$ with radius $r$ that has $k$ points within its distance. As shown by the following graphic:

For perfomance issues,
I need to normalize this circumference into a square of side $l$ = $2r$, illustrated bellow. This mean that my basic structure is now a square of side $l$.
My question is: what is the minimum value of points $q$ to ensure that the squared circumference has at least $k$ point inside the "radius", i.e., it has the same configuration of $c$ ($k$ points within the radius),
considering that the points in the square have an uniform distribution inside the square.
For example, something as $q=factor*k$.

A: If I understand correctly your question, you are going to throw $q$ points uniformly at random inside a square and want to have at least $k$ of them inside the inscribed circle.
You can never be sure of this, there will always be a probability that all points fall outside the circle. The probability that one point falls inside the circle is $\alpha=\pi/4$ (ratio of areas).
If $m$ is the number of points that fall inside the circle, then $m$ follows a binomial distribution ($q,\alpha$), with mean $q\alpha$ and variance $q \alpha (1 -\alpha)$. If you want that the average number of points is $k$, then you should pick $q = \alpha k\approx 1.27 k$
If you want instead that the probability $P(m\ge k)$ is large, you can compute the cumulative of the binomial numerically. Or you can approximate it (if $q$ is large) via the CLT. Or you can also dictate that you want that $k$ is (say) three standard deviations below the mean, so:
$$  q\alpha - k = 3 \sqrt{q \alpha (1 -\alpha)}$$
and get $q$ (as a function of $k$) from that.


text:
Q: Elegant way to perform array properties comparison using Linq Any clue about how to perform the following code using Linq?
for (Int32 i = 0; i < array1.Count; ++i)
{
    if (!array1[i].Name.Equals(array2[i].Name, StringComparison.OrdinalIgnoreCase))
        return false;
}

A: It's probably worth double checking to ensure that array1 and array2 are at least as long as bones.Count... so
Enumerable
 .Range(0, new[] {bones.Count, array1.Length, array2.Length}.Min())
 .All(i => array1[i].Name.Equals(array2[i].Name, StringComparison.OrdinalIgnoreCase))

A: array1.All((a, i) => a.Name.Equals(array2[i].Name, StringComparer.OrdinalIgnoreCase);

A: If you want to know if all names in the arrays are equal  at the same index you can use:
bool allEqualNamesAtSamePosition = array1
    .Zip(array2, (arr1, arr2) => new { arr1, arr2 })
    .All(x => string.Equals(x.arr1.Name, x.arr2.Name, StringComparison.OrdinalIgnoreCase));

But normally i prefer a plain for-loop if something depends on the index. In my opinion LINQ even decreases readability in that case.


text:
Q: Angularjs ocultar y mostrar respuesta formulario Tengo un formulario para rellenar y hacer el cálculo de un préstamo.
Me aparece el formulario y un botón Enviar. Cuando rellene el formulario y le doy al botón Enviar quiero que se me muestre el resultado.
Estoy trabajando con Angularjs. No se como usar el ng-hide ni el ng-show.
El formulario oculto del resultado del cálculo de la cuota lo tengo, pero no se como mostrarlo al hacer click al boton enviar.
Este es mi código de Html:

//ABANCA

        Préstamos en 24H.
        Haz tus cuentas.

            <form action="http://localhost:58498/api/Cuota" class="form-horizontal"
                  method="get" role="form" id="formulario-cuotas">

                        ¿Cuánto quieres pedir?
                        <input class="form-control" data-val="true"
                               data-val-cuotas="El campo de las Cuotas está vacío. No es válido"
                               data-val-required="El campo Cuotas es obligatorio." id="Cuotas"
                               name="cantidad" type="number" value="">

                    "Con el préstamo 24h puedes pedir a partir

                    de 500€, pero para cantidades de hasta 3000€

                    tiene que ser en la "
                        modalidad de
                        tarjeta

                    ".Por eso este simulador empieza en 3000€ que

                    es lo mínimo que puedes pedir en la modalidad

                    de préstamo. Ten en cuenta que no puedes

                    solicitar más de lo que cuesta lo que vayas

                    financiar."

                        ¿Cuándo deseas devolverlo?
                        <input class="form-control" data-val="true"
                               data-val-cuotas="El campo de los plazos está vacío. No es válido"
                               data-val-required="El campo Plazos es obligatorio." id="Plazos"
                               name="plazos" type="text" value="">

                    "Puedes devolverlo en un plazo maximo de 96 meses,

                    osea, 8 años"

                        <input type="radio" class="form-check-input" name="tipo" id="optionsRadios1" value="hipotecario" checked="">

                                Crédito Hipotecario.

                        <input type="radio" class="form-check-input" name="tipo" id="optionsRadios2" value="personal" checked="">

                                Crédito Personal.

            </form>

            <button id="btnenviar" name="btnenviar" class="btn btn-primary input-group">
                    ENVIAR
                </button>

                <button name="btnEnviar" class="btn btn-primary" ng-class="color" ng-click="enviar()">
                    NG-ENVIAR
                </button>

                @*
*@

                      <form method="get" action="http://localhost:58498" class="hide form-horizontal" role="form" id="formulario-respuesta">

Resultado:

Cantidad

Cuota

Plazos

Tipo

                      </form>

                       @*
*@

A: Recuerda que la ventaja de trabajar con Angularjs es que todo lo que cambie en el controlador se ve reflejado de inmediato en la vista y también viceversa. Para lo que necesitas puedes definir una variable que te permita ocultar y mostrar elementos en tu vista, tambien dar clases dependiendo de una condicion, etc.
Tambien me di cuenta que tu formulario va directamente a la URL de tu API, deberias cambiar esto y hacerlo desde el controlador para utilizar aun mas lo potente de angularJS y trabajar con ng-model
En tu controlador deberia ser algo asi :
.controller('CalculoCreditoCtrl, [$scope, $http, function($scope,$http){
      $scope.enviar = function() {
        data = data = {nombre : $scope.data.nombre, apellidos : $scope.data.apellidos, cuotas : $scope.data.cuotas}
        $http({
            method: 'POST',
            url: 'http://localhost:58498/api/Cuota',
            data: data

        }).then(function(response) {
             if(response.respuesta){
                $scope.mostrar_resultado = true;
             }
        });
    }
}])

Y en tu vista el formulario deberia ir asi :

     <input class="form-control" data-val="true"
                       data-val-cuotas="El campo de las Cuotas está vacío. No es válido"
                       data-val-required="El campo Cuotas es obligatorio." ng-model="data.cuotas"
                       name="cantidad" type="number" value="">

Tu variable $scope.mostrar_resultado puedes imprimirla desde tu vista con {{mostrar_resultado}} y puedes ocuparla para ocultar o mostrar un elemento

Si te das cuenta borre id=cuotas y lo reemplace por ng-model=data.cuotas, este tag ng-model te permite acceder a los valores de tus inputs desde tu controlador! Esto es una de las ventajas de AngularJS que te ayuda en el manejo de tus datos de forma rapida! , tu codigo no ocupa mucho Angularjs a pesar de que estas implementandolo, te aconsejo que estudies un poco mas de AngularJS para que lo aproveches al maximo!
Te dejo un link muy completo para comenzar con AngularJS
Tutorial AngularJS

A: Tu $scope.enviar() que debe estar en el controlador, agregale esta linea:
$scope.enviar() {
    $scope.showResult = true;
}

Y al div padre de todo el resultado, o div contenedor agregale esto:

    Aquí va el resultado

Con ng-show le decimos que muestre o haga visible un elemento HTML solamente si se cumple la condición dada, en este caso si showResult es verdadero
 o true.
No es necesario utilizar este bloque que veo en tu código:
@*
*@

@*
*@

También observo en tu codigo varios ng-show="" , en el resultado, pues estos no son necesarios, con que utilices uno solo en el div contenedor o padre de todo el resultado es suficiente, bueno tambien depende de que tanto quieras ocultar.