text:
Q: What does mean SSL_library_init is not reentrant for practical purposes? I'm using openssl library to open a TLS connexion to some server. Reading the library documentation (yes, some people still read documentations and man pages) I stumbled upon the sentence "SSL_libary_init() is not reentrant".
I understand generally speaking what is a non reentrant function: ie some function that keeps an internal state in such a way that calling it twice at the same time or interrupting it while it executes may cause mayhem (the function not doing what callers are expecting).
But in the specific case of SSL_library_init() I wonder what it actually means.

*

*does it mean that if some interrupt occurs while calling SSL_library_init() it won't correctly initialize SSL library ? Hence am I supposed to disable all accessible interrupts before calling it and reenable the needed ones aftwerward ?

*does it means that it's thread unsafe, and that I should ensure that two threads can't call it at the same time ? (looks likely, even if thread safety does not exactly means the same as reentrant).

*does it means I should'nt call it two times in the program lifetime, or that calling it while SSL connections are open it will wreak havoc ?
AS I'm working on a proxy with one end being client and the other one being server, both ends could potentially be using TLS services, (but i could also be only one end, or none). Should I manage SSL library as a system wide singleton ? If this is the case it's easy enough to manage but it is not exactly a reentracy issue as I understand the word.
I do not know the short word for a function that should only be called once...
I also have a similar question for SSL_CTX_new(). The documentation states it should only be called once per program lifetime. This is annoying as it seems to restrict both server and client (or several independant server or client instances running in the same process) to use the same SSL_METHOD and it does not feel right, but I still hope in this case it's merely some documentation inaccuracy.
Does anyone have enough experience with openSSL to explain what I should or should not do with OpenSSL initialisations code to stay on the safe side ?

A: I can give you a hint based on what I'm seeing.   I have a CentOS 7 / Django 1.9.3 / Apache 2.4 / mod_ssl / Python 3.4 web server that receives https: connections from users.  While processing requests, the server needs to query a backend for information needed to satisfy the request.  The backend query works fine when run standalone, but it generates:
OSError(0, 'Error')
Line 810, /lib64/python3.4/ssl.py

803  def do_handshake(self, block=False):
804      """Perform a TLS/SSL handshake."""
805      self._check_connected()
806      timeout = self.gettimeout()
807      try:
808          if timeout == 0.0 and block:
809              self.settimeout(None)
810          self._sslobj.do_handshake()          # <<<-------

when run in the Apache WSGI context.
If in fact mod_ssl is causing my error, that implies that the library is thread safe (because Apache of course can serve multiple web requests concurrently) but non-reentrant (because SSL cannot be used twice -- e.g. for front-end and back-end connections -- in a single thread).
Surely two-tier web servers are a mature design pattern so there must be a workaround.   Thanks for posting that bit about non-reentrancy - it was the first clue I've found that might be the cause of my problem.
For reference, my code calls a RESTful service that takes the user's distinguished name extracted from SSL_CLIENT_CERT and returns user attributes in JSON format:
import requests, urllib

URL = 'https://example.com/rest/user_info/'

def get_user_info(dn)
    query = URL + urllib.parse.quote(dn)
    return requests.get(query, cert=('server.crt', 'server.key'), verify='ca_bundle.crt').json()

That code works perfectly when run from the command line on the web server (in the WSGI directory as user apache) but blows up when invoked by Apache itself.


text:
Q: What are the rules for structuring Java source files, and/or declaring/importing packages to ensure error-free compilation? I have several files kept in a package, customQ.  This package is imported into a test client called QWithExceptions.  The source tree is arranged as follows:
/tryThis09_01/+
              |
              -QWithExceptions.java
              |
              /customQ/+
                       |
                       -circularQ.java
                       -staticQ.java
                       -emptyQException.java
                       -fullQException.java

The test client compiles without error when I cd to tryThis09_01/ and run $javac QWithExceptions.java.
However, when I decided to experiment a little I find that my intuition regarding packages and their structure is completely off.  The actual package customQ and the test client QWithExceptions is buried more deeply in a source tree like so:
~/learningJava/beginnersGuide/chapter09/tryThis09_01/+
                                                     |
                                                     -QWithExceptions.java
                                                     |
                                                     /customQ/+
                                                              |
                                                              -circularQ.java
                                                              -staticQ.java
                                                              -emptyQException.java
                                                              -fullQException.java

The linter in my development environment suggested that I change the package declaration in customQ/*.java from package customQ; to package beginnersGuide.chapter09.tryThis09_01.customQ;.  After doing so, I then changed the import statement in the test client to reflect the new package name and moved QWithExceptions.java to ~/learningJava/ and executed $javac QWithExceptions.java, which resulted in a flurry of compilation errors.
I've also tried $javac -cp .:$CLASSPATH QWithExcpetions.java and $javac -d . -cp .:$CLASSPATH QWithExcpetions.java, as well as moving QWithExceptions.java further up and further down the source tree one directory at a time, all with various errors.
At the moment, I'm grappling with a bad class file error.  While I understand that the compiler wants me to move the offending file somewhere else in the file tree (or perhaps modify the package declarations or import statements) I'm not sure how to do this without invoking a package does not exist error.
I'm surely missing some essential rule of package writing that isn't (to me) immediately obvious from the trivial implementations found on the broader web or in my Java texts.  If you know what it is, please share your wisdom.

A: I cannot reproduce your issue because you forgot to show the error messages and file content. But I can show you how it works:
My folder structure:
stefan@stefanpc:~/learningjava$ tree
.
├── beginnersGuide
│   └── chapter09
│       └── tryThis09_01
│           └── customQ
│               └── Test.java
└── Main.java

File Test.java:
package beginnersGuide.chapter09.tryThis09_01.customQ;

public class Test
{
   public int i;
}

File Main.java:
import beginnersGuide.chapter09.tryThis09_01.customQ.Test;

public class Main {

    Test test;

    public static void main(String[] args){
        System.out.println("Hello");
    }
}

Compile:
stefan@stefanpc:~/learningjava$ javac Main.java
stefan@stefanpc:~/learningjava$

Classes and the related filenames should start with an uppercase character. But I assume that this is not your problem cause.
Recommendations of Oracle:
https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html

A: Java requires a package declaration align with the folder structures.  For example if you have a package a.b.c' declared at the  top of a source file, you need to put that path in an a/b/c folder structure.  Note that the folder structure is relative to the source root during compilation.  So if you have your code in a 'src' folder, and try to compile from the context the parent of that 'src', you will get errors because the folder structure looks like src/a/b/c to the compiler.  Likewise, if your compilation context is set to folder 'a', you would get errors because now the folder looks like b/c to the compiler.
This is a common issue for people new to Java.  It's meant to make things easy to find but can be an annoyance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache with mod_wsgi emitting error concerning database in django First off, I have searched and tried numerous answers on this topic but none seems to help.
For some reason, I am having a weird error with Apache and django. Here's my setup:
I am running Mac OS X El Capitan, I am using the OS Apache 2.4 and I have installed mod_wsgi extension. I can run django through the terminal using the "runserver" command without any issues. I am also running my django project in a virtual environment. I installed python3 so that I don't have to use the OS python 2. The virtual environment is therefore based on python 3.
My django project connects to mysql using the mysqlclient driver as recommended in the django docs. My django version is 1.9.
I have configured my apache vhost file to serve my django project using this vhost configuration:
<VirtualHost *:80>

ServerName simplesurvey.proj
ServerAdmin admin@simplesurvey.proj

Alias /static /Users/UncharteD/Sites/project/survey/static/
<Directory /Users/UncharteD/Sites/project/survey/static/>
    Require all granted
</Directory>

<Directory /Users/UncharteD/Sites/project/surveyproject/>
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>

WSGIDaemonProcess simplesurvey python-path=/Users/UncharteD/Sites/project/:/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages
WSGIProcessGroup simplesurvey
WSGIScriptAlias / /Users/UncharteD/Sites/project/surveyproject/wsgi.py

I am getting a 500 error status in my web browser. I have added simplesurvey.proj as an entry to my host file. Here is the browser message precisely:
Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

I checked my Apache error log and it consists of this:
Full Apache error log
The most important bit (I think) is the stack trace. Why is it failing to load a module when the command line version can perfectly do everything?  Here is a bit from the log:
   [Thu May 05 18:31:52.828568 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0] mod_wsgi (pid=64376): Target WSGI script '/Users/UncharteD/Sites/project/surveyproject/wsgi.py' cannot be loaded as Python module.
[Thu May 05 18:31:52.828660 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0] mod_wsgi (pid=64376): Exception occurred processing WSGI script '/Users/UncharteD/Sites/project/surveyproject/wsgi.py'.
[Thu May 05 18:31:52.828681 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0] Traceback (most recent call last):
[Thu May 05 18:31:52.828701 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/Sites/project/surveyproject/wsgi.py", line 16, in <module>
[Thu May 05 18:31:52.828779 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     application = get_wsgi_application()
[Thu May 05 18:31:52.828792 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
[Thu May 05 18:31:52.828875 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     django.setup()
[Thu May 05 18:31:52.828898 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/__init__.py", line 18, in setup
[Thu May 05 18:31:52.828973 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     apps.populate(settings.INSTALLED_APPS)
[Thu May 05 18:31:52.828991 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
[Thu May 05 18:31:52.829136 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     app_config.import_models(all_models)
[Thu May 05 18:31:52.829150 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models
[Thu May 05 18:31:52.829224 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     self.models_module = import_module(models_module_name)
[Thu May 05 18:31:52.829234 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
[Thu May 05 18:31:52.829309 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     __import__(name)
[Thu May 05 18:31:52.829320 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/Sites/project/survey/models.py", line 22, in <module>
[Thu May 05 18:31:52.829432 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     class Genre(models.Model):
[Thu May 05 18:31:52.829441 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/db/models/base.py", line 108, in __new__
[Thu May 05 18:31:52.829807 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     new_class.add_to_class('_meta', Options(meta, app_label))
[Thu May 05 18:31:52.829817 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/db/models/base.py", line 307, in add_to_class
[Thu May 05 18:31:52.829844 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     value.contribute_to_class(cls, name)
[Thu May 05 18:31:52.829852 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/db/models/options.py", line 263, in contribute_to_class
[Thu May 05 18:31:52.830098 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
[Thu May 05 18:31:52.830109 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/db/__init__.py", line 36, in __getattr__
[Thu May 05 18:31:52.830150 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     return getattr(connections[DEFAULT_DB_ALIAS], item)
[Thu May 05 18:31:52.830158 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/db/utils.py", line 212, in __getitem__
[Thu May 05 18:31:52.830249 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     backend = load_backend(db['ENGINE'])
[Thu May 05 18:31:52.830258 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/db/utils.py", line 116, in load_backend
[Thu May 05 18:31:52.830271 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     return import_module('%s.base' % backend_name)
[Thu May 05 18:31:52.830279 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
[Thu May 05 18:31:52.830291 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     __import__(name)
[Thu May 05 18:31:52.830297 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]   File "/Users/UncharteD/.virtualenvs/survey/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 28, in <module>
[Thu May 05 18:31:52.830400 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0]     raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
[Thu May 05 18:31:52.830420 2016] [wsgi:error] [pid 64376] [remote 127.0.0.1:0] ImproperlyConfigured: Error loading MySQLdb module: No module named _mysql

Any help on how to fix this would be appreciated. Thanks

A: Maybe a permission issue?
Apache has it's own user, so maybe that user don't have access to your virtualenv path, specially since it's inside a user folder. That's usually fixed by adding the apache user to your usergroup.
At least I know that's how it works for Linux, I'm guessing it kinda the same for Macs?


text:
Q: I cannot display dynamic page title using spring 3 and apache tiles 2.2 I have a problem using spring 3 and tiles 2.2.2 . I can't display a dynamic page title.
These are my config/jsp files:
layout.jsp
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

        <title><tiles:getAsString name="title" ignore="true"/></title>

        <tiles:insertAttribute name="header" />

                <tiles:insertAttribute name="body" />
                <tiles:insertAttribute name="menu" />

        <tiles:insertAttribute name="footer" />

Spring config file:
<bean id="tilesviewResolver"
    class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
    <property name="order" value="0" />
    <property name="requestContextAttribute" value="requestContext" />
    <property name="viewClass"
        value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/tiles.xml</value>
        </list>
    </property>
    <property name="tilesProperties">
        <props>
            <prop key="org.apache.tiles.evaluator.AttributeEvaluator">org.apache.tiles.evaluator.el.ELAttributeEvaluator
            </prop>
        </props>
    </property>
</bean>

tiles.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
    <definition name="base.definition" template="/WEB-INF/views/layout.jsp">
        <put-attribute name="title" value="" />
        <put-attribute name="header" value="/WEB-INF/views/inc/header.jsp" />
        <put-attribute name="menu" value="/WEB-INF/views/inc/menu.jsp" />
        <put-attribute name="body" value="" />
        <put-attribute name="footer" value="/WEB-INF/views/inc/footer.jsp" />
    </definition>

    <definition name="item/itemDetail" extends="base.definition">
        <put-attribute name="title" value="%{title}"/>
        <put-attribute name="body" value="/WEB-INF/views/item/itemDetail.jsp" />
    </definition>

</tiles-definitions>

the page title isn't replaced with title value rendered by controller, instead %{title}.
Thanks in advance

A: I think that your page definition should look like this (note the 'expression' attribute and '$' instead of '%'):
<definition name="item/itemDetail" extends="base.definition">
    <put-attribute name="title" expression="${title}"/>
    <put-attribute name="body" value="/WEB-INF/views/item/itemDetail.jsp" />
</definition>

Are you sure that there is an attribute called ${title} in a relevant scope? Have you tried rendering the value of ${title} directly in the itemDetail.jsp page?
Here's the relevant documentation, tiles uses the servlet container's EL support for this:
http://tiles.apache.org/2.1/framework/tutorial/advanced/el-support.html.


text:
Q: Как записать это "arr = []; ⏎ arr.push(smtn);" в одну строку? Есть такой небольшой кусочек кода:
if (Rect.__instances__) {
  Rect.__instances__.push(this);
} else {
  Rect.__instances__ = [];
  Rect.__instances__ = [].push(this);
}

Суть: если у класса есть свойство __instances__, то пихаем в него this. Если нет, то сначала инициализируем __instances__ пустым массивом, а после этого пихаем в него this.
Нужно записать это условие в одну строку вида:
Rect.__instances__ ? Rect.__instances__.push(this) : Rect.__instances__ = [].push(this);

Но этот код вместо того, чтобы вернуть массив со значением this внутри, просто возвращает единицу.
Тогда я попробовал сделать так:
Rect.__instances__ ? Rect.__instances__.push(this) : Rect.__instances__ = (() => {return []}).push(this);

На что мне выдало ошибку вида:

Uncaught TypeError: (intermediate value).push is not a function

Пробовал еще и так:
Rect.__instances__ ? Rect.__instances__.push(this) : Rect.__instances__ = (() => {new Array()}).push(this);

Ошибка та же.
Теперь прошу помощи здесь.
Кстати, если кто-то понял, что делает этот код и для того, что я пишу есть решение получше, вроде методов стандартной библиотеки, то такой подход тоже сгодится :)
P.S. Я добавил к вопросу тег lambda, потому что здесь, вроде как именно про это речь и идет. Дело в том, что лямбды в JavaScript'е я гуглил, и в ответ мне выдавало только инфу, связанную со стрелочными ф-ми. Поэтому рискнул предположить, что, поскольку дело тут, скорее всего, именно в стрелочной функции, то и тег "лямбда" сюда подходит.

A: Выбирай. Вроде последний вариант хороший.
if (Rect.__instances__) {
  Rect.__instances__.push(this);
} else {
  Rect.__instances__ = [this];
}

Rect.__instances__ ? Rect.__instances__.push(this) : (Rect.__instances__ = [this]);

if (!Rect.__instances__) {
  Rect.__instances__ = [];
}

Rect.__instances__.push(this);

(Rect.__instances__ = Rect.__instances__ || []).push(this);

A: (Rect.__instances__ = []).push(this);

или
Rect.__instances__ = [this];

а push возвращает новую длину массива, поэтому Вы и наблюдали единицу в первоначальном варианте кода.

A:

var Rect={};

if (Rect.__instances__) {
  Rect.__instances__.push("1111");
} else {
  Rect.__instances__ = new Array("1111");
}
console.log(Rect)


text:
Q: How do I make a MySQL constraint to disallow certain column values for a single row? I have a Table.
word      singular_only      plural_only
homework       1                  0       #homework has no plural
dog            0                  0       #dog and dogs are both real words
scissors       0                  1       #scissor is not a valid singular noun
 x             1                  1       #should not be insertable

I want to allow the first three rows but not the fourth. How do I add a constraint for this. The values in singular_only and plural_only are boolean. The columns mean whether a word only has a plural form or singular form or both (if both booleans are false). Obviously if something can only be singular it cannot also be plural. What is the best way to model this in MySQL.
Is it better to add this constraint in MySQL or to ensure that the overlying code never tries to insert these values.
In other words
singular_only NAND plural_only should also be true

A: You can't add a constraint on one column based on another column except to constrain matching values, which you do not want to do.  You should be using a single column to set "singular/plural" status.  There are several solutions including using an integer (0,1,2 for the three possible states), an enum, and even another table.  I'll leave the choice up to you, but I would favor the flexibility and clarity of another table.


text:
Q: How can a web user be authenticated through their machine without providing a username and password? I'm wondering how I can authenticate a user through their device, so they don't have to provide a username and password?
For example I'm on an Android tablet and I connect to www.mysite.com (which is an asp.net site).  I want the web browser to submit something to www.mysite.com to handle the authentication so the user doesn't have to put in a username and password and can only use the service from the device.

A: For our use case we were able to control the url passed to the server.  To initiate the process we have the user login once and we generate a guid to be appended to the url when they initially hit our site.  When they hit our site with a guid and aren't logged in, we log them in.


text:
Q: Android: Query nearby locations from firebase I have a firebase database(realtime database) with more than 700 objects. Each one of them has latitude and longitude. I would like to know if there is some way to query them and show only those which are near to the device location. I've tried to understand geofire but I couldn't.
This is a example from one object in firebase:

and this is what i've been using to show all data:
ChildEventListener childEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
                mDatabase = FirebaseDatabase.getInstance().getReference();
                Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());

                //Get firebase info for each gym
                Gym gym=dataSnapshot.getValue(Gym.class);
                gym.setGym_id(dataSnapshot.getKey());

               //Set custom marker with firebase info
                LatLng newLocation= new LatLng(Double.parseDouble(gym.getLatitude()),Double.parseDouble(gym.getLongitude()));
                if (dataSnapshot.hasChild("raid")){
                    Marker marker= mMap.addMarker(new MarkerOptions()
                            .position(newLocation)
                            .title(gym.getName())
                            .snippet(gym.getUrl())
                            .icon(BitmapDescriptorFactory.fromBitmap(bMapRaid)));
                    marker.setTag(gym);
                } else {
                    Marker marker= mMap.addMarker(new MarkerOptions()
                            .position(newLocation)
                            .title(gym.getName())
                            .snippet(gym.getUrl())
                            .icon(BitmapDescriptorFactory.fromBitmap(bMap)));
                    marker.setTag(gym);
                }
            }

A: yes, if you have a main tree node with all your usersID and inside each userID you have latitude and longitude, you can query all your users tree, and get inside of each one your latitude and longitude, and then you can do the logic to check if each pulled lat and long is nearby yours.
this is how you retrieve all the data, lets say you have a main tree node Users and inside that you have each userUID with latitude and longitude inside of each one, you should do something like this
  mDatabase.child("Users").addValueEventListener( new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<Users> users = new Arraylist<>(); //an arraylist to save all the latitude and longitude values
            for(DataSnapshot post : dataSnapshot.getChildren() ){
                // Iterate through all your users and get latitude and longitude
               Users u = users.getValue(Users.class); //here you need a pojo in which you will have the variables you want to fetch, they need to be named exactly as your database one , remember, a pojo is just a class with setters and getters
               //and then just get your values and add them to your array
              long latlang =  u.latitudelongitude; //store your latlang
// in your case you dont have 1 key with latitude and longitude, you will have to fetch them separate, just do long latitude = u.latitude; and long longitude = u.longitude;
               users.add(latlang);  //add it to your arraylist

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });

then after you get all the values, just retrieve them from the arraylist and compare them to yours, do some logic there and you are done
I would suggest to you to store latitude and longitude in just 1 key and not separated, as it will be easier to fetch and use the value, then you can use regex to trim it out and get what you want from it
happy coding !


text:
Q: Insert break or divide one line by another I use an online LaTeX editor to finish a series of equations: I want to break one line so that it's divided by the second.
This is what I currently have:
[c/[2*G*m/c^2]]/[m/[h/(2*pi)]*[h*[c/[2*pi*[c/[2*G*(200*$\odot$)/c^2]]]]^4/c^2]/c^4]=>1

However, I want something like this:
[c/[2*G*m/c^2]]
/
[m/[h/(2*pi)]*[h*[c/[2*pi*[c/[2*G*(200*M⊙)/c^2]]]]^4/c^2]/c^4]=>1

How do I do that?


text:
Q: Manipulating x64 Unwind Info To Match Assembly Hook Edit: I appear to have been mistaken, the backtrace works wonderfully from anywhere on Linux -- it is only when remote debugging from gdb on ubuntu to remote windows that the stacktrace gets absolutely destroyed after entering one of the memory allocation functions in msvcrt... dammit microsoft.
And this happens for both 64bit and 32bit windows, so I'm not sure this is related to the unwind information...
Edit: It appears adding -g3 and -Og has helped with part of the issue in some programs but the problem still persists in other programs, cannot post their source here as it is IP of my company -- sorry!
Background
I am using gcc to compile ubuntu->ubuntu and mingw to compile ubuntu->windows.
I have created a cross platform (linux + windows) memory tracking & leak detection library which hooks malloc/calloc/realloc/free with an assembly bytepatch on the first instructions (not IAT/PLT hooking).
The hook redirects to a gate which checks if the hooks are enabled in the current thread and redirects to the memory tracking hook function if they are, otherwise it just redirects to the trampoline of the real function if they are disabled for that thread.
The library works great and detects leaks on linux/windows (probably would work on mac but I don't have one).
I use the library to programmatically detect leaks from within my code, I can install callbacks on the memory allocation routines and programmatically raise breakpoints (by looping and waiting for debugger to attach then executing asm("int3")) inside the callbacks so that I can attach to my program while it's inside of a call that leaks memory.
Everything works great up until I try to view a backtrace from within my callback, I understand this is is probably because the unwind information is probably not matching my stack anymore because I have inserted new frames and data via the hook routines I have inserted.
Edit: If I am mistaken about the unwind info mismatching the stack being the cause of the incorrect backtrace then please correct me!
The Question
Is there any small hacks I can do to trick GDB into correctly rebuilding the backtrace from within my hook callbacks?
I understand that I can manually walk and edit the unwind info with libdwarf or something but I imagine that would be incredibly cumbersome and large.
So I am wondering if perhaps there is a hack or a cheat I can do which would trick GDB into properly rebuilding the backtrace?
If there are no easy hacks or tricks then what are all of my options for fixing this issue?
Edit: Just to clear up the exact call order of everything:
program
   V
malloc
   V
hook_malloc -> hooks are disabled -> return malloc trampoline -> real malloc > program
   V
hooks are enabled
   V
Call original malloc -> malloc trampoline -> real malloc -> returns to hook
   V
Record memory size/info etc from malloc
   V
Call user defined callback -> **User defined callback* -> returns to hook
   V
return to program

It is the "User Defined Callback" where I want to capture a backtrace

A: Apparently this is the same problem GDB Windows ?? in Backtraces
And the solution was to simply add -g3 to the mingw compile flags and viola I have non-broken backtraces!
Edit: Nevermind, this isn't the whole answer. It appears like this fix worked for some test programs, but other programs still appear to show incorrect backtraces like:
(gdb) bt
#0  malloc_callback (s=38, rv=0x2c5058) at test_dll.c:729
#1  0x000000000040731d in hook_malloc_raw (file=0x410ea1 <__FUNCTION__.63079+55> "", function=0x410ea1 <__FUNCTION__.63079+55> "", line=0, s=38, rv=8791758343065)
#2  0x0000000000407367 in hook_malloc (s=38)
#3  0x000007fefda20b9e in ?? ()
#4  0x0000000000000026 in ?? ()
#5  0x0000000000410ea1 in __FUNCTION__.63079 ()
#6  0x0000000000000000 in ?? ()

Obviously Frame #4 isn't actually a stack frame, and I'm not sure why frame #5 is labeled "__FUNCTION__.63079".
Edit2: If people are going to downvote this at least leave a comment saying why


text:
Q: Insert null value into SQL Server database I have this code
public void insertAssignment(long mediaEvent_ID, long mediaBranch_ID,
int? isPremiere, int? isNew, int? isLastChance,
int? isPrevShown, int season_ID, int? audio_ID,
int? video_ID, DateTime startdate)
{
    query = "insert into Assignment Values(" + mediaEvent_ID+ ","
    + mediaBranch_ID + "," + isPremiere + "," + isNew + ","
    + isLastChance + "," + isPrevShown
    + "," + season_ID + "," + audio_ID + "," + video_ID + ",'" +
    startdate.ToString("MM/dd/yyyy") + ")";   }

I have a problem while insert if any attribute is null like isPremiere=null problem
is insert {values(mediaEvent,mediaBranch,(is empty not contains a values ),......)}
How can I resolve this problem?

A: If you were writing a tsql with literals, you would need to detect the null scenario and append "null" rather than the value, so the SQL looks like
1,2,null,4,5

If you see what I mean. However, this is a bad way to do it - your SQL right now is really really dangerous. You should parameterize instead - this solves a range of problems:

*

*sql injection(your code is a security risk right now)

*formatting (dates etc)

*null values

*query plan reuse (or the lack of it)

For example:
query = "insert into Assignment Values(@eventId, @branchId, @isPremiere, @isNew, ...)"

where you add a parameter with value for each of the placeholders. Note that due to how ado.net you need to represent nulls with DBNull:
cmd.Parameters.AddWithValue("foo",
    foo == null ? (object)DBNull.Value : (object)foo);

(For each parameter)
Note that orms and micro-orms will help make this simple. For example with dapper:
DateTime foo = ...
int? bar = ...
connection.Execute(
     @"insert ... values (@foo, @bar)",
    new { foo, bar });

A: I have solved my problem below style
string sql= insert into Table(limit) values("+TBkapidaMinLimit.Text==""?"null":TBkapidaMinLimit.Text)+")"


text:
Q: Change the default currency in crm.lead model (odoo 12) In the Module: CRM > MyPipeline ,
I want to Change the default currency of the
'Expected revenue' by the possibility to choose from the activated currencies
field in res.company model (Currency)
So , I changed the currency field , but does not work
class crm_currency(models.Model):
    _inherit = 'crm.lead'

    planned_revenue = fields.Monetary('Expected Revenue', currency_field='currency_id', track_visibility='always')

Can someone help me please.

A: You need to change the currency_field option of the planned_revenue field in the kanban view.
<record id="crm_case_kanban_view_leads_inherit" model="ir.ui.view">
    <field name="name">crm.lead.kanban.lead.inherit</field>
    <field name="model">crm.lead</field>
    <field name="inherit_id" ref="crm.crm_case_kanban_view_leads"/>
    <field name="arch" type="xml">

        <xpath expr="//div[hasclass('o_kanban_record_subtitle')]/t/field[@name='planned_revenue']" position="attributes">
            <attribute name="options">{'currency_field': 'currency_id'}</attribute>
        </xpath>
    </field>
</record>

Make sure that currency_id field is not empty or you will get a TypeError
TypeError: columnState.data[0].data[currencyField] is undefined


text:
Q: Display variable result from servlet to jsp arraylist i am trying to display my data from mysql into the jsp through servlet
problem i am facing are im not sure if the data is passing, i am getting the NullPointerException error. it doesnt even display any data taken from the mysql
what i am trying to do is to display all my data from my mysql id,name,price into the jsp in a format table
result.jsp
<%
        ArrayList<ProductBean> list=(ArrayList<ProductBean>)request.getAttribute("list");
        for (int i = 0; i < list.size(); i++) {
                list.get(i).getItemID();
                list.get(i).getName();
                list.get(i).getPrice();
            }
        %>

product.java
  connection = DriverManager.getConnection(connectionUrl + dbName, userId, password);
            statement = connection.createStatement();
            String sql = "SELECT id,name,price FROM item";

            ArrayList < ProductBean > list = new ArrayList < ProductBean > ();

            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                String itemID = resultSet.getString("id"); //fetch the values present in database
                String name = resultSet.getString("name");
                String price = resultSet.getString("price");
                list.add(new ProductBean(itemID, name, price));

            }
            request.setAttribute("list", list);
            request.getRequestDispatcher("/result.jsp").forward(request, response);

ProductBean.java
public class ProductBean {

    private String itemID;
    private String name;
    private String price;

    public String getItemID() {
        return itemID;
    }
    public void setItemID(String itemID) {
        this.itemID = itemID;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }

    public ProductBean(){
    }

    public ProductBean(String itemID, String name, String price){
        this.itemID = itemID;
        this.name = name;
        this.price = price;
    }
}

A: To display use out.println() if you are not getting NULL pointer Exception
<%
        ArrayList<ProductBean> list=(ArrayList<ProductBean>)request.getAttribute("list");
        for (int i = 0; i < list.size(); i++) {
                 out.println(list.get(i).getItemID());
                 out.println(list.get(i).getName());
                 out.println(list.get(i).getPrice());
            }
        %>

Use can also use JSTL
<c:forEach var="i" items=${list}>
  <c:out value="${i.itemID}"/>
  <c:out value="${i.name}"/>
  <c:out value="${i.price}"/>

</c:forEach>


text:
Q: regex negative query on string RE2 google sheets I do Google sheets and I'm fighting with REGEXREPLACE function past few hours, in general I have this:
string1: "blah blah blah @abc blah @bcd blah blah"

And I want this:
string2: "@abc @bcd"

I try to extract it with REGEXEXTRACT(string1,"@[^\s]+") but this function won't work global, so I use REGEXREPLACE to replace everything else than @abc and @bcd to "", but to do that I need to negate @[^\s]+!
How to do that?

A: I think this can helps (With $1 substitution):
/(?:.*?(@\S*))|(.*)/ig

[Regex Demo]

A: (edit) I suggested the other answers wouldn't work in Sheets, but I didn't look at @shA.t's answer closely, which in fact works perfectly. This would be the Sheets implementation:
=REGEXREPLACE(L1,"(?:.*?(@\S*))|(.*)","$1")
My original answer:
Unfortunately I think the other answers won't work in the context of Google Sheets, which doesn't support "look-aheads" in spreadsheet function regex.
See if this works:
=ArrayFormula(TRIM(JOIN(" ",IFERROR(REGEXEXTRACT(SPLIT(L1," "),"^@.+")))))

A: Thank you shA.t ... I was trying to do a similar thing with JSON file extracting data fields using google sheets by including what I wanted then running into the restrictions of RE2 used by sheets. Using REGEXREPLACE and excluding what I didn't want worked like a charm, just substituted by trial and error till It was perfect
=REGEXREPLACE(L1,"(?:.*?{("guid":".*?")})|(.*)","$1")

demo
After looking at it closer I realized I wanted the headers to be removed as well, so the final RE2 is even simpler
(?:.*?:(".*?"))|(.*)

demo


text:
Q: Querying local datastore in using ParseQueryAdapter gives 0 results even after successfully pinning Background:
I am working on a group messaging app for Android using parse.com as my backend.
Working:

*

*I Have a ParseQueryAdapter which queries for ChatGroups from the local datastore using:
public ChatGroupAdapter(final Context context) {
       super(context, new ParseQueryAdapter.QueryFactory<ChatGroup>() {
          public ParseQuery<ChatGroup> create() {
              ParseQuery<ChatGroup> chatGroupQuery = ParseQuery.getQuery(ChatGroup.class);
              chatGroupQuery.fromLocalDatastore();
              Log.d(ChatGroup.class.getName(), "Constructor query: " +
              chatGroupQuery + " made");
              //noinspection unchecked
              return chatGroupQuery;
          }
   });
}

*The fragment that contains it listens to it by adding a ParseQueryAdapter.OnQueryLoadListener. If the ParseQueryAdapter cannot retrieve the ChatGroups from the local datastore, it retrieves it from parse, pins it and then triggeres the ParseQueryAdapter to retry loading from the local datastore using: .loadObjects();. Here is a code snippet from my fragment:
@Override
    public void onLoaded(List<ChatGroup> groups, Exception e) {
        l.d("onLoaded called");
        if (e != null) {
            e.printStackTrace();
            updateLocalDatastore();
        } else if (groups == null) {
            l.w("Received null group list.");
            updateLocalDatastore();
        } else if (groups.size() == 0) {
            l.w("Received group list of size zero.");
            updateLocalDatastore();
        } else {
            l.d("Chat groups loaded successfully");
        }
    }

private void updateLocalDatastore() {
    final ParseQuery<ChatGroup> groupQuery = ParseQuery.getQuery(ChatGroup.class);
    groupQuery.findInBackground(new FindCallback<ChatGroup>() {
        @Override
        public void done(final List<ChatGroup> chatGroupList, ParseException e) {
            if (e != null) {
                e.printStackTrace();
            } else {
                if (chatGroupList != null) {
                    ParseObject.pinAllInBackground(chatGroupList, new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            if (e != null) {
                                e.printStackTrace();
                            } else {
                                l.d("Successfully pinned: " + chatGroupList.size() +
                                        " groups to local datastore. Reloading adapter");
                                groupAdapter.loadObjects();
                            }
                        }
                    });
                } else {
                    l.e("Received null group list from cloud! " +
                            "Local datastore update failed!");
                }
            }
        }
    });
}

Result:
And here is a simplified log of the execution:
ChatFragment: onCreate
ChatFragment﹕ Initializing chat groups
ChatFragment﹕ Loading chat groups
ChatFragment: onStart
ChatFragment: onResume
ChatFragment﹕ onLoaded called
ChatFragment﹕ Received group list of size zero.
ChatFragment﹕ Successfully pinned: 3 groups to local datastore. Reloading adapter
ChatFragment﹕ Loading chat groups
ChatFragment﹕ onLoaded called
ChatFragment﹕ Received group list of size zero.
ChatFragment﹕ Successfully pinned: 3 groups to local datastore. Reloading adapter
ChatFragment﹕ Loading chat groups
ChatFragment﹕ onLoaded called
ChatFragment﹕ Received group list of size zero.
ChatFragment﹕ Successfully pinned: 3 groups to local datastore. Reloading adapter
ChatFragment﹕ Loading chat groups
ChatFragment﹕ onLoaded called
ChatFragment﹕ Received group list of size zero.

It seems obvious to me that the ParseQueryAdapter should retrieve a list of 0 the first time which triggers the updateLocalDatastore() which pulls 3 ChatGroups from parse, pin them and then it should receive 3 from the local datastore. However as seen in the log, it continues to find 0 ChatGroups from the local datastore even after pinning them successfully!
The project setup seems fine:
Parse.enableLocalDatastore(this);
Parse.initialize(this, AppProps.properties.appId, AppProps.properties.clientKey);
ParseUser.enableRevocableSessionInBackground();
Parse.setLogLevel(Parse.LOG_LEVEL_DEBUG);
ParseObject.registerSubclass(ChatGroup.class);

What am I doing wrong?! Am I missing something?
I implemented the exact same logic with ParseUser and it worked flawlessly! There seems to be something wrong with doing the same with GroupChat:
@ParseClassName("ChatGroup")
public class ChatGroup extends ParseObject {

Some say that it is a parse bug with relations in the local datastore. But I am not even using relations. Even a simple query from the local datastore doesn't work.

A: Although I couldn't fix the problem, I discovered what the issue was. The issue is related to an underlying bug with the Parse SDK of Android: ParseQuery gives 0 objects when querying from local datastore even after successfully pinning


text:
Q: Random float - uniform w.r.t. continuous number line How to generate floats which are uniform w.r.t. the continuous number line? (i.e., a number between 1 and 2 is equally likely as a number between 100000 and 100001).
I only know how to generate random floats uniform w.r.t. the distinct bit patterns (i.e., each bit pattern is equally likely).
The algorithm should be uniform along a given range of the representable numbers (i.e., 4.0 to 6.0 or (as an extreme) float.min_value to float.max_value).

A: One can translate the generate_uniform_real from
https://github.com/boostorg/random/blob/develop/include/boost/random/uniform_real_distribution.hpp to create random floats uniform w.r.t the continuous number line.


text:
Q: Sklearn encoding on columns with multiple classes on same cell Let's suppose I have the following DataFrame:
   Column
0  A - B - C
1      A - B
2      A - C
3          A
4          B
5          C

I want to encode the "Column" but I have multiple classes in the same cell. Using pandas I can do the following to get the proper encoding output:
df['Column'].str.get_dummies(sep=' - ')
   A  B  C
0  1  1  1
1  1  1  0
2  1  0  1
3  1  0  0
4  0  1  0
5  0  0  1

How can I do the same transformation using Sklearn?

A: Another approach is to use the MultiLabelBinarizer class as it supports an iterable as input.
df['Column'] = df['Column'].str.split(' - ')
enc = MultiLabelBinarizer()
enc.fit_transform(df['Column'])

A: Looks like you can do this with CountVectorizer specifying how you want to identify boundaries.
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
df = pd.DataFrame({'Column': ['A - B - C', 'A - B', 'A - C', 'A', 'B', 'C']})

vectorizer = CountVectorizer(analyzer=lambda x: x.split(' - '))
X = vectorizer.fit_transform(df['Column'])

X.toarray()
array([[1, 1, 1],
       [1, 1, 0],
       [1, 0, 1],
       [1, 0, 0],
       [0, 1, 0],
       [0, 0, 1]])

vectorizer.get_feature_names()
['A', 'B', 'C']


text:
Q: How to hide tr of a table when one tr of checkbox is checked in jquery? In a table i have tr's. In first tr i have checkbox.If that checkbox is unchecked , the other tr values must be hide.. If it is checked ,all other tr are shown.
I have shown it in fiddle,once check and say me solution please,
http://jsfiddle.net/Y39Bu/99/
html

  <input type="checkbox" id="checker">

  Hii

  Hii

  Hii

js
$(document).ready(function () {
    var checkbox = $('#checker');
    var dependent = $('#dependent-box');
    if (checkbox.attr('checked') !== undefined){
       dependent.show();
    } else {
        dependent.hide();
    }

    checkbox.change(function(e){
       dependent.toggle();
    });
});

A: div cant be nested in table. Try like following.

$(document).ready(function () {
    var checkbox = $('#checker');
    var dependent = $('tr').not(':first');

    checkbox.change(function () {
        dependent.toggle(this.checked);
    }).change(); //auto execute after documet ready
});

            <input type="checkbox" id="checker">

        Hii

        Hii

        Hii

A: You should use tbody instead of div.
Note: You can use many tbody in a table

$(document).ready(function () {
        var checkbox = $('#checker');
        var dependent = $('#dependent-box');
        if (checkbox.attr('checked') !== undefined){
           dependent.show();
        } else {
            dependent.hide();
        }

        checkbox.change(function(e){
           dependent.toggle();
        });
    });

      <input type="checkbox" id="checker">

      Hii

      Hii

      Hii

A: you can try like this

  <input type="checkbox" id="checker">

  Hii

  Hii

  Hii

Here is javascript code
   $(document).ready(function () {
    var checkbox = $('#checker');
    var dependent = $('.dependent-box');
    if (checkbox.attr('checked') !== undefined){
       dependent.show();
    } else {
        dependent.hide();
    }

    checkbox.change(function(e){
       dependent.toggle();
    });
});


text:
Q: Base constructor in C# - Which gets called first? Which gets called first - the base constructor or "other stuff here"?
public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}

A: As others have said, the base constructor gets called first. However, constructors are not really the first thing that happens.
Let's say you have classes like this:
class A {}

class B : A {}

class C : B {}

First, field initializers will be called in order of most-derived to least-derived classes. So first field initializers of C, then B, then A.
The constructors will then be called in the opposite order: First A's constructor, then B, then C.

A: I'd say base
EDIT see:
http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructorsInCS11122005010300AM/ConsNDestructorsInCS.aspx
there it says:
using System;
class Base
{

public Base()
{
    Console.WriteLine("BASE 1");
}
public Base(int x)
{
    Console.WriteLine("BASE 2");
}
}

class Derived : Base
{
public Derived():base(10)
{
    Console.WriteLine("DERIVED CLASS");
}
}

class MyClient
{
public static void Main()
{
    Derived d1 = new Derived();
}
}

This program outputs
BASE2
DERIVED CLASS

A: Base Constructor is called first. But the initializer of fields in derived class is called first.
The calling order is

*

*derived class field initializer

*base class field initializer

*base class constructor

*derived class constructor

(You can treat 2 and 3 as a whole to construct the base class.)
Taken from CSharp Language Speification 5.0:

10.11.3 Constructor execution
Variable initializers are transformed into assignment statements, and these assignment
  statements are executed before the invocation of the base class
  instance constructor. This ordering ensures that all instance fields
  are initialized by their variable initializers before any statements
  that have access to that instance are executed. Given the example
using System;
class A
{
    public A() {
        PrintFields();
    }
    public virtual void PrintFields() {}
}
class B: A
{
    int x = 1;
    int y;
    public B() {
        y = -1;
    }
    public override void PrintFields() {
        Console.WriteLine("x = {0}, y = {1}", x, y);
    }
}

when new B() is used to create an instance of B, the following
  output is produced:
x = 1, y = 0

The value of x is 1 because the variable initializer is executed
  before the base class instance constructor is invoked. However, the
  value of y is 0 (the default value of an int) because the assignment
  to y is not executed until after the base class constructor returns.
  It is useful to think of instance variable initializers and
  constructor initializers as statements that are automatically inserted
  before the constructor-body. The example
using System;
using System.Collections;
class A
{
    int x = 1, y = -1, count;
    public A() {
        count = 0;
    }
    public A(int n) {
        count = n;
    }
}
class B: A
{
    double sqrt2 = Math.Sqrt(2.0);
    ArrayList items = new ArrayList(100);
    int max;
    public B(): this(100) {
        items.Add("default");
    }
    public B(int n): base(n – 1) {
        max = n;
    }
}

contains several variable initializers; it also contains constructor
  initializers of both forms (base and this). The example corresponds to
  the code shown below, where each comment indicates an automatically
  inserted statement (the syntax used for the automatically inserted
  constructor invocations isn't valid, but merely serves to
  illustrate the mechanism).
using System.Collections;
class A
{
    int x, y, count;
    public A() {
        x = 1;                                // Variable initializer
        y = -1;                               // Variable initializer
        object();                         // Invoke object() constructor
        count = 0;
    }
    public A(int n) {
        x = 1;                                // Variable initializer
        y = -1;                               // Variable initializer
        object();                         // Invoke object() constructor
        count = n;
    }
}
class B: A
{
    double sqrt2;
    ArrayList items;
    int max;
    public B(): this(100) {
        B(100);                               // Invoke B(int) constructor
        items.Add("default");
    }
    public B(int n): base(n – 1) {
        sqrt2 = Math.Sqrt(2.0);           // Variable initializer
        items = new ArrayList(100);   // Variable initializer
        A(n – 1);                         // Invoke A(int) constructor
        max = n;
    }
}

A: Don't try to remember it, try to explain to yourself what has to happen. Imagine that you have base class named Animal and a derived class named Dog. The derived class adds some functionality to the base class. Therefore when the constructor of the derived class is executed the base class instance must be available (so that you can add new functionality to it). That's why the constructors are executed from the base to derived but destructors are executed in the opposite way - first the derived destructors and then base destructors.
(This is simplified but it should help you to answer this question in the future without the need to actually memorizing this.)

A: Actually, the derived class constructor is executed first, but the C# compiler inserts a call to the base class constructor as first statement of the derived constructor.
So: the derived is executed first, but it "looks like" the base was executed first.

A: Eric Lippert had an interesting post on the related issue of object initialization, which explains the reason for the ordering of constructors and field initializers:
Why Do Initializers Run In The Opposite Order As Constructors? Part One

Why Do Initializers Run In The Opposite Order As Constructors? Part Two

A: Base class constructors get called before derived class constructors, but derived class initializers get called before base class initializers. E.g. in the following code:
public class BaseClass {

    private string sentenceOne = null;  // A

    public BaseClass() {
        sentenceOne = "The quick brown fox";  // B
    }
}

public class SubClass : BaseClass {

    private string sentenceTwo = null; // C

    public SubClass() {
        sentenceTwo = "jumps over the lazy dog"; // D
    }
}

Order of execution is: C, A, B, D.
Check out these 2 msdn articles:

*

*Why do initializers run in the opposite order as constructors? Part One

*Why do initializers run in the opposite order as constructors? Part Two

A: The base constructor will be called first.
try it:
public class MyBase
{
  public MyBase()
  {
    Console.WriteLine("MyBase");
  }
}

public class MyDerived : MyBase
{
  public MyDerived():base()
  {
    Console.WriteLine("MyDerived");
  }
}

A: http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=777
Base Constructor gets called first.

A: The Exception Constructor will be called, then your Child class constructor will be called.
Simple OO principle
Have a look here
http://www.dotnet-news.com/lien.aspx?ID=35151

A: The base constructor will be called first, otherwise, in cases where your "other stuff" must make use of member variables initialized by your base constructor, you'll get compile time errors because your class members will not have been initialized yet.

A: base(?) is called before any work is done in the child constructor.
This is true, even if you leave off the :base() (in which case, the 0-parameter base constructor is called.)
It works similar to java,
public Child()
{
   super(); // this line is always the first line in a child constructor even if you don't put it there! ***
}

*** Exception: I could put in super(1,2,3) instead.  But if I don't put a call to super in explicitly, super() is called.

A: Constructor calls are called (fired) from the bottom up, and executed from the top down. Thus, if you had Class C which inherits from Class B which inherits from Class A, when you create an instance of class C the constructor for C is called, which in turn calls the instructor for B, which again in turn calls the constructor for A. Now the constructor for A is executed, then the constructor for B is executed, then the constructor for C is executed.


text:
Q: Dividing a plane with lines A while back, one of my friends challenged me to find out how many regions I can divide a plane into given $n$ lines. For instance:

He also told me that the formula to find the maximum number of lines on the plane is $$\frac{1}{2}\left(n^2+n+2\right).$$
How is this derived? (I would prefer an intuitive example as I have not studied any particularly advanced fields of geometry, set theory or whatever is needed to rigorously prove the formula).

A: Each new line you add can cut each of the other lines at most once. If you arrange it this way, then the line cuts the region that it belongs to before cutting the first line into two, and then every time it crosses a line, it cuts another region in two. So the number of new regions is the number of lines you had before plus 1. That is, the nth line adds n new regions. Taking into account that you start with 1 region when n = 0, you get
$$
R = 1 + \sum^n_{i=1}i = 1 + \frac{n(n+1)}{2} = \frac{n^2 + n + 2}{2}.
$$


text:
Q: How to make row hover cover the selection in datatable? I want to add a row hover to the Webix datatable using hover property, but it doesn't affect to the selected row by default.
I've tried to modify the :hover of the selection class, but the current notation works only for the hovered cell (while I need a hovered row):
<style>
  .bluehover{
      background:lightblue;
  }
  .webix_row_select:hover{
      background:lightblue !important;
  }
</style>

Snippet here.
Will appreciate any help.

A: Just change
.webix_row_select:hover{
    background:lightblue !important;
}

to
.webix_row_select *:hover{
    background:lightblue;
}

Updated snippet

A: I think the solution from @aisah is not up to date anymore.
Under webix 8 one only needs to set hover:<css_class> and define
.<css_class>{background: <my_color>;} without the hover selector.
Snippet
Webix Documentation


text:
Q: Angular 2 - moving from local to test env I just created a small Angular 2 page which retrieves
data from SQL DB and display them in a table. All good here..
I deployed that from my local machine to a test environments ( we have many ).
We use Bamboo to deploy..
But when I run my page, it says it's not able to find
any of node modules - essentially it just hangs
on "loading app". On F12 I see 404s for all app/node-modules/system.js files, etc..
Just to mention I did not run an npm install
on my new environment after deployment since the node modules are all present in my package ( I am new to node and Angular 2)
Please, let me know what am I missing. The page works just fine on local machine.

A: by

Just to mention I did not run an npm install On my new environment after deployment since the node modules are all present in my package

Do you mean the file package.json?
It looks like you are missing the node_module files and will need to run npm install on your new environment.
This will install all the node_modules listed in your package.json file.


text:
Q: Decorating Lifecycle Hooks in vue.js Does anyone know a good way to decorate lifecycle hooks from within the vue component? I am adding a function in the mounted in my component that gets called from the app.vue when the screen size changes. When I navigate away from the page I want to remove this function. Currently I have to do it in the destroy method on the component. If I was able to pass in the destroyed method on the component when I am creating the listener and decorate it with the logic to destroy the listener I would not have to worry about someone adding the listener on a component and not adding the removal of the listener in the destroy method.
public AddUpdateIsMobileFunction(fn: (screenType: any) => void, destroyHook: any): any {
        this.updateIsMobileFunctions.push(fn);
        const currentFunctionPlacementInArray: number = this.updateIsMobileFunctions.length;
        const destroySelf: () => void = () => {
            this.updateIsMobileFunctions.splice(currentFunctionPlacementInArray, 1);
        }
        const originalDestroyHook: any = _.deepClone(destroyHook)
        destroyHook = () => {
            originalDestroyHook();
            destroySelf();
        }
        return destroySelf;
    }

In the component
private mounted(): void {
        this.destroyIsMobileFunction = this.$Global.AddUpdateIsMobileFunction((screenType: any) => {
            this.isMobile = screenType.isMobile;
            console.log("test is mobile fn")
        }, pass in the destroyed function here )
    }
remove the function below
    private beforeDestroy(): void {
        console.log('in the destroy function in the vue component')
        this.destroyIsMobileFunction();
    }


text:
Q: TextView onMeasure caused NullPointerException I have a layout created by hard code in my project,I have seen some logs like below,but I can't reappear that.I have setLayoutParams() in the TextView,but it is not useful.This layout is a detail page ,I have defined some ids for these views and I had copy this layout for another detail page,so the two pages used same ids for their views,and the layout is same ,is this conflict ?I need some help,THX!
java.lang.NullPointerException
    at android.widget.TextView.onMeasure(TextView.java:6559)
    at android.view.View.measure(View.java:16552)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5130)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1052)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
    at android.view.View.measure(View.java:16552)
    at android.widget.RelativeLayout.measureChild(RelativeLayout.java:689)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:473)
    at android.view.View.measure(View.java:16552)
    at android.widget.RelativeLayout.measureChild(RelativeLayout.java:689)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:473)
    at android.view.View.measure(View.java:16552)
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1226)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
    at android.view.View.measure(View.java:16552)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5130)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16552)
    at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1226)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.widget.ScrollView.onMeasure(ScrollView.java:326)
    at android.view.View.measure(View.java:16552)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
    at android.view.View.measure(View.java:16552)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5130)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16552)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5130)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16552)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
    at android.view.View.measure(View.java:16552)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
    at android.view.View.measure(View.java:16552)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5130)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16552)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5130)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16552)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5130)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2340)
    at android.view.View.measure(View.java:16552)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1927)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1124)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1306)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1011)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5638)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:786)
    at android.view.Choreographer.doCallbacks(Choreographer.java:591)
    at android.view.Choreographer.doFrame(Choreographer.java:560)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:772)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5143)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
    at dalvik.system.NativeStart.main(Native Method)


text:
Q: How to use BufferingForwardingAppender along with EventLog appender to get email alerts? I need some idea to implement the following requirement in the web application .
I am using log4net in a custom dll to log the errors. I completed the log4net implementation and its working fine.[aspx errors are logged in EventLog and the asp errors are logged in FileAppender] .All the loggerError() methods are in the custom dll.
Now i want to monitor the logging,suppose if there is a situation like the loggerError() method is called more than 20 times in just 5 mins bse of Fatal error or database is down,then i want to track that and send email to admin.
My ideas,
1.Set a timer and count variable to  track the number of hits .
2.After each hit check the number of hits and the secs.
3.If it exceeds the threshold limit .then trigger the email...
Not sure how this will work or is there any other way to achieve it.
Thanks in advance

A: I would suggest writing your own Appender to house this logic.  The Appender could be used as a wrapper for another Appender (maybe the SmtpAppender?). The ForwardingAppender looks like a good example of a "wrapper" Appender.  As each log message comes in, apply your timing and severity logic.  If your criteria are met, forward the message to the "wrapped" Appender.
Alternatively this Appender could contain its own logic for generating and sending email (or whatever notification scheme you would like to use).
This Appender could be configured via the standard log4net configuration mechanism (app.config, separate config, etc) so the time span, error level, error count, could be configurable.
Here is an idea for how something like this might be implemented as an Appender:
public class MultiThresholdNotifyingAppender : AppenderSkeleton
{
  private Queue<LoggingEvent> loggingEventQueue = new Queue<LoggingEvent>();

  private DateTime windowStart;

  public Level LevelThreshold { get; set; }
  public TimeSpan WindowLength { get; set; }
  public int HitThreshold { get; set; }

  public void Append(LoggingEvent loggingEvent)
  {
    if (loggingEvent.Level < LevelThreshold)
    {
      if (loggingEventQueue.Count == 0) return;

      if (loggingEvent.TimeStamp - windowStart) >= WindowLength)
      {
        //Error level is less than threshold and the time window has elapsed.  Remove any queued LoggingEvents
        //until all LoggingEvents in the queue fall within the time window.
        while (loggingEventQueue.Count > 0 && loggingEventQueue.Peek().TimeStamp - windowStart >= WindowLength)
        {
          loggingEventQueue.Dequeue();
        }

        windowStart = loggingEventQueue.Peek().TimeStamp;

        return;
      }
    }

    //If we got here, then the Error level is >= the threshold.  We want to save the LoggingEvent and we MIGHT
    //want to notify the administrator if the other criteria are met (number of errors within time window).
    loggingEventQueue.Enqueue(loggingEvent);

    //If this is the first error in the queue, start the time window.
    if (loggingEventQueue.Count == 1) windowStart = loggingEvent.TimeStamp;

    //Too few messages to qualify for notification.
    if (loggingEventQueue.Count < HitThreshold - 1) return;

    //Now we're talking!  A lot of error messages in a short period of time.
    if (loggingEvent.TimeStamp - windowStart >= WindowLength)
    {
      //Build a notification message for the administrator by concatenating the "rendered" version of each LoggingEvent.
      string message = string.Join(Enviroment.NewLine, loggingEventQueue.Select(le => le.RenderedMessage));
      SendTheMessage(message);
    }

    //After sending the message, clear the LoggingEvents and reset the time window.
    loggingEventQueue.Clear();
    windowStart = loggingEvent.TimeStamp;
  }

  public void Append(LoggingEvent[] loggingEvents)
  {
    foreach (var le in loggingEvents)
    {
      Append(le);
    }
  }
}

The idea is to configure your threshold (maybe along with your notification method) values on the appender.  Configure your loggers to send their messages to this appender, in addition to any other appenders you want to send them to (EventLog, File, etc).  As each logging message comes through, this appender can examine it in the context of the configured threshold values and send the notification as necessary.
There could very well be threading issues in this code (unless log4net handles that for you), so you might need a lock when accessing the queue.
Note that this code has not been compiled nor has it been tested.
See this link for some sample custom Appenders in the log4net repository:
http://svn.apache.org/viewvc/logging/log4net/trunk/examples/net/2.0/Appenders/

A: Since this is for a web application, I would suggest using an Application Variable to keep track of the last 10 errors.  The next time an error occurs, replace the oldest error (if necessary to keep the error count under 10) with the new error.  Put in some logic to check the dates of the error, and adjust the severity level accordingly.


text:
Q: How can I compare rows in Unix text files and add them together in another text file? I have a text file 1 that has 3 columns. The first column contains a number, the second a word (which can be either a sting like dog or a number like 1050), the third column a TAG in capital letters.
I have another text file 2 that has 2 columns. The first column has a number, the second one has a TAG in capital letters.
I want to compare every row in my text file 1 with every row in my text file 2. If the TAG in column [3] in text file 1 is the same as the TAG in column [2] in text file 2, then I want to store the number in text file 1 next to the number in text file 2 next to the word in text file 1. There are no duplicate TAGS in text file 2 and there are no duplicate words in text file 1.
Illustration:
Text file 1
2    2737    HPL
32   hello   PLS
3    world   PLS
323  .       OPS

Text file 2
342  HPL
56   PLS
342  DCC
4    OPS

I want:
2   342  2737
32  56   hello
3   56   world
323 4  .

A: You can do this in awk like this:
awk 'FNR==NR { h[$2] = $1; next } $3 in h { print $1, h[$3], $2 }' file2 file1

The first part saves the key and column from file 2 in an associative array (h), the second part compares column 3 from file 1 to this array and prints the relevant parts.


text:
Q: Moving multiple uploaded images I scaled multiple images using for loop. Now I want to move those images into a folder.
How can I do that?
move_uploaded_file($_FILES['image']['tmp_name'],'uploads/'.$_FILES['image']['name']);

I have this code but only one image can be place in the uploads folder and the other images are missing.

A: This code is working finr for me
form.html
<form enctype="multipart/form-data" action="upload.php" method="post">
Image1: <input name="userfile[]" type="file" />

Image2: <input name="userfile[]" type="file" />

<input type="submit" value="Upload" />
</form>

Upload.php
<?php
error_reporting(E_ALL);
ini_set("display_errors",1);
$success = 0;
$fail = 0;

$uploads_dir = 'uploads';
$count = 1;
foreach ($_FILES["userfile"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["userfile"]["tmp_name"][$key];
        $name = $_FILES["userfile"]["name"][$key];
        $uploadfile = "$uploads_dir/$name";
        $ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
        if (preg_match("/(jpg|gif|png|bmp)/",$ext)){
            $newfile = "$uploads_dir/picture".str_pad($count++,2,'0',STR_PAD_LEFT).".".$ext;
            if(move_uploaded_file($tmp_name, $newfile)){
                $success++;
            }else{
                echo "Couldn't move file: Error Uploading the file. Retry after sometime.\n";
                $fail++;
            }
        }else{
            echo "Invalid Extension.\n";
            $fail++;
        }
    }
}
echo "
 Number of files Uploaded:".$success;
echo "
 Number of files Failed:".$fail;


text:
Q: Why supertabular in multicols won't split into columns? I expect the long table to split into columns in multicols environment, but it doesn't.
\begin{multicols}{2}[\begin{center} Class number of real quadratic field \end{center}]

\begin{supertabular}{|*{2}{m{1.2cm}<{\centering}|}}
    \hline
    $d$ & $h$ \\ \hline
    $2$ & $1$ \\
    $3$ & $1$ \\
       ...
    $163$ & $1$ \\
    $165$ & $2$ \\ \hline
\end{supertabular}

\end{multicols}

and I get the following:


text:
Q: ng-include - Controller is called multiple times Situation:
I am trying to include a partial with ng-include without the need for any routing. I just want to include a specific partial of many dynamically. This is more or less how it looks like:
<div ng-controller="SomeController">
    //This controller defines a $scope.getPartial(id)
    <ng-include src="getPartial(something.id)"></ng-include>
</div>

It works, the partial is included. But looking at the console I can see that the controller is called several times and the first time it is called, I get a 404

GET path/to/partials/undefined.html [HTTP/1.1 404 Not Found 162ms]

it seems that something.id is not defined, when the include is made for the first time.
Questions:

*

*how can I simply include a partial, without creating a new scope?

*if that's not possible, how can I make sure, the controller is called only once?

*and how can I avoid the 404?

I'm fairly new to AngularJS and may therefore make wrong assumptions about stuff or miss obvious things, please enlighten me.

A: *

*ngInclude creates a new scope by definition so you can't easily circumvent it. And, since nested scopes inherit from each other your newly created scope will be able to read whatever is in your SomeController, so you shouldn't have any problems with new scope.

*ngInclude's src attribute will get re-evaluated on each $digest scope, so you can't stop it from calling your controller's method repeatedly. For that matter you need to make sure your method is light and fast and it returns the same output given the same input

*You may avoid initial 404 by returning empty string "" when id is not yet defined:

$scope.getPartial = function(id){
  if(!id){
    return "";
  }
  ...
}


text:
Q: Modelica.Blocks.Tables.CombiTable1Ds I want to connect the output of a Combitable to the signal current source as shown in the code below, but it is not possible because the output of table is an array but the input of current source is a scalar.
model TableTest
  Modelica.Blocks.Tables.CombiTable1Ds combiTable1Ds1(table = [0, 0; 1, 1; 2, 4; 4, 16])  annotation(
    Placement(visible = true, transformation(origin = {-4, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
  Modelica.Blocks.Sources.Constant const(k = -5)  annotation(
    Placement(visible = true, transformation(origin = {-46, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
  Modelica.Electrical.Analog.Sources.SignalCurrent signalCurrent1 annotation(
    Placement(visible = true, transformation(origin = {48, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 90)));
equation
  connect(const.y, combiTable1Ds1.u) annotation(
    Line(points = {{-35, 0}, {-17, 0}}, color = {0, 0, 127}));
  annotation(
    uses(Modelica(version = "3.2.3")));end TableTest;

A: In your case, the CombiTable1Ds only has one output in its vector. Simply connect it to the current source with:
connect(combiTable1Ds1.y[1], signalCurrent1.u);

If you use Dymola, when you draw a connection select y[1] instead of the default y[:]
Best regards
Rene Just Nielsen


text:
Q: Flex AS3 : Find and remove elements from container of certain class How can I remove only every image found in a Bordercontainer which also holds Textinputs and Buttons ?
i tried:
for(var i:int=0;i<container.numElements;i++){
if(container.getElementAt(i) is Image){
container.removeElementAt(i);}
}

But as expected this loop does not fully work since the numElements changes which means that not all Images get removed.
I know there is some simple trick to this...but I cant think of it right now...Please help

A: As commenters have suggested, it seems like looping backwards would be the way to do it.  I'd try something like this:
var totalElements : int = container.numElements;
for(var i:int=totalElements-1;i>=0;i--){
 if(container.getElementAt(i) is Image){
  container.removeElementAt(i);
 }
}

By storing the numElements in a variable before starting the loop, you can be sure that the value will not change while processing the loop.  Since your going backwards, you don't have to worry about the child index changing.
A second option would be to queue up the image instances in one loop and remove them in a second loop using the removeElement method.  I suspect the two loop method will have significantly worse performance.

A: Looping backwards would be 1 way to do this.
Another would be
for(var i:int=0; i<container.numElements; i++){
    if(container.getElementAt(i) is Image){
        container.removeElementAt(i);
        i--; //This nullifies the effect of removing an element
    }
}


text:
Q: Inequality on exponentials : $\frac{1}{e^x-1}$ I was reading page 12 of this note on the internet, but it seems unclear to me why the following inequality holds:

from the 2nd to 3rd line of the above image.

All I could argue is that $e^x-1 = (e^{x/2}-1)(e^{x/2}+1) $, hence, we have that
$$ (e^x-1)^{-1} \le (e^{x/2}+1)^{-1} .$$
where $x$ is such that $e^{x/2}-1 \ge 1 \Leftrightarrow x \ge \log 4. $ But this is no where as good as the inequality provided... I guess we split into cases? As this is part of a proof for DCT, so we need a function that dominates $g_N$.


text:
Q: How to download an image as stream then upload it? I have a lot of images on my website and want to migrate the images to a new hosting. then I made a script to scrape it using xray. once I got the url I want to download the file without writing it to hardisk and then directly upload it to my new hosting.
I am using Strapi and "strapi-provider-upload-wasabi" to upload my image. with my code I always getting 400 Bad request
request.get(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        data = "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');

        var form = {
            "refId": body.id,
            "ref": "comic",
            "field": "cover",
            "files": data,
            "path": "/"
        }

        request({
            uri: 'http://localhost:1337/upload',
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            formData: form
        }, function optionalCallback(err, httpResponse, body) {

            if (err) {
                return console.error('upload failed:', err);
            }
            // console.log(httpResponse);
            console.log('Upload successful!  Server responded with:', httpResponse.statusMessage);
        });
    }
});

A: First step would be to check error message.
Make sure that model comic has upload field.

response.headers["content-type"]

should be:

response.headers["Content-Type"]

Form Data should be FormData object:

https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

Which version of Strapi do you have?
Have you checked latest documentation?

https://strapi.io/documentation/3.0.0-beta.x/plugins/upload.html

Also, it would be good to try with some up-to-date provider, e.g.

https://www.npmjs.com/package/strapi-provider-upload-local


text:
Q: Google duplicate content issue for social network applications I am making a social network application where user will come and share the posts like facebook. But now I have some doubts like lets say a user is just shared a content by coping it from another site and same with the case of images. So does google crawler consider it as a duplicate content or not?
If yes then how I can tell to the google crawler that "don't consider it as a spam, its a social networking site and the content is shared by the user not by the me". Is there any way or any kind of technique that help me.

A: Google might consider it to be duplicate content, in which case the search algorithm will choose 1 version, which it believes to be the original or more important one and drop the other.
This isn't a bad thing per se - unless you see that most of your site's content is becoming duplicated.
You can use canonical URL declarations to do what you are saying, but i wouldn't advise it.

A: If your website belongs to one of these types - forum or e-commerce, it will not be punished for duplicate content issue. I think "social platform" is one type of forum.
If your pages are too similar, the result is that the two or more similar pages will scatter the click rate, flow etc, so the rank in SERPs may not look well.
I suggest do not use "canonical" because this instruction tell the crawlers do not crawl/count this page. If you use it, in the webmaster tool, you will see the indexed pages decrease a lot.
Do not too worry about the duplicate content issue. You can see this article: Google's Matt Cutts: Duplicate Content Won't Hurt You, Unless It Is Spammy


text:
Q: url rewrite how to send everything else to index.php condition there,
This sould be a simple task for anyone who knows, but I am new to Apache rewrites, so please bear with me.
I wrote 2 rewrite conditions and they work. I need to write a third - so that everything else would go to index.php file. The problem is - if I add the third rule, it is always applied despite first 2.
RewriteEngine On
RewriteRule   ^new/?$   new.php  [NC,L]
RewriteRule   ^thanks(.*)$ thankyou.php [NC,L]
RewriteRule   ^(.*)$ index.php

Thanks for help.

A: I believe the answer lies in the following paragraph about the L flag used with the RewriteRule directive:

If you are using RewriteRule in either .htaccess files or in
   sections, it is important to have some understanding of
  how the rules are processed. The simplified form of this is that once
  the rules have been processed, the rewritten request is handed back to
  the URL parsing engine to do what it may with it. It is possible that
  as the rewritten request is handled, the .htaccess file or
  section may be encountered again, and thus the ruleset may be run
  again from the start. Most commonly this will happen if one of the
  rules causes a redirect - either internal or external - causing the
  request process to start over.

I think what happens is that after the rewrite is executed, somehow control is given back to the URL parsing engine and the rules are run again.
You can prevent this behaviour by adding a few rewrite conditions to the last rule:
<IfModule mod_rewrite.c>

RewriteEngine On

RewriteRule new/?$ new.php [NC,L]
RewriteRule thanks(.*)$ thankyou.php [NC,L]

# Only rewrite to index.php if the current request is not for an existing file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

</IfModule>


text:
Q: if we injects only primitive values of the same class through XML file then can we say we did the dependency injection in spring? I referred some documents according to the spring in dependency injection.In some of them I found that if we insert primitive values of the same class using XML file then it is dependency injection.Is it right or wrong?
Or if we insert other class dependency(we insert reference of other class) through XML file is the dependency injection.Or both are right?
Student.java

package simple;

public class Student {

private int studentId;
private int studentAge;

public int getStudentId() {
    return studentId;
}
public void setStudentId(int studentId) {
    this.studentId = studentId;
}

public int getStudentAge() {
    return studentAge;
}
public void setStudentAge(int studentAge) {
    this.studentAge = studentAge;
}

}

Beans.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean class="simple.Student" id="student">
    <property name="studentId" value="1" />
    <property name="studentAge" value="20" />
</bean>

Is this dependency injection or not?

A: It's a naïve example, but you may claim this is a dependency injection.

A dependency is an object that can be used (a service). An injection
  is the passing of a dependency to a dependent object (a client) that
  would use it. The service is made part of the client's state.[1]
  Passing the service to the client, rather than allowing a client to
  build or find the service, is the fundamental requirement of the
  pattern. [wikipedia]

So your injector in this case the Spring framework via the xml bean definition provide the student id and age.
From my point of view your example will not help you better understand the dependency injection concept.
Let me explain:
As far as I like to understand dependency injection should be used mostly to create Services (usually singletons and not instance of prototype beans) the service dependencies can be inject externally.
Prototype creation via spring is not a common use case (I will omit the explanation for now).
A better example will be a StudentDAO  (DAO - Data Access Object) that will allow finding all Students or a Student by id. A StudentFinder that depends on StudentDAO.
Let's assume you have two types of repositories used to store students file based and database.
So you will define an interface to your DAO.
public interface StudentDAO {
    List<Student> findAll();
    Student find(String studentId);
}

And two implementations:
File
public class StudentFileDAO implements StudentDAO {}

JDBC
public class StudentJdbcDAO implements StudentDAO {}

A finder that depends the DAO:
public class StudentFinder {
    private StudentDAO studentDAO;

    public void setStudentDAO(StudentDAO studentDAO) {
        this.studentDAO = studentDAO;
    }

    public List<Student> findAll() {
        return studentDAO.findAll();
    }

    public Student find(String studentId) {
        return studentDAO.find(studentId);
    }
}

Now when you want to define what type of DAO to use you will set Beans.xml as
<bean class="simple.StudentFinder" id="studentFinder">
<property name="studentDAO" ref="studentDAO"/>
</bean>

<bean class="simple.StudentJdbcDAO" id="studentDAO ">
<property name="studentDAO" ref="studentDAO"/>
</bean>

Or
<bean class="simple.StudentFinder" id="studentFinder">
<property name="studentDAO" ref="studentDAO"/>
</bean>

<bean class="simple.StudentFileDAO" id="studentDAO ">
<property name="studentDAO" ref="studentDAO"/>
</bean>

(Note that spring profiles will be better here, but let keep it this way so the example will be simple.)
Depending on the bean.xml you will provide with your system you define your system usage (jdbc/file). So going back to the definition from Wikipedia the client (studentFinder) does to build or find the service (DAO) it defined as  part of it's state in the Beans.xml


text:
Q: ERROR in Cannot read property 'loadChildren' of undefined Webpack compilation fails throwing Cannot read property 'loadChildren' of undefined.
This Happens when i try to load routes from some function like below
export const routes: Routes = getRoutes();

function getRoutes() {
    return [{ path: 'homepage', component: HomeComponent }];
}

When i export routes normally the webpack compilation will be successful.like below,
export const routes: Routes = [{ path: 'homepage', component: HomeComponent }];

And am mounting these routes in lazy loaded module.

A: As a guess, the getRoutes function should be exported as well. AoT doesn't know how to compile when declaration is hidden.
So try
export function getRoutes() {
    return [{ path: 'homepage', component: HomeComponent }];
}


text:
Q: primefaces tabView skip the form validation when tab change I'm using PrimeFaces 3.3 and Mojarra 2.17.
I have a page that contains a p:tabView. The second tab contains a textbox and required="true". When I navigate from the second tab to first tab, it will validate the textbox is empty and display an error message (I have a PhaseListener class to display the error in global p:messages). How to skip this validation?
I can't found any solutions in:

*

*http://code.google.com/p/primefaces/issues/detail?id=3423

*http://code.google.com/p/primefaces/issues/detail?id=4143
and I do not want to use PrimeFaces p:wizard.
My tabView.xhtml:

        <ui:include src="#{test.tab1}"></ui:include>

        <ui:include src="#{test.tab2}"></ui:include>

In my Java class:
public void onTabChange(TabChangeEvent event) {
     this.setTab1("tab1.xhtml");
     this.setTab2("tab2.xhtml");
 }

My tab1.xhtml:
<h:form id="form1">

    tab1 page

</h:form>

My tab2.xhtml:
<h:form id="form2">

        tab2 page

</h:form>

My PhaseListener class:
public class MyPhaseListener implements PhaseListener {
    @Override
    public void afterPhase(PhaseEvent e) {
        if (e.getPhaseId() == PhaseId.PROCESS_VALIDATIONS) {
            if (FacesContext.getCurrentInstance().getMessageList().size() > 0) {
                String number = String.valueOf(FacesContext.getCurrentInstance().getMessageList().size());
                String errorMsg = "there are " + number + " errors.";
                FacesContext.getCurrentInstance().addMessage(
                        null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMsg,
                                errorMsg));
            }
        }
    }
}

A: I solved my problem by adding the code:
FacesContext.getCurrentInstance().renderResponse();
under TabChangeEvent method in backign bean..
eg:
public void onTabChange(TabChangeEvent event) {
  this.setTab1("tab1.xhtml");
  this.setTab2("tab2.xhtml");
  FacesContext.getCurrentInstance().renderResponse();
}

A: Add immediate="true" attribute in your ajax event tag. This will prevent your fields to be validated, and just your listener will be called:


text:
Q: How to load google recaptcha siteKey dynamically using some component variable..? <re-captcha formControlName="recaptcha" (resolved)="resolved($event)" siteKey="reCaptchakey"></re-captcha>
in component HTML and,
public reCaptchakey: string = <SITE_KEY>;
in ts file, but this is not working, so how to load site key value using variable..??

A: I have found the solution, Just change siteKey="reCaptchakey" to [siteKey]="reCaptchakey" and It will work fine..!!


text:
Q: The Walmart Marketplace OAuth API keeps throwing SYSTEM_ERROR.GMP_GATEWAY_API error I've been trying to authenticate with the Walmart Marketplace API for both sandbox and production but have so far been unsuccessful. In all cases when I ping a request to the "Token API" (https://sandbox.walmartapis.com/v3/token) I get back the the following error code: "SYSTEM_ERROR.GMP_GATEWAY_API". I've tried to authenticate with both JSON and XML but no luck.
Here is my request with JSON:
{
  url: 'https://sandbox.walmartapis.com/v3/token',
  data: { grant_type: 'client_credentials' },
  options: {
    headers: {
      Authorization: 'Basic <base64String>=',
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
      'WM_SVC.NAME': 'Walmart Marketplace',
      'WM_QOS.CORRELATION_ID': '1bca34cd-478f-4022-8c13-9b88293f56b2',
      'WM_SVC.VERSION': '1.0.0'
    }
  },
  method: 'post'
}

Here is the error I'm getting with JSON:
error: [
    {
      code: 'SYSTEM_ERROR.GMP_GATEWAY_API',
      description: 'Illegal character in query at index 172: http://partner-read-srvc-app.prod2.partnerreadservice1.catdev.prod.walmart.com/partner-read-srvc-app/services/org/client/search?_s=cross_ref_key==ClientId;cross_ref_value=="8cdc9a4f-3518-4941-9b62-5bc88bac5f3c;buId==0;martId==0',
      info: 'System encountered some internal error.',
      severity: 'ERROR',
      category: 'DATA',
      causes: [],
      errorIdentifiers: {}
    }

The error mentions index 172 but I'm not exactly sure what it's referring to. Having looked at their docs here I'm following the implementation to the letter.
Here is my request for XML:

{
  url: 'https://sandbox.walmartapis.com/v3/token',
  data: '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
    '<grant_type>client_credentials</grant_type>',
  options: {
    headers: {
      Authorization: 'Basic <base64String>=',
      Accept: 'application/xml',
      'Content-Type': 'application/xml',
      'WM_SVC.NAME': 'Walmart Marketplace',
      'WM_QOS.CORRELATION_ID': 'be1ff777-9c7b-4ca2-8b9c-ac31696dbf79',
    }
  },
  method: 'post'
}

But this is also fails.
Does anyone know why these requests may be failing and perhaps provide a working example in JS of a request to authenticate with the API?

A: var request = require('request');
var options = {
  'method': 'POST',
  'url': 'https://sandbox.walmartapis.com/v3/token',
  'headers': {
    'WM_SVC.NAME': 'Walmart Marketplace',
    'WM_QOS.CORRELATION_ID': 'test',
    'Accept': 'application/json',
    'Authorization': 'Basic afafaf...',
    'WM_SVC.VERSION': ' 1.0.0',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  form: {
    'grant_type': 'client_credentials'
  }
};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});

This works for me. Make sure you have the Authorization build correctly. it is in the format "Basic Base64encode(cliendId:clientSecret)"
I think the they way you are sending the grant_type attribute is incorrect.


text:
Q: KendoUI add event after a component initialization How can I add a change event after initialization in a KendoUI autocomplete? I'm building in this way, but I don't know how to do this with the component already built.
<input id="autocomplete" />
<script>
$("#autocomplete").kendoAutoComplete({
  change: function(e) {
    var value = this.value();
  }
});
</script>

A: See this link: http://docs.telerik.com/kendo-ui/api/javascript/ui/autocomplete#events-change
<input id="autocomplete" />
<script>
function autocomplete_change(e) {
  var value = this.value();
  // Use the value of the widget
}
$("#autocomplete").kendoAutoComplete();
var autocomplete = $("#autocomplete").data("kendoAutoComplete");
autocomplete.bind("change", autocomplete_change);
</script>