text:
Q: Reconstruction of 3D model using three 2D images (looking at the same object in 3 different views) I came across a requirement to reconstruct 3 dimensional image of an object using three cameras placed around it such that it (each camera's field of view together) covers the entire object under view.

*

*I have already worked a little on stereo vision (using two cameras). In this, we obtain a 3D point cloud. I don't think this will be necessary in my case since I need not calculate the exact x, y and z distances. I only have to get a 3D model. Is my approach right? I have read about Stereo Vision using multiple cameras. Should I use this?

*I came across this comment by Image Analyst: "images must actually undergo a filtered back projection reconstruction process to build the 3D image from the images taken at different angles." I did not understand this clearly. I do not have a stack of images, I have only 3 images of the same object but with different views. How should I proceed with this? What are the terms which are used in my case? Is it called 3D Reconstruction?

*I also saw about SfM (Structure from Motion). My object / scene is not in motion.

*I saw this code available. This too takes different slices of a brain and converts them into a 3D image. Is there anyway I can alter this code to suit my need or is it a completely different application?

As far as I have understood, with the three images (of different views of same object) I have to first match features (say SIFT) and then get the disparity (?). Or should I use Image stitching and deal with the stitched image (maybe create a 3D point cloud with this)?
Please tell me how to go about this application. What are the necessary topics I should read about?
My application is to only capture the object in 3D (using 3 cameras) and save this 3D image.
Regards,
Meghana.
Edit:

*

*I have also come across Three-View Geometry (PART III of "Multiple View Geometry in Computer Vision by Hartley and Zisserman"). I don't think this is the same as what I want. In my case the scenes wouldn't overlap to a large extent. The field of view of each camera would overlap only a little (the cube's edges, as shown below), it won't be the same as in a stereo pair of cameras looking at a common scene. So stereo matching won't be feasible. Is my understanding correct? How should I deal with it?


text:
Q: Arbitrary code execution despite Data Execution Prevention Nowadays with protections like W^X , is it still possible to successfully exploit buffer overflows with for example NOP Slide ?

A: The exploitability of a buffer overflow is very variable based on the surrounding code. For example, are other mitigation techniques in place such as stack canaries. However if you are only considering DEP/W^X then yes, it can still often be possible to exploit them.
How you would go about exploiting it greatly depend on the type of buffer overflow. Judging from you mentioning using a NOP slide, I assume you're talking about a simple stack based buffer overflow. In this case, you can use techniques such as Return Oriented Programming (ROP) or Jump Oriented Programming (JOP). These techniques reuse code that exists in sections of memory that are already marked as executable. Therefore, you do not require memory that is marked both as executable and writeable.
One tecnique for mitigating these code reuse attacks is Control Flow Integrity (CFI) checking. This mitigation tries to only allow the code to flow through known "good" paths. This has begun to gain more mainstream support in recent years with e.g. compiler support from clang/llvm.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check check box checked or not? Code not working:
if($('#primayins').attr('checked'))
{
   $("#tx_nm0x0_pricingplan").val(1);
}
else
{
   $("#tx_nm0x0_pricingplan").val(2);
}

Every time it is getting false

A: Try with:
if($('#primayins').prop('checked'))
...

Alternatively:
if($('#checkbox').is(':checked'))
...


text:
Q: How to require password if single-user mode is selected Solaris 11? I want to demand root password when running single-user mode on Solaris 11. Unfortunately any of the guides seem to work in my case.
The /etc/default/sulogin is commented as required, uncommenting and changing to PASSREQ=YES doesn't do anything either.
Help appreciated


text:
Q: Chrome extension : can't use storage API in popup.js? In my popup.html, I have this
<script src="popup.js"></script>

so then in my popup.js I try to run
chrome.storage.sync.set({"testkey": 'test'});

I got error of Uncaught TypeError: Cannot read property 'sync' of undefined
I'd declare my permission properly :
  "permissions": [
    "http://*/*", "https://*/*","storage"
  ],
  "browser_action": {
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  }

A: Is it possible that it is trying to cal it before storage exists. try a
setTimeout('chrome.storage.sync.set({"testkey": 'test'});', 150);

to set it off after a delay to make sure it isn't related to load.
only thing is it will run that in global(window) scope. not sure if that matters.


text:
Q: Jquery URL Parameter I've got this function:
$.urlParam = function(name){
            var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
            if (results==null){
                return null;
            }
            else{
                return results[1] || 0;
            }
        };

Fiddle
I put a ?param1 behind the URL but nothing is showing up, the firebug console doesn't say anything.
Can you guys help me?


text:
Q: I want to access my Moodle courses details using ASP.NET web application through moodle authentication APIs.How to do that? I want to access my Moodle courses details using ASP.NET web application through  moodle authentication APIs.How to do that?

A: You'll need to set up web services in Moodle. Choosing which functions to be available externally. Then use a protocol like REST to retrieve the data.
Here is a client example:
https://docs.moodle.org/dev/Creating_a_web_service_client
Here is how to set up web services:
https://docs.moodle.org/38/en/Using_web_services
This is the main page for web services:
https://docs.moodle.org/38/en/Web_services


text:
Q: Python email module ImportError: No module named utils My installation of Python's requests library has been working perfectly for months and it has decided to break today.
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/requests/__init__.py", line 58, in <module>
    from . import utils
  File "/usr/local/lib/python2.7/dist-packages/requests/utils.py", line 26, in <module>
    from .compat import parse_http_list as _parse_list_header
  File "/usr/local/lib/python2.7/dist-packages/requests/compat.py", line 7, in <module>
    from .packages import chardet
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/__init__.py", line 3, in <module>
    from . import urllib3
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/__init__.py", line 10, in <module>
    from .connectionpool import (
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py", line 37, in <module>
    from .request import RequestMethods
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/request.py", line 6, in <module>
    from .filepost import encode_multipart_formdata
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/filepost.py", line 8, in <module>
    from .fields import RequestField
  File "/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/fields.py", line 1, in <module>
    import email.utils
ImportError: No module named utils

The trouble calling utils is related to the email module in Python 2.7
>>> import email
>>> import email.utils
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named utils

utils is clearly a part of Python's email library, but it can't be accessed.  If I uninstall and reinstall:
$ sudo pip install email

Collecting email
  Downloading email-4.0.2.tar.gz (1.2MB)
    100% |████████████████████████████████| 1.2MB 286kB/s
Installing collected packages: email
  Running setup.py install for email
Successfully installed email-4.0.2

Worst of all utils.py is actually present.  What am I doing wrong?
$ ls /usr/local/lib/python2.7/dist-packages/email/
base64mime.py   errors.py       header.py      message.py      parser.pyc
base64mime.pyc  errors.pyc      header.pyc     message.pyc     quoprimime.py
charset.py      feedparser.py   __init__.py    mime            quoprimime.pyc
charset.pyc     feedparser.pyc  __init__.pyc   _parseaddr.py   test
encoders.py     generator.py    iterators.py   _parseaddr.pyc  utils.py
encoders.pyc    generator.pyc   iterators.pyc  parser.py       utils.pyc

A: Most likely one of your own modules in the module search path (including the current working directory) is actually called email. This will cause Python to pick up that module instead, and it will shadow the email module from the standard library, leading to that import error.
Rename that module to something else, and you should be good.


text:
Q: Stop terminal output of MySQL command line From the terminal in Mac Mountain Lion, I'm running the following command:
mysql -h localhost -u root -p -B database | gunzip < db.sql.gz

It executes fine and the database is created but the file contents are put into the std out so I see the contents being spat out into the terminal window as it executes.
Can anyone tell me the switch to turn off the terminal output? I've Googled this but I can't figure it out. Besides, it will be documented here for others now ;)

A: You've got the commands backwards. data flows through pipes left -> right:
gzcat db.sql.gz | mysql -h localhost -u root -p -B database

As well, gunzip unzips the file, but does not output its contents. use gzcat instead to simply dump the unzipped content to stdout. The | pipe then "catches" that output and redirects it to mysql, which uses it as input.

A: follow the command with
 > /dev/null

and normal output is suppressed but errors are still shown
follow the command with
 > /dev/null 2>&1

and everything, including errors is supressed


text:
Q: Oracle report, add currency symbol after values If I add currency symbol to values it's look like: $5000, I want that currency symbol will be after value: 5000$, possible to format ?

A: Something like this?
select to_char(5000, '9999l'), to_char(5000, 'l9999')
from dual

Here is a sqlfiddle demo

If you don't want to specify the length you can do (I don't like this solution...):
select substr(trim(to_char('1', 'l9')), 1, 1) || 5000
from dual

Here is another sqlfiddle demo


text:
Q: perl won't locate down_force method of Thread::Semaphore? I verified that the package is installed with perldoc -l Thread::Semaphore, but i still get this error:
Can't locate object method "down_force" via package "Thread::Semaphore" at <filename line#>
my code:
: #use perl
   eval 'exec perl -S $0 ${1+"$@"}'
   if 0;

use threads;
use threads::shared;
use Thread::Semaphore;

my $s = Thread::Semaphore->new();

$s->down_force();    #it complains about this one

#some code here...

A: You probably have version 2.09 of Thread::Semaphore, which doesn't have the down_force() method. Try upgrading to the most recent version, which is currently 2.12.


text:
Q: Is it true that $n> a^2\Rightarrow n!>a^n$, $n\in\mathbb{N}, a\in\mathbb{R}$? If so, how can it be proven? (I have evaluated it up to $n=25$.)
If not, does there exist a $k\in\mathbb{R}$ such as that $n> a^k\Rightarrow n!>a^n$, with $n\in\mathbb{N},a\in\mathbb{R}$?

It is true, and to prove it, it suffices to show that $n!^2\geq n^n$ with induction.
For $n=1$ we have that $1\geq1$, which is true. Suppose $n!^2\geq n^n$. Then, $(n+1)!^2=(n+1)^2n!^2\geq (n+1)^2n^n$. We need to show that
$$\begin{align}
&(n+1)^2n^n\geq (n+1)^{n+1}\Leftrightarrow\\
\Leftrightarrow &n^n \geq (n+1)^{n-1}\Leftrightarrow\\
\Leftrightarrow &\ln(n^n)\geq \ln((n+1)^{n-1})\Leftrightarrow\\
\Leftrightarrow &n\ln n\geq (n-1)\ln(n+1)\Leftrightarrow\\
\Leftrightarrow &\frac{n}{n-1} \geq \ln(n+1-n)=\ln1=0\quad,
\end{align}$$
which is true!!

A: Converting above realization to an answer.

We prove $ \left( n! \right)^2 \ge n^n $ by means of induction.
For $n=1$, we have $ 1 \ge 1 $, which is true. Now suppose that $ \left( n! \right)^2 \ge n^n $. Then, $$ \begin {align*} \left( (n+1)! \right)^2 &= \left( n + 1 \right)^2 \left( n! \right)^2 \\&\ge \left( n + 1 \right)^2 n^n. \end {align*} $$Furthermore, $$ \begin {eqnarray*} \left( n+1 \right)^2 n^n &\ge& (n+1)^{n+1} \\ \iff \left( n + 1 \right) n^n &\ge& (n+1)^n \\ \iff n^n &\ge& (n+1)^{n-1} \\ \iff \ln \left( n^n \right) &\ge& \ln \left( \left( n + 1 \right)^{n-1} \right) \\ \iff n \ln n &\ge& \left( n - 1 \right) \cdot \ln \left( n + 1 \right) \\ \iff \frac {n}{n-1} &\ge& \ln \left( n + 1 - n \right) = \ln 1 = 0, \end {eqnarray*} $$ which is true, so we are done. $\Box$


text:
Q: How to parse websocket in nodejs Sending message using web socket send function.
ws.send(msg);
ws.send(msg);
ws.send(msg);
ws.send(msg);
ws.send(msg);
ws.send(msg);
ws.send(msg);

I'm getting packets in the on("data") event as hellworldhelloworldhelloworld...
How do I separate one packet from one another?


text:
Q: What are the differences between Tables and Categorical Arrays, and cell and struct arrays? In the newest version of MATLAB there are two new data types: Tables and Categorical Arrays.
Table is a new data type suitable for holding data and metadata, and can be used with mixed-type tabular data that are often stored as columns in a text file or in a spreadsheet. It consists of rows and column-oriented variables.
Categorical arrays are useful for holding categorical data - which have values from a finite list of discrete categories.
In previous versions I would have handled these use cases using cell and struct arrays. What are the differences between these and the new data types?

A: I haven't upgraded yet so I can't play around but based on this video and this article I can already see some advantages. They're not necessarily adding functionality that you couldn't do before, but rather just taking the hassle out of it. Using readtable over xlsread is immediately appealing to me. Being able to access columns by name rather than just by index is great, I do it in other languages often. In a table where column order doesn't really matter (unlike a matrix) it's really convenient to be able to address a column by it's name instead of having to know the column order. Also you can merge table using the join function which wasn't that easy to do with cell arrays before. I see that you can name the rows too, I didn't see what advantage that gives you and I can't play around but I know in some languages (like PANDAS in Python and I think in R as well) naming rows means you can work with time series data with different series that are not completely overlapping and not have to worry about alignment. I hope this is the case in Matlab too! Categorical arrays also look like just an extra layer of convenience, kind of like an enum. You never actually need a enum but it just makes development more pleasant.
Anyway that's just my two cents, I probably won't get an opportunity to play around with them any time soon but I look forward to using them when I do need them.

A: I use the table format to organize different input/output cases in my data, where the result may come from different tables. Main advantages compared to struct or cell array:

*

*convenient table functions such as join, innerjoin, outerjoin

*the use of fields <> more robust programming than arrays

*data format is easy to export/import (e.g. delimited .txt file) <> no fprintf()

*the data file can be opened in excel/Calc (libreoffice) <> no .mat


text:
Q: Simple asynchronous task with asyncio I have a function that takes a lot of time to run, but actually has returns no program relevant value -- it simply does some IO / plotting to store current progress.
I would like to asynchronously call it, and have found the newly core'd asyncio library. My main function then looks something like
async def doStuff(input):
    plt.figure()
    plt.plot(input)
    plt.savefig('foobar.pdf')

However, it's unclear to me how to exactly call that. All examples I've seen do a variant on
loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(doStuff()

but actually, I just need a single call (not a loop), and explicitely do not want to wait ever for it to finish. What's the most trivial implementation of that in the asyncio framework?


text:
Q: Use my application for NFC payment when not set as default Hi I'm working on android application for NFC payments.
There is an option in Android settings to use an open application instead of the default one. For example when I have default application set to Android Pay and I open my app before the payment - I want to use my app for the payment instead of the default one. See image bellow.

I tested it, but unfortunately I paid with Android Pay instead of my app that was running in foreground.
I did not find any word in documentation, if I have to add something to manifest, register something etc..?
I have service with intent filter and meta data in my manifest and when the app is set as default for payment, it is working correctly:
<service
        android:name="com.example.MyWalletHceService"
        android:exported="true"
        android:permission="android.permission.BIND_NFC_SERVICE">
        <intent-filter>
            <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/>
        </intent-filter>

        <meta-data
            android:name="android.nfc.cardemulation.host_apdu_service"
            android:resource="@xml/apduservice"/>
    </service>

Adding apduservice xml content:
<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
android:apduServiceBanner="@drawable/ic_logo_nfc_system"
               android:description="@string/nfc_service_title"
               android:requireDeviceUnlock="false">

<aid-group
    android:category="payment"
    android:description="@string/nfc_aid_desc">
    <!-- Following is a PPSE AID. You must always include this AID in order for payments to
         work-->
    <aid-filter android:name="@string/aid_number"/>
    <!-- Following AID list is specific to the application requirements.
       If your application supports the type of card that these AID represents,
       you must include those AID in your configuration file -->
    <aid-filter android:name="@string/aid_mc_filter"/> <!-- Mastercard DEBIT/CREDIT -->
</aid-group>

A: So I finally found a solution!
You have to use setPreferredService(Activity, ComponentName) in your current foreground activity. It is recommended to to call it inside onResume() and also do not forget to call unsetPreferredService(Activity) once the activity is not in foreground (onPause() is good place to call it).
One more thing:
setPreferredService(Activity, ComponentName) and unsetPreferredService(Activity) were added in API 21, so be sure not to call them from older API.


text:
Q: Is there a way for me to get the invoked package.json script because process.cwd() only returns where the package.json is located is there a way I could get the path where I executed the package.json script inside my directory
I tried this as an example
executed command
cd app/source/component && yarn generate

package.json is located in the app directory
"scripts": {
    "generate": "node -e 'console.log(process.cwd())'"
},

returns /Users/work/Documents/projects/.../packages/app
but I want to get the directory
packages/app/source/component


text:
Q: Spring Boot support maven multi-module I am trying to convert my existing multi-module maven Spring project to Spring Boot project. The reason is make it self contain and follow Martain Fowler's microservices concept.
However, the problem I have encounter is when try to clean build, seems the spring boot is trying to find the Main method from every module, which of course will failed.
Is this feature currently supported by Spring Boot 1.1.6.RELEASE or I did something wrong?
Thanks

A: It sounds like you've added Spring Boot's Maven plugin to every module in your build – it's what's looking for a main method. You should only add the Spring Boot plugin to a module if its a service that you want to run. If the module's just code that's shared between your services, the Spring Boot plugin isn't needed in that module.


text:
Q: Publish a web service on Visual Studio 2010 I created a web service in C#, using Visual Studio 2010 ( Framework .NET 3.5). In debug mode it works great, but now I must publish it on the internet, so that I can consume it in remote (the app that will consume the web service is an android app).
So the question is: how do I publish my web service on Internet so that I can consume it in remote?
Thanks in advance; this is a work for taking my degree!

A: A simple way: you switch to release mode, update your web.config for production, right click on your service project and from the menu select publish. Then you publish it to the local folder. This way it copies only the files needed. Then you copy the contents of the folder to your remote site using ftp, for example, your hosting provider should have given you the credentials.
for some hosters it is also possible to publish directly but I don't use this.


text:
Q: How to remove all the detected lines from the original image using Python? I am trying to remove all the lines present in the image.
I am able to detect the lines but when I am trying to remove the lines, I am still getting few small lines in the final image. I have used cv2.getStructuringElement to get both the horizontal and vertical lines. In some cases, the final image is getting completely distorted and I am not able to move forward
The image is taken from google

    res = verticle_lines_img + horizontal_lines_img
    res = cv2.bitwise_not(res)
    fin=cv2.bitwise_or(img_bin, res,mask =cv2.bitwise_not(res))
    fin= cv2.bitwise_not(fin)
    exp =255-res
    final = cv2.bitwise_and(exp,img_bin)
    final = cv2.bitwise_not(final)
    exp = ~exp
    finalised = cv2.bitwise_and(img_bin,final)
    finalised = cv2.bitwise_not(finalised)

Please help! Thanks

A: Here's an approach

*

*Convert image to grayscale

*Otsu's threshold to obtain binary image

*Remove horizontal lines

*Remove vertical lines

After converting to grayscale, we Otsu's threshold to get a binary image
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

From here we construct a special horizontal kernel to detect horizontal lines. Once the lines are detected, we fill in the lines to effectively remove the line
# Remove horizontal
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,1))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 2)

Similarly, to remove vertical lines, we construct a special vertical kernel
# Remove vertical
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,10))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 2)

Here's the detected lines in green

Result

You can fine tune the results by adjusting the kernel size. For instance, changing (10,1) to say (15,1) will tighten the line detection while lowering it to (5,1) will loosen the detection
Full Code
import cv2

image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Remove horizontal
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,1))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 2)

# Remove vertical
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,10))
detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), 2)

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()


text:
Q: Cross join (pivot) with n-n table containing values I have 3 tables :
TABLE MyColumn (
  ColumnId INT NOT NULL,
  Label VARCHAR(80) NOT NULL,
  PRIMARY KEY (ColumnId)
)

TABLE MyPeriod (
  PeriodId CHAR(6) NOT NULL, -- format yyyyMM
  Label VARCHAR(80) NOT NULL,
  PRIMARY KEY (PeriodId)
)

TABLE MyValue (
  ColumnId INT NOT NULL,
  PeriodId CHAR(6) NOT NULL,
  Amount DECIMAL(8, 4) NOT NULL,
  PRIMARY KEY (ColumnId, PeriodId),
  FOREIGN KEY (ColumnId) REFERENCES MyColumn(ColumnId),
  FOREIGN KEY (PeriodId) REFERENCES MyPeriod(PeriodId)
)

MyValue's rows are only created when a real value is provided.
I want my results in a tabular way, as :
Column   | Month 1 | Month 2 | Month 4 | Month 5 |
Potatoes |   25.00 |    5.00 |    1.60 |    NULL |
Apples   |    2.00 |    1.50 |    NULL |    NULL |

I have successfully created a cross-join :
SELECT
    MyColumn.Label AS [Column],
    MyPeriod.Label AS [Period],
    ISNULL(MyValue.Amount, 0) AS [Value]
FROM
    MyColumn CROSS JOIN
    MyPeriod LEFT OUTER JOIN
    MyValue ON (MyValue.ColumnId = MyColumn.ColumnId AND MyValue.PeriodId = MyPeriod.PeriodId)

Or, in linq :
from p in MyPeriods
from c in MyColumns
join v in MyValues on new { c.ColumnId, p.PeriodId } equals new { v.ColumnId, v.PeriodId } into values
from nv in values.DefaultIfEmpty()
select new {
    Column = c.Label,
    Period = p.Label,
    Value = nv.Amount
}

And seen how to create a pivot in linq (here or here) :
(assuming MyDatas is a view with the result of the previous query) :
from c in MyDatas
group c by c.Column into line
select new
{
  Column = line.Key,
  Month1 = line.Where(l => l.Period == "Month 1").Sum(l => l.Value),
  Month2 = line.Where(l => l.Period == "Month 2").Sum(l => l.Value),
  Month3 = line.Where(l => l.Period == "Month 3").Sum(l => l.Value),
  Month4 = line.Where(l => l.Period == "Month 4").Sum(l => l.Value)
}

But I want to find a way to create a resultset with, if possible, Month1, ... properties dynamic.
Note : A solution which results in a n+1 query :
from c in MyDatas
group c by c.Column into line
select new
{
    Column = line.Key,
    Months =
        from l in line
        group l by l.Period into period
        select new
        {
            Period = period.Key,
            Amount = period.Sum(l => l.Value)
        }
}

A: Do you have calendar periods (1-12) or fiscal periods (1-12 or 1-13 depending on the year)?
Would you only run the report for one year?
If possible, I would break the PeriodId into two fields of Year & Period.  This will make it easier to select for a specific year.  The queries will be simpler.


text:
Q: importlib can't find module cat test.py
from importlib import import_module

bar = import_module('bar', package='project')

ls project/
__init__.py
__init__.pyc
bar.py
bar.pyc

python test.py
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    bar = import_module('bar', package='project')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named bar

Listing imported modules (sys.modules) doesn't show any module project.
I can import bar using the python shell.
Any ideas?

A: It needs a dot in front of bar .. :-(
bar = import_module('.bar', package='project')

A: The documentation for import_lib says that

If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

Thus the expression can also be written as
bar = import_module('..bar',package='project.bar')


text:
Q: change label by radio selection I have these HTML Snippet :

            @Html.AntiForgeryToken()
            @Html.ValidationSummary()

            <input type="radio" value="hagh" checked="checked" name="reg">حقیقی</input>

            <input type="radio" value="hogh" name="reg">حقوقی</input>

        نام

            <input name="regname" type="text" />

        نام خانوادگی

            <input name="regLsatNameEcoCode" type="text" />

        کد ملی

            <input name="regNatCodeRegNo" type="text" />

        نام نماینده

            <input name="regDepName" disabled="disabled" type="text" />

            تلفن همراه

            <input name="regMobile" type="text" />

            کد

            <input name="regCityCode" type="text" />

            تلفن ثابت

            <input name="regPhoneNo" type="text" />

            <button class="orange">
                ورود</button>

I want to change label caption when user change the radio selection. I was confused in how to get selected radio when user click them and how to change label text. Is it true to access label as $('#labelname').val(sometext)?

A: Use below snippets :
$(function(){
    $("input:radio").click(function(){
        if($(this).is(":checked")){
            $('#labelname').val(sometext);
        }
    });
});

Hope this will help !!

A: You can access the appropriate label using traversal methods or by getting the name from the radio and using that to create ID selector for label.
I prefer traverse as it is less tedious to write
$(function(){
    $("td input:radio").change(function(){
       var labeltext = this.checked ? 'checked text' : 'unchecked text';
       $(this).parent().prev().find('label').text( labeltext);

    });
});


text:
Q: DoesNotExist at /cart/ matching query does not exist I want show item in cart.html page in my cart but when i add tshirt item in cart it's gives Error Product matching query does not exist. and when i add Product item in cart it gives error Tshirt matching query does not exist when I click on Cart
cartitem.py file:
def cartitem(request):
    cart=request.session.get('cart')
    if cart is None:
        cart=[]
    for c in cart:
        tshirt_id=c.get('tshirt')
        product_id=c.get('product')
        product=Product.objects.filter(id=product_id)
        tshirt=Tshirt.objects.get(id=tshirt_id)
        c['size']= Sizevariant.objects.get(tshirt=tshirt_id, size=c['size'])
        c['tshirt']=tshirt
        c['product']=product
    return render(request,"cart.html",{"cart":cart})

A: Try to use this :-
There are some antipatterns in your view.
def cartitem(request,pk):

    cart=request.session.get('cart')
    if cart is None:
        cart=[]

    for c in cart:
        tshirt_id=c.get('tshirt')
        product_id=c.get('product')
        product = get_object_or_404(Product,pk=pk)
        tshirt=Tshirt.objects.get(pk=pk)

        c['size']= Sizevariant.objects.get(tshirt=tshirt_id, size=c['size'])
        c['tshirt']=tshirt
        c['product']=product

    return render(request,"cart.html",{'cart':cart,'product':product,'tshirt':tshirt})

Change your urls.py into this :-
path('<int:pk>',views.cartitem,name='carttime'),


text:
Q: Efficiently process through 3 millions Pandas dataframe rows I neeed to process a large csv file with 3 million rows, and 7 columns.
 Shape of DataFrame: (3421083, 7)
My plan is to delete all rows that contain a certain value (customer id) Here is how I proceed:
#keep track of iterations
track = 0

#import all transactions (orders.csv)
transactions = pd.read_csv('transactions.csv')

#We select all orders that are electronics orders and put them into a df
is_electronics = transactions[transactions.type == "electronics"]

#Create arrays that will store users to destroy in transactions.csv
users_to_remove = []

#iterate to add appropriate values:

#  we add all users that ordered electronics  to a list
for user in is_electronics.user_id:
    users_to_remove.append(user)

#We delete from orders.csv
for user in users_to_remove:
    transactions = transactions[transactions.user_id != user]
    track += 1
    if track == 100000:
        print(track)
        track = 0

transactions.to_csv('not_electronics.csv', index = False)

This operation takes ages im running it since 1 hour and it still didnt finish.
I have a quad core desktop i5 with 3.2 ghz and 8gb of ram. But in the activity monitor, the computer only uses 5 gbs of ram and 40% of my cpu.
Is there any way to speed up the computation of this process? Either by changing the code or using other libraries?
I also have a gpu (gtx 970) can I use it to process this?
Thank you.

A: Use isin
is_electronics = transactions.type == 'electronics'
users_to_remove = transactions.loc[is_electronics, 'user_id'].unique()
transactions[~transactions.user_id.isin(users_to_remove)]

Deleted Prior Suggestion that was here to be safe

For posterity, this is @DSM's suggestion
is_electronics = transactions.type.values == 'electronics'
users = transactions.user_id.values
transactions[~np.in1d(users, users[is_electronics])]


text:
Q: iOS Swift app - 24 hour format from Settings app is not respected for Germany and France I have to display date and time in an iOS app based on locale (Region) and time format (24-Hour vs 12-Hour) set in the device Settings app.
I am using below code for the same :-
class func getDateTimeString(_ fromDate: Date?) -> String {
    var dateTimeString = ""
    if let date = fromDate {
        let format = DateFormatter()
        format.timeZone = .current
        format.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMM dd, YYYY hh:mm a", options: 0, locale: Locale.current)
        dateTimeString = format.string(from: date)
    }
    return dateTimeString
}

This works good to display date as per any locale (Region) set in Settings app. Like for India, it displays date as dd-mmm-yyyy. For US - mmm dd, yyyy. For Germany - dd. mmm yyyy
However, as per time format this works good for regions like US, UK, India, Australia but not for France and Germany. As in it displays the time in 12-hour (AM/PM) format or 24-hour format based on what is selected in the Settings app for US, UK, India and Australia but for Germany and France it displays time only in 12-hour format with AM and PM, irrespective of what is set in time format in Settings app.
Is this expected? If yes, why? If no, what am I missing here? I observed one thing though. Changing the Region to US, UK, India, Australia in Settings changes the time format automatically to 12 hour format under Date&Time settings. However, it remains 24-hour format when changing region to Germany or France.
To resolve the 12-hour format issue for regions like Germany and France, I took cues from https://stackoverflow.com/a/49438640/3148811 and had to modify above code to -
class func getDateTimeString(_ fromDate: Date?) -> String {
    var dateTimeString = ""
    if let date = fromDate {
        let format = DateFormatter()
        format.timeZone = .current
        if let dateFormatterString = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current), dateFormatterString.firstIndex(of: "a") != nil {
            format.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMM dd, YYYY hh:mm a", options: 0, locale: Locale.current)
        } else {
            format.dateFormat = DateFormatter.dateFormat(fromTemplate: "MMM dd, YYYY HH:mm", options: 0, locale: Locale.current)
        }
        dateTimeString = format.string(from: date)
    }
    return dateTimeString
}

Is this a good way to resolve the same?


text:
Q: How to get sparse graph Laplacian matrix in python? I have a sparse matrix A in csr_matrix format. A is the weighted adjacency matrix of an undirected graph and thus symmetric and nonnegative. I want to calculate its graph Lapalican.
I used to work with MATLAB, where the code is pretty simple:
L = diag(sum(A,2)) - A   % or L=diag(sum(A))-A because A is symmetric

But how can we do it in Python? I am new to sparse matrices in Python. I can only come up with a quite ugly solution:
import numpy as np
import scipy.sparse as sps
L = sps.diags(np.reshape(np.array(A.sum(axis=1)), A.shape[0])) - A

Does anyone know a more elegant solution?

A: This is how the networkX library does it for a sparse matrix A - very similar to your method with small improvements (keeping everything sparse):
n,m = A.shape
diags = A.sum(axis=1)
D = sps.spdiags(diags.flatten(), [0], m, n, format='csr')
D - A


text:
Q: Borrow checker issue in `zip`-like function with a callback I'm trying to implement a function that steps though two iterators at the same time, calling a function for each pair. This callback can control which of the iterators is advanced in each step by returning a (bool, bool) tuple. Since the iterators take a reference to a buffer in my use case, they can't implement the Iterator trait from the stdlib, but instead are used though a next_ref function, which is identical to Iterator::next, but takes an additional lifetime parameter.
// An iterator-like type, that returns references to itself
// in next_ref
struct RefIter {
    value: u64
}

impl RefIter {
    fn next_ref<'a>(&'a mut self) -> Option<&'a u64> {
        self.value += 1;
        Some(&self.value)
    }
}

// Iterate over two RefIter simultaneously and call a callback
// for each pair. The callback returns a tuple of bools
// that indicate which iterators should be advanced.
fn each_zipped<F>(mut iter1: RefIter, mut iter2: RefIter, callback: F)
    where F: Fn(&Option<&u64>, &Option<&u64>) -> (bool, bool)
{
    let mut current1 = iter1.next_ref();
    let mut current2 = iter2.next_ref();
    loop {
        let advance_flags = callback(&current1, &current2);
        match advance_flags {
            (true, true) => {
                current1 = iter1.next_ref();
                current2 = iter2.next_ref();
            },
            (true, false) => {
                current1 = iter1.next_ref();
            },
            (false, true) => {
                current2 = iter1.next_ref();
            },
            (false, false) => {
                return
            }
        }
    }
}

fn main() {
    let mut iter1 = RefIter { value: 3 };
    let mut iter2 = RefIter { value: 4 };
    each_zipped(iter1, iter2, |val1, val2| {
        let val1 = *val1.unwrap();
        let val2 = *val2.unwrap();
        println!("{}, {}", val1, val2);
        (val1 < 10, val2 < 10)
    });
}

error[E0499]: cannot borrow `iter1` as mutable more than once at a time
  --> src/main.rs:28:28
   |
22 |     let mut current1 = iter1.next_ref();
   |                        ----- first mutable borrow occurs here
...
28 |                 current1 = iter1.next_ref();
   |                            ^^^^^ second mutable borrow occurs here
...
42 | }
   | - first borrow ends here

error[E0499]: cannot borrow `iter2` as mutable more than once at a time
  --> src/main.rs:29:28
   |
23 |     let mut current2 = iter2.next_ref();
   |                        ----- first mutable borrow occurs here
...
29 |                 current2 = iter2.next_ref();
   |                            ^^^^^ second mutable borrow occurs here
...
42 | }
   | - first borrow ends here

error[E0499]: cannot borrow `iter1` as mutable more than once at a time
  --> src/main.rs:32:28
   |
22 |     let mut current1 = iter1.next_ref();
   |                        ----- first mutable borrow occurs here
...
32 |                 current1 = iter1.next_ref();
   |                            ^^^^^ second mutable borrow occurs here
...
42 | }
   | - first borrow ends here

error[E0499]: cannot borrow `iter1` as mutable more than once at a time
  --> src/main.rs:35:28
   |
22 |     let mut current1 = iter1.next_ref();
   |                        ----- first mutable borrow occurs here
...
35 |                 current2 = iter1.next_ref();
   |                            ^^^^^ second mutable borrow occurs here
...
42 | }
   | - first borrow ends here

I understand why it complains, but can't find a way around it. I'd appreciate any help on the subject.
Link to this snippet in the playground.

A:
Since the iterators take a reference to a buffer in my use case, they can't implement the Iterator trait from the stdlib, but instead are used though a next_ref function, which is identical to Iterator::next, but takes an additional lifetime parameter.

You are describing a streaming iterator. There is a crate for this, aptly called streaming_iterator. The documentation describes your problem (emphasis mine):

While the standard Iterator trait's functionality is based off of
  the next method, StreamingIterator's functionality is based off of
  a pair of methods: advance and get. This essentially splits the
  logic of next in half (in fact, StreamingIterator's next method
  does nothing but call advance followed by get).
This is required because of Rust's lexical handling of borrows (more
  specifically a lack of single entry, multiple exit borrows). If
  StreamingIterator was defined like Iterator with just a required
  next method, operations like filter would be impossible to define.

The crate does not currently have a zip function, and certainly not the variant you have described. However, it's easy enough to implement:
extern crate streaming_iterator;

use streaming_iterator::StreamingIterator;

fn each_zipped<A, B, F>(mut iter1: A, mut iter2: B, callback: F)
where
    A: StreamingIterator,
    B: StreamingIterator,
    F: for<'a> Fn(Option<&'a A::Item>, Option<&'a B::Item>) -> (bool, bool),
{
    iter1.advance();
    iter2.advance();

    loop {
        let advance_flags = callback(iter1.get(), iter2.get());
        match advance_flags {
            (true, true) => {
                iter1.advance();
                iter2.advance();
            }
            (true, false) => {
                iter1.advance();
            }
            (false, true) => {
                iter1.advance();
            }
            (false, false) => return,
        }
    }
}

struct RefIter {
    value: u64
}

impl StreamingIterator for RefIter {
    type Item = u64;

    fn advance(&mut self) {
        self.value += 1;
    }

    fn get(&self) -> Option<&Self::Item> {
        Some(&self.value)
    }
}

fn main() {
    let iter1 = RefIter { value: 3 };
    let iter2 = RefIter { value: 4 };
    each_zipped(iter1, iter2, |val1, val2| {
        let val1 = *val1.unwrap();
        let val2 = *val2.unwrap();
        println!("{}, {}", val1, val2);
        (val1 < 10, val2 < 10)
    });
}

A: The issue with this code is that RefIter is being used in two ways, which are fundamentally at odds with one another:

*

*Callers of next_ref recieve a reference to the stored value, which is tied to the lifetime of RefIter

*RefIter's value needs to be mutable, so that it can be incremented on each call

This perfectly describes mutable aliasing (you're trying to modify 'value' while a reference to it is being held) - something which Rust is explicitly designed to prevent.
In order to make each_zipped work, you'll need to modify RefIter to avoid handing out references to data that you wish to mutate.
I've implemented one possibility below using a combination of RefCell and Rc:
use std::cell::RefCell;
use std::rc::Rc;

// An iterator-like type, that returns references to itself
// in next_ref
struct RefIter {
    value: RefCell<Rc<u64>>
}

impl RefIter {
    fn next_ref(&self) -> Option<Rc<u64>> {
        let new_val = Rc::new(**self.value.borrow() + 1);
        *self.value.borrow_mut() = new_val;
        Some(Rc::clone(&*self.value.borrow()))
    }
}

// Iterate over two RefIter simultaniously and call a callback
// for each pair. The callback returns a tuple of bools
// that indicate which iterators should be advanced.
fn each_zipped<F>(iter1: RefIter, iter2: RefIter, callback: F)
    where F: Fn(&Option<Rc<u64>>, &Option<Rc<u64>>) -> (bool, bool)
{
    let mut current1 = iter1.next_ref();
    let mut current2 = iter2.next_ref();
    loop {
        let advance_flags = callback(&current1, &current2);
        match advance_flags {
            (true, true) => {
                current1 = iter1.next_ref();
                current2 = iter2.next_ref();
            },
            (true, false) => {
                current1 = iter1.next_ref();
            },
            (false, true) => {
                current2 = iter1.next_ref();
            },
            (false, false) => {
                return
            }
        }
    }
}

fn main() {
    let iter1 = RefIter { value: RefCell::new(Rc::new(3)) };
    let iter2 = RefIter { value: RefCell::new(Rc::new(4)) };
    each_zipped(iter1, iter2, |val1, val2| {
        // We can't use unwrap() directly, since we're only passed a reference to an Option
        let val1 = **val1.iter().next().unwrap();
        let val2 = **val2.iter().next().unwrap();
        println!("{}, {}", val1, val2);
        (val1 < 10, val2 < 10)
    });
}

This version of RefIter hands out Rcs to consumers, instead of references. This avoids the issue of mutable aliasing - updating value is done by placing
a new Rc into the outer RefCell. A side effect of this is that consumers are able to hold onto an 'old' reference to the buffer (through the returned Rc), even after RefIter has advanced.


text:
Q: Enabling Metrics with External Timings in Esper We're using Esper and Metrics Reporting are not working while external timings are enabled. When I disable the external timings, the metrics are back working again.
UpdateListener statsListener = this;

esper.getEpAdministrator().createEPL("select * from
com.espertech.esper.client.metric.EngineMetric",
QQQ_ENGINE_METRIC).addListener(statsListener);
esper.getEpAdministrator().createEPL("select * from
com.espertech.esper.client.metric.StatementMetric",
QQQ_STATEMENT_METRIC).addListener(statsListener);

//...

@Override
public void update(EventBean[] arg0, EventBean[] arg1) {
log.info("arg0 " + arg0 + ((arg0 != null) ? arg0.length : 0));
}

And I get no log output on the update method.
My esper.xml settings:
  <engine-settings>
    <defaults>
      <metrics-reporting enabled="true" jmx-engine-metrics="true"
engine-interval="1000" statement-interval="1000" threading="true"/>
    </defaults>
  </engine-settings>

We're using CurrentTimeSpanEvent as an external timing source.
esper.sendEvent(new CurrentTimeSpanEvent(lastEsperTime, 250));

We need external timings because we're running some automated tests on new EPL directives with old data and events, and the data rate on the tests are different than with the live data.
I also tried changing the CurrentTimeSpanEvent to a series of CurrentTimeEvents events:
if (originalEsperTime < lastEsperTime) {
    long tmptt = originalEsperTime;
    while (tmptt < lastEsperTime) {
        esper.sendEvent(new CurrentTimeEvent(tmptt));
        tmptt += 250;
    }
    esper.sendEvent(new CurrentTimeEvent(tmptt));
}

A: Perhaps you forgot to configure or set external-timer on? Or you forgot to set the time before creating statements? If you can provide a complete test class and not just code snippets this issue could probably be resolved by looking at the code.

A: Esper external timings should be initialized, initially, from the current system time, ie System.currentTimeMillis(). This is a basic use case where the metrics fail:
public class Main implements UpdateListener {
    public static class TestEvent {
        public TestEvent(String name) {
            this.name = name;
        }

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    private EPServiceProvider esper;
    private EPAdministrator epAdministrator;
    private EPRuntime epRuntime;

    private boolean externalTiming = true;
    private long currentTimeExternal;

    public void update(EventBean[] arg0, EventBean[] arg1) {
        if (arg0 != null && arg0.length > 0)
            System.out.println(new Date().toString() + " arg0: " + arg0[0]);
    }

    public void run() {
        Configuration esperConfig = new Configuration();
        esperConfig.configure(new java.io.File("esper.xml"));

        esper = EPServiceProviderManager.getProvider("AsantosEsperTest",
                esperConfig);
        epAdministrator = esper.getEPAdministrator();
        epRuntime = esper.getEPRuntime();

        // This breaks metrics. For the metrics to work, the initial timing
        // event on external timing should be system time at engine
        // initialization.
        currentTimeExternal = 0;

        initializeExternalTiming();
        initializeMetrics();
        initializeEventType();
        initializeStatements();

        while (true) {
            epRuntime.sendEvent(new TestEvent("QQQ"));

            if (externalTiming) {
                epRuntime.sendEvent(new CurrentTimeSpanEvent(
                        currentTimeExternal));
                currentTimeExternal += 150 * 2;
            }

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

    private void initializeStatements() {
        epAdministrator.createEPL("select * from TestEvent").addListener(this);
    }

    private void initializeMetrics() {
        epAdministrator.createEPL(
                "select * from com.espertech.esper.client.metric.EngineMetric")
                .addListener(this);
        epAdministrator
                .createEPL(
                        "select * from com.espertech.esper.client.metric.StatementMetric")
                .addListener(this);
    }

    private void initializeExternalTiming() {
        if (externalTiming) {
            epRuntime.sendEvent(new TimerControlEvent(
                    TimerControlEvent.ClockType.CLOCK_EXTERNAL));
            epRuntime.sendEvent(new CurrentTimeEvent(currentTimeExternal));
        }
    }

    private void initializeEventType() {
        epAdministrator.getConfiguration().addEventType(TestEvent.class);
    }

    public static void main(String[] args) {
        Main m = new Main();
        m.run();
    }
}

esper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<esper-configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://www.espertech.com/schema/esper"
  xsi:schemaLocation=
    "http://www.espertech.com/schema/esper/esper-configuration-2.0.xsd">
  <engine-settings>
    <defaults>
      <metrics-reporting enabled="true" jmx-engine-metrics="true" engine-interval="1000" statement-interval="1000" threading="false"/>
    </defaults>
  </engine-settings>
</esper-configuration>


text:
Q: C++ design pattern platform specific api I am working on Windows. I have to see certain set of API's for Windows 2008 and above and different set of API's for other flavors of Windows. I want to know what is the best way to design such kind of stuff, so that my main driver code do not have #ifdef
For Example:
In Windows 2008 We have API
EVT_HANDLE WINAPI EvtOpenLog(
  __in  EVT_HANDLE Session,
  __in  LPCWSTR Path,
  __in  DWORD Flags
);

and For Windows 2003 we have another API which does the same.
HANDLE OpenEventLog(
  __in  LPCTSTR lpUNCServerName,
  __in  LPCTSTR lpSourceName
);

What I am looking for is having some kind of wrapper API in my code which internally handles these calls.

A: You can write an Platform Abstraction Layer, which will expose a common interface for all api types and for each port then you can implement the interface. You can provide the abstraction as an separate library for each port which ensures that your calling application remains the same only the library to be linked changes.

A: One approach would be to have an interface in a header that doesn't change and to have separate .cpp's for each platform that you require.  You then compile only the .cpp that you need for a given platform.
A second approach is to have a single base class interface that doesn't change and to have subclasses that modify code as necessary through virtual functions, but I don't recommend this approach.
Yet another approach would be to use something like the PIMPL (pointer to implementation) idiom.  This approach will allow your header interface to never change and will also hide all platform-specific data in a private class implementation. Here's a semi-decent article on this design pattern.


text:
Q: How to put a Node.js variable inside my ? PROBLEM:
I have some Firebase code in a script tag, but it doesn't execute. How should I write my <%=id%> variable in it ?
Normally, when I click the button, a request should be fired to update the upvote value in Firebase, but nothing happens.
The code doesn't execute but I get no errors.

CODE:
file.ejs

<%=post.title %>

        <img class = "postImg"  src="/images/uploads/<%= post.image %>">
           <%= post.upvotes - post.downvotes%> HP

Here is the router file.
file.js
var express = require("express");
var router = express.Router();

var firebase = require("firebase");

router.get('/details/:id', function(req, res){
    global.page_name = "fun";
    var id = req.params.id;
    var funPostRef = firebase.database().ref("posts/fun/"+id);

    funPostRef.once('value', function(snapshot){
        var funPost = snapshot.val();
        res.render('fun/details', {post: funPost, id:id});
    });
});

module.exports = router;

N.B.: Firebase is also initialised in my app.js file.
EDIT:
If I try this version of the code, the firebase request is triggered every time I reload the page, not when I click. How can I make sure it is triggered only when I click ?
<% var upvotesRef =  firebase.database().ref("posts/fun/"+id+"/upvotes");
var downvotesRef = firebase.database().ref("posts/fun/"+id+"/downvotes"); %>

$('.UpvoteButton').click(function () {
      <% upvotesRef.transaction(function (upvotes) {
          if (!upvotes) {
             upvotes = 0;
          }
             upvotes = upvotes + 1;
             return upvotes;
      }); %>
   });

EDIT 2:
Found the error ! What does it mean ?

This is very weird since I am authenticated when I click the button and these are my security rules:
{
  "rules": {
    ".read": "true",
    ".write": "auth != null"
  }
}

EDIT 3:
I also get the following (non crashing) error message before:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
EDIT 4:
If I change my rules to:
{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}

The button works perfectly !
But how come the code doesn't work with the previous rule although I am authenticated ???

A: Since you're using a templating language you don't need the + operators:
var upvotesRef =  firebase.database().ref("posts/fun/<%=id%>/upvotes");

A: You could try to "echo" the id with <%- id %>
sadly I can not comment (not enough rep) otherwise I would have asked if you see the id if you inspect the button.


text:
Q: Compute the residue of the quotient $\frac{f(z)}{g(z)}$ at $a$.
Let $f,g \in H(D(a;r))$ and assume that $f$ has a zero of order $m$ and $g$ a zero of order $m+1$ at $a$. Prove that
  $$\mathrm{Res}\left(\frac{f(z)}{g(z)}, a\right)=(m+1)\frac{f^{(m)}(a)}{g^{(m+1)}(a)}$$

What I did first was writing
$$f(z)=\frac{h_1(z)}{(z-a)^m} \; g(z)=\frac{h_2(z)}{(z-a)^m}$$
where both $h_1, h_2$ are holomorphic on the open disc and $h_1(a)\neq 0, h_2(a)\neq 0$. Then, by the Cauchy Formula for derivatives
$$\begin{align*}
(m+1)\frac{f^{(m)}(a)}{g^{(m+1)}(a)} &= (m+1) \frac{\frac{m!}{2\pi i}\int_{\gamma(a;r/2)}\frac{h_1(z)}{(z-a)^{m+1}} dz }{\frac{(m+1)!}{2\pi i}\int_{\gamma(a;r/2)}\frac{f(z)}{(z-a)^{m+2}} dz}\\
&= \frac{(m+1)!}{(m+1)!}\int_{\gamma(a;r/2)}\frac{f(z)}{g(z)} dz\\
&= \int_{\gamma(a;r/2)} \frac{f(z)}{g(z)} dz\\
&= 2\pi i\cdot \mathrm{Res} \left( \frac{f(z)}{g(z)} ; a\right)
\end{align*}$$
so I get and extra factor $2\pi i$ and I don't know what I did wrong. Any help would be great with that.

A: I can't follow what you're doing. Me, I would let $f(z) = (z-a)^m(c_m + c_{m+1}(z-a) +\cdots),$ $ g(z) = (z-a)^{m+1}(d_{m+1}+ d_{m+2}(z-a)+ \cdots),$ where $c_m, d_{m+1} \ne 0.$ Thus for $z$ near $a,z\ne a,$
$$\frac{f(z)}{g(z)} = \frac{1}{z-a}\cdot \frac{c_m + c_{m+1}(z-a) +\cdots}{d_{m+1} +d_{m+2}(z-a)+ \cdots} = \frac{1}{z-a}\cdot h(z).$$
Now $h$ is the quotient of holomorhic functions that are both nonzero at $a,$ so $h(z)$ extends to be holomorphic near $a,$ with $h(z) = h(a) + h'(a)(z-a) + \cdots$ there. So
$$\frac{f(z)}{g(z)} = \frac{h(a)}{z-a} + h'(a) + \cdots.$$
Thus the residue of $f/g$ at $a$ is $h(a) = c_{m}/d_{m+1}.$ Since $c_m,d_{m+1}$ are Taylor coefficients of $f,g,$ we get the result.


text:
Q: Splitting a string of bytes to vector of BYTES in C++ I have a string of bytes that looks like the following:
"1,3,8,b,e,ff,10"

How would I split this string into an std::vector of BYTEs containing the following values:
[ 0x01, 0x03, 0x08, 0x0b, 0x0e, 0xff, 0x10 ]
I'm trying to split the string using ',' as the delimiter, but I'm having some trouble getting this to work.  Can someone give me a helping hand on how to accomplish this?
So I have tried this:
    std::istringstream iss("1 3 8 b e ff 10");
    BYTE num = 0;
    while(iss >> num || !iss.eof())
    {
        if(iss.fail())
        {
            iss.clear();
            std::string dummy;
            iss >> dummy;
            continue;
        }
        dataValues.push_back(num);
    }

But this pushes the ascii byte values into the vector:
49 //1
51 //3
56 //8
98 //b
101 //e
102 //f
102 //f
49 //1
48 //0

I'm instead trying to fill the vector with:
 0x01
 0x03
 0x08
 0x0b
 0x0e
 0xff
 0x10

A: You've just been missing to adapt some small issues appearing with your use case for the linked answer from my comment:
    std::istringstream iss("1,3,8,b,e,ff,10");
    std::vector<BYTE> dataValues;

    unsigned int num = 0; // read an unsigned int in 1st place
                          // BYTE is just a typedef for unsigned char
    while(iss >> std::hex >> num || !iss.eof()) {
        if(iss.fail()) {
            iss.clear();
            char dummy;
            iss >> dummy; // use char as dummy if no whitespaces
                          // may occur as delimiters
            continue;
        }
        if(num <= 0xff) {
            dataValues.push_back(static_cast<BYTE>(num));
        }
        else {
            // Error single byte value expected
        }
    }

You can see the fully working sample here on ideone.

A: A working sample code (Tested in GCC 4.9.0 with C++11):
The file save.txt contain: 1,3,8,b,e,ff,10 as the first and unique line.
Output:
1
3
8
b
e
ff
10

The idea is:

*

*Use std::getline to read line by line.

*Use boost::split to split the line according to the separator.

*User std::stringstream to convert from hex string to unsigned char.

Code:
#include <fstream>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/lexical_cast.hpp>

int main(int argc, char* argv[]) {
    std::ifstream ifs("e:\\save.txt");

    std::string line;
    std::vector<std::string> tokens;
    std::getline(ifs, line);
    boost::split(tokens, line, boost::is_any_of(","));

    std::vector<unsigned char> values;
    for (const auto& t : tokens) {
        unsigned int x;
        std::stringstream ss;
        ss << std::hex << t;
        ss >> x;

        values.push_back(x);
    }

    for (auto v : values) {
        std::cout << std::hex << (unsigned long)v << std::endl;
    }

    return 0;
}

A: Just to demonstrate another, probably much faster, way of doing things consider reading everything into an array and using a custom iterator to do the converting.
class ToHexIterator : public std::iterator<std::input_iterator_tag, int>{
    char* it_;
    char* end_;
    int current_;
    bool isHex(const char c){
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
    }
    char toUpperCase(const char c){
        if (c >= 'a' && c <= 'f'){
            return (c - 'a') + 'A';
        }
        return c;
    }
    int toNibble(const char c){
        auto x = toUpperCase(c);
        if (x >= '0' && x <= '9'){
            return x - '0';
        }
        else {
            return (x - 'A') + 10;
        }
    }
public:
    ToHexIterator() :it_{ nullptr }, end_{ nullptr }, current_{}{}                  //default constructed means end iterator
    ToHexIterator(char* begin, char* end) :it_{ begin }, end_{ end }, current_{}{
        while (!isHex(*it_) && it_ != end_){ ++it_; };  //make sure we are pointing to valid stuff
        ++(*this);
    }
    bool operator==(const ToHexIterator &other){
        return it_ == nullptr && end_ == nullptr && other.it_ == nullptr && other.end_ == nullptr;
    }
    bool operator!=(const ToHexIterator &other){
        return !(*this == other);
    }
    int operator*(){
        return current_;
    }
    ToHexIterator & operator++(){
        current_ = 0;
        if (it_ != end_) {
            while (isHex(*it_) && it_ != end_){
                current_ <<= 4;
                current_ += toNibble(*it_);
                ++it_;
            };
            while (!isHex(*it_) && it_ != end_){ ++it_; };
        }
        else {
            it_ = nullptr;
            end_ = nullptr;
        }
        return *this;
    }
    ToHexIterator operator++(int){
        ToHexIterator temp(*this);
        ++(*this);
        return temp;
    }
};

The basic use case would look like:
char in[] = "1,3,8,b,e,ff,10,--";
std::vector<int> v;
std::copy(ToHexIterator{ std::begin(in), std::end(in) }, ToHexIterator{}, std::back_inserter(v));

Note that it may be faster to use a look up table to do the ascii to hex nibble conversion.
Speed can be VERY dependent on compiler optimization and platform, however because some of the istringstream functions are implemented as virtuals or pointer to functions (depending on the standard library implementation) the optimizer has trouble with them. In my code there are no victuals or function pointers and the only loop is inside the std::copy implementation which the optimizer is used to dealing with. Its also generally faster to loop until two addresses are equal rather than loop until the thing some changing pointer points to is equal to something. At the end of the day its all speculation and voodoo but on MSVC13 on my machine mine is about 10X faster. Here is a live example http://ideone.com/nuwu15 on GCC which is somewhere between 10x and 3x depending on the run and depending on which test goes first (probably because of some caching effects).
All in all there is undoubtedly more room for optimization etc. and anyone who says "mine is always faster" at this level of abstraction is selling snake oil.
Update: using a compile time generated look up table increases speed further: http://ideone.com/ady8GY (note that I increased the size of the input string to decrease noise so this is not directly comparable to the above example)


text:
Q: How can one use ffmpeg to position a video exactly at a specific pixel position in jpeg? For example,

*

*there is a jpeg with dimensions 1900x1000 and it has a frame (a rectangle) with pixel coordinates 490x100 and 1400x500

*a video with resolution 720p needs to be placed within this rectangle

Could you pls share the ffmpeg command to concatenate the jpeg and video? I tried -hstack and -xstack filters. But, couldn't get the video inside the rectangle.
TIA

A: Your rectangle has a size of 910x400, so you have to downscale the 1280x720 video to fit. But the aspect ratios do not match. So you need to also pad or crop the 1280x720 video to properly fit inside 910x400 if you want to preserve the aspect ratio.
Combine these answers:

*

*Resizing videos with ffmpeg to fit into static size

*How to overlay with ffmpeg?
Crop to fit
ffmpeg -i image.jpg -i video.mp4 -filter_complex "[1]scale=910:400:force_original_aspect_ratio=increase,crop=910:400[fg];[0][fg]overlay=x=490:y=100,format=yuv420p" -c:a copy -movflags +faststart output.mp4

Pad to fit
ffmpeg -i image.jpg -i video.mp4 -filter_complex "[1]scale=910:400:force_original_aspect_ratio=decrease,pad=910:400:-1:-1[fg];[0][fg]overlay=x=490:y=100,format=yuv420p" -c:a copy -movflags +faststart output.mp4

Squish/stretch to fit
This will ignore the aspect ratio and will result in a distorted image.
ffmpeg -i image.jpg -i video.mp4 -filter_complex "[1]scale=910:400,setsar=1[fg];[0][fg]overlay=x=490:y=100,format=yuv420p" -c:a copy -movflags +faststart output.mp4


text:
Q: Pyspark select column value by start with special string I use Spark 2 from PySpark. The dataframe looks like
a = [('n_a xxxx 1111',0), ('n_A xxsssxx 1211',0),('n_a 1111',0),('n_c xxxx 1111',0)]
a = spark.createDataFrame(a, ['des', 'id'])
a.show(10,False)

I would like to select the row which des_column starts with 'n_a'(case insensitive) and get the first 4 digits number to build a new column the result should looks like
b = [('n_a 1111', ), ('n_A 1211', ),('n_a 1111', )]
b = spark.createDataFrame(b, ['new_column'])
b.show(10, False)

A: You can use regexp_extract
from pyspark.sql.functions import *

r = ("(?i)"            # Case insensitive
     "^(n_a)"          # Leading n_a
     "(?:\s\S+\s|\s)"  # Either whitespace string whitespace or whitespace
     "([0-9]{4})")     # Four digit number

a.select("id", concat_ws(
    " ",
    regexp_extract("des", r, 1),  #  n_a prefix
    regexp_extract("des", r, 2)   #  number
).alias("new_column")).where(trim(col("new_column")) != "")

which gives:
+---+----------+
| id|new_column|
+---+----------+
|  0|  n_a 1111|
|  0|  n_A 1211|
|  0|  n_a 1111|
+---+----------+

A: Try the code snippet below:
from pyspark.sql.functions import concat_ws
from pyspark.sql.functions import regexp_extract
list = ['n_a', 'n_A']
a.where(a.des.substr(1, 3).isin(list)).select(concat_ws(' ', regexp_extract('des', '(\w\_\w).*(\d\d\d\d).*', 1), regexp_extract('des', '(\w\_\w).*(\d\d\d\d).*', 2)).alias('new_column')).show(10, False)

it gives you:
+----------+
|new_column|
+----------+
|n_a 1111  |
|n_A 1211  |
|n_a 1111  |
+----------+

Hope this solved your problem.
It mainly uses two functions:
where(a.des.substr(1, 3).isin(list))

for the reqirement "select column value by start with special string"
Then the concat:
concat_ws(' ', regexp_extract('des', '(\w\_\w).*(\d\d\d\d).*', 1), regexp_extract('des', '(\w\_\w).*(\d\d\d\d).*', 2)).alias('new_column')

for "get the first 4 digits number to build a new column", which is using regex:
(\w\_\w).*(\d\d\d\d).*

A: Try this:
import pyspark.sql.functions as f

a=a.withColumn('des_clean', f.regexp_replace('des', "\s([^\s]+)\s", " "))
a=a.withColumn('split',f.split(f.col('des_clean'), "\s"))
a=a.withColumn('first', f.col('split').getItem(0))
a=a.withColumn('second', f.col('split').getItem(1))
a=a.filter("first in ('n_a', 'n_A')")
a.select('des_clean').show(10)


text:
Q: Cost and Usage by Instance without manual tagging Question
I'm trying to get the cost of all instances, be that a db instance or web app, for a time period.
However at the moment I can only seem to retrieve the cost by service when using the AWS Cost Explorer.
Eventually I'm looking to access these costs via the Costs API automatically in a plug and play kind of way, so I wont know what tags have been applied or which ones I should use, thus why I want to avoid using tagging if possible.
Question
Is there a way to do this without manually assigning each instance a tag, and then grouping by said tag.


text:
Q: How to start the Remote Access service if get error 1068? When trying to start the Remote Access Connection Manager service, I always get an error message saying:

Error 1068: The dependency service or group failed to start.

I configured and included all dependencies listed here, but Remote Access Connection still won't start. Instead, other dependencies that are running as automatic start up.
I'm using Windows 7 64-bit.
Below is a screenshot of the error message:

A: Well I went through a lot of posts and I finally figured out that I had, last week, disabled Windows Event Log service. Turn that on and Joy to my World. That was the cause for all my grief.
Hope this helps.

A: Here is the best fix:

*

*Used msconfig to switch to safe mode boot

*Booted to safe mode

*Ran cmd.exe as an administrator

*Typed "cd C:\Windows\System32\LogFiles\WMI"

*Typed "rename RtBackup RtBackup2"

*Used msconfig to switch to normal boot mode

*Reboot and found event viewer working

A: I bet you can't open the Event Viewer in Administrative Tools too. I found out that Windows Event Log was disabled.
So in case to solve all this, go to

*

*Control Panel → Administrative Tools → Services → Windows Event Log

*Right-click "Properties → Startup type" if disabled, turn it on to automatic

Enabling this unblocks the opportunity to Enable/start the Remote Access Connection Manager and Remote Access Auto Connection Manager.
It worked for me.

A: FIXED!
After several days of absolute frustration, trying to fix this Error 1068 and related issues, I am overjoyed to have finally found a solution! Read further only if you are encountering Error 1068 or Error 5 AND are having trouble starting up the relevant services:
ISSUE DETAILS:
Basically my intent was to turn my laptop into a WiFi router, so I went through online tutorials which somehow didn't seem to work. When I got into troubleshooting mode, I found out that the ICS (Internet Connection Sharing) required a few services to be enabled and working properly. A couple of them were not started, so I fixed those, but then I encountered a couple of services which wouldn't start (Error 1068) even when I tried, I knew I was onto something.
THE FIX:
1) Enable all services as advised in the "Let me fix it myself" section of this page.
If you're having trouble finding Services, go to msconfig.exe (through Start Menu search) and then go to tab "Services"
2) If you encounter a problem (such as Error 1068) while trying to enable the service "Remote Access Connection Manager" like I did, then it may actually be dependent on the service "Windows Event Log", which in my case wasn't started and refused to start manually (Error 5, if I remember correctly). To start it, first change the security/permissions on the logs folder as described on this page
3) Then make sure you reboot, then start up the service "Windows Event Log", followed by the other offending services that weren't starting earlier. Once all relevant services are running, reboot again and you should be all set.
Last but not the least, don't forget to turn on your WiFi radio before you attempt to tether!
LONG STORY SHORT: the culprits are: services "Remote Access Connection Manager" and "Remote Access Auto Connection Manager", which depend on service "Windows Event Log", which depends on the correct permissions on folder %WINDIR%\System32\WinEvt\Logs
Let me know if this ends up working for you!

A: It's always a great idea to read the event logs.
From Event viewer > Windows log > System
You will see logs related to your problem. mine was like this:

The Remote Access Connection Manager service depends on the Secure
  Socket Tunneling Protocol Service service which failed to start
  because of the following error:  The operation completed successfully.

A: i had the same problem but i found the solution:
Step 1:
Make sure all the dependency services of "Remote Access Connection Manager"" are started in services list..
a. Click Start, type services.msc in the Start Search box.
b. Select Services in the Programs list. If you are prompted for an administrator password or confirmation, type your password or click Continue
c. Right-click Remote Access Connection Manager service and then click Properties.
d. On the General tab, click Manual next to Startup type.
e. On the General tab, click Start under Service status, and then click OK.
f. Also check for the Dependency services.
The following are the dependency services of "Remote Access Connection Manager":
i. Secure Socket Tunneling Protocol Service
ii. Telephony
iii. Plug and Play
iv. Remote Procedure Call (RPC)
v. DCOM Server Process Launcher
vi. RPC Endpoint Mapper
Make sure the above services are started in the services list. If not, start all of the above services and check.

A: Follow these instructions:

*

*Go to Start → Run → services.msc to open the Services control panel.

*For each of the following services, right-click on it, select Properties and set startup type to Manual or Automatic to enable the service:

*

*Remote Access Auto Connection Manager

*Remote Access Connection Manager

*Telephony

*Windows Remote Management (WS-Management)

*TCP/IP NetBIOS Helper

That should fix the problem.


text:
Q: Health check fails after switching from ALB to NLB? The health check in my target group fails after I switched my load balancer type from "application" to "network". I need to use the network load balancer in order to do a vpc link in api gateway. I attached a security group to my ALB but this is no longer needed for the NLB.
I understand the the NLB operates on Layer 4. My ALB listened for HTTPS on port 443 and the target group HTTP on port 80. Now, my NLB listens for TCP on port 80 and the target group TCP on port 80.
If I alter the security group attached to my EC2 instances and allow All TCP traffic from anywhere then the health check starts passing again. But, I don't want to allow traffic from anywhere. I also tried setting source to my vpc security group, but this did not work either.
Therefore, I am not sure what I should be setting source to in my security group. In my security group, is there a way I can restrict All TCP to just internal traffic? Does the NLB do something different to ALB which might be causing my health check to fail?

A: Ended up just using the cidr range of all subnets attached to the network load balancer.
It appears that for Network Load Balancers you have to just allow all traffic for everything in the NLB or restrict it to the cidr range of all subnets attached to the load balancer.


text:
Q: Cross Joining a Table on itself with Count I need to join a table on itself while joining other tables and doing count calculations on them. I'm using SQL Server 2008 R2 by the way.
Current State - I have three tables MergedSessionsID, EventsSeparated and EventsDescriptions.
MergedSessionsID, this is where I manipulate the data - the sessions essentially by specifying the Company Name and Session Time (see below for example of data).
EventsSeparated table links up with MergedSessionsID. Basically a Session can have one or many Events.
EventsDescription table contains the description of the event, e.g. this and that happend to the user.
My goal here is to understand the total number of events that happened for a certain period of time. Exhibit 1 is the result of running the query below.
However I also want to compare the old data to new data and see how the number of events changed. So as in Exhibit 2, this is what I imagine the view would like - showing the PreCounter for data in March, 2210 and PostCounter for data in April 2210.
What is the best way to implement this?
SELECT E.[Event]
      ,COUNT(1) AS Counter
      ,ED.[Event Description]
FROM [ShipCompanies].[dbo].MergedSessionsID AS S
    INNER JOIN [ShipCompanies].dbo.EventsSeparated AS E
        ON S.ID = E.ID
    INNER JOIN [ShipCompanies].dbo.EventDescription AS ED
        ON E.[Event] = ED.[Unique ID]
WHERE S.Company = 'SuperSpaceShipOne'
  AND S.[Session Time] BETWEEN '2210-03-02' AND '2210-03-05'
GROUP BY E.[Event], ED.[Event Description]
ORDER BY E.[Event]

SELECT * FROM MergedSessionsID
ID   Company             Session Time
1   SuperSpaceShipOne   2210-03-05
2   SuperSpaceShipOne   2210-03-03
3   SuperSpaceShipOne   2210-03-02
4   SuperSpaceShipOne   2210-04-01
5   SuperSpaceShipOne   2210-04-02
6   SuperSpaceShipOne   2210-04-03

SELECT * FROM EventsSeparated
ID  Event
1   2000
2   2001
2   2002
3   2001
4   2002
5   2002
6   2002

SELECT * FROM EventDescription
Unique ID   Event Description
2000        'User Entered the Pod'
2001        'User Initiated Launching Sequence'
2002        'User Error encountered'

Exhibit 1. Merged Output Summary Table (What I have now)
Event   Counter  Event Description
2000    1        'User Entered the Pod'
2001    2        'User Initiated Launching Sequence'
2002    1        'User Error encountered'

Exhibit 2. Merged Output Summary Table (What I want to get to)
Event  PreCounter   Event Description                  PostCounter
2000   1            'User Entered the Pod'              0
2001   2            'User Initiated Launching Sequence' 0
2002   1            'User Error encountered'            3

A: Select E.[Event]
    , Sum( Case
           When S.[Session Time] Between '2210-03-02' And '2210-03-05' Then 1
           Else 0 End ) As PreCounter
    , Sum( Case
           When S.[Session Time] Between '2210-04-02' And '2210-04-05' Then 1
           Else 0 End ) As PostCounter
      , ED.[Event Description]
From [ShipCompanies].[dbo].MergedSessionsID As S
    Join [ShipCompanies].dbo.EventsSeparated As E
        On S.ID = E.ID
    Join [ShipCompanies].dbo.EventDescription As ED
        On E.[Event] = ED.[Unique ID]
Where S.Company = 'SuperSpaceShipOne'
    And (
        S.[Session Time] Between '2210-03-02' And '2210-03-05'
        Or S.[Session Time] Between '2210-04-02' And '2210-04-05'
        )
Group By E.[Event], ED.[Event Description]
Order By E.[Event]


text:
Q: How to power a portable project with multiple components? I am working on a senior project and I have been tasked with the battery and power supply, and I am a newbie to power.
This will be an "iPad" sort of device, so ideally, we want a built-in battery that will power multiple components and have the ability to charge via wall outlet, or USB.
We have three main components to power: a touchscreen monitor (+12 VDC for backlight, +5 VDC for monitor), an FPGA (+7 - 15 VDC), and a microcontroller (+3.3 - 5 VDC). What is the best approach to this?

A: A lithium pack of 4S or 14.8V. Regulate down to 12V and 5V. Switch up the charging voltage as needed. Or take a look at existing devices with the same needs. Any number of iPad information, or Android tablet reference designs. A dedicated PMU, power management unit may be ideal. Look at Texas Instruments website for some ideas.
Also see if the back light can work at a lower voltage, and you may get away with a 3s battery instead.
Edit:
All iPads use multiple parallel cell 1S Lipo setups. In that case, you regulate the input voltage down and regulate the output up for 5V and 12V. Like any typical usb power bank, reference designs are everywhere.

A: First of all you have to know the characteristics of your system:

*

*voltage range and tolerances

*max current

*min operating time

*max charging time

*requirements for battery type (LiPo, Li-ion etc.) there are restrictions for certain industries

*max dimensions

*Any other requirements e.g. like switching off voltages individually is necessary

*costs

Only then you can decide what your final design will look like, whether you will use switched power supplies or linear regulators.


text:
Q: The "content" component has been registered but not used here is my App.vue
<template>
    <div>
        <top />
        <content />
    </div>
</template>

<script>
    import content from './components/content.vue'
    import top from './components/top.vue'
    export default {
        name: 'App',
        components: { top, content }
    }
</script>

<style>
    * {
        padding: 0;
        margin: 0;
    }
</style>

The lint keeps forming me that

The "content" component has been registered but not used.

However, I actually use it.
Can anyone tell me why this happens?


text:
Q: Typescript - How to declare anonymous object with known properties? In JS, a lot of my modules are just objects that wrap static functions, enums and properties. For example, I've got a module Debug which is similar to this (I really simplified it):
export default Debug = {
    // Current mode set, enum value from Modes. Setted outside of the module (see below).
    mode : null,

    // Enum of all possible modes
    Modes : {
        DEV : 0,
        PROD : 1,
    },

    // getter, checks if it's in production mode
    get isInProdMode() {
        return Debug.mode === Debug.Modes.PROD;
    },

    // If the condition is met, it will throw an error in development mode, or just silently log a warning in production mode
    assert : function(condition, message){
        if (condiftion) {
            if (Debug.isInProdMode)
                console.warn(message);
            else
                throw message;
        }
    }
}

// index.js
Debug.mode = Debug.Modes.DEV;

How can I make an anonymous object like this in Typescript? With an Enum as property? And a getter function? All properties are known.
I'm really stuck.

A: The way I've tended to resolve these scenarios is to just make interfaces for the properties of the anonymous objects, and then interfaces for the anonymous objects:
enum Modes {
    DEV     = 0,
    PROD    = 1,
}

interface IDebug {
    mode: Modes | null;
    Modes: typeof Modes;
    readonly isInProdMode: boolean;
    assert: (condition: boolean, message: string) => void;
}

const Debug: IDebug = {
    mode: null,
    Modes,
    get isInProdMode() {
        return Debug.mode === Debug.Modes.PROD;
    },
    assert: (condition, message) => {
        if (condition) {
            if (Debug.isInProdMode) {
                console.warn(message);
            } else {
                throw message;
            }
        }
    },
};

export default Debug;

A: I would say that the idiomatic way would be to use namespaces.
namespace Debug {
  export enum Modes { DEV, PROD }

  export var mode: Modes = Modes.DEV;

  export function isInProdMode(): boolean {
    return mode === Modes.PROD;
  }

  export function assert(condition: boolean, message: string) {
    if (condition) {
      if (isInProdMode()) {
        console.warn(message);
      } else {
        throw message;
      }
    }
  }
}

export default Debug

However, namespaces don't support getters and setters, so that getter would need to be converted into a regular function.
If you need to declare this code as an object, then you could define the enum first, then reference in from the object.
enum Modes { DEV, PROD }

const Debug = {
  mode: Modes = Modes.DEV,
  get isInProdMode(): boolean {
    return Debug.mode === Modes.PROD;
  },
  assert(condition: boolean, message: string) {
    // ...
  }
}

A: // index.js
import Debug from './debug';

Debug.mode = Debug.Modes.DEV;
console.log(Debug.isInProdMode);
// false


text:
Q: Is there any way to build ZeroMQ for emscripten? When I try to build zeromq c library to Emscripten, It produces an error which states that dynamic linking error : no such file or directory.
Is there any way to compile existing c library to Emscripten. Should i add any arguments along with the emconfigure step?
I tried to compile with the guidance of emscripten official page. Unfortunately i am still unclear about the build steps of c library to emscripten.
wget https://github.com/zeromq/libzmq/releases/download/v4.2.2/zeromq-4.2.2.tar.gz
./autogen.sh
emconfigure ./configure
emmake make
emmake make install
ldconfig

Shared Error: No dynamic linking  Shared Error : No input files

A: currently its not possible to build zeromq with emscripten.Possible way is you need to write your own zmq library that supports emscripten standard or have a look on other sources for building zeromq.


text:
Q: ZFC - Prove existence of set {A_1, A_2, A_3, ...} Good morning,
I am currently taking a course in axiomatic set theory and I have encountered a problem in showing the existence of a certain infinite (countable) set.
Let $A_1$, $A_2$, $A_3$, ... be a countably infinite number of given sets. How can I prove the existence of the set $\{A_1,A_2,A_3,...\}$? Which axioms do I need to use?
I have already made some research, but I have not found an explicit explanation on how to prove the existence of the above set. Its existence is usually simply assumed but not formally proven. I just know that the existence of the finite set $\{A_1,A_2,...,A_{n-1},A_n\}$ can be shown using the pairing and union axioms.
Thanks for your help!

A: Replacement.
You have the set of natural numbers, and for each natural number $i$ you have a unique $A_i$. It is the axiom of replacement which lets you "replace" each $i\in\Bbb N$ with the corresponding $A_i$ and still have a set.


text:
Q: Resolver doesn't work as expected I created a resolver and except that all components will load after the resolver will be finish to run, but the components are sometimes loaded before the resolver function is done.
The resolver code is:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { ApiService } from '../services';
import { AppState } from 'spotlightcloud-angular-common-website';
import { Locale } from '../locale/locale';

@Injectable()
export class MetricsLocaleResolver implements Resolve<any> {
  constructor(public api: ApiService, public appState: AppState, private locale: Locale) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
    return this.api.get('monitoring', 'uiconfiguration/metricsmetadata', {}).subscribe(
      localeData => {
        console.log('localeData: ', localeData);
        this.locale.setMetricsLocaleObj(localeData);
      }
    );
  }
}

The localeData print sometimes appears after the print in the component (in onChanges lifecycle).

A: Change
return this.api.get('monitoring', 'uiconfiguration/metricsmetadata', {}).subscribe(

to
return this.api.get('monitoring', 'uiconfiguration/metricsmetadata', {}).map(

If you call .subscribe() you return a Subscription, the router expects an Observable, Promise, or boolean value instead.
The callback also should return a boolean value
  localeData => {
    console.log("localeData:",localeData);
    this.locale.setMetricsLocaleObj(localeData);
    return true;
  }


text:
Q: How to get the id of the clicked row and using that id display that row's information-Using backbone.js I have a table and every tr has a button inside it. Now when I clicked that button I want to listen to the click event and display that tr's information on the page.
here is the html:

            Date

                Manage

            expiry

                Manage

Js:
$('.manage-cc').on("click", function() {
  var clicked = $(this).closest('tr'); //getting the tr clicked
   var manageCC = new manageCCModel([],{ id: id });
   manageCC.fetch({
    url: 'fetch/account/list',
    success: function(managecc){
        var manageCCTemplate = Mustache.render(manageCCTmpl, managecc.attributes.data);
        $("#account").html(manageCCTemplate);
});

Above im trying to fetch the information of the tr clicked, however in my case,no matter which 'tr' i click, it always displays the information of the first 'tr'. Also I'm able to listen to the click event above, but I'm not sure where to store that 'id' so that when the click occurs, the event will look for which 'tr' has been clicked and will display that information on the page.
http://jsfiddle.net/tLen4o7L/
Please find below the o/p of my html table:

Below is the place where, the button clicks and above is the image shown of the info page displayed on the click.....

here is the source:

      Manage

Please let me know of needed more details.
Any ideas how to achieve this??
Thanks

A: First you need to fix the html

           Expire Date:
           10 March 2015

                    <button class="button manage-cc">Manage</button>

           Card number:
           1111222233334444

                    <button class="button manage-cc">Manage</button>

With this html, you can do something like:
 $('.manage-cc').on("click", function() {
      var clickedrow = $(this).closest('tr');
      var descriptionCell = clickedrow.firstChild();
      var valueCell = descriptionCell.next();

      $("#account").html(descriptionCell.text() + " : " + valueCell.text() );
  });

Here is a simple demo : https://jsfiddle.net/tLen4o7L/1/

A: DEMO
Each of the button-containing divs need to be inside a td element.
To get the index of the row clicked use:
var index = $(this).closest('table').find('tr').index(clicked);

To get the id of the row clicked use:
var id = clicked.prop('id');

Bear in mind that your tr elements do not have ids.

A: in html you can have a data attribute on any tag.  you can use this to associate data with the element like this:

      Date

         Manage

       expiry

          Manage

now you can just look at the data of the "this" element in your event and know which row you are on.
some documentation:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes


text:
Q: How to generate a  list in Laravel without value attributes In order for my Select2 widgets to work properly, I need the very first option to have no value attribute and no text.  Having no text is not difficult with Laravel, of course, but having no value attribute seems to be impossible.  How can I make Laravel generate select lists without value attributes—at least for some of the options?

A: You will have to loop over the array/data object yourself and store the information in your own format.  Using Form::select() will generate this with the appropriate values already, simply replace with your own code to loop over them without the value attribute.


text:
Q: finishactivity not finishing the current activity I have activities called ACITIVTYA,ACITIVTYB,ACITIVTYC.
ACITIVTYB and ACITIVTYC extends ACTIVITYA
In ACITIVTYA which is the parent acitivty,i want to  reload the ACTIVITYB. i used the following code
finishActivity(1000);
Intent intent = new Intent(ACITIVTYB.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent,1000);

But the  finishActivity(1000); doesnot work, when the same ACTIVITYB is in the screen.
It works from different activity ie when ACTIVITYC is in the screen i can reload the ACTIVITYB. But When ACTIVITYB is in the screen i cannot reload the same ACTIVITYB.

A: You can use:
getActivity().setResult(350, null);
getActivity().finish();

A: if you want to finish your current activty yout must have to remove that from activity stack befire going to next screen fir that you have to use
youractivity.this.finish();


text:
Q: Ressurrection - Granted by which power? By what power, is resurrection granted?
Known resurrections:

*

*Thoros of Myr has resurrected Beric Dondarrion, no less than 6 times, but only after he lost his faith, indicating friendship is the key factor.

*Qyburn raised The Mountain. He's speculated to be undead, rather than alive, but he's walking and sentient, none the less. Qyburn is an ex-maester, and by no means religious.

*In Season 6 of the TV show but not the books (not up to A Dance With Dragons):

*
* Melisandre resurrects Jon Snow; she repeats the spell over and over, but nothing happens, until she utters the word "Please!", indicating she beseeched Jon to raise himself rather than asking her god.

* Benjen Stark was resurrected by the Children of the Forest and maintains his sentience and ability to speak

*

*In the books but not the TV show (not up to episode 9 of Season 6):

 Beric Dondarrion passed his life force to Lady Stoneheart while the red preist Thorros watched

So, do gods really play a role in resurrecting people? If not, what does?
An even more extreme example is how wights can be raised. In Season 5 of the TV show but not the books (not up to A Dance With Dragons):

 the Night King (maybe all White Walkers) can raise an entire battle field as wights, just by waving his hand...

A: The answer is: We do not know yet for sure because this enigma has neither been disclosed in books yet nor has it been been disclosed in Show. Aye that's the worst sort of answer but It is what it is. We gotta wait till new episodes and books to find the answer for sure (For both book and show canons)

Show
Jon's Resurrection: You are assuming that she was asking Jon to come to life, instead of asking her God. There is no evidence for your claim here. If she were to ask Jon, why bother with very long prayer and ritual? If on a cold morning my car does not start and I say "Please start", does it mean that I am asking the car to start on its own accord? It was just a way of expressing her dismay when it did not work as she had planned. Besides, Mel has already confirmed that she does not have the power to do it whenever she wants, R'hllor grants it to her if he wants to.
Night's King Raising Armies of Dead: We do not know much about the others. According to Melisandre, they are spawns of the Great other, the god of darkness whose name must not be uttered. If R'hllor (Lord of light) can grant this gift of resurrection to his followers, I suppose his rival god, Lord of darkness, can bestow a similar gift on his followers.

Books
The two events mentioned above never happened in books. But following two did.
Dondarrion's resurrection: Thoros of Myr did not lose his faith in his god. He never had much faith to begin with. He just followed a ritual following Beric's first death, which he had learnt as a red priest. To his own surprise, Lord of Light gave Beric back. Thoros also agrees he does not have the power, only his God decides who still has some work to do for him and thus sends the dead back.
From A Storm of Swords, Chapter 39, Arya's POV:

"Could you bring back a man without a head?" Arya asked. "Just the
  once, not six times. Could you?"
"I have no magic, child. Only prayers. That first time, his
  lordship had a hole right through him and blood in his mouth, I knew
  there was no hope. So when his poor torn chest stopped moving, I gave
  him the good god's own kiss to send him on his way. I filled my
  mouth with fire and breathed the flames inside him, down his throat to
  lungs and heart and soul. The last kiss it is called, and many a time
  I saw the old priests bestow it on the Lord's servants as they died.
  I had given it a time or two myself, as all priests must. But never
  before had I felt a dead man shudder as the fire filled him, nor seen
  his eyes come open. It was not me who raised him, my lady. It was the
  Lord. R'hllor is not done with him yet. Life is warmth, and warmth
  is fire, and fire is God's and God's alone."

Mountain's resurrection: Qyburn was stripped of his chain because he dabbled in study of necromancy and vivisection. But Qyburn learnt enough of the art to reanimate The Mountain. Qyburn's knowledge appears to be a combination of both magic and science. We can not say if the Mountain ever died in the first place. Qyburn might have found a way to keep him alive even after his head was sent to Dorne. Cersei noted that even at that time Qyburn was still experimenting and some foul thing was screaming in his chambers.
There are different sorts of magic in World of Ice and Fire. The Red Priests have their own magic, Children of Forest have their own magic, Valyrians had their own blood magic, Warlocks have their own magic etc etc. All these different types do not necessarily lead to one common source. We do not even know if gods are real in WOIAF or not but one thing is clear; the powers are real enough.


text:
Q: Python Google Voice API Login Error: AttributeError: 'NoneType' object has no attribute 'group' I was hoping somebody could help me figure out why I am getting this error when trying to login through the Google Voice API. I tried substituting the usr and pwd variables with the string literals and still got the same error. Please help!
from googlevoice import Voice
import keyring

if __name__ == '__main__':
    gv = Voice()
    usr = keyring.get_password('2', '2')
    pwd = keyring.get_password('1', '1')
    client = gv.login(usr,pwd)

Throws the following error:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "/Users/<usrname>/workingProjects/<projectname>/lib/python3.10/site-packages/googlevoice/voice.py", line 76, in login
    ).group(1)
AttributeError: 'NoneType' object has no attribute 'group'