text:
Q: A one-to-one function in a surjective composition is bijective. Suppose that $g \circ f$ is the composition of $f:X \to Y$ and $g:Y \to Z$. Suppose that $g \circ f$ is onto.

*

*Prove that if $g$ is one-to-one, then $g$ is bijective and $f$ is onto.

This is the last part of a series of problems stemming from the original statement; I proved that g is surjective, but this part of the problem has me stumped. Maybe it's something really obvious that I'm missing, but I generally don't have a good grasp on injections, surjections, and bijections, so maybe not.

A: Since you have already proved $g$ is onto and it is given that $g$ is one-one, $g$ must be bijective.
Suppose $f$ is not onto. Then $\exists y\in Y|y\notin f(X)$. Thus $g(y)\notin g(f(X))$ violating the surjectivity of $g\circ f$. Do you notice how we used the one-oneness of $g$ in this conclusion?


text:
Q: Firebase - get a list of data from two different nodes This is how the firebase data structure is:
    { "Entertainment":{
          "Book":{
                    0:{ id = 1234
                        genre = horror
                        // data of some object type
                      }
                    1:{ id = 2345
                        genre = romance
                      // data of some object type
                      }
                    2:{ id = 3456
                        genre = horror
                      // data of some object type
                      }
                 }
            "Movie":{
                    0:{ id = 6789
                        genre = horror
                        // data of some object type
                      }
                    1:{ id = 9876
                        genre = horror
                      // data of some object type
                      }
                    2:{ id = 0000
                        genre = action
                      // data of some object type
                      }
                 }
           }
  }

Now I want to get a list of all books and movies based upon the genre. To retrieve just the books/movies (one type of item) I am doing the following:
ItemService.prototype.getItems = function (searchOptions) {
    let _this = this;

    return bookRef
        .orderByKey()
        .once('value')
        .then(function (items) {
            let promises = [];
            let promise;
            let filteredItems = [];
            let item;
            let endTime = '';
            let genre = searchOptions.genre;

            items = items.val();

            for (let key in items) {
                if (items.hasOwnProperty(key) && items[key].genre &&
                    items[key].genre.toLowerCase() === genre.toLowerCase()) {

                    item = items[key];
                    items[key].itemId = key;

                    promise = Promise.resolve(item);
                    promise.then(function (item) {
                            if (!item) {
                                return;
                            }

                            filteredItemss.push({
                                itemId: item.itemId,
                                title: item.item_title,
                                genre: item.genre,
                                ..................
                            });
                        });

                        promises.push(promise);

                }
            }

            return Promise.all(promises)
                .then(function () {

                    filteredItems = _.sortBy(filteredItems, 'title');

                    return {
                        total: filteredItems.length,
                        results: filteredItems
                    };
                })
        });

Now, how can I get the list of another item and append the two lists together to return? Basically, what I want to do is, when user selects a genre, then it will show the user a list of all available books and movies under that genre. Can this be achieved? Any help is appreciated, TIA.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ошибка 400 (Bad Request) в AJAX Клиентская
<script>
$.ajax({
    type: 'POST',
    url: '/api/getlisteat',
    chache: false

});
</script>

Серверная:
    public function actionGetlisteat()
    {

        $file = json_decode(

file_get_contents('../use_config/config.json'), true)['eat'];
        return json_encode($file);
    }

A: У вас в Ajax POST. Способ получения данных для метода контроллера не задан, стало быть, по умолчанию - GET. Нужно согласовать

A: Вот мой вариант:
chache == cache ? true : false )


text:
Q: illegalargumentexception - Project running on Netbeans but not on Tomcat as War file I made a project on Netbeans on my local machine with JDK 1.7 (32-bit)
On running the application (using tomcat 8.0 server on netbeans), it works perfectly on http://localhost:8080/WebApplication1.
I copied the war file from the dist directly and transferred it to my Windows VM server with tomcat 8.0 and jdk 1.8 installed (64-bit). Then the war file was uploaded through tomcat's manager web app.
Note: 'localhost:8080/' and 'localhost:8080/manager' ran without any issue.
However, when I go and run the application (http://localhost:8080/WebApplication1) - it throws the following errors.
org.apache.jasper.JasperException: Unable to compile class for JSP
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:579)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause
java.lang.IllegalArgumentException: Page directive: invalid value for import
    org.apache.jasper.compiler.Node$PageDirective.validateImport(Node.java:610)
    org.apache.jasper.compiler.Node$PageDirective.addImport(Node.java:593)
    org.apache.jasper.compiler.Parser.parsePageDirective(Parser.java:344)
    org.apache.jasper.compiler.Parser.parseDirective(Parser.java:458)
    org.apache.jasper.compiler.Parser.parseFileDirectives(Parser.java:1782)
    org.apache.jasper.compiler.Parser.parse(Parser.java:136)
    org.apache.jasper.compiler.ParserController.doParse(ParserController.java:227)
    org.apache.jasper.compiler.ParserController.parseDirectives(ParserController.java:117)
    org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:194)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:356)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

The <%page import %> I have in my JSPs are 'java.util.*' and 2 java classes which are part of my project. Rest my java classes import some 'java.' packages
Additional info:

*

*I have set 'Path' environment variable to 'C:\Program Files\Java\jdk 1.8\bin'

*I have tried including 'org.apache.jasper.jar' to my project (& war) too

*jdbc4.jar is also imported in library

What seems to be the problem? I am unable to make out the source of the problem.
Is it because of 32-bit vs 64-bit? or jdk 1.7 vs 1.8? or missing environment variable? or problem in  tomcat configuration? something else?

A: Problem was in my import statement, which included:
Original code
 <%@page contentType="text/html" pageEncoding="UTF-8" language="java" import="java.util.*,mypackage.one.*,mypackage.two.*;"%>

The issue was the ; at the end of the import statement!
Corrected code:
 <%@page contentType="text/html" pageEncoding="UTF-8" language="java" import="java.util.*,mypackage.one.*,mypackage.two.*"%>

A: Use Tomcat 7.0.21 some tomcat version giving this error, I have also faced the same issue with version 7.0.59 .


text:
Q: $\varepsilon$-neighborhood set notation as $V_{\varepsilon}(a)$ and proof question Two questions regarding the set $V_{\varepsilon}(a)$.  It is defined in the book I am currently using as
$$V_{\varepsilon}(a)=\{x\in\mathbb{R}:|x-a|<\varepsilon\}$$
1).  Why the $V$?  I suppose there is a reason for using most notation and abbreviation (like using $\mathbb{R}$ for the reals, or $n$ to represent a natural number...)
2).  Let $\varepsilon>0, \delta>0, a\in\mathbb{R}$.  Show that $V_{\varepsilon}(a)\cap V_{\delta}(a)$ and $V_{\varepsilon}(a)\cup V_{\delta}(a)$ are $\gamma$-neighborhoods of $a$ for appropriate values of $\gamma$.
So I say,
$$V_{\varepsilon}(a)\cap V_{\delta}(a)=\{x\in\mathbb{R}:|x-a|<\varepsilon \text{ and } |x-a|<\delta\}$$
$$=\{x\in\mathbb{R}:|x-a|<\min{(\varepsilon,\delta)}\} $$
Letting $\gamma=\min{(\varepsilon,\delta)},$
$$=\{x\in\mathbb{R}:|x-a|<\gamma\}=V_{\gamma}(a)$$
Therefore, $V_{\varepsilon}(a)\cap V_{\delta}(a)$ is a $\gamma$-neighborhood of $a$.
If this is all i need, I assume the union of two neighborhoods is also a $\gamma$-neighborhood by using the $\max$ function instead?

A: For your first question, I can only wager an educated guess, but it's likely that $V$ comes from the French voisinage.  I should note that I don't speak or read French, but according to google voisinage translates generally as "vicinity" or "neighborhood," and which seems to be the proper translation of the "neighborhood" in a mathematical context, based on a search of MathSciNet and Wikipedia (English and French).
Since a decent amount of work in analysis and topology was published in German or French, it's not uncommon to see variables takes from words in these languages.  Some other examples that come to mind are $G_\delta$, from the German Gebeit and Durchschnitt ("open" and "intersection" repectively), $F_\sigma$ from the French fermé and somme ("closed" and "union"), and $K$ or $\mathbb{K}$ for a field, from the German Korpus.
As far as your proof is concerned, it's certainly correct.   You have the right idea for unions, too.  Note that depending on the definition, you might be proving more than is strictly necessary.  In particular, it depends on precisely what an $\varepsilon$-neighborhood is.  The most natural definition to me is that $U$ is a $\varepsilon$-neighborhood of $a \in \mathbb{R}$ if and only if $U$ contains some $V_\varepsilon(a)$, i.e., if and only if there exists $\varepsilon > 0$ such that $V_\varepsilon(a) \subseteq U$.  In this case, you've proven that $V_\varepsilon(a) \cap V_\delta(a)$ is in fact a set of the form $V_\gamma(a)$, so it's certainly a $\gamma$-neighborhood of $a$.


text:
Q: Установка .CAB файлов на Windows Доброго времени суток!
Уверен, что для всех присутствующих здесь (кроме меня) вопрос пятикопеечный.
Загрузил купленный в интернет-магазине дистрибутив такого вида
http://clip2net.com/s/6j3Fre
Подскажите пожалуйста, как правильно установить это на компьютер (ОС: Windows 7).
Я так понимаю, что простым их разархивированием дело не обойдется.
Может быть программы есть какие специальные? (Вроде CabInstaller для WinMobile )
Заранее спасибо!
A: pkgmgr /ip /m:<path><file name>.cab

есть еще DISM, который идет как замена pkgmgr и т.п.
http://www.wincert.net/forum/topic/4939-how-to-use-windows-7-dism-by-muiz/
http://technet.microsoft.com/en-us/library/hh825265.aspx


text:
Q: Using VBA to Select and Highlight Excel Rows How can I tell Excel to highlight rows by their row number.  For instance, let's say I wanted row 6, 10, 150, 201 highlighted.  Thanks.

A: As an alternative to Motes' answer,  you can use conditional formatting.
Eg: select A1:J500, Conditional formatting >> New rule >> Use a formula...
For the formula enter: =OR(ROW()=6, ROW()=10, ROW()=150, ROW()=201)

A: Here is another one based on Mote's .EntireRow.Interior.ColorIndex
This one doesn't restrict you to enter the row numbers but gives the user the flexibility to choose the rows at runtime.
Option Explicit

Sub Sample()
    Dim Ret As Range

    On Error Resume Next
    Set Ret = Application.InputBox("Please select the rows that you would like to color", "Color Rows", Type:=8)
    On Error GoTo 0

    If Not Ret Is Nothing Then Ret.EntireRow.Interior.ColorIndex = 6
End Sub

FOLLOWUP

Is there a way to write the macro to read the row numbers from a list and highlight the rows?

Yes there is a way. Let's say the list in Cell A1 to A10 then you can use this code
Option Explicit

Sub Sample()
    Dim i As Long, sh As Worksheet

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    '~~> Set this to the sheet where the rows need to be colored
    Set sh = Sheets("Sheet2")

    '~~> Change Sheet1 to the sheet which has the list
    With Sheets("Sheet1")
        For i = 1 To 10
            If Not Len(Trim(.Range("A" & i).Value)) = 0 And _
            IsNumeric(.Range("A" & i).Value) Then _
            sh.Rows(.Range("A" & i).Value).Interior.ColorIndex = 3 '<~~ Red
        Next i
    End With

LetsContinue:
    Application.ScreenUpdating = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

A: For basic VBA code, you can always start recording a macro, perform the action, stop recording, look at what code was generated, and then clean that up to do what you want. For example, recording the action of highlighting a row (setting the value of Interior.Color) gives you:
Rows("13:13").Select
Range("C13").Activate
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 65535
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With

The selection commands and extraneous Interior properties can be removed giving you:
Rows("13:13").Interior.Color = 65535

Adding in the row multi-select:
Rows("6:6,10:10,150:150,201:201").Interior.Color = 65535

Summary:

*

*Record macro

*View Excel's version

*Use/Edit what code you need

A: objWB.Cells(rowNum,201).EntireRow.Interior.ColorIndex = 6

etc

A: Update: Didn't realize the date on this, but thought I'd add this in since it was relevant to the chosen answer.
In addition to Siddharth Rout's answer, since I don't have enough rep to comment yet, you can dynamically figure out how many rows there are in your worksheet with these two lines.  xlCellTypeConstants could be changed to another XlCellType constant that you need, and the range can always be changed to accommodate to your spreadsheet.
Dim numRows As Integer
numRows = Range("A2", Range("A1048576").End(xlUp)).SpecialCells(xlCellTypeConstants).Cells.Count

A: Sorry if it is not as concise or elegant as other answers, but it gets the job done.  When I was writing code for my own application I needed to loop through my code.  Also, instead of highlighting the entire row, I only needed to highlight a portion of the rows.
Sub Highlight()
Dim ThisWB As Workbook
Dim ThisWS As Worksheet
Dim rows(0 To 3) As Integer
Dim test As String

Set ThisWB = ActiveWorkbook
Set ThisWS = ThisWB.Sheets("Sheet1")

rows(0) = 6
rows(1) = 10
rows(2) = 150
rows(3) = 201

For i = 0 To 3
    test = "A" & rows(i) & ":H" & rows(i)
    ThisWS.Range(test).Interior.ColorIndex = 15
Next i

End Sub

A: You might be able to achieve the same thing using conditional formatting

*

*put list of values in a column (I use a separate tab and give the list a name)

*under conditional formatting - New Rule - "use a formula to determine with cells to format"

*read this article http://www.howtogeek.com/howto/45670/how-to-highlight-a-row-in-excel-using-conditional-formatting/

*the rule uses vlookup in the formula- =$A2=VLOOKUP($A2,list,1,FALSE)


text:
Q: jasmine async callback was not invoked within timeout specified I am new to Protractor and javascript. I know there are a lot of questions and solutions regarding this error. But none of the solutions gave me a clear understanding of async callback and this error still persists for me.
I am using the Page Object model. Please refer the below code that I framed on my own:
elements.js:
var pageElements = function(){};

pageElements.prototype = Object.create({},{
  usernameField:{get: function(){return element(by.id('username'));}},
  passwordField:{get: function(){return element(by.id('password'));}},
  signinButton:{get: function(){return element(by.xpath("xpath"));}},
  formField1:{get: function(){return element(by.xpath("xpath1"));}},
  formField2:{get: function(){return element(by.xpath("xpath2"));}},
});

module.exports = pageElements;

controls.js:
var EC = protractor.ExpectedConditions;
var controls = require('../Controls/controls.js');

exports.waitForElementById = async function(id){
  debugger;
  var isVisible = EC.visibilityOf(id);
  await browser.wait(isVisible,50000);
  browser.sleep(3000);
};

exports.waitForElementByXpath = async function(xpaths){
  var isVisible = EC.visibilityOf(xpaths);
  await browser.wait(isVisible,50000);
  browser.sleep(3000);
};

exports.sendKeysById = async function(ids, value){
  controls.waitForElementById(ids);
  var isVisible;
  for(i = 1; i<5; i++){
    isVisible = EC.visibilityOf(ids);
    if(isVisible){
        return await ids.sendKeys(value).then(function(){
            browser.sleep(500);
        }) .catch(error => {
            console.log('---------Error: Element not sent by id-----------');

            throw error;
        });
    }
  }
}

exports.clickElementById = async function(id){
  controls.waitForElementById(id);
  var isClickable;
  var processingBar;
  var check;
  for(i = 1; i<5; i++){
    isClickable = EC.elementToBeClickable(id);
    processingBar = EC.invisibilityOf(element(by.xpath("//*[contains(@id,'exterroLoader')]")));
    check = EC.and(isClickable,processingBar);
    if(check){
        return await id.click().then(function(){
            browser.sleep(500);
        }) .catch(error => {
            console.log('---------Error: Element not clicked by id-----------');
            throw error;
        });
    }
  }
};

formOperations.js
browser.ignoreSynchronization = true;
var controls = require('./controls.js');
var pageElements = require('./elements.js');
var e;

exports.form1 = async function(){
    e = new pageElements();
    browser.get("https://form.htm");
    await controls.sendKeysById(e.usernameField);
    await controls.sendKeysById(e.passwordField);
    await controls.clickByXpath(e.signinButton);
    await controls.sendKeysById(e.formField1);
};

exports.form2 = async function(){
    e = new pageElements();
    browser.get("https://form.htm");
    await controls.sendKeysById(e.usernameField);
    await controls.sendKeysById(e.passwordField);
    await controls.clickByXpath(e.signinButton);
    await controls.sendKeysById(e.formField2);
};

TestCases.js
var ignore = function(exp){return{it:((typeof exp==='function')?exp():exp)?function(){}:it}};

describe('Automation', function() {
var controls = require('./controls.js');
browser.ignoreSynchronization = true;
browser.get('https://prre2eauto.exterrocloud.info');

it('Form 1', async function(){
    var a = require('./formOperations.js');
    await a.form1();
});

it('Form 2', async function(){
    var a = require('./formOperations.js');
    await a.form2();
});

});

The above is given an example code but the model I m using is exactly the same.
What I am exactly facing is

*

*form1 is executed successfully without any errors.

*form2 is executed successfully but gives the following error:
Jasmine spec timed out. Resetting the WebDriver Control Flow.
Message:
[31m    Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.[0m
Stack:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5)

Please help on this as this takes much longer time for me to understand.

A: Try the below one
var controls = require('./controls.js');
describe('Automation', function() {

beforeEach(async() =>{ //This block will be executed before every `it` block
await browser.waitForAngualrEnabled(true);
await browser.get('https://prre2eauto.exterrocloud.info');
});

it('Form 1', async function(){
    var a = require('./formOperations.js');
    await a.form1();
});

it('Form 2', async function(){
    var b = require('./formOperations.js');
    await b.form2();
});

});

Hope it helps you


text:
Q: align ul tag inside divs side by side I'm trying to make a
 with some
 lists inside it, but for some reason I cant make it work. I'm trying to make something like this:

My Code I've made is this:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

4421:blabla

4421:blabla

4421:blabla

4421:blabla

4421:blabla

4421:blabla

4421:blabla

4421:blabla

A: Check this snippet.
Here I am using flexbox to align the lists inside the div side by side.
By default, the flex-direction will be row, hence we don't need to specify it explicitly.

.list-wrapper {
  display: flex;
}
<link
  href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
  rel="stylesheet"
/>

4421:blabla

4421:blabla

4421:blabla

4421:blabla

4421:blabla

4421:blabla

4421:blabla

4421:blabla


text:
Q: AWS Lambda Snowflake Python Connector hangs attempting to connect I have a small AWS Lambda function that looks like this:
It grabs the credentials to connect to Snowflake from SSM Parameter Store, and then calls snowflake.connector.connect. It's meant to obviously go grab data from my Snowflake data warehouse. However, the code hangs and never finishes the snowflake.connector.connect call.
I believe my subnets and networking are set up properly:

*

*Just to test and develop, I set my security group to allow all inbound and outbound traffic on all ports.

*I have my Lambda running in a private subnet, and a route table that directs 0.0.0.0/0 to the NAT Gateway instance. In my code, I print(requests.get('http://216.58.192.142')) just to prove that I do indeed have internet connectivity.

*I have many large dependencies that don't fit in the 200MB deploy package for Lambdas, so I have my dependencies mounted in an EFS file system at /mnt/efs path, and I add /mnt/efs/python to my PYTHONPATH in the code before I start to import those dependencies.

import boto3
import snowflake.connector
print("Getting snowflake creds")
session = boto3.session.Session()
ssm = session.client("ssm")
obj = ssm.get_parameter(Name="snowflake", WithDecryption=True)
sf_creds = json.loads(obj.get("Parameter").get("Value"))

def get_data(event, context):
    print(requests.get('http://216.58.192.142'))
    print("Executing")
    print("got parameter, connecting")
    con = snowflake.connector.connect(
        user=sf_creds["USER"],
        password=sf_creds["PASSWORD"],
        account=sf_creds["ACCOUNT"],
        ocsp_response_cache_filename="/tmp/ocsp_response_cache"
    )
    print("connected")

When I run this same exact code locally on my MacBook, I am able to connect fairly quickly, within a second or two. My snowflake-python-connector version is 2.3.2.
However, no matter how long I try, the connect method hands when it executes in an AWS Lambda function. I'm really not sure what is going on.
I've verified that

*

*the AWS Lambda function is connected to the internet (it receives a [200 OK] from the requests.get call).

*security groups are as permissive as possible (allow all traffic on all ports both inbound and outbound)

*I have not touched the NACL

Really, I'm at a loss as to why this is happening, especially given that the code works fine on my local machine - could someone try to point me in the right direction?

A: Lambda can respond with 200, but there can be exception in logs. Check out the CloudWatch logs of this lambda.


text:
Q: What is the correct syntax for accessing a class member function for a pointer-to-class object contained within an array? I have the following function, stdDev, which accepts an array of pointers to objects of the Student class. Student class has a member function getScores(), which returns a student's score as a double.
Here is the code below:
double stdDev(Student array[], int SIZE) {

    double sum, std_sum, mean, std_mean = 0;
    double *std_scores = NULL;
    std_scores = new double[SIZE];

    for (int i = 0; i < SIZE; i++) {
        sum += array[i]->getScore;
    }
    mean = sum / SIZE;

    for (int i = 0; i < SIZE; i++) {
        std_scores[i] = pow((array[i]->getScore - mean), 2);
        std_sum += std_scores[i];
    }
    std_mean = std_sum / SIZE;

    return sqrt(std_mean);
}

On lines 8 and 13 in the above code, I get the following errors:
expression must have pointer type

and
'*': illegal operation on bound member function expression

I'm new to pointer syntax with C++. Any assistance is appreciated.

A: The short answer to your question is:
    sum += answer[i].getScore;

Except that you need to call the function (not just refer to it), so it should be:
    sum += answer[i].getScore();

Other problems:

*

*You don't initialize sum to zero.

*You leak std_scores.  In reverse order of preference:

*

*Delete it with delete [] std_scores at the end of your function.

*Declare it as `std::vector std_scores(SIZE);

*Don't use an array at all.  Just use double score2 = pow((array[i].getScore() - mean), 2);
Finally points:

*

*C++ is not C89 - you should delay declaring your variables until you can give them a value.  std_scores is a particularly glaring example of that - you initialize to NULL and then immediately assign a new value.  Apart from sum and std_sum (and i) you don't need any non-const variables.

*The code would be nicer with std::accumulate

*There are better algorithms for calculating mean and standard deviation that are more numerically stable.


text:
Q: Return vector> & from c++ method to python list of tuples using swig typemap I'm having a lot of troubles trying to wrap a c++ method that returns a constant reference to a vector of pairs to a Python list of tuples using %typemap(out).
I currently have something like this:
myclass.h:
#inlcude <vector>
using std::vector;
class MyClass {
private:
    const vector<pair<int,int>> & _myvector;
public:
    MyClass(const vector<pair<int,int>> & myvector );
    const vector<pair<int,int>> & GetMyVector() const;
}

myclass.cpp:
#include "myclass.h"

MyClass::MyClass(const vector<pair<int,int>> & myvector): _myvector(myvector){};

const vector<pair<int,int>> & MyClass::GetMyVector() const {
    return _myvector;
};

myclass.i: (checking ommited)
%module MyClass
%include "std_vector.i"

namespace std {
    %template(vector_pair_int) vector<pair<int,int>>;
}

%typemap(in) (const vector_pair_int &){

    $1 = new vector<pair<int,int>>;
    int size = PyList_Size($input);
    for (int i=0; i<size; i++){
        PyObject *o = PyList_GetItem($input,i);
        PyObject *o1 = PyList_GetItem(o,0);
        PyObject *o2 = PyList_GetItem(o,1);
        $1->push_back(make_pair(PyInt_AsLong(o1),PyInt_AsLong(o2)))
}

}

%typemap(out) (const vector_pair_int &) {
    $result = PyList_New($1.size());
    vector<pair<int,int>>:: const_iterator it;
    int count=0;
    for (it= $1.begin(); it!= $1.end(); ++it){
        PyObject * tup = PyTuple_Pack(2, it->first,it->second);
        PyList_SET_ITEM($result,count,tup);
        count++;
    }
}

Ok so the first thing that I dont quite understand is that the previous code for the typemap (out) doesnt compile because it tells me that $1 is a pointer to the container not a reference. When I change the use of $1 as a pointer, it compiles but it doesnt work.
Second, in the case that compiles, the typemap(in) works (the c++ container is correctly filled), but when I try to retrieve the container from python I get garbage. When I pass to the constructor something like MyClass([(1,2)]), and then I use GetMyVector() it returns a python list but of size 3 and with garbage on the tuples... what I'm doing wrong???

A: A custom typemap is not necessary for this case.  SWIG has built-in support for vector and pair templates, but you have to declare the pair template as well as the vector template:
%module x

%include <std_pair.i>
%include <std_vector.i>
%include <std_string.i>
%template() std::pair<int,int>;
%template(PairVector) std::vector<std::pair<int,int> >;

%{
#include "MyClass.h"
%}

%include "MyClass.h"

Example:
>>> import x
>>> a=x.PairVector(((1,2),(3,4),(5,6)))
>>> b=x.MyClass(a)
>>> b.GetMyVector()
((1, 2), (3, 4), (5, 6))

But note because your class is written to hold a reference to the passed-in vector and not a copy, you have to hold a reference to it for the lifetime of MyClass.  For example:
>>> del a
>>> b.GetMyVector()
*Undefined Behavior (crash, empty vector, etc.)*


text:
Q: WFS won't load properly in QGIS I am trying to access a WFS from geoserver in QGIS, and when I load it, it comes in very strangely:

I can access it directly from the postgres database and it comes in fine. I'm wondering if there are settings to the geoserver layer I can adjust so that it comes in properly? WMS comes in ok, except when zoomed to full extent not all the features draw, in areas where there are a lot of polygons (it is a parcel layer with @ 170K records). When I zoom in on the WMS, the feature draw. But I'd really like to figure out what is going on with the WFS. I've also tried to load in feature for a limited extent with the same result.

A: I do not know the main reason but the GML from the service has some odd coordinate values:
http://52.24.37.126:8080/geoserver/Iada_workspace/ows?service=wfs&version=1.0.0&request=getfeature&typename=Iada_workspace:parcels&maxfeatures=100

gml:coordinates xmlns:gml="http://www.opengis.net/gml" ts=" " cs=","
  decimal=".">-1.295840489020236E7,5410000.64865586,0
  -Infinity,-1.295837966400454E7,5410000.48182336 0,-Infinity,-1.295837994378932E7 5409958.2865818,0,-Infinity
  -1.295839798043889E7,5409958.40587354,0 -Infinity,-1.295840516987279E7,5409958.45341379 -1.295840489020236E7,5410000.64865586,0

It looks like your data have XYZ coordinates with all the Z values of "-Infinity". Perhaps that makes problems for QGIS. Because you do not seem to know real Z I would have a try by converting parcel polygons into XY geometries and publishing these 2D parcels as a new feature type.


text:
Q: Date minus 1 year? I've got a date in this format:
2009-01-01

How do I return the same date but 1 year earlier?

A: // set your date here
$mydate = "2009-01-01";

/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));

// format and display the computed date
echo date("Y-m-d", $lastyear);

A: Although there are many acceptable answers in response to this question, I don't see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php
So, for reference, you can also use a \DateInterval to modify a \Datetime object:
$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));

echo $date->format('Y-m-d');

Which returns:
2008-01-01

For more information about \DateInterval, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php

A: Using the DateTime object...
$time = new DateTime('2099-01-01');
$newtime = $time->modify('-1 year')->format('Y-m-d');

Or using now for today
$time = new DateTime('now');
$newtime = $time->modify('-1 year')->format('Y-m-d');

A: an easiest way which i used and worked well
date('Y-m-d', strtotime('-1 year'));

this worked perfect.. hope this will help someone else too.. :)

A: You can use strtotime:
$date = strtotime('2010-01-01 -1 year');

The strtotime function returns a unix timestamp, to get a formatted string you can use date:
echo date('Y-m-d', $date); // echoes '2009-01-01'

A: Use strtotime() function:
  $time = strtotime("-1 year", time());
  $date = date("Y-m-d", $time);

A: On my website, to check if registering people is 18 years old, I simply used the following :
$legalAge = date('Y-m-d', strtotime('-18 year'));

After, only compare the the two dates.
Hope it could help someone.

A: You can use the following function to subtract 1 or any years from a date.
 function yearstodate($years) {

        $now = date("Y-m-d");
        $now = explode('-', $now);
        $year = $now[0];
        $month   = $now[1];
        $day  = $now[2];
        $converted_year = $year - $years;
        echo $now = $converted_year."-".$month."-".$day;

    }

$number_to_subtract = "1";
echo yearstodate($number_to_subtract);

And looking at above examples you can also use the following
$user_age_min = "-"."1";
echo date('Y-m-d', strtotime($user_age_min.'year'));


text:
Q: Is there any way I can create group and invite users using REST API? Is there any way I can create group and invite users using REST API?
I have tried this one
Request
POST https://www.yammer.com/api/v1/groups.json
{
"name": "test name",
"private": false,
"description": "A test group"
}
Response
Client error response [url] https://www.yammer.com/api/v1/groups.json [status code] 404 [reason phrase] Not Found
Update
Group Creation API is working. Now need to know how I will invite user on that group.

A: try to send the parameters in the URL,
POST
https://www.yammer.com/api/v1/groups.json?name=test_name&private=false

A: Give a try to that endpoint : https://api.yammer.com/api/v1/group_memberships.json?group_id=[:group_id]&user_id=[:user_id]&approve=1
Use an access token from a verified admin, it will invite the user and validate his invitation in the same time.


text:
Q: iOS: UICollectionViewCell ContentView subview always count One How to add dynamic view inside UICollectionViewCell but when I scroll UICollectionView the view has remove and add last index of cell.
Now I have add view on all Appear cell.

A: You should be adding/removing subviews at cellForItemAtIndexPath().
That is to say, you should probably removeAllSubviews() and then cell.addSubview(yourSubview) every time.

A: Try to add this
cell.contentView.removeAllSubviews()
cell.contentView.addSubview(yourSubview)

May this help u
let me know if it works.


text:
Q: Google Cloud Run Container Networking I have a system of apps/services in docker containers that, when I bring them up using docker-compose, talk to each other using a bridge network.
Workers start up and register themselves with a manager. The manager assigns the workers work to do. In order to do this, the workers need to know where the manager is, and the manager needs to know where the workers are.
I want to deploy them all to Google Cloud Run.
At the moment, in docker via docker-compose, they talk to each other using their container names. For example the worker might call: http://manager:5000/register?name=worker1&port=5000 to register on startup, and then the manager can call http://worker1:5000 to send work. All thanks to the fact that they're connected to the same bridge network.
How does this work with Google Cloud Run? As far as I can see, when you create a service linked with a container, you get a permanent URL to communicate with your app once it has started. The app in the container doesn't know what the URL is.
Can I use the service names to communicate with each other in the same way as a docker bridge network?

A: In fact, you can't orchestrate in the same way the workers. Indeed, the Cloud Run services reply to an HTTP request. When an instance is spawn, there is no registration to a manager.
If you want to perform several task in parallel, perform several HTTP requests.
If you want a strong isolation between the different instances of a same service, set the concurrency param to 1 (only 1 HTTP request is processed in the same time by an instance of the service).
For information, you can have up to 100 instances for a same service.
So, deploy a manager service, and a worker service. The manager service perform HTTP request to worker with the right param for doing the right job.
Take care of the job duration. For now, the timeout can be set up to 900 seconds (15min) maximum
About the naming, the pattern is the following: https://<service-name>-<project-hash>.run.app/

A: Cloud Run currently does not support hostname based service discovery for other services in your project.
Currently, your best bet is to configure service URLs that your app depends on using environment variables or something like that.


text:
Q: Cannot install ghc-mod due to "unattainable version of base" I'm trying to install the ghc-mod library on Windows. Using stack install ghc-mod shows this lengthy error message:
Error: While constructing the build plan, the following exceptions were encountered:

In the dependencies for ghc-mod-5.8.0.0:
    Cabal-2.4.1.0 from stack configuration does not match >=1.18 && <1.25  (latest matching version is 1.24.2.0)
    base-4.12.0.0 from stack configuration does not match >=4.6.0.1 && <4.10  (latest matching version is 4.9.1.0)
    cabal-helper must match <0.8 && >=0.7.3.0, but the stack configuration has no specified version  (latest matching
                 version is 0.7.3.0)
    djinn-ghc must match <0.1 && >=0.0.2.2, but the stack configuration has no specified version  (latest matching
              version is 0.0.2.3)
    extra-1.6.17 from stack configuration does not match <1.6 && >=1.4  (latest matching version is 1.5.3)
    ghc-8.6.5 from stack configuration does not match >=7.6 && <8.2
    ghc-syb-utils must match <0.3 && >=0.2.3, but the stack configuration has no specified version  (latest matching
                  version is 0.2.3.3)
    haskell-src-exts-1.20.3 from stack configuration does not match <1.20 && >=1.18  (latest matching version is 1.19.1)    hlint-2.1.11 from stack configuration does not match <2.1 && >=2.0.8  (latest matching version is 2.0.15)
    monad-journal-0.8.1 from stack configuration does not match <0.8 && >=0.4  (latest matching version is 0.7.2)
    optparse-applicative-0.14.3.0 from stack configuration does not match >=0.13.0.0 && <0.14  (latest matching version
                                  is 0.13.2.0)
    temporary-1.3 from stack configuration does not match <1.3 && >=1.2.0.3  (latest matching version is 1.2.1.1)
needed since ghc-mod is a build target.

Some different approaches to resolving this:

  * Build requires unattainable version of base. Since base is a part of GHC, you most likely need to use a different
    GHC version with the matching base.

Apparently, I need to change the version of ghc, but my version is higher than the one required, so updating doesn't help. Should I downgrade? How to do it without messing up the rest of my ghc ecosystem?
Using cabal to install it gives similar results.

A: In stackage you can find all the LTS versions and all the possible releases you can download:

and here is the list of all the dependencies you need for ghc-mod:

You need to check that you don't have any outdated or unmatched.

A: Sorry, but you can't do this unless you are willing to downgrade to GHC 8.0. Note in the dependencies list it says ghc (>=7.6 && <8.2). There is no GHC 8.1 (odd numbers are for testing), so its back to GHC 8.0.
Stackage provides a curated list of package versions which are known to compile together, along with a version of GHC. Each Long Term Support (LTS) is a specific set of these versions. As you can see from the list posted by Damián Rafael Lattenero that means going back to LTS-9.21.
The problem is that ghc-mod uses GHC as a library as well as a compiler, so it is very sensitive to the version, and you have to use the same version of the compiler for both ghc-mod and the software you are developing; having got a working version of ghc-mod you can't just switch to a later version of GHC for your own program.
Assuming you still want to do this, get stack installed. Then edit your ~/.stack/config.yaml file (on Windows type stack path --stack-root to find where this is stored). Change it to say resolver: lts-9.21. Then say stack install ghc-mod.


text:
Q: Access 2013 - Dlookup with double Hello i've a little problem with my VBA code i'm trying to select the right gps number (double) which matches to the string Name in table tblpersonal and the string in the textbox tabletbesitzerbox. The GPS number should be displayed in the textbox fkgps:
Private Sub SP_Besitzersuche_Click()

    DoCmd.OpenForm "F-Tablet-Hinzufuegen-Neu"
    Dim Sim As Double

    Sim = Nz(DLookup("[GPS]", _
        "tblPersonal", _
        "Name = " & Forms![F-Tablet-Hinzufuegen-Neu]![tabletbesitzerbox]), "")

   FKGPS.Value = Sim

End Sub

The error shows me: Syntaxerror (missing Operation) in query expression 'Name = XY'
I'm thankful for every help :)

A: String parameters must be enclosed in quotes. When building the criteria in VBA, it is easiest to use single quotes:
Sim = Nz(DLookup("[GPS]", _
    "tblPersonal", _
    "Name = '" & Forms![F-Tablet-Hinzufuegen-Neu]![tabletbesitzerbox] & "'"), 0)


text:
Q: How to place an arrowhead at the end of each line of a polyline using PolylineDecorator? I am experimenting with PolylineDecorator for leaflet. I intend to draw a polyline with arrowheads at the end of each line. I have this code:
var somePoints = [];
for (var rowIndex in rows) {
    somePoints.push(L.latLng(rows[rowIndex].Lat, rows[rowIndex].Lon));
}
var pl = L.polyline(somePoints);
pl.addTo(map);
var decorator = L.polylineDecorator(pl, {
    patterns: [
        // defines a pattern of 10px-wide dashes, repeated every 20px on the line
        {offset: 0, repeat: 50, symbol: L.Symbol.arrowHead({pixelSize: 8, polygon: false, pathOptions: {stroke: true}})}
    ]
}).addTo(map);

which produces this

My intention is to have an arrowhead at each end of line (the marker positions). If I change offset to "100%" and repeat to 0, then I have this:

we have an arrow at the very last marker, but no arrowheads for the other markers. I know we can achieve what I want by drawing each line as a separate polyline with an offset of "100%" and repeat of 0, but I wonder whether this can be achieved using a single polyline with more than two points in the parameters of decorator. Is this possible or should I modify my code to have n - 1 polylines with arrowheads?

A: I know this is like stupid old but I am actually in the process of building a plugin for this purpose:
https://github.com/slutske22/leaflet-arrowheads
As per request in the comment, here is a working codesandbox with a bunch of examples:  https://codesandbox.io/s/leaflet-arrowheads-example-zfxxc
I am almost done fleshing out the readme and will soon request it to be added to the leaflet plugin list.  Let me know what you think, if you find it helpful / any more feature requests / general feedback.


text:
Q: Removing all periods after a letter If I have a file like so:
stuff
 stuff.1
 stuff.2
 stuff.3
 12.5
 45.2
 stugg
 stugg.1
 stugg.2
 5.2
 8
 amber
 amber.1
 amber.2
 amber.3
 amber.4
 7
 21.2
 amst
 amst.1
 5
and I want to remove duplicates of stuff & stugg &amber &amst
where everything ending with .number counts as a duplicate how do I do this with awk? or sed?
The output should be
stuff
 12.5
 45.2
 stugg
 5.2
 8
 amber
 7
 21.2
 amst
 5

A:
sed -n '/^[[:blank:]]*[[:alpha:]]/ {/\.[[:digit:]]\+$/! p}' file

For lines that start with a letter, if the line does not end with a dot and digits, print that line.

Found the updated requirements in the comments:
awk '$1 !~ /[[:alpha:]]\.[[:digit:]]+$/' file

Ah, that will omit something like "notseen.1", even if it's not a duplicate:
awk '
  {root = $1; sub(/\.[[:digit:]]+$/, "", root)}
  $1 ~ /[[:alpha:]]\.[[:digit:]]+$/ && seen[root] {next}
  {print; seen[root] = 1}
' file


text:
Q: Check if value was greater than x for y consecutive months period in changes history I have table with members level changes. It has historical changes of level of all members and date when change happened. For example I can list changes for member number 5:
select * from memberlevelhistory where member = 5

result:
member  changedate  level
5       2012-04-01  2
5       2012-03-01  3
5       2012-02-01  2
5       2011-02-01  6
5       2011-02-01  6
5       2010-03-15  6
5       2010-02-01  5
5       2010-01-01  5
5       2009-10-01  4
5       2009-08-27  2
5       2009-08-01  1

Last entry in history table is current level.
QUESTION:
How to list all members that had level higher or equal to 3 for period of 3 months or more ?
That is a simplified version of the question. To make it even more fun I need only members that didn't drop below the starting level during this 3 month period. So if a member started the 3 month period with level 4 and is only level 3 on the last month then that member is excluded from the list.
Any help, even with the simplified question is much appreciated.
EXTENDED VERSION:
I also need this period of >=3 months of level >=3 happen inside last 6 months window.

A: This might be a case for not exists. An entry is valid if there is not another entry with level less than currently selected record in next three months. This solves both requirements. There might be an issue with last entry per member where level is appropriate, but span is not known. I've decided to remove those records, but you might have other ideas.
Sql Fiddle with example is here.
select distinct mlh.member
  from memberlevelhistory mlh
 where mlh.level >= 3
   and not exists
       (
         select null
           from memberlevelhistory mlh2
          where mlh2.member = mlh.member
            and mlh2.changedate >= mlh.changedate
            and mlh2.changedate < dateadd(month, 3, mlh.changedate)
            and mlh2.level < mlh.level
       )
    -- The last entry might have appropriate level
    -- But we cannot tell how long it lasted,
    -- So we are going to remove it.
   and exists
       (
         select null
           from memberlevelhistory mlh3
          where mlh3.member = mlh.member
            and mlh3.changedate > mlh.changedate
       )

EDIT:
I have rewritten not exists() to left join and added 'last entry lasting until today' criterion.
Sql Fiddle with example is here.
select distinct mlh.member
  from memberlevelhistory mlh
  left join memberlevelhistory mlh2
    on mlh2.member = mlh.member
   and mlh2.changedate >= mlh.changedate
   and mlh2.changedate < dateadd(month, 3, mlh.changedate)
   and mlh2.level < mlh.level
 where mlh.level >= 3
   and mlh2.member is null
   and datediff(month, mlh.changedate, getdate()) >= 3

Query rewritten:
; with ranges as
(
  select mlh.member, mlh.changedate StartRange, min(isnull(mlh2.changedate, getdate())) EndDate
    from memberlevelhistory mlh
    left join memberlevelhistory mlh2
      on mlh2.member = mlh.member
     and mlh2.changedate >= mlh.changedate
     and mlh2.level < mlh.level
   where mlh.level >= 3
  group by mlh.member, mlh.changedate
 having datediff (month, min(isnull(mlh2.changedate, getdate())), getdate()) <= 6
    and datediff (month, mlh.changedate, min(isnull(mlh2.changedate, getdate()))) >= 3
)
select distinct member
  from ranges

And Sql Fiddle is here.
I believe that 100 and 101 should be included because both had a good run for 3 months and this was on in march which is six months before this moment.
What I did is to generate ranges when somebody had a good run, and then test this ranges for duration of 3 months or more and ending date in last six months.
UPDATE: if I finally got it right, you need that duration is lasting for three months in last six months. To calculate that one might truncate changedates to current date - six months. Using that as starting point, and finding ending point of a range as first mlh having lower level and higher date as ending point one has enough information to calculate duration.
; with ranges as
(
  select mlh.member,
  -- If good range starts more than six months before today
  -- truncate it to today - 6 months
         case when datediff (month, mlh.changedate, getdate()) > 6
              then dateadd(month, -6, getdate())
              else mlh.changedate
              end StartRange,
  -- First bad mlh after current changedate
         min(isnull(mlh2.changedate, getdate())) EndRange
    from memberlevelhistory mlh
    left join memberlevelhistory mlh2
      on mlh2.member = mlh.member
     and mlh2.changedate >= mlh.changedate
     and mlh2.level < mlh.level
   where mlh.level >= 3
  group by mlh.member, mlh.changedate
  -- As above, limit good range to max six months before today
  -- And only get those lasting at least three months
 having datediff (month, case when datediff(month, mlh.changedate, getdate()) > 6
                              then dateadd(month, -6, getdate())
                              else mlh.changedate
                          end,
                         min(isnull(mlh2.changedate, getdate()))) >= 3
)
select distinct member
  from ranges

Sql Fiddle with example is here.

A: SELECT * FROM (
  SELECT MEMBER, CHANGEDATE, LEVEL, COUNT(LEVEL) AS COUNT
  FROM MEMBERLEVELHISTORY
  GROUP BY MEMBER, CHANGEDATE, LEVEL)
WHERE LEVEL >= 3
AND COUNT >= 3;

This should help you our for the simplified version, in order to group results consecutively is beyond me though!


text:
Q: get new x/y positions of element after scroll using jQuery Lets say I have an  tag as follows:

        Click Me

and my CSS are:
body{ padding:10px;}
.wrapper { height:1000px; width:500px;}

Currently I am using .offset()  of Jquery to get the X/Y positions of  tag.
var offset = $(".a1").offset();
var top = offset.top;
var left = offset.left;

Now when I scroll the page and check of  tag's x,y co-ordinates, they remain the same, i.e. ineffective of page scrolling.
I want to get the new X,Y positions of  tag after scrolling the page related to the screen.
If this  tag gets hidden after scrolling down, I want its position in negative values.
Check this fiddle: http://jsfiddle.net/xQh5J/9/
Please help.

A: The link element's position w.r.t. the document does not change when you scroll. To get the position of the element w.r.t. the window's top-left, you can take it's offset() and subtract the window's scrollTop form what you get:
var offset = $(".a1").offset();
var w = $(window);
alert("(x,y): ("+(offset.left-w.scrollLeft())+","+(offset.top-w.scrollTop())+")");

Demo: http://jsfiddle.net/xQh5J/10/


text:
Q: Stop Liquibase from removing Oracle hints I have Oracle statements containing hints. But Liquibase keeps removing them. I guess Liquibase thinks they are block comments ... for some reason.
As such I've tried adding stripComments:false but without any luck.
Example
--changeset AUTHOR:ID (stripComments:false)
Insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX(CUSTOMER,CUSTOMER_PK) */ Into CUSTOMER Values (value1, value2, etc)

Does anyone have an idea of how to stop Liquibase from removing the Oracle hints?

A: found the issue, forgot to add stripcomments on one changeset


text:
Q: Is this binomial coefficient identity already known? $ \sum_{k=r}^{n} {n \choose k} = \sum_{k = r - 1}^{n-1}{k \choose r -1}2^{n-1-k}  $
The proof is trivial but I haven't seen this identity anywhere. Perhaps it's a special case of a more general identity?

A: Whatever sums of hypergeometric terms are around can be solved by the techniques of Petkovsek, Wilf, Zeilberger's "A = B"


text:
Q: Java regular expression for matching filenames or filetypes I am trying to write a java regular expression where my application should restrict the names of the files or filetypes mentioned in the regex from being attached to an email. I started the regex like this,
    .*\\.(?:jpeg|jpg)$.

Is this correct?. Right now it is not working(matching). Also, how can I add new file types or filenames to this expression incase if I want to expand this regex. Like say, I want to add the vcf file types also here in this regex, how should I do that? Also, If I need to add the filenames, say abc.bmp from being attached, how and where should I include that filename in this regex?. Any help is greatly appreciated as I am new to this regex.

A: what about
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
    // good
} else {
    // bad
}

I read your comment under m.buttners answer and propose the following:
List<String> allowedExtensions = loadExtensionsFromConfig(); // implement this
boolean isFileAllowed = false;
for (String extension : allowedExtensions) {
    if (fileName.endsWith(extension)) { // this is case sensitive!
        isFileAllowed = true;
        break;
    }
}

A: It should be something like this:
.*\\.(jpe?g)$

A: The reason it's not matching is simply the . at the end. This tries to match a character after the end of the string. That, obviously, can't work. Remove it, and you should be fine. Note that you can reduce (?:jpeg|jpg) to jpe?g.
This is not saying that a regex is the right approach to this problem. I prefer jlordo's approach, as long as there is only a small amount of possible file extensions. This is just to let you know where you went wrong with the regex.
Note that either .* or $ is redundant. If you are using match it requires the pattern to match the entire string anyway. In that case you don't need to assert $ again. If you use find, then you don't need to match parts of the the string that are arbitrary anyway, so you can leave out the .*.
EDIT:
After the discussion in the comments, if you have a set of allowed extensions, plus a set of allowed specific file names, this would be the general regular expression:
^(?:.*\\.(?:all|allowed|file|extensions)|all\\.allowed|file\\.names)$


text:
Q: Dynamically update Animation in QML I've got a property animation in QML that scrolls a list of names. It's supposed to scroll from a certain fixed y value, to the negative of its own height, so that it just exactly disappears off the screen.
However, the list of names is dynamic and can be added to at any point, therefore I want the animation to have an updated to value as soon as this happens. That part, I've got down, but the animation doesn't seem to be reinitialized with the new value, and retains the old animation length.
Is there any way to do what I want in QML?
Thansk.

A: I don't think your approach is correct.
You may want to check out the ListView Item and its positionViewAtIndex method.


text:
Q: How to prevent calling public method directly I have a class below that I implemented as a Singleton, and added few methods to use with and without parameters, leaving off the details:
public class LogManager
{
    public static LogManager Instance
    {
        get
        {
            return instance;
        }
    }

    public LogManager Create(Guid productId)
    {
        _productId = productId;
        return Instance;
    }

    public LogManager Create()
    {
        return Instance;
    }

    public void WriteStateChangeEvent()
    {
    }
}

Is there any way to restrict calling Instance directly so it can be called like this LogManager.Instance.Create(newProductId).WriteStateChangeEvent() or LogManager.Instance.Create().WriteStateChangeEvent() but never like this LogManager.Instance.WriteStateChangeEvent()
This is not a general OOP Singleton pattern question but a question about specific implementation

A: You shouldn't actually have a singleton here, because you don't conceptually have a single object.
You should simply expose a constructor for the type publicly, possibly with a factory Create method if you really need it, and then have WriteStateChangeEvent called on each of those separately initialized (and by the looks of it, immutable) instances.
Having a single instance of the class represent multiple conceptual instances of the class by simply "reusing" it over and over is confusing to users of the class and very error prone.
If there is any state that is really conceptually independent of all of the instances, then that can be represented in static fields.

The alternative approach, assuming there is some other important reason to have a singleton, would be to remove the Create method entirely and simply pass productId as a parameter to WriteStateChangeEvent, so that you are no longer storing state that is tied to a conceptual instance.


text:
Q: Display element at the top inside display:flex container I try to display complex elements at the page, it should has image at the left top and text at the right side, I use display:flexbox for the parents of those elements to achive that, but images displays at the center of block
I have tried to change position and display properties but it didn't change anything,  I can move it using margin-top: -200px but it's not a good solution.
That's how my code looks in html:

    <CompanyLogo fileName={fileName} url={url} />

{renderFacts(facts)}

company-details class:
.company-details {
  display: flex;
}

The CompanyLogo component has:
.company-logo {
  width: 250px;
  margin-right: 200px;
}

Please help me to

A: I think that you have something similar to this in your CompanyLogo component, a div inside wrapping the content.

So, if it's the case, add the following style:
.company-logo {
    width: 250px;
    margin: 0;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
}

A: Try with:
.company-logo {
  align-self: flex-start;
  width: 250px;
  margin-right: 200px;
}

A: add  "order:-1;" -> company-logo


text:
Q: How to change column names of autodetected partitions created by Glue Crawler? I have bucket which is used as destination for a Kinesis Firehose stream.
Firehose automatically creates date-based prefixes on that bucket using the yyyy/mm/dd/HH format.
Then I created a crawler that will search for data into this bucket and configured it as follow:

After running the crawler, it creates a table with the following schema:
| #   | Column name   | Data type | Key           |
| --- | -----------   | --------- | ------------- |
| 1   | numberissues  | int       |               |
| 2   | group         | string    |               |
| 3   | createdat     | string    |               |
| 4   | companyunitid | string    |               |
| 5   | partition_0   | string    | Partition (0) |
| 6   | partition_1   | string    | Partition (1) |
| 7   | partition_2   | string    | Partition (2) |
| 8   | partition_3   | string    | Partition (3) |

If I rename the partition-* to their right counterparts year, month, day and hour, the table is ready for me to use.
However, if the crawler runs again, the schema revets the column names to the original partition-*.
I know this would work for Hive partition schemas year=2018/month=04..., but I want to know if it's possible to "hint" Glue about the partition field names.
Another alternative would be trying to change the Firehose prefixing, but I couldn't find anything that suggests this is even possible.

A: In this case you can set the "Ignore the change and don't update the data catalog" option.
Then you can rename the columns. This will allow the crawler to detect new partitions on the next run but keep therenamed names.

A: It is now possible to specify a custom format for the S3 prefixes written by Firehose. To comply with the Hive style of partitions, you can use this syntax in your prefix:
beginning_of_prefix/year=!{timestamp:yyyy}/month=!{timestamp:MM}/day=!{timestamp:dd}/hour=!{timestamp:HH}/

Example output:
beginning_of_prefix/year=2021/month=09/day=03/hour=16/

This will enable your Glue crawler to recognize the names of the partitions.
In a bit more details, the !{namespace:value} syntax AWS introduced allows accessing the timestamp that Firehose uses for partitioning and printing it into the prefix. This is done by specifying timestamp as a namespace, and a valid Java DateTimeFormatter string as the value. Note that:

When evaluating timestamps, Kinesis Data Firehose uses the approximate arrival timestamp of the oldest record that's contained in the Amazon S3 object being written.

And that:

If you specify a prefix that doesn't contain a timestamp namespace expression, Kinesis Data Firehose appends the expression !{timestamp:yyyy/MM/dd/HH/}to the value in the Prefix field.

(So if you don't use the timestamp namespace, the old way of partitioning is used)
Other namespaces also enable partitioning by firehose error type for the error output prefix for example.
Source
Docs


text:
Q: Can someone explain me the following implementation of Stack using Linked List in Java? Can someone explain me the following implementation of Stack using Linked List in Java? The link is this: http://algs4.cs.princeton.edu/13stacks/LinkedStack.java.html And this is the code:
       public class LinkedStack<Item> implements Iterable<Item> {
    private int N;          // size of the stack
    private Node first;     // top of stack

    // helper linked list class
    private class Node {
        private Item item;
        private Node next;
    }

    /**
     * Initializes an empty stack.
     */
    public LinkedStack() {
        first = null;
        N = 0;
        assert check();
    }

    /**
     * Is this stack empty?
     * @return true if this stack is empty; false otherwise
     */
    public boolean isEmpty() {
        return first == null;
    }

    /**
     * Returns the number of items in the stack.
     * @return the number of items in the stack
     */
    public int size() {
        return N;
    }

    /**
     * Adds the item to this stack.
     * @param item the item to add
     */
    public void push(Item item) {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        N++;
        assert check();
    }

    /**
     * Removes and returns the item most recently added to this stack.
     * @return the item most recently added
     * @throws java.util.NoSuchElementException if this stack is empty
     */
    public Item pop() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        Item item = first.item;        // save item to return
        first = first.next;            // delete first node
        N--;
        assert check();
        return item;                   // return the saved item
    }

    /**
     * Returns (but does not remove) the item most recently added to this stack.
     * @return the item most recently added to this stack
     * @throws java.util.NoSuchElementException if this stack is empty
     */
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        return first.item;
    }

    /**
     * Returns a string representation of this stack.
     * @return the sequence of items in the stack in LIFO order, separated by spaces
     */
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this)
            s.append(item + " ");
        return s.toString();
    }

    /**
     * Returns an iterator to this stack that iterates through the items in LIFO order.
     * @return an iterator to this stack that iterates through the items in LIFO order.
     */
    public Iterator<Item> iterator()  { return new ListIterator();  }

    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator implements Iterator<Item> {
        private Node current = first;
        public boolean hasNext()  { return current != null;                     }
        public void remove()      { throw new UnsupportedOperationException();  }

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next;
            return item;
        }
    }

    // check internal invariants
    private boolean check() {
        if (N == 0) {
            if (first != null) return false;
        }
        else if (N == 1) {
            if (first == null)      return false;
            if (first.next != null) return false;
        }
        else {
            if (first.next == null) return false;
        }

        // check internal consistency of instance variable N
        int numberOfNodes = 0;
        for (Node x = first; x != null; x = x.next) {
            numberOfNodes++;
        }
        if (numberOfNodes != N) return false;

        return true;
    }

    /**
     * Unit tests the <tt>LinkedStack</tt> data type.
     */
    public static void main(String[] args) {
        LinkedStack<String> s = new LinkedStack<String>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-")) s.push(item);
            else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
        }
        StdOut.println("(" + s.size() + " left on stack)");
    }
}

Everything is clear except the need of the check() method. What I don't understand is why after each operation (i.e. pop, peek) we need to check for consistency the number of elements in the stack and the variable N (the size of the stack). Don't we keep these two values consistent all the time? I really don't see what is the use of the check() method?

A: The check() method above is used only in assertions.
Assertions can provide a real-time check of intended invariants. They're disabled by default.
You can enable assertions to detect errors or debug, typically in a development environment.


text:
Q: Check validation before save rails Using Stripe and want to:
 1. check model validation
 2. if no errors process card token.
 3. If card works then save new record.
Below I have it where it processes card first, then if successful, saves record.  Unfortunately that record might fail validation but the card was already charged.
As a hack I have a js validation (that mirrors the model validations) in the view that doesn't allow the form to be submitted until the terms are met.
Tourregistration.rb Controller
    def create
token = params[:tourregistration][:stripeToken]
begin
  charge = Stripe::Charge.create(
  :amount => (params[:tourregistration][:invoice].to_d*100).round,
  :currency => "usd",
  :source => token,
  :description => "Example charge"
  )
rescue Stripe::CardError => e
  # The card has been declined
  redirect_to :back, :notice => "#{e}"
else

@tourregistrations = tourregistration_data.map do |tourregistration_params|
  Tourregistration.new(tourregistration_params)
end

@tourregistrations.each(&:save)

  if @tourregistrations.all?(&:valid?)
    flash[:notice] = 'Sign-up Complete'
    redirect_to root_url
  else
    redirect_to :back, :notice => "Something went wrong. Please fill in all fields."
  end
end

end
Tourregistration.rb Model
class Tourregistration < ActiveRecord::Base
belongs_to :patron
belongs_to :tour
has_one :referrer

validates :fname, length: { minimum: 2}
validates :lname, length: { minimum: 2}
validates :email, presence: true
validates :price, presence: true
validates :invoice, presence: true
validates :patron_id, presence: true
validates :tour_id, presence: true
end

A: Other than callbacks, you can use a database transaction, for example :
ActiveRecord::Base.transaction do
  results = @tourregistrations.map(&:save) # validate and save the records
  raise ActiveRecord::Rollback if results.any?{|result| result == false } # rollback the transaction if any registration failed to be saved
  payment = charge_card # process the payment
  raise ActiveRecord::Rollback unless payment # rollback if payment failed
end

As a side note, this kind of logic is a textbook example for a service object.


text:
Q: Generate a list of numbers equal to the number of rows in a table I have table with 7 rows; I want a query which will return the values shown in the second query, using the using total number of rows in the table, without using the table name.
CREATE TABLE IF NOT EXISTS `graph_owner` (
  `owner_id` int(5) NOT NULL AUTO_INCREMENT,
  `owner_name` varchar(256) COLLATE utf8_unicode_ci NOT NULL,

  PRIMARY KEY (`owner_id`)

);
INSERT INTO `graph_owner` (`owner_id`, `owner_name`) VALUES
(1, 'test1'),
(2, 'test2'),
(3, 'test3'),
(4, 'test4'),
(5, 'test5'),
(6, 'test6'),
(7, 'test6');

SELECT *
FROM (
    SELECT 1 AS id
    UNION SELECT 2
    UNION SELECT 3
    UNION SELECT 4
    UNION SELECT 5
    UNION SELECT 6
    UNION SELECT 7
) AS t

SQL Fiddle

A: select owner_id from graph_owner order by owner_1d

A: I am going to assume that you don't really mean to do it without using the table name, as even you know that's impossible. Thus, I think you really mean that you don't want to select the contents of the column. You can number your rows:
select `graph_owner`.*,
(@rowNumber := @rowNumber + 1) rowNumber
from `graph_owner`, (select @rowNumber := 0) r

If you only want the number without the contents of the table:
select (@rowNumber := @rowNumber + 1) rowNumber
from `graph_owner`, (select @rowNumber := 0) r;

Here's an updated fiddle where I've changed the primary key to be not consecutive: http://sqlfiddle.com/#!2/703fe/4


text:
Q: Finding duration of head yaw movements from video signal I need to find the duration of head yaw movement. The head tracking is
obtained  from video file that tracks head movements for each frame.
For example, the signal plotted below has three head yaw movements.
Is there a  way to find out the duration of signal change in the rectangles?
Yaw signal:

I used SG filter and find peaks but it gives a lot of unrelated peaks as shown :
order =4 ;
framelen =11;
x=yaw_deg;
lx = 20;

sgf = sgolayfilt(x,order,framelen);

plot(sgf);
grid on;

hold on;
sgf=-sgf;
[pks_smoothed,locs_smoothed,widths_smoothed,proms_smoothed] = findpeaks(sgf ,'MinPeakProminence',0.009);
pks_smoothed = -pks_smoothed;
plot(locs_smoothed,pks_smoothed,'g*');
text(locs_smoothed+.02,pks_smoothed,num2str((1:numel(pks_smoothed))'));

A: If you're looking for a quick solution and have the signal processing toolbox you can use the findpeaks function. Playing around with various parameters should allow you to identify your peaks.
inv_signal = -signal;
[pks,locs,w] = findpeaks(inv_signal,'MinPeakWidth',...,'MinPeakProminence',...);


text:
Q: Divisibility theorem based proof for any square mod 4 being either 0 or 1 Kindly help me in understanding the below proof for given statement:
If $n$ is a square, then leaves a remainder $0$ or $1$ when divided by 4.
Proof: The divisibility theorem states that for two integers $a,b$ with $b>0$, then there is a unique pair of integers $q$ and $r$ such that $a =qb +r$ and $0\le r <b$.
Let the number $n= a^2$, for $a$ being an integer. If $b$(divisor)$=4$, then $a = 4q +r$, where $r \in \{0, 1, 2, 3\}$, so that $n = (4q+r)^2 = 16q^2 + 8qr + r^2$.
If $r=0$, then $n=4(4q^2 +2qr) +0$; if $r=1$, then $n=4(4q^2 +2qr)+1$; if $r=2$, then $n =4(4q^2 +2qr+1) +0$; and if $r =3$, then $n = (4q^2 +2qr+2)+1$. In each case , the remainder is $0$ or $1$.

The difficulty lies in the last para. where according to me it should be:
If $r=0$, then $n=4(4q^2 +2qr) +0$; if $r=1$, then $n=4(4q^2 +2qr)+1$; if $r=2$, then $n =4(4q^2 +2qr) +2$; and if $r =3$, then $n = (4q^2 +2qr)+3$.

A: I think you missed the fact that the last $r$ is squared in the expression of $n$.
If $r=2$, then you have $$\begin{align}n=&16q^2+8qr+r^2\\=&16q^2+8q\cdot 2 + 2^2 \\=& 16q^2+16q+4\\=&4(4q^2+4q+1).\end{align}$$
For $r=3$, you missed a $4$ when writing the original solution, so you have
$$\begin{align}n=&16q^2+8qr+r^2\\=&16q^2+8q\cdot 3 + 3^2\\=&16q^2+24q+9\\=&16q^2+24q+8+1\\=&4(4q^2+6q+2)+1\end{align}$$
and since $r=3$, that's the same as $$n=4(4q^2+2qr+2)+1$$

A: Any integer is of the form $2n$ or $2n-1$ (i.e odd or even)
Now sq. of any number will be in the form $$(2n)^2 =4p or (4n-1)^2 =4q +1$$
So we find when that if $n$ is a square, then leaves a remainder $0$ or $1$ when divided by $4$.


text:
Q: Postgres will not allow new connections, suspended process, waiting error Environment
PostgreSQL 9.5, EnterpriseDB Postgres installer
Windows Server 2012R2 with Active Directory
Symantec End Point Protection
Symptom:
After about 1 week of running, one of PostgreSQL process (postgres.exe) showed "suspended" in task manager, and I cannot kill it in the task manager ("Access Denied" error message appeared). This "suspended" process was not the master PID as indicated in postmaster.pid file.
Current live connections still work but one cannot establish new connections. The only solution that I have is to restart the Server
Other information:
The PostgreSQL service is run under a domain account.
The maximum connection was never reached as it is set as 1000 and we only had about 10 connections.
There was plenty of available memory there. The total memory is 288GB and only 8% was used
There were minimum hard drive activities as it occurred. The C drive where PostgreSQL was installed had about 86GB of free space.
There are additional 4 table spaces that are not on C drive but spread over 4 hard drives. Each of 4 hard drives has more than 500GB of space.
we have been using the same configuration files for years and the same file is also used on a second PostgreSQL server, which does not have the issue at all.
The PostgreSQL logs had something like this when this happened and it continues to produce this warning message every minute or so:
2017-06-28 19:40:21 CDT WARNING:  worker took too long to start; canceled
2017-06-28 19:41:21 CDT WARNING:  worker took too long to start; canceled
2017-06-28 19:42:21 CDT WARNING:  worker took too long to start; canceled
2017-06-28 19:43:21 CDT WARNING:  worker took too long to start; canceled


text:
Q: check as a root if a special path set How do I check as a root if a special path set? This command
sudo echo $ANDROID_SDK_HOME

will show the path's value for a normal user and not for a root.

A: Step 1:
Open a terminal if necessary with CTRL+ALT+T
Step 2:
logon as root
sudo -i

Step 3:
Check the path
echo $ANDROID_SDK_HOME

Step 4:
If you opened a terminal at step one close it and you are no longer root; otherwise log out as root
exit


text:
Q: Testflight won't install iphone app on iPad that doesn't have GPS built-in I have a person who wants to install my iPhone app via Testflight on an iPad Air.  Specs:
Device Information:
Device: iPad4,1
iOS Version: 10.3.2
Language: en-US (English (United States))
Carrier: N/A
Timezone: PDT
Architecture: N/A
Connection Status: WiFi
Paired Apple Watch: N/A

They are getting an error "This build incompatible with your device. Requires 9.1 or later".  I assume this is because their iPad doesn't have built-in GPS.  However, this person stated they have enhanced location capability through an external GPS receiver which provides 10-foot accuracy.
I've installed this app on several iPads having GPS, so incompatibility is likely the GPS features of the app.  I've also made a build of the app targeting the exact version of iOS 10.3.
Does anyone have experience with this and a way to get past this without requiring a version of the app without GPS?
Thanks.

A: If your app requires the presence of GPS (or AGPS) hardware when tracking locations and you specifically mentioned gps capability, then your app won't  install on the devices without GPS.
You can remove this key.

*

*Go to Info.plist

*Look for the key UIRequiredDeviceCapabilities (Required device capabilities) and remove the key gps from the list.

Note: I don't think external GPS will help is this case for app installation.


text:
Q: Change the size of SVG according to device size in D3.js? I am trying to visualize map and charts using leaflet.js and d3.js. I want to make the view device compatible. But my charts and maps are not device compatible. The code of showing a simple bar chart is below:
function updateCharts(data){

var margin = {top: 20, right: 20, bottom: 70, left: 40},
width = 400 - margin.left - margin.right,
height = 250 - margin.top;
var x = d3.scale.ordinal().rangeRoundBands([ 0, width ], .05);
var y = d3.scale.linear().range([ height, 0 ]);

var xAxis = d3.svg.axis().scale(x).orient("bottom");
var yAxis = d3.svg.axis().scale(y).orient("left").ticks(20);

x.domain(data.map(function(d) { return d.time; }));
y.domain([0, d3.max(data, function(d) { return d.speed1; })]);

var svg=d3.select("#bar").append("svg").attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom).append("g").attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

var transition = svg.transition().duration(750), delay = function(d, i) {
    return i * 50;
};
svg.append("text").attr("x", width / 2).attr("y", 0).style("text-anchor",
        "middle").text("Speed of Lane1 Vs Time");

//Create X axis label
svg.append("text")
    .attr("x", width / 2 )
    .attr("y",  height + margin.bottom)
    .style("text-anchor", "middle")
    .text("Time");

svg.append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 0-margin.left)
    .attr("x",0 - (height / 2))
    .attr("dy", "1em")
    .style("text-anchor", "middle")
    .text("Speed");

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .selectAll("text")
    .style("text-anchor", "end")
    .attr("dx", "-.8em")
    .attr("dy", "-.55em")
    .attr("transform", "rotate(-90)" );

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".71em")
    .attr("x",5)
    .style("text-anchor", "middle");

svg.selectAll("rect")
    .data(data)
    .enter().append("rect").transition().delay(0)
    .style("fill", "red")
    .attr("x", function(d,i) { return x(d.time); }) //v
    .attr("width", x.rangeBand())
    .attr("y", function(d) { return y(d.speed1); })
    .attr("height", function(d) { return height - y(d.speed1); });
//function(d){return " "+d.datetime;}

//transition.select(".y.axis").call(yAxis);

// New SVG
}

In the html I also added meta tag for device compatibility like below:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Even if the deveice size is small there appears horizontal Scrollbar. But i don't want to see such scrollbar horizontally. I want the charts and maps to be fitted within the device width. Can anyone kindly help me to solve this?

A: Example (note: uses jQuery):
var $graphic = $('#graphic');
function drawGraphic() {
    var margin = { top: 10, right: 10, bottom: 30, left: 30 };
    var width = $graphic.width() - margin.left - margin.right;
    $graphic.empty();
    // ... code to create the chart ...
}
d3.csv("data.csv", function(data) {  //loading data, may differ
    // ... manipulate data here ...
    drawGraphic();
    window.onresize = drawGraphic;
}

A method based on D3 responsive charts described here: http://blog.apps.npr.org/2014/05/19/responsive-charts.html
My example is described here: http://bl.ocks.org/michalskop/2fa7d4c0ae029c36ba4e
See it in action here: http://bl.ocks.org/michalskop/raw/2fa7d4c0ae029c36ba4e/
My demo for Leaflet based responsive map: http://bl.ocks.org/michalskop/raw/001f6182db52d08f4925/


text:
Q: Mongodb - cannot set dbpath to point to another volume /etc/mongodb.conf:
# Where to store the data.
dbpath=/vol3/var/lib/mongodb

$ mongo
MongoDB shell version: 2.4.9
connecting to: test
Thu Jun 26 15:01:24.017 Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145
exception: connect failed

$ less +G /var/log/mongodb/mongodb.log
Thu Jun 26 14:16:26.462 [initandlisten] exception in initAndListen: 10296
*********************************************************************
 ERROR: dbpath (/vol3/var/lib/mongodb) does not exist.
 Create this directory or give existing directory in --dbpath.
 See http://dochub.mongodb.org/core/startingandstoppingmongo
*********************************************************************
, terminating
Thu Jun 26 14:16:26.462 dbexit:
Thu Jun 26 14:16:26.462 [initandlisten] shutdown: going to close listening sockets...
Thu Jun 26 14:16:26.462 [initandlisten] shutdown: going to flush diaglog...
Thu Jun 26 14:16:26.462 [initandlisten] shutdown: going to close sockets...
Thu Jun 26 14:16:26.462 [initandlisten] shutdown: waiting for fs preallocator...
Thu Jun 26 14:16:26.462 [initandlisten] shutdown: lock for final commit...
Thu Jun 26 14:16:26.462 [initandlisten] shutdown: final commit...
Thu Jun 26 14:16:26.462 [initandlisten] shutdown: closing all files...
Thu Jun 26 14:16:26.462 [initandlisten] closeAllFiles() finished
Thu Jun 26 14:16:26.462 dbexit: really exiting now

$ ls -lah /vol3/var/lib/mongodb
ubuntu@ip-172-31-41-33:~$ ls -lah /vol3/var/lib/mongodb
total 45G
drwxr-xr-x  4 mongodb mongodb 4.0K Jun 26 14:14 .
drwxr-xr-x 42 root    root    4.0K Apr 24 06:50 ..
drwxr-xr-x  2 mongodb mongodb 4.0K May 21 08:56 journal
-rw-------  1 mongodb mongodb  64M May 20 09:34 test.0
-rw-------  1 mongodb mongodb 128M May 20 09:34 test.1
-rw-------  1 mongodb mongodb  16M May 20 09:34 test.ns
drwxr-xr-x  2 mongodb mongodb 4.0K May 13 23:33 vita
-rw-------  1 mongodb mongodb  64M May 20 09:37 vita.0
-rw-------  1 mongodb mongodb 128M May 17 11:51 vita.1
-rw-------  1 mongodb mongodb 2.0G May 20 09:39 vita.10
-rw-------  1 mongodb mongodb 2.0G May 20 09:39 vita.11
-rw-------  1 mongodb mongodb 2.0G May 17 18:58 vita.12
-rw-------  1 mongodb mongodb 2.0G May 17 19:05 vita.13
-rw-------  1 mongodb mongodb 2.0G May 15 23:47 vita.14
-rw-------  1 mongodb mongodb 2.0G May 15 15:09 vita.15
-rw-------  1 mongodb mongodb 2.0G May 17 11:50 vita.16
-rw-------  1 mongodb mongodb 2.0G May 16 12:36 vita.17
-rw-------  1 mongodb mongodb 2.0G May 16 13:20 vita.18
-rw-------  1 mongodb mongodb 2.0G May 16 13:59 vita.19
-rw-------  1 mongodb mongodb 256M May 17 11:51 vita.2
-rw-------  1 mongodb mongodb 2.0G May 16 14:39 vita.20
-rw-------  1 mongodb mongodb 2.0G May 16 15:20 vita.21
-rw-------  1 mongodb mongodb 2.0G May 16 16:02 vita.22
-rw-------  1 mongodb mongodb 2.0G May 17 16:31 vita.23
-rw-------  1 mongodb mongodb 2.0G May 17 19:00 vita.24
-rw-------  1 mongodb mongodb 2.0G May 18 08:23 vita.25
-rw-------  1 mongodb mongodb 512M May 17 11:51 vita.3
-rw-------  1 mongodb mongodb 1.0G May 17 11:51 vita.4
-rw-------  1 mongodb mongodb 2.0G May 17 11:51 vita.5
-rw-------  1 mongodb mongodb 2.0G May 17 21:42 vita.6
-rw-------  1 mongodb mongodb 2.0G May 17 18:56 vita.7
-rw-------  1 mongodb mongodb 2.0G May 17 19:04 vita.8
-rw-------  1 mongodb mongodb 2.0G May 17 17:25 vita.9
-rw-------  1 mongodb mongodb  16M May 20 09:39 vita.ns

/vol3 was created was monted from /dev/xvdf, and as you can see the files are there.
Any clue on what's wrong will be greatly appreciated.


text:
Q: I had Teltonika FMA120 Device with c# application , i can't send command from server to device to enable relay? I had Teltonika FMA120 Device its working fine with my c# application ,
I got IMEI from device the server acknowledge the device then i got all Position data.
But i can't send any command from server to device.
If i want to enable DOUT 1 and DOUT2 , tO access relay .
I write below in my Stream
                            Library.WriteErrorLog("Sending Test Data-----------------------");

                        byte[] ReplyBytesCmd;
                        ReplyBytesCmd = new byte[] { 0x00, 0x0d, 0x8c, 0x00, 0x02, 0x00, 0xb3, 0x00, 0x01, 0x01, 0x00, 0xb4, 0x00, 0x01, 0x01 };
                        //                                  len , id  ,       prms,        1st,           , val , 2nd ,           , val

                        stream.Write(ReplyBytesCmd, 0, 15);
                        Library.WriteErrorLog("Sending Test Data" + ReplyBytesCmd.ToString());

Dout1 - Port Id 179
Dout2 - Port Id 180
as per Teltonika Protocol.

A: For Teltonika FMBXXX devices you have to ACK the all the position data that you receive, all of the frames (there may be multiple if it has buffered data).
Then, after you ACK the last position data frame and the device is not sending anything, it is awaiting your commands. This is why it does not close the TCP connection.

A: The type of message you are sending to the FMA120 is unfamiliar to me. You can however use the Codec12 protocol for sending SMS/GPRS command from the server to the device. For example you can wrap the command 'setdigout 11' in a Codec12 message.


text:
Q: PDO database connection can not be used in other classes, but others can? I've been working on a databaseHandler php class, which should connect to the database and then be usable in other PHP files, atleast this was the plan. I've come across the problem that it cannot use any PDO related functions in my PHP class, i've tried checking if it was null, or not set at all (but it was) and i've also tried using a dummy function that just echos something which was to test if the class isn't undefined in others.
<?php
class databaseHandler {

    private $db;
    private static $instance;

     function __construct() {
        $this->buildDatabaseConnection();
    }

    public static function getInstance() {
        if(!self::$instance) {
            self::$instance = new databaseHandler();
        }

        return self::$instance;
    }

    private function buildDatabaseConnection() {
        require 'dbconfig.php';
        try {
    $this->db = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE . ";charset=utf8", USER, PASSWORD);
    if(isset($this->db)) {
        if(!is_null($this->db)) {
            echo "isn't null";
        }
    }
    } catch(PDOException $e) {
        $e->getMessage();
    }
    }

    public function getConnection() {
        return $this->$db;
    }

    public function getSomeShit() {
        echo "some shit";
    }

}
?>

The problem might be with the getConnection() php function, does it actually return the PDO object here? Because the main problem lays with the fact that i get this error when i use my getConnection function in other classes:
Notice: Undefined variable: database in     F:\Websites\DevProject\php\functions.php on line 69

Fatal error: Uncaught Error: Call to a member function prepare() on null in F:\Websites\DevProject\php\functions.php:69 Stack trace: #0 F:\Websites\DevProject\php\functions.php(51): register('qwe', 'sdasd', 'asdasd', 'asdas', '01-01-1970') #1 F:\Websites\DevProject\register.php(123): datelessRegister('qwe', 'sdasd', 'asdasd', 'asdas') #2 {main} thrown in F:\Websites\DevProject\php\functions.php on line 69

and line 69 would be this:
$stmnt = $database->prepare("SELECT $username, $email FROM " . USERTABLE);

Where the $database variable is the class instance:
$database = databaseHandler::getInstance();

If i try to var_dump it in my registration php file, it'll tell me this:
object(databaseHandler)#1 (1) { ["db":"databaseHandler":private]=> object(PDO)#2 (0) { } }

However, when i use it inside of my function, it will say it is 'NULL', why is it null in a function but defined globally?
All the errors relate to the object, and in there it tells me the pdo is undefined (i've tried checking if it was null, but it wasn't!)
Any help would be great, thanks in advance.

A: In the return statement of getConnection method you should write the class variable without $:
return $this->db;

Also, you  must do the queries on the PDO connection instead of your database handler class, so $database = databaseHandler::getInstance(); should be
$database = databaseHandler::getInstance()->getConnection();

or you can simply use the __call magic method to keep your code as it is right now:
public function __call($method, $args)
{
    return call_user_func_array(array($this->db, $method), $args);
}

Also, to clarify how to use this class, you should call it inside every method you need the database to be used, not only once on the top of your file, because defining it there it will not be available inside your methods/functions unless you don't use the global statement to import the variable. However usage of the global variable is not encouraged and it is considered as a bad practice. An example on how to use the database would be:
public function doSomething()
{
    $db = databaseHandler::getInstance()->getConnection();
    $db->prepare(....);
}

public function doSomethingElse()
{
    $db = databaseHandler::getInstance()->getConnection();
    $db->prepare(....);
}

If you know there are many methods inside your class that uses the database then you can define it as a class variable and set the db instance in the constructor.

A: The problem seems to be in the getConnection() function. Since $db is field you must do.
return $this->db;

However this is a very complex class structure for a simple problem.
You can directly extend your class from PDO
class DatabaseHandler extends PDO {
    function __construct() {
        parent::__construct('mysql:host=host_name;dbname=db_name', 'user_name', 'password');
        parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
}

And create an object of this whenever you want to do database transaction.
$db = new DatabaseHandler();
$stmt = $db->prepare(".....");
$stmt->execute();

A: You seem to be having issues with scopes.
$database = databaseHandler::getInstance();

function doSomething()
{
    // $database is not defined in this scope
    $database->getConnection()->prepare(/* ... */);
}

You have to declare it as part of the global scope
function doSomething()
{
    global $database;
    $database->getConnection()->prepare(/* ... */);
}


text:
Q: How to link a JMenuItem to a JButton Let's say I have a JMenuItem with a text inside "Exit", and a JButton with the text "Exit",
the command which JButton will use is System.exit(0), of course using Action Listener, Ok i Know, I can put the same codes when clicking on the JMenuItem, but isn't there a way, that when I click on the JMenuItem, the JButton is clicked so then the following commands are executed (JButton commands)?

A: What you can do is create an Action object, and use that for both your JButton and your JMenuItem.
Action exit = new AbstractAction() {
        private static final long serialVersionUID = -2581717261367873054L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    };
exit.putValue(Action.NAME, "Exit");
exit.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_X);

JButton exitButton = new JButton(exit);
JMenuItem exitItem = new JMenuItem(exit);

A: A good way to do this is to set the same ActionListener to both components. Like this:
JButton button = new JButton ("Exit");
JMenuItem item = new JMenuItem ("Exit");

ActionListener exitaction = new ActionListener ()
{
    public void actionPerformed (ActionEvent e)
    {
        System.exit (0);
    }
};

button.addActionListener (exitaction);
item.addActionListener (exitaction);

However, I would recommend against using System.exit (0). The better way of closing the program (which I assume is basically a JFrame) is by setting
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE)
(where frame is the window of the program)
and calling frame.dispose () in the ActionListener.

A: I consider the best way to do this is to register the same ActionListener instance in the event listeners of both JMenuItem and JButton, it's like using the old Command design pattern.
I would not recommend trying to trick the events 'engine' like making the JMenuItem fire the event related to the pressing of the JButton, since that is not what's happening but what you seem to want is to reuse both actions to 2 distinct events.

A: You can try to save the button as a class field
private JButton button;

and insert in the click event handler of the menu item the code
button.doClick();

but the solution of SoboLAN is more elegant.


text:
Q: Add a caution over 18 I have an adult blog and I was wondering if there's a code  I can put on my blog to do something like a caution asking if you're over 18 or leave the blog now, something like what you see if you go here
I wish I could manage the transparency of the warning...

A: You can use several different languages to achieve this effect like jquery, javascript, and php.  The link below can help you get started on reading up on how it can be done with some good informational tips:
Age Verification
Hope this helps you get started

A: That's enough to set NSFW (not safe for work) label turn on in your Tumblr blog settings:


text:
Q: How far can a sub-light-speed particle travel? And how fast will it arrive? If we send a photon away from earth, it would eventually reach a comoving distance of about 16.5 billion light years (the universe's event horizon). I'm interested in how far (in comoving distance) particles moving below $c$ can eventually travel and at what velocity they would arrive if they were to reach a distant comoving galaxy near the end of this journey.
A simple answer to both would be that a particle moving at $kc$ (where $0<k<1$) could eventually travel $k$ times as far as light could. This is what I get if I assume $v_{peculiar}$ is always equal to $kc$ and $v_{recessional} = H(t) \cdot distance(t)$ (both in proper coordinates) and take the integral of velocity over time to get the distance.
However, I've also heard that the momentum of a particle reduces as it travels, resulting in redshift for photons (since they can't lose velocity) and in velocity loss for other particles. It seems that this could affect the above calculations. For example, this textbook says $\frac{\dot{p}}{p}=-H$.
Does this mean that a particle launched at $kc$ would instead travel less than $k$ times 16.5 billion light years and arrive at a galaxy near that limit with a relative (proper) velocity near zero?
(Bonus points if you could derive an equation for the the maximum distance as a function of $k$.)

A: The cosmological event horizon is the furthest distance light can travel and is also the upper bound to how far a massive particle can travel. A free falling massive particle will asymptotically approach a point which is receding from the point which it started with the same recessional velocity as its original peculiar velocity.
I believe the correct expression would be:
$$s = \int^{\infty}_{t_0} \frac{kdt}{a(t)}$$
Where $s$ is the total comoving distance traveled by the particle, $t$ is cosmological time, $t_0$ is the time the particle set off,  $k$ is the peculiar speed of the particle at $t_0$ and $a(t)$ is the scale factor.


text:
Q: How to write a script with javascript which fills in then submits a prompt? I am trying to write a script (using node.js) which I can use as a task runner or test automation script. I have a web application which uses socket.io where a user can communicate with the server. The application is basically chat application where multiple users can communicate with the server and each other. What I'm trying to do with the script is:

*

*Open the URL (done)

*Wait for page to load (done)

*Fill in Prompt which will be a username then submit

*Then repeat 1-3 as another user

The application itself works but I am just in the process of creating scripts which will allow some form of automation testing to observe changes in the css.
So I have the prompt within index.html in a  element:
username = prompt("What is your username?");

and this is the test script within server.js (a node.js server):
ar open = require('open');

console.log('Test script starting...');

open("http://localhost:8080");

console.log('Waiting for DOM to be loaded...');

setTimeout(function(){
    console.log('DOM loaded!');
    //Fill in prompt and submit prompt

}, 5000);

Is it possible to fill in a prompt then submit using a script and what language or framework is better for this purpose?


text:
Q: Benefit of using Nested class in java what are the benefits of using nested class in Java? In many examples it seems to me it only adds complexity to the design. Is there any example that shows the power of using nested class in comparison to for example composite pattern?

A: Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:

*

*It is a way of logically grouping classes that are only used in one place.

*It increases encapsulation.

*Nested classes can lead to more readable and maintainable code.

(from the docs)
I think that the best case I can think of, off the top of my head would be the implementation of nodes in some sort of collection class (tree, linked list, map, etc). There is no reason why the node implementation should be exposed to the public, and since it is only used by the internals of your collection, it makes sense to make the node class nested inside the collection class.
Something along the lines of..
public class MyTree {
  private class TreeNode {
    //implementation details...
  }

  //public api, where implementation references TreeNode
}

A: I would use a nested class in a case, where I mostly need this class inside the surrounding class. This could be usages like event listeners.
Or in the case when I need to fulfill a specific interface as a parameter to an API method and only create this structure in this specific top level class.
This avoids the creation of more top level classes - messing your code base - that are not useful to any other class.
Hope this helps. :)

A:
Is there any example that shows the power of using nested class in comparison to for example composite pattern?

Nearly all the Iterator implementations and the implementations for keySet() and values() are nested.  The actual name is not important but they need access to the outer class to do their work.
Having these be top level classes wouldn't be elegant or encapsulated.

A: There are many examples I can think of to use nested classes
1- Extending a class for the purpose of using it just inside this instance with a different behavior than usual (overriding a method or more)
2- A short hand for implementing and passing an event listener to whatever method in one single step
3- Implementing a class that is too specific to be defined globally (or with package visibility or private or whatsoever). and you just want to hide it into the larger class
I do agree though that the usage of inner classes would complicate the code no matter how hard you try to make the for formatter beutiful but it has its uses, so as my own rule of thumb I only use inner classes when I'm sure that one of the above applies and that its size will be minimal in order not to vandalize my code
and for that mattar keep all the code minimal :)

A: We use nested (inner) classes when we know that this class will primarily be used only by the class that it will be written into. It keeps the package structure cleaner. Complexity is reduced by making use of an IDE where you can easily find classes that are not listed in the package structure.

A: As requested a real world example, take a look at the ArrayList implementation for the jdk.
You could find it here:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/ArrayList.java#ArrayList
You will find (among other things) the iterator class inside the Arraylist class. I would guess, the reason for this behavior (as for most of the iterable collection subclasses) is the direct connection between the collection and its iterator. You do not need it outside the class.
You can find nested class in more places inside the jdk.