text:
Q: can I link library except specific symbol? Condition 1.  I have myassembly.s which do not have main.

Condition 2.  Instead, myassembly.s have global symbol _start.

Condition 3.  I wanna link _IO_stdin_used to output binary.
...and here is problematic part.
_IO_stdin_used is asserted on crt1.o as you can see :

jiwon@jiwon:/tmp$ readelf -s /usr/lib/i386-linux-gnu/crt1.o
Symbol table '.symtab' contains 17 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 00000000     0 SECTION LOCAL  DEFAULT    1
     ...
     8: 00000000     4 OBJECT  GLOBAL DEFAULT    4 _fp_hw
     9: 00000000     0 NOTYPE  GLOBAL DEFAULT  UND __libc_csu_fini
    10: 00000000     0 FUNC    GLOBAL DEFAULT    2 _start
    11: 00000000     0 NOTYPE  GLOBAL DEFAULT  UND __libc_csu_init
    12: 00000000     0 NOTYPE  GLOBAL DEFAULT  UND main
    13: 00000000     0 NOTYPE  WEAK   DEFAULT    6 data_start
    14: 00000000     4 OBJECT  GLOBAL DEFAULT    5 _IO_stdin_used
    15: 00000000     0 NOTYPE  GLOBAL DEFAULT  UND __libc_start_main
    16: 00000000     0 NOTYPE  GLOBAL DEFAULT    6 __data_start

Question.  Can I link crt1.o without _start?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

...

I attach my situation more specifically as it may be information needed for analysis.
Here is myassembly.s.
As aforementioned situation, It use _start and don't have main.
.global _start
_start:
 push $_STRING1
 push $_STRING2
 call printf
 push $0
 call exit
_STRING1:
 .string "gogo\n"
_STRING2:
 .string "%s"

I assemble and linked it :
jiwon@jiwon:/tmp$ as -o stackoverflow.o stackoverflow.s
jiwon@jiwon:/tmp$ ld -o stackoverflow -dynamic-linker /lib/ld-linux.so.2  /usr/lib/i386-linux-gnu/crti.o -lc stackoverflow.o /usr/lib/i386-linux-gnu/crtn.o

jiwon@jiwon:/tmp$ ./stackoverflow
gogo

As you can see above, the output binary works well.
However, when I tried crt1.o to be linked, the error happens.
jiwon@jiwon:/tmp$ ld -o stackoverflow -dynamic-linker /lib/ld-linux.so.2  /usr/lib/i386-linux-gnu/crti.o -lc stackoverflow.o /usr/lib/i386-linux-gnu/crtn.o /usr/lib/i386-linux-gnu/crt1.o
/usr/lib/i386-linux-gnu/crt1.o: In function `_start':
(.text+0x0): multiple definition of `_start'
stackoverflow.o:(.text+0x0): first defined here
/usr/lib/i386-linux-gnu/crt1.o: In function `_start':
(.text+0xc): undefined reference to `__libc_csu_fini'
/usr/lib/i386-linux-gnu/crt1.o: In function `_start':
(.text+0x11): undefined reference to `__libc_csu_init'
/usr/lib/i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'

Question (Same)  Can I link crt1.o without _start?

A: Instead of pulling in the whole rat's tail of crt1.o, how about you simply define _IO_stdin_used yourself?  Just put this code in one of your assembly files:
        .section .rodata
        .globl _IO_stdin_used
        .type _IO_stdin_used, @object
        .align 4
_IO_stdin_used:
        .int 0x20001
        .size _IO_stdin_used, 4

Otherwise, if you just want to require the presence of _IO_stdin_used without defining it yourself (for example, because some file in the libc defines it), just put this line into one of your assembly files:
        .globl _IO_stdin_used

This causes the assembler to mark _IO_stdin_used as an undefined global symbol which the linker has to pull in from somewhere.


text:
Q: What is the purpose of protected modifier for static methods I found such an usage of protected modifier while searching for a solution for my other question: Ignoring case in strings with unitils ReflectionComparator
In the org.unitils.reflectionassert.ReflectionComparatorFactory class there is a method with the signature:
protected static List<Comparator> getComparatorChain(Set<ReflectionComparatorMode> modes)
But this is only a particular case.
After all we can always extend such any non-final class and "override" it's static protected method with the new public modifier. Say, we have a class A:
public class A {
    protected static void test() {
        // do some stuff
    }
}

and want to use it in another package:
public class UseA {
    private static class MyA extends A {
        public static void test() {
            A.test();
        }
    }

    void useA() {
        // A.test(); compile error, sure
        MyA.test();
    }
}

I concentrate my question on a general situation when some static method was declared as protected. I'm not asking about non-static fields or methods, because in some cases class can have a private constructor or a very complicated constructor with lots special params. But what is the purpose of such "hiding" static methods if entire class isn't final? Is such usage an OOP mistake or just a very weak "protection"?

A:
But what is the purpose of such "hiding" static methods if entire class isn't final?

A protected static method would allow you to provide "utility" type functionality to derived classes, without exposing them in the public API where they might not make sense on their own.
I don't know the implementation of the getComparatorChain method you reference, but I imagine it's such a method. It would be marked static if it's not tied to any specific instance, and marked protected so as not to be a part of the public API, but also to allow derived classes to re-use the utility method in it's own implementation.

A: Overriding a static method reference means hiding it's implementation. See: Java Documentation's Overriding and Hiding Methods

Static Methods
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:

*

*The version of the overridden instance method that gets invoked is the one in the subclass.

*The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Weird blocks when adding Elements to MonoTouch Dialog RootElement after it is shown In an app I am building I use the following pattern: If the user clicks on a hierarchical navigation element I open the next UIViewController immediately, and it takes care about loading its data itself and shows a loading spinner if it is going over the network.
Now most list views are created using MonoTouch. On one DialogViewController I have an issue with adding many element to the views RootElement after the screen has already been show.
At first the StringElements appear fine on screen, but if you scroll quickly up and down the text on each line becomes a block:

Code to reproduce the issue:
        var root = new RootElement("Root");
        var dvc = new DialogViewController(root) { AutoHideSearch = true, EnableSearch = true };

        nav.PushViewController(dvc, true);

        Task.Factory.StartNew(() => {
                Thread.Sleep(TimeSpan.FromSeconds(1));
            UIApplication.SharedApplication.InvokeOnMainThread(() => {
                var sec = new Section();

                for (int i = 0; i < 100; i++)
                {
                    var el = new StyledStringElement("Test", "Test", UITableViewCellStyle.Value1);
                    sec.Add(el);
                }

                root.Add(sec);
            });
        });

Interestingly only the string on the left looks like a block, while the one on the right is fine. On a side note, in their MWC (demo) app, Xamarin created a new RootElement to repopulate the twitter list as well.

A: There does not seem to be a reload of the data source called on the main thread to correctly render the new values:
var dvc = new DialogViewController(new RootElement(""));
_root = new UINavigationController();
_root.PushViewController(dvc, true);
_window.RootViewController = _root;

Task.Factory.StartNew(() => {
    Thread.Sleep(TimeSpan.FromSeconds(1));
    var section = new Section("");
        foreach (var i in Enumerable.Range(1, 100)) {
            section.Add(new StyledStringElement(i.ToString(), "cell", UITableViewCellStyle.Value1));
        }

    dvc.Root.Add(section);
    BeginInvokeOnMainThread(() => {
        dvc.ReloadData();
    });
});

A: I exactly have the same issue when I'm rendering dynamically the element in an BeginInvokeOnMainThread statement
If I do load my elements in the constructor, the UI is blocked but the elements will render well.
and thanks for the tip dvc.ReloadData will work as well for me


text:
Q: Send large Json data to php via ajax call I need to post large amount of json data to php file via ajax, but its is showing me 413 entity too large error.
I have tried using data type as json but it still shows the same error.

$.ajax({
    url: ajaxURL,
    data: "ajax=true&action=manageSavedLayouts&a=" + result + "&b=" + encodeURIComponent(productdb),
    success: function(result) {
        console.log(result);
        //  alert(result);
    }
});

This is the code i am using to make the ajax call and the variable which is causing problem is productdb.
Any help will be greatly appreciated.
Thanks in advance.

A: $.ajax({
    url: ajaxURL,
    type: "POST",
    data: {
        ajax: true,
        action: "manageSavedLayouts",
        a: result,
        b: productdb
    }
    success: function(result) {
        console.log(result);
    }
});

A: Use type POST, e.g.:
$.ajax({
    url: ajaxURL,
    type: 'POST',
    data: "ajax=true&action=manageSavedLayouts&a=" + result + "&b=" + encodeURIComponent(productdb),
    success: function(result) {
        console.log(result);
    //  alert(result);
    }
});


text:
Q: Why crontab doesn't execute a scheduled bash script? I have seen a lot of times (1, 2 )this question, but I didn't find the answer, so here I go.
I'm running Debian 11, but I guess it works the same for any Debian-like distro.
My crontab -e looks like:
...
@reboot sleep 20 && /opt/isPromscaleOnOrOff.sh
...

And the content of isPromscaleOnOrOff.sh:
#!/bin/bash

SERVICE="promscale"
if pgrep -x "$SERVICE" >/dev/null
then
    echo "$SERVICE is running"
else
    echo "$SERVICE is stopped, I will run it now"
    nohup promscale --db-name asdf1234--db-password asdf1234 --db-user asdf1234 --db-ssl-mode allow --install-extensions & >> /dev/null
    disown
fi

But when I restart the VM the script isn't runing, tho the cron logs in /var/log/syslog show the crontab starting the script.
What I wanna achieve can be easilly done daemonizing the process (wich I indeed did), I just wanna know why crontab doesn't start up my script.

A: Jobs run through cron aren't run in the same runtime environment that you have on your desktop. None of your PATH changes, or other environment  variable settings from ~/.bashrc are automatically propagated to  your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).
One can set environment variables for all one's cron jobs in the crontab file
Read man 5 crontab.
Look at the results of  echo "=== id ===";id;echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.
Since the command part of the crontab line is, by default,  interpreted by /bin/sh, which has a simpler syntax than /bin/bash, I recommend having command be a call to a bash script  (executable, mounted, starts with #!/bin/bash) which sets up the environment,  then calls the desired program.


text:
Q: Transition matrix between bases of a polynomial vector space Im stuck on how to find a transition matrix for the change of basis between two polynomial bases.
lets say that the bases are A={3, x} and B={x, 4+x}.
I understand a method for finding the transition matrix when the elements of the bases are themselves actual vectors. I can just set up an augmented matrix and use row reduction of the new basis vectors to get the result.
I'm assuming in this case I have to think in more algebraic terms, and Ive read the textbook about 15 times now but its just not making any sense. If someone can explain how to solve this Id be very grateful.

A: You need to write the elements of one basis in the other one. For example,
$$
3=-\frac34\,x+\frac34\,(4+x),\ \ \ x=1\,x + 0\, (4-x).
$$
The transition matrix is then
$$
\begin{bmatrix} -\frac34&1\\\frac34&0\end{bmatrix}
$$


text:
Q: How to continue execution of code only when windows service is completed? I have a Windows service which performs a fairly long running task. At the moment, I spawn a new thread, which executes a method which goes off and calls this windows service. This code looks like:
Thread thread = new Thread(new ThreadStart(ExecyuteLongRunningMethod));
thread.Start();
thread.Join();

Higher up in the callstack (when this code is done), a message box popups stating the result of the operation.
However, while this block of code executes (ExecuteLongRunningMethod calls the windows svc), a message box popups stating that nothing has changed as a result of the operation, but because this is before the code block above has completed, the wrong message box appears.
Thus, the question is, what would be the proper way to only continue execution in the winforms app (this is what calls the windows svc), ONLY when the windows service is finished? I am thinking that the approach above is incorrect as the thread will call the windows service (another process), so while the windows service does its stuff, my code (winforms app) will continue. Either some sort of signaling is required, or something like named pipes?
The app is in .NET 3.5.
Thanks

A: Why don't you use a BackgroundWorker, so you can set an event for its completion?
In Backgroundworker running method you can run the service and wait for a manual reset event (for example) or a mutex and, when received this you can exit main method.
So OnCompleted event is raised in your main thread (UI for example) and the job is done...
In your app add a Backgroundworker and name it bgw.
Then you can do:
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
    // 1. Run the service
    // 2. Wait for mutex
}

private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // Here you can handle the end of the service
    // and return the status in main thread
}

A: Expose the status of your service execution via a WCF API and call it using netTcp or named pipes, you could poll the service or use a WCF CallBack.


text:
Q: Django 1.7 AttributeError: 'WSGIRequest' object has no attribute 'user' I have read some similar posts but none helped me plus I was recommended to create a new question.
I try to reach to admin page of an inherited web-site and I created a user for that matter but I reach to the admin page I get the below stack trace. I have also added the settings.py in case it helps.
Any input is much appreciate it.
M
settings.py
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XXXXX'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# ALLOWED_HOSTS = ['0.0.0.0', 'localhost']
ALLOWED_HOSTS = ['192.168.1.36',  'localhost']

# Application definition

INSTALLED_APPS = [

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'south',
    'CordeliaHanelBackend',
    'tastypie',
    'StudioHanel',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CordeliaHanelBackend.urls'

PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (
    '/var/www/CordeliaHanelBackend-master/StudioHanel/templates2',
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # 'DIRS': ['/var/www/CordeliaHanelBackend-master/StudioHanel/templates2'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CordeliaHanelBackend.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }

}

# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    # os.path.join(BASE_DIR, "static"),
    # '/var/www/CordeliaHanelBackend-master/StudioHanel/templates2',
    '/var/www/CordeliaHanelFrontend-master/www/dist/',
        # '/var/www/CordeliaHanelFrontend-master/www/app',
        # '/var/www/CordeliaHanelBackend-master/StudioHanel/static',
    )

# STATIC_ROOT = '/var/www/CordeliaHanelFrontend-master/www/app'

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

# DEFAULT_FILE_STORAGE = '/var/www/CordeliaHanelFrontend-master/www/app'

SOUTH_DATABASE_ADAPTER = {
'default': 'south.db.sqlite3'
}

Stack-trace / Error log
[Wed Nov 16 20:50:07.826886 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644] Internal Server Error: /admin/
[Wed Nov 16 20:50:07.826923 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644] Traceback (most recent call last):
[Wed Nov 16 20:50:07.826927 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]   File "/var/www/CordeliaHanelBackend-master/env/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
[Wed Nov 16 20:50:07.826930 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]     response = wrapped_callback(request, *callback_args, **callback_kwargs)
[Wed Nov 16 20:50:07.826932 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]   File "/var/www/CordeliaHanelBackend-master/env/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 225, in wrapper
[Wed Nov 16 20:50:07.826934 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]     return self.admin_view(view, cacheable)(*args, **kwargs)
[Wed Nov 16 20:50:07.826937 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]   File "/var/www/CordeliaHanelBackend-master/env/lib/python2.7/site-packages/django/utils/decorators.py", line 105, in _wrapped_view
[Wed Nov 16 20:50:07.826939 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]     response = view_func(request, *args, **kwargs)
[Wed Nov 16 20:50:07.826941 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]   File "/var/www/CordeliaHanelBackend-master/env/lib/python2.7/site-packages/django/views/decorators/cache.py", line 52, in _wrapped_view_func
[Wed Nov 16 20:50:07.826944 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]     response = view_func(request, *args, **kwargs)
[Wed Nov 16 20:50:07.826946 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]   File "/var/www/CordeliaHanelBackend-master/env/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 193, in inner
[Wed Nov 16 20:50:07.826948 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]     if not self.has_permission(request):
[Wed Nov 16 20:50:07.826951 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]   File "/var/www/CordeliaHanelBackend-master/env/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 150, in has_permission
[Wed Nov 16 20:50:07.826953 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644]     return request.user.is_active and request.user.is_staff
[Wed Nov 16 20:50:07.826955 2016] [wsgi:error] [pid 30866:tid 139796884670208] [remote 127.0.0.1:59644] AttributeError: 'WSGIRequest' object has no attribute 'user'

WSGI file
import os

master/env/lib/python2.7/site-packages/')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CordeliaHanelBackend.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

A: I had the same problem and I fixed by:
1) changing MIDDLEWARE to MIDDLEWARE_CLASSES
2) commenting out SecurityMiddleware
like below:
MIDDLEWARE_CLASSES = [
    # 'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


text:
Q: Handling email forwards for Reply Mail Management within Marketing Cloud We have a specific use case where we are facing a challenge with campaign email forwarding.
We are trying to capture email replies inside sfmc. Let's say a campaign email goes out to a customer from SFMC. The customer replies to that email. Currently we have enabled Reply Mail Management (RMM) that allows us to capture this direct email reply, and we are able to process the response and use it for our custom logic. In our case, we use that response to begin creating a lead. We stitch some other data to the info extracted from this response and go on to generate our lead. As of now, RMM allows ONLY direct replies to be captured, because when the recipient responds to their campaign email, the To-address generated contains a unique string that routes the reply to SFMC (in simple words). But here's our challenge:
In some cases, the original customer/recipient forwards their campaign email to a colleague and when that colleague responds via email, we are not able to capture that within sfmc. Because they were not the original contact the email was sent out to.
Are there any solutions out there, where we can handle this forwarding situation using any available tools/logic inside sfmc. Any insight would be appreciated!


text:
Q: What is the proper way to add retry loop to VBA code In the following code, we occasionally get collision errors. If it would wait a second and retry, it would go through.
I want it to try once. If it fails, log the error and retry. If it fails 3 times, MsgBox to the user, give up and return. The only way I can think of is using a GOTO back to the ExeHandler. Seems there should be a better way.
  Public Function RunADO(strContext As String, strSQL As String, Optional intErrSilent As Integer = 0, Optional intErrLog = -1) As Integer
  On Error GoTo ErrHandler
  ExeHandler:

     PostToLog strContext, "SQL: " & strSQL
     CurrentProject.Connection.Execute strSQL, dbFailOnError
     RunADO = -1
     Exit Function
  ErrHandler:
     RunADO = 0
     If intErrSilent = 0 Then
        MsgBox Err.Number & ": " & Err.Description, vbCritical, "Run ADO"
     End If
     If intErrLog = -1 Then
        PostErrorToLog Err.Number, strContext, Err.Source & ":" & Err.Description & ": " & "SQL: " & strSQL
     End If
  End Function

A: Perhaps something like this...
    Option Explicit

    Private Const MaxRetries As Long = 3

    Public Function RunADO(strContext As String, strSQL As String, Optional intErrSilent As Integer = 0, Optional intErrLog = -1) As Integer
        Dim attemptCounter As Long
        For attemptCounter = 1 To MaxRetries
            RunADO = RunADOInternal(strContext, strSQL, intErrSilent, intErrLog)
            If RunADO = -1 Then
                Exit Function
            End If
            If intErrSilent = 0 And attemptCounter >= MaxRetries Then
                MsgBox Err.Number & ": " & Err.Description, vbCritical, "Run ADO"
                RunADO = 0
                Exit Function
            End If
            If intErrLog = -1 Then
                PostErrorToLog Err.Number, strContext, Err.Source & ":" & Err.Description & ": " & "SQL: " & strSQL
            End If
            Application.Wait (Now + TimeValue("0:00:01"))
        Next attemptCounter
    End Function

    Private Function RunADOInternal(strContext As String, strSQL As String, Optional intErrSilent As Integer = 0, Optional intErrLog = -1) As Integer
      On Error GoTo ErrHandler

         PostToLog strContext, "SQL: " & strSQL
         CurrentProject.Connection.Execute strSQL, dbFailOnError
         RunADO = -1
         Exit Function
    ErrHandler:
         RunADO = 0
    End Function

A: Consider using a Do / Loop statement that ends when the maximum number of attempts have been made.
Public Function RunADO(strContext As String, _
                       strSQL As String, _
                       Optional intErrSilent As Integer, _
                       Optional intErrLog = -1) As Integer

    Dim Attempts As Integer

    Do While Attempts < 3
        On Error Resume Next
        PostToLog strContext, "SQL: " & strSQL
        CurrentProject.Connection.Execute strSQL, dbFailOnError
        If Err.Number Then
            If intErrSilent = 0 Then
               MsgBox Err.Number & ": " & Err.Description, vbCritical, "Run ADO"
            End If
            If intErrLog = -1 Then
               PostErrorToLog Err.Number, strContext, _
                              Err.Source & ":" & Err.Description & ": " & "SQL: " & strSQL
            End If
            Attempts = Attempts + 1
        Else
            RunADO = -1
            Exit Do
        End If
     Loop
  End Function


text:
Q: Subscribe to EventEmitter in Angular2 not working I'm learning Angular 2. I'm trying to send data from a component to other on the click of the first one.
Both components are siblings.
This is my code so far:
First Component:
@Component({
  selector: 'jsonTextInput',
  templateUrl: '../templates/jsonTextInput.html',
  directives: [Card, CardTitle, CardDescription, Icon],
  providers: [JsonChangeService]
})

export class JsonTextInput {
  json: string = '';

  constructor (private jsonChangeService: JsonChangeService) {
    this.jsonChangeService = jsonChangeService
  }

  process () {
      this.jsonChangeService.jsonChange(this.json)
  }
}

This is the service:
import {Injectable, EventEmitter} from '@angular/core';
@Injectable()

export default class JsonChangeService {
  public jsonObject: Object;

  stateChange: EventEmitter<any> = new EventEmitter<any>();

  constructor (){
    this.jsonObject = {};
  }

  jsonChange (obj) {
    console.log('sending', obj)
    this.jsonObject = obj
    this.stateChange.emit(this.jsonObject)
  }
}

The call from the first component to the service is working, since the sending is being printed.
This is the second Component
@Component({
  selector: 'jsonRendered',
  templateUrl: '../templates/jsonrendered.html',
  directives: [Card, CardTitle],
  providers: [JsonChangeService]
})

export class JsonRendered {
  private jsonObject: Object

  constructor (private jsonChangeService: JsonChangeService) {
    this.jsonChangeService = jsonChangeService
    this.jsonObject = jsonChangeService.jsonObject
    this.jsonChangeService.stateChange.subscribe(json => { this.jsonObject = json; console.log('Change made!') })
  }

  ngOnInit () {
    console.log(1)
  }

  ngOnChanges () {
    console.log(2)
  }

  renderJson () {
    console.log(3)
  }
}

The function inside the subscribe to stateChange never runs. What am I missing?
EDIT
This is the content of my stateChange EventEmitter:
_isAsync: true
_isScalar: false
destination: undefined
dispatching: false
hasCompleted: false
hasErrored: false
isStopped: false
isUnsubscribed: false
observers: Array[0]
source:undefined

A: You have two different instances of JsonChangeService. That's why you don't receive message between components. You need to have one instance service, i.e. on parent component or on top level like this:
bootstrap(AppComponent, [JsonChangeService])


text:
Q: Showing that $\frac{1}{2^n +1} + \frac{1}{2^n +2} + \cdots + \frac{1}{2^{n+1}}\geq \frac{1}{2}$ for all $n\geq 1$
Show that $$\frac{1}{2^n +1} + \frac{1}{2^n +2} + \cdots + \frac{1}{2^{n+1}}\geq \frac{1}{2}$$ for all $n\geq 1$

I need this in order to complete my proof that $1 + \frac{n}{2} \leq H_{2^n}$, but I don't have any ideas.
I know it is true at least for the first $20$ cases, but I can't prove it. Any suggestions?

A: Hint: how many summands are there? What is the smallest summand?

A: Hint for every $1\leq k\leq 2^n$
$$\frac{1}{2^n+k}\geq \frac{1}{2^{n+1}} $$
do every term in your sum is greater then $\frac{1}{2^{n+1}} $ and in the sum there is $2^n$ terms so  your sum is greater then $2^n$ times $\frac{1}{2^{n+1}} $  $\cdots$

A: $$\sum_{k=1}^{2^n} \frac{1}{2^n+k} \geq \sum_{k=1}^{2^n} \frac{1}{2^n+2^n} =\sum_{k=1}^{2^n} \frac{1}{2^{n+1}}$$
the rightmost sum equals $\frac{1}{2}$, in fact we have a strict inequality.

A: First, see that this sum has $2^n$ terms. Then, $\forall k\in \{1,\dots,2^n\}$, you have $\frac{1}{2^n+k}\geq\frac{1}{2^{n+1}}$.
Summing these inequalities, you get the result.

A: This answer addresses this part (really the main part) of your question:

I need this in order to complete my proof that $1 + \frac{n}{2} \leq H_{2^n}$, but don't have any ideas.

Consider the following exercise, the solution of which answers your question directly (skip ahead to the "induction proof" part of this answer for a proof of your claim without the fluff):

Exercise: Prove by induction that for any $n\in\mathbb{Z}^+$, there exists an $m$ so that $H_m\geq n$. Conclude that as $m\to\infty$, $H_m\to\infty$.

Proof. In order to see that the harmonic series diverges, it is enough to show that, for any $n\in\mathbb{Z}^+$, there exists an $m$ such that $H_m\geq n$. To see this, partition the series into groups, with each group totaling at least $1/2$ as follows:
$$
1+\frac{1}{2}+\underbrace{\frac{1}{3}+\frac{1}{4}}_{\geq 1/2}+\underbrace{\frac{1}{5}+\cdots+\frac{1}{8}}_{\geq 1/2}+\underbrace{\frac{1}{9}+\cdots+\frac{1}{16}}_{\geq 1/2}+\cdots.
$$
Now, the number of groups may be made as large as necessary. More formally, for each $k\geq 1$,
$$
\sum_{i=2^k+1}^{2^{k+1}}\frac{1}{i}\geq\sum_{i=2^k+1}^{2^{k+1}}\frac{1}{2^{k+1}}=(2^{k+1}-2^k)\frac{1}{2^{k+1}}=\frac{1}{2}.\tag{1}
$$
Claim: For each $p\geq 0$,
$$
S(p) : H_{2^p}\geq 1+\frac{p}{2}.
$$
By proving this claim, which is your overall goal anyway, we will have proved what is desired in the exercise above, since for every $n$, choose $p$ so large that $1+\frac{p}{2}\geq n$, and then use $m=2^p$.
Below is an inductive proof of the claim above:

Induction Proof
Claim: For each $p\geq 0$, $S(p) : H_{2^p}\geq 1+\frac{p}{2}$.
Base step: When $p=0$, $H_1\geq 1$, and this confirms that $S(0)$ is true.
Induction step: Fix some $\ell\geq0$, and assume that
$$
S(\ell) : H_{2^\ell}\geq 1+\frac{\ell}{2}
$$
is true. To be shown is that $S(\ell+1)$ follows where
$$
S(\ell+1) : H_{2^{\ell+1}}\geq 1+\frac{\ell+1}{2}.
$$
Beginning with the left-hand side of $S(\ell+1)$,
\begin{align}
H_{2^{\ell+1}} &= H_{2^\ell}+\sum_{i=2^\ell+1}^{2^{\ell+1}}\frac{1}{i}\\[1em]
&\geq H_{2^\ell}+\frac{1}{2}\tag{by $(1)$}\\[1em]
&\geq 1+\frac{\ell}{2}+\frac{1}{2}\tag{by $S(\ell)$}\\[1em]
&= 1+\frac{\ell+1}{2},
\end{align}
we end up at the right-hand side of $S(\ell+1)$, completing the inductive step.
By mathematical induction, for every $p\geq 0$, the statement $S(p)$ is true. $\Box$
Thus, for every $n$, there exists an $m$ so that $H_m\geq n$. That is, $\lim_{m\to\infty}H_m=\infty$.

Note: If desired, you may also prove that, for $n\geq 1$, $H_{2^n}\leq 1+n$, an observation that allows you to conclude that (in light of the claim we just proved)
$$
1+\frac{n}{2}\leq H_{2^n}\leq 1+n.
$$


text:
Q: Total variation and relative $\ell_\infty$ metric Let
$$D_{tv}(P,Q) = \frac{1}{2}\sum_{a \in A}|P(a)-Q(a)|$$
and
$$D_{\infty}(P,Q) = \sup_{a \in A} \log \max\{\frac{P(a)}{Q(a)}, \frac{Q(a)}{P(a)}\},$$
where $P$ and $Q$ denote probability measures on a finite set $A$.
Can you show that
$$D_{tv}(P,Q) \leq 1- \exp(-D_{\infty}(P,Q)) \leq D_{\infty}(P,Q)?$$

A: The inequality $1- \exp(-D_{\infty}(P,Q)) \leq D_{\infty}(P,Q)$ is just an instance of the elementary inequality $e^u\ge1+u$ for all real $u$.
Let us show an improved version of the inequality $D_{tv}(P,Q) \leq 1- \exp(-D_{\infty}(P,Q))$, namely,
\begin{equation*}
 D_{tv}(P,Q) \leq 1- \exp(-D_{1,\infty}(P,Q)),
\end{equation*}
where
\begin{equation*}
 D_{1,\infty}(P,Q) := \sup_{a \in A} \ln\frac{P(a)}{Q(a)}
 \le D_{\infty}(P,Q).
\end{equation*}
Indeed, for brevity let $r:=\exp D_{1,\infty}(P,Q)[\ge1]$. Then $Q(a)\ge \frac1r\,P(a)$ for all $a\in A$. So, substituting $x=P(a)-Q(a)$ into the identity $x_+:=\max(0,x)=\frac12\,(|x|+x)$ for all real $x$ and using the identity $\sum_{a \in A}(P(a)-Q(a))=0$, we have
\begin{multline*}
 D_{tv}(P,Q) = \sum_{a \in A}(P(a)-Q(a))_+
 \le\sum_{a \in A}(1-\tfrac1r)P(a)=1-\tfrac1r \\
 =1- \exp(-D_{1,\infty}(P,Q)),
\end{multline*}
as desired.


text:
Q: SDL_GetRendererInfo crash the following program runs until SDL_GetRendererInfo is called (in function RenderInit()), and then stops working before SDL_GetError can do anything. replacing global_renderer with a null SDL_Renderer pointer doesn't cause a crash and the expected sdl error is gotten.
#include <iostream>
#include <list>
#include "SDL.h"
using namespace std;
//global variables:
bool run = true; // whether or not the program should be running

int global_window_width = 50; //width of window in tiles

int global_window_height = 35; //height of window in tiles

SDL_Window* global_window = NULL; //points to primary window

SDL_Renderer* global_renderer = NULL; //points to renderer for main window

SDL_RendererInfo* global_renderer_info = NULL; //points to info about above renderer once it's initialized

SDL_Texture* spritesheet = NULL; //holds the spritesheet

SDL_Event event; //for holding currently in-handling event

//function declarations:
int init();  //initialize SDL

int windowInit(); //initialize window

int renderInit(); //create renderers

int viewInit(); //manages all window, rendering, etc stuff

int loadSpritesheet(); //loads spritesheet

void cleanup(); //free up memory, etc

void dispatchEvent(); //main event handling

//function definitions:
int init()
{
    if ( SDL_Init(SDL_INIT_EVERYTHING) !=0 )
    {
        cout << "could not initialize SDL. " << SDL_GetError();
        return 1;
    }

    return 0;
}

int windowInit()
{
    global_window = SDL_CreateWindow("roguelike",
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SDL_WINDOWPOS_UNDEFINED,
                                  global_window_width * 10,
                                  global_window_height * 10,
                                  SDL_WINDOW_SHOWN);
    if(global_window == NULL)
    {
        cout << "could create window. " << SDL_GetError();
        return 1;
    }
    return 0;
}

int renderInit()
{
        global_renderer = SDL_CreateRenderer(global_window,
                                             -1,
                                             SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_ACCELERATED );
        if (global_renderer == NULL)
        {
            cout << "could not create renderer" << SDL_GetError();
            return 1;
        }
        SDL_SetRenderDrawColor(global_renderer,0xFF,0xFF,0xFF,0xFF);
        if (SDL_GetRendererInfo(global_renderer, global_renderer_info) != 0)
        {
            cout << "could not get renderer info" << SDL_GetError();
            return 1;
        }

        return 0;
}

int viewInit()
{
    if (windowInit() == 1)
    {
        return 1;
    }
    else if(renderInit() == 1)
    {
        return 1;
    }
    else if(loadSpritesheet() == 1)
    {
        return 1;
    }
    return 0;
}

int loadSpritesheet()
{
    SDL_Surface* tempsurf = NULL; //using surface to get image initially, but since surfaces use cpu rendering we switch to textures immediately

    tempsurf = SDL_LoadBMP("spritesheet.bmp"); //puts image in the surface

    if (tempsurf == NULL)
    {
        cout << "failed to load spritesheet";
        SDL_FreeSurface(tempsurf); //we don't need tempsurf anymore
        return 1;
    }
    spritesheet = SDL_CreateTextureFromSurface(global_renderer, tempsurf);
    if (spritesheet == NULL)
    {
        cout << "failed to create spritesheet texture";
        SDL_FreeSurface(tempsurf); //we don't need tempsurf anymore
        return 1;
    }
    SDL_FreeSurface(tempsurf); //we don't need tempsurf anymore
    return 0;
}

void cleanup()
{
    SDL_DestroyWindow(global_window);
    global_window = NULL;
    SDL_DestroyRenderer(global_renderer);
    global_renderer = NULL;
    SDL_DestroyTexture(spritesheet);
    spritesheet = NULL;
    global_renderer_info = NULL;
    SDL_Quit();
}

void dispatchEvent()
{
    SDL_PollEvent(&event); //stores current event information
    switch(event.type)
    {
        case SDL_QUIT:
        {
            run = false;
            break;
        }
    }
}
//classes:

class Layer // each layer holds visuals for a certain subset of what is to be displayed; environment, HUD, menu, etc.
{
    Layer(){};
};

class Camera  //renders environment, ui, etc in a series of layers
{
        int width, height; //in tiles
        SDL_Texture* texture_draw; //texture the camera draws to and sends to be displayed
        list<Layer*> layer_list; //list of layers to be rendered, back --> front
    public:
        Camera(int x, int y, SDL_Renderer* renderer): width(x), height(y) //(width, height, renderer for camera to use)
        {
            texture_draw = SDL_CreateTexture(global_renderer,global_renderer_info->texture_formats[0] , SDL_TEXTUREACCESS_TARGET, 10*width, 10*height);
        };
};

//main loop
int main(int argc, char *argv[]) //main function, needed by SDL
{
    if(init() == 0)
    {
        if(viewInit() == 0)
        {
            while(run)
            {
                dispatchEvent();

            }
        }
    }
    cleanup();
    return 0;
}

A: You're asking SDL_GetRendererInfo to write renderer info to location global_renderer_info points to, which is NULL. Writing to NULL causes segmentation fault. This should be expected behaviour.
Correct code should allocate memory for renderer info (preferably on stack or in global area) and write to that location, e.g.:
SDL_RendererInfo info = {0};
SDL_GetRendererInfo(global_renderer, &info);
// ... use info fields

A: Fixed by: instead of declaring global_renderer_info as a pointer to an SDL_RendererInfo, I instead declared the object directly and changed the rest of the code accordingly.


text:
Q: Which program is preventing FileZilla from connecting to the server? At first, I had no problem with FileZilla connecting to the server, but recently when I try to connect to any server, FileZilla shows me this error message:
Status: Connecting to 92.222.103.103:21...
Status: Connection established, waiting for welcome message...
Error:  Connection timed out
Error:  Could not connect to server
Status: Waiting to retry...
Status: Connecting to 92.222.103.103:21...
Status: Connection established, waiting for welcome message...
Error:  Connection timed out
Error:  Could not connect to server
Status: Connecting to 92.222.103.103:21...
Status: Connection established, waiting for welcome message...
Error:  Connection timed out
Error:  Could not connect to server

I think a program is using the same port and not allowing FileZilla to connect.


text:
Q: How to restore a Consumable In app Purchases? I'm developing an iOS game where the users can buy some amount of internal currency (say 1000 golds) by a Consumable In App Purchase.
How to restore a Consumable Purchase if the users want to transfer their balance from one device to another?
In Apple's docs it says that we have to use our own server. But how to get user's Apple IDs? Or may be there is some other way to track consumable purchases?

A: If what you want to do is to share the products the user buys across different devices; you will need to:

*

*Keep the game state in the server and obtain it from the device.

*Identify users somehow, i.e. username/pass.

*Update the game state in the server each time the user buys/consumes/gains products
If you only need to share state across different installs on the same device, you could just use the device ID to identify the user.

A: You will need to be able to store the users state in a manner independent of the device they are using to access your game. So this would mean implementing a server based user profile with authentication (and appropriate security), or using some third party service.
Note that since iOS 4.1 you have the ability to use GameKit, which provides alot of these benefits for you. If you use GameKit then you will be able to retrieve user information from GKPlayer, and use this information to store currency amounts and other state in your own server.


text:
Q: Using the Node module SSH2 with shell My aim is to make a web application that allows it's user to connect to an SSH server remotely, i.e. without installing an SSH client on their computer. So this means my server will be an intermediate interface between the user and their SSH server/s.
I found an SSH2 module for node: https://github.com/mscdex/ssh2
I figured the most appropriate method of connecting was using the shell() method.
The following is a basic attempt to get a shell working.
var Connection = require('ssh2');

var c = new Connection();

c.on('ready', function() {
   c.shell(onShell);
});

var onShell = function(err, stream) {
    if (err != null) {
        console.log('error: ' + err);
    }

    stream.on('readable', function() {
        var chunk;
        while (null !== (chunk = stream.read())) {
            console.log('got %d bytes of data', chunk.length);
        }
    });

    stream.write('ls\r\n');

    console.log('Shell');

}

c.connect({
    host: 'localhost',
    port: 22,
    username: 'matt',
    password: 'password'
});

It connects fine, and there are no errors, but the "got %d bytes of data" does not show. How can I fix this?
Furthermore would this method be sensible in a large scale application with potentially many simultaneous different connections?

A: ssh2 currently does not use streams2 yet because things get tricky because of the two (stdout and stderr) "sub-"streams and trying to handle backpressure in a sane way. I am still hoping I can find some solution via streams2 though.
For now, you will have to listen for 'data', 'drain', etc. events instead.
UPDATE: ssh2 v0.3.x now supports streams2.

A: I wrote a wrapper class for ssh2 that handles running multiple commands in a SSH shell session and can SSH tunnel to multiple hosts using nested host objects. Each hosts config object has its own commands, command event handlers, end of session handler and authentication parameters. Commands responses can be checked for prompts or results that require extra handling or addition/removal of commands from a commands array. It also times out if a command produces an unexpected prompt that is not handled and would normally cause the process to hang waiting for a response it will never get.
Check it out:
Extensive info in the readme, test examples provided, additional info in the git wiki.
https://www.npmjs.org/package/ssh2shell
https://github.com/cmp-202/ssh2shell


text:
Q: mysterious program crash: where to look for clues? On Ubuntu 14.04, I often experience the following: open an application, and within 15 seconds or so the application window simply disappears from screen. If I ps aux | grep nameOfApplication it will not show up, so something has closed/killed it. This only happens once per session just after startup, and doesn't happen every time. So far it has happened with Firefox, Thunderbird, and gnome-terminal. In my recollection it has never happened with Nautilus, and I just experienced it happening to gnome-terminal after having opened Nautilus first and browsed to a folder, so it's not necessarily the first application launched that gets killed. My desktop environment is cairo-dock, not Unity, though I don't have an a priori reason to suspect cairo-dock as the culprit.
My question: where can I look for clues as to what is happening and why? These crashes aren't triggering apport or whoopsie, so presumably if I figure out the cause my next stop should be Launchpad?

update
The problem didn't happen for a few days, but this morning it recurred. I booted up, started firefox, started gnome-terminal and ran tail -f .xsession-errors, switched focus back to firefox, then a few seconds later firefox disappeared.  Here is the initial tail of .xsession-errors; unfortunately nothing was added when firefox vanished:
[~] $ tail -f .xsession-errors
Fontconfig warning: "/etc/fonts/conf.d/50-user.conf", line 14: reading configurations from ~/.fonts.conf is deprecated. please move it to /home/dan/.config/fontconfig/fonts.conf manually

** (gnome-terminal:2600): WARNING **: Couldn't connect to accessibility bus: Failed to connect to socket /tmp/dbus-x4UUa9owca: Connection refused

(gnome-terminal:2600): GLib-GIO-CRITICAL **: g_settings_get: the format string may not contain '&' (key 'monospace-font-name' from schema 'org.gnome.desktop.interface'). This call will probably stop working with a future version of glib.
Fontconfig warning: "/etc/fonts/conf.d/50-user.conf", line 14: reading configurations from ~/.fonts.conf is deprecated. please move it to /home/dan/.config/fontconfig/fonts.conf manually

** (gnome-user-share:2696): WARNING **: Couldn't connect to accessibility bus: Failed to connect to socket /tmp/dbus-x4UUa9owca: Connection refused

** (telepathy-indicator:2698): WARNING **: Couldn't connect to accessibility bus: Failed to connect to socket /tmp/dbus-x4UUa9owca: Connection refused

To me these all look unrelated, but I'm hoping more experienced users will see something that I don't.

A: I'd start by running it from a terminal. You've already said that your graphical terminal is a problem application, so use a TTY:

*

*Control+Alt+F1 to get to TTY1

*Log in.

*Run DISPLAY=:0 gnome-terminal to launch a problem application on your display (obviously change the display number if you're running more than one).

*Switch back to the X server with Control+Alt+F7 and use the Gnome Terminal until it crashes.

*Switch back to TTY1 and view the error message.

In my experience, things dying off for no reason usually comes down to RAM issues or graphics drivers. Either of these two have just enough fingers in just enough pies to cause many headaches.
Assuming you don't find a nice Googleable error message, I'd run a memtest (from grub or a LiveCD/USB) and look at whether there are more stable drivers for the graphics card. Then change kernel version. By this point it's just as much about reproducing the error and noticing what you changed.

A: The output of programs invoked through the GUI is sent to the file .xsession-errors in your home directory, so you should look here for clues.
Since the output of all the programs goes to the same place, it might be hard to tell what is coming from the crashing program. If you want to be able to get the output of a specific program, start it from a terminal. Either type the name of the executable on the command line, e.g. type firefox at the shell prompt, or redirect the output to a file:
{ firefox; echo $?; } </dev/null >~/firefox-$(date).log 2>&1 & disown

You can close the terminal once you've issued this command.
All the output from Firefox will be logged into a file called firefox-DATE.log in your home directory. Once Firefox exits, the last line in the log file will be the status code: 0 for a normal exit, 1–127 for an error, and 128–255 if Firefox died due to a signal (e.g. 139 for a segmentation violation, i.e. an invalid pointer access).
There are two main culprits for frequent crashes:

*

*Video driver bugs. If you're using a 3D environment such as Unity (the default), try using a 2D environment instead, such as LXDE without Compiz.

*Defective RAM. RAM can go bad over time. Test your RAM. Reboot your computer and press and hold Shift as soon as you see a message about the keyboard being initialized; you should see a Grub boot menu after a few seconds. (If you can't see the boot menu, see Pressing shift does not get me into any grub menu.) Let the test run for at least one full pass. If it reports an error, change your RAM immediately and verify all your data — bad RAM can lead to insidious data corruption.


text:
Q: Using an enum as a mapkey results in a RAW in the database I'm trying to use an enum as a mapkey for a map in Hibernate, but Hibernate stores my enum as a RAW:
I have this enum:
public enum AccountType implements Serializable {
    CASH,
    CREDIT_CARD,
    GIRO,
    INVOICE,
    OTHER;
}

Which I'm trying to use as a key in a map:
@CollectionOfElements
@MapKey(columns =  @Column(name="ACC_TYPE"),
  targetElement = AccountType.class)
@Column(name="ACCOUNT_NO")
public Map<AccountType, String> getAccounts() {
  return accountMap;
}

What happens here is that Hibernate stores the enum as a raw in the database instead of a varchar:
"Column Name"   "Data Type"
"COMPANY_ID"    "NUMBER(19,0)"
"ACC_TYPE"      "RAW"
"ACCOUNT_NO"    "VARCHAR2(255 CHAR)"

I want this to be stored as a varchar. I've tried to add @Enumerated(value = EnumType.STRING), but it looks like that doesn't work on the mapkey.

A: You might try defining a Hibernate UserType for the enum mapping.  This would allow you to specify the db column type to use in the DDL.
See https://www.hibernate.org/265.html
HTH
Tom

A: There's the @MapKeyEnumerated JPA annotation, but as of Hibernate core 3.6.5 it doesn't seem to do much to change the generated DDL type. I still see raw :(


text:
Q: structure If not work into method static Model Laravel The following code retrieves a model from the database if the value passed as a parameter in the method is defined, however, it also implicitly ends up creating a new model.
What is the problem?.
public static function findOrCreateShoppingCartById($shopping_cart_id) {
  if($shopping_cart_id) {
    $cart = ShoppingCart::find($shopping_cart_id);
    return $cart;
  }
  $newCart = ShoppingCart::create();
  return $newCart;
}

Try to put exit; but still disrespect him
Can someone help me find the solution to the problem?
Thank you


text:
Q: R: Function that creates a new column and assigns a score based off of the difference I am trying to create a function that calculates a score based off of the user inputs of a cost and a weight.  I am trying to subtract the user input from a column in the dataframe passed into the function and then assign a score based off of the difference and the user inputs for the weight.  I then wish to add this column to the dataframe.  However, I'm having difficulty getting it to work properly.  Any help would be greatly appreciated.
I am basically just trying to assign a score to a school based off the difference between the user's input of costs and the school's actual cost. So, for instance, if the user wants a cost of 25000 and the school costs 15000, then I want it to give this school a maximum score. If the cost of the school significantly exceeds the user's input cost, then I want to give this a low score. I want it to calculate the score for each row in my data frame.  Here's what I have so far.
distance = function(table, a, weighta) {
 dist = c((table$In.state.tuition - a))
 if (any(dist <= 0)) {
     score = 10
 }
 else score = 0

finalscore = weighta*score
table$Score = finalscore
return(table)
}

A: Never mind, I got it to work using the ifelse function.  Thanks!

A: I'm not totally sure what your question is, or what code you've tried, but it seems to me that you want to award a score of 10*weighta to the scools with tuitions under some user-defined threshold. If it's so, I think this is easily obtained by standard code (I used some random values):
set.seed(123)                                     # make it reproducible
df<-data.frame(In.state.tuition =rnorm(20,50,2), score=rep(0,20))
a<-49                                             # arbitrary number
weighta<-3                                        # another arbitrary number
df$score[df$In.state.tuition<=a]<-10*weighta      # use indexing
df
   In.state.tuition score
1          48.87905    30
2          49.53965     0
3          53.11742     0
4          50.14102     0
5          50.25858     0
6          53.43013     0
7          50.92183     0
8          47.46988    30
9          48.62629    30
10         49.10868     0
11         52.44816     0
12         50.71963     0
13         50.80154     0
14         50.22137     0
15         48.88832    30
16         53.57383     0
17         50.99570     0
18         46.06677    30
19         51.40271     0
20         49.05442     0

Is this what you wanted?
As a sidenote, I guess from your last comment in your question where you state "I want to calculate a score for each column" that you actually meant "I want to calculate a score for each row in the In.state.tuition column".


text:
Q: Two routers network routing settings I have two routers, Router A is connected to the internet, and Router B is connected to the LAN port of Router A.
Router A:
192.168.1.1
Subnet 255.255.255.0
Router B:
IP leased from router A: 192.168.1.2
Its own ip: 192.168.0.1
subnet 255.255.255.0
I have a machine C plugged to router A with ip 192.168.1.3
also a machine D plugged to router B with ip 192.168.0.199

I want to access machine D from a machine C. What settings do I need to change to do that?

A: Router A needs to know which route to use to reach the 192.168.0.0/24 network.
Initially try adding a static route that says it can reach 192.168.0.0/24 via 192.168.1.2.
On a Cisco router running IOS you'd do
 ip route 192.168.0.0 255.255.255.0 192.168.1.2

On your unspecified  make and model of router you'll have to use a web-interface or read the manual to find it's equivalent.

A: If your network is as simple as your diagram, with no NAT surprises, then there just needs to be a static route for 192.168.0.0/255.255.255.0 pointing to 192.168.1.2.  This route can be on either Router A or Machine C, the latter being more restrictive than the former.

A: If these are standard residental "routers" with 4 LAN ports, then you actually have a device that is a combination of router and switch.  The 4 LAN ports are a switch.  Devices connected to that will see each other without you having to do anything other than take care of IP address setup, which is normally DHCP's job.  You can "cascade" switches and things will work just fine.
If you are looking to just connect more than 4 devices in your home to the Internet, Router B does not need to be doing routing or DHCP at all, and the functionality should be disabled.  Connect "router" B to a LAN port in router A, and anything else you need to the LAN ports on router B and as long as router B is not doing DHCP or anything else, it should just work.

A: I am assuming 192.168.0.1 is not the gateway used on router B, but rather its own IP on the LAN interface. If router A is giving out addresses through DHCP, it is also informing B of what gateway to use, and this should be 192.168.1.1. If you can access the internet from B's subnet, this is the case, unless you have a very excentring setup that needs a far more detailed explanation.
To answer your question, machines C and D are on seperate networks, but D can initiate a connection with C just fine. It can't find the IP 192.168.1.3 on its own subnet, so it passes on the request to its gateway, i.e. router B, who does know where the target machine is located.
The other way around is more difficult. Neither host D itself nor its gateway, router A, knows that traffic intended for 192.168.0.199 should traverse through router B. Even if they did, for instance by defining a route '192.168.0.0/24 trough 192.168.1.2', router B would not allow the packets to pass from its WAN interface to the LAN interface.
Although you may be better off using B as a 'dumb' switch instead of a router by simply connecting everything to its LAN ports, it is possible to circumvent this issue without changing the network topology. You will need to forward ports on router B that are used in communication originating outside the 192.168.0.0/24 network.
For instance, if machine D is running a web server, to which communication must be initiated from machine C, you will want to configure router B to forward port 80 towards 192.168.0.199. Alternatively, given your router supports such a feature, you can place machine D in router B's DMZ, thus forwarding all ports to this machine, unless they are configured otherwise. Normally, this could be regarded as insecure, but in this case, the machine will still be protected through router A, unless the 192.168.1.0/24 network is compromised.

A: You are preforming network address translation twice and it's probably set to moderate/strict settings. So Router B is hiding it's private addresses from connections initiated from outside router b's subnet and vice versa. This is because it assumes the network attached to it's WAN port is the public web. Normally this is fine because if the connection is established from inside the private network the router then knows where to send the incoming traffic back to. But in your case both sides are preforming NAT so each side is hiding it's private addresses from the other. This is why you need port forwarding behind a NAT so the router knows where to route connections being initiated from outside the network. A great way to understand what is happening is to look into UDP hole punching which is what many VNC and gaming applications use to allow connections to be initiated from outside.
Strict NAT is generally a limitation with consumer grade routers, but some of the better ones allow you to adjust NAT settings. Alternatively you can use DD-WRT, tomato, or another thrid party firmware that allows adjustments made to the NAT. You can also use port forwarding (which is a little more cumbersome) as mentioned by other users.

A: (Assuming you can get router B's WAN interface to be a normal ethernet interface, like on a cable router)
You need to set static routes on both machines C and D.  If you have something more than basic doing DHCP and the machines C and D get their addresses from DCHP, you could push the routes out to all DHCP clients automatically.
Otherwise, you can set the routes like this:
Windows
Machine C
route -p ADD 192.168.0.0 MASK 255.255.255.0 192.168.1.1 METRIC 1

Machine D
route -p ADD 192.168.1.0 MASK 255.255.255.0 192.168.0.1 METRIC 1

Linux (added to network interface settings)
Machine C
route add -net 192.168.0.0/24 gw 192.168.1.1

Machine D
route add -net 192.168.1.0/24 gw 192.168.0.1


text: Q: Get the absolute url for BLOB image I'm working with BLOB image in PHP. My images has no absulut url ( like this : www.example.com/my_image) . I need it because i'm woking with facebook open graph image sharing. How can i fix that?


text:
Q: can't change the payload text in the Get Started button I'm trying to change the payload text "USER_DEFINED_PAYLOAD" in the Get Started button in my Facebook Messenger chatbot. For example like this:
curl -X POST -H "Content-Type: application/json" -d '{
  "setting_type":"call_to_actions",
  "thread_state":"new_thread",
  "call_to_actions":[
    {
      "payload":"start"
    }
  ]
}' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN"

Like the example at https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button but with another payload text.
But the returned value of the payload is still "USER_DEFINED_PAYLOAD"!! I can change other payload texts in other messenges but not in this Get Started button. I wonder if anyone here might know how to change this payload text??

A: The request has changed for setting GET_STARTED payload .
https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<access_token>
{
  "get_started":{
    "payload":"FB_GET_STARTED"
  }
}

Here is the documentation :
Facebook GET_STARTED documentation


text:
Q: How do I invoke managed bean from an ICEfaces modal popup? I am using Eclipse Luna EE, Tomcat v7.0 and ICEFaces 3.2
I have a form for label printing that the user enters information such as item number, item name and label type. The user then submits the form. This sends the information to a label printer, in a ZPL string, which then prints out the correct label for the item. This all works no problem.
The form makes a check against the print quantity, in case of a high value (100+ in production). If the print quantity is over a certain value (> 2. purely for testing purposes) then the "testFlag" boolean is set to true, the modal box is displayed and an error flag is set so that the print command doesn't execute.
The modal box asks if the user entered the correct quantity, with Yes/No buttons available.
The printUI and the modal popup are inside the same <ice:form> element, with the popup box rendered and visible if the testFlag is set to true.
The Problem:
When I click the "Yes" button in the modal box, it doesn't carry out the action I have assigned to it (System.out.println("Yes Button!")). The modal box closes and nothing happens.
I can then resubmit the form and the modal box appears again, then I click "Yes" and nothing happens.
If I change the quantity to 2 and submit, then it executes the print command no problem.
I am guessing that it is a problem with the way the session is being handled.
Question:
How do I get the "Yes" button on the modal box to carry out the code I am wanting?
I've tried:
Using <ice:commandLink>, <h:button>, <h:commandButton>, <h:commandLink>
Having the modal popup and the form in separate <ice:form> tags (This refreshed the session and removed all entered data).
Using an actionListener
code containing the form:
<h:body>
    <div id="surround">
        <ice:form id="test" prependId="false">
            <ui:include src="./printUI.xhtml" />
            <ui:include src="./printQtyPopup.xhtml" />
        </ice:form>
    </div>
</h:body>

printQtyPopup.xhtml
    <ui:composition>
        <ice:panelPopup modal="true" visible="#{validateBean.testFlag}" rendered="#{validateBean.testFlag}">
            <f:facet name="header">
                <ice:outputText value="Print Quantity Check" />
            </f:facet>
            <f:facet name="body">
                <ice:panelGrid>
                    <ice:outputText value="You selected a print quantity of: #{validateBean.printAmount}" />
                    <ice:outputText value="Is this correct?" />
                    <ice:panelGroup>
                        <ice:commandButton value="No" />
                        <ice:commandButton value="Yes" action="#{validateBean.checkQtyYes}" />
                    </ice:panelGroup>
                </ice:panelGrid>
            </f:facet>
        </ice:panelPopup>
    </ui:composition>

Relevant ValidateBean.java code
    public void validate() { //validation checks are carried out when the user clicks "Print" on the printUI.
        if (!errorFlag && checkQty && printQty > 2) {
            testFlag = true;
            errorFlag = true;
            System.out.println("Qty Check Modal");
        }

        if (!errorFlag) {
            if (printQty > 0) {
                initialiseString();

                initialisePrinter();

                clear();
            } else {
                printQty = 0;
                errorMessage = true;
                quantityInvalid = true;
                errorFlag = true;
            }
        }
    }

    public void checkQtyYes() {
        System.out.println("Yes Button!");
    }

A: I found an alternative.
I have removed the modal popup and any code linked with it.
I have added in a <ice:panelConfirmation> at the end of my form. This is only rendered if the print quantity is above whatever number I set.
I get the number by using a valueChangeListener="#{validateBean.printQtyChange}" on my Print Quantity <h:inputText> with onblur="submit()"
I tried the onchange="submit()" but ran into problems when submitting a string of print jobs. I would have to press "ENTER" to force the onchange attribute to activate, which I have been assured the users don't want.

The <ice:panelConfirmation> works by pausing the submit of the form and waits for a response before it either continues or stops the submit. Which accomplishes what I was trying to achieve with the modal popup.

Print Quantity Input Text:
<h:inputText id="printQty" value="#{validateBean.printAmount}" size="8" autocomplete="off"
    maxlength="3" required="true" onblur="submit()"
    valueChangeListener="#{validateBean.printQtyChange}" />

valueChangeListener:
public void printQtyChange(ValueChangeEvent e) {
    printAmount = e.getNewValue().toString();

    try {
        ls.setPrintQty(Integer.parseInt(printAmount));
    } catch (NumberFormatException eve) {
        errorMessage = true;
        quantityInvalid = true;
        errorFlag = true;
    }

    printQty = ls.getPrintQty();

    System.out.println("Qty : " +printQty);

    if (printQty < 1) {
        errorMessage = true;
        quantityInvalid = true;
        errorFlag = true;
    }
}

Panel Confirmation:  inside the <ice:form>. Just before the closing of the form
<ice:panelConfirmation id="confirmQty"
    acceptLabel="Yes"
    cancelLabel="No"
    message="Your entered the quantity: #{validateBean.printQty}. Is this correct?"
    title="Confirm Quantity"
    draggable="false"
    rendered="#{validateBean.printQty > 2}" />

Print Button: tied in with the <ice:panelConfirmation>
<ice:commandButton styleClass="button" id="printButton" value="Print"
    actionListener="#{validateBean.validate}" panelConfirmation="confirmQty" />

If anyone does know of a way to invoke a managed bean from a conditional ICEfaces modal popup that would be great also.

UPDATE
I've since changed all my <h:inputText> to <ice:inputText> and added the partialsubmit="true" to my input field for the quantity. with adding this I have been able to remove the onblur="submit()"
NEW Print Quantity Input Text:
<ice:inputText id="printQty" value="#{validateBean.printAmount}" size="8" autocomplete="off"
    maxlength="3" required="true" valueChangeListener="#{validateBean.printQtyChange}"
    partialSubmit="true" />

This has removed the issue where sometimes it still had problems when submitting a string of jobs.
I haven't put partialsubmit="true" on the <ice:form> because I had to then declare every other input field as partialsubmit="false" to prevent unnecessary code being executed. It's tidier to only have it on the input field I want to check.


text:
Q: Maven deployment to heroku error I'm trying to deploy a java/maven application to heroku platform, everything goes ok until I try to access the result link.
 Despite of successfully build the link I open shows this error:
        An error occurred in the application and your page could not be served. Please try again in a few moments.

        If you are the application owner, check your logs for details.

>  [INFO] ------------------------------------------------------------------------
       [INFO] BUILD SUCCESS
       [INFO] ------------------------------------------------------------------------
       [INFO] Total time: 6.571 s
       [INFO] Finished at: 2016-10-06T20:06:45+00:00
       [INFO] Final Memory: 24M/164M
       [INFO] ------------------------------------------------------------------------
-----> Discovering process types
       Procfile declares types -> (none)
-----> Compressing...
       Done: 87.3M
-----> Launching...
       Released v9
       https://restaurant-challenge.herokuapp.com/ deployed to Heroku

Thanks :D

A: That's not an error. But your build output shows that you don't have any process types defined (which means heroku won't know how to run your app):
Procfile declares types -> (none)

You'll need to create a Procfile and add it to your Git repo. Most Java apps have a Procfile that contains something like:
web: java -cp target/classes:target/dependency/* com.example.Main

A: Application Logs:

2016-10-06T22:15:32.100143+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=restaurant-challenge.herokuapp.com request_id=1296ef81-571d-47e5-98dc-5d03903cc510 fwd="202.12.102.10" dyno= connect= service= status=503 bytes=
2016-10-06T22:15:33.413012+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=restaurant-challenge.herokuapp.com request_id=d141a43d-6b8c-49f6-beda-3015cb6ed095 fwd="202.12.102.10" dyno= connect= service= status=503 bytes=
2016-10-07T00:00:23.973558+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=restaurant-challenge.herokuapp.com request_id=a67f3093-7ca0-4eaa-9a49-0eb1a0d51fd8 fwd="200.144.94.28" dyno= connect= service= status=503 bytes=
2016-10-07T00:00:24.773937+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=restaurant-challenge.herokuapp.com request_id=e2566da5-e666-46ea-b8bb-e4bb74c7758b fwd="200.144.94.28" dyno= connect= service= status=503 bytes=
2016-10-07T00:03:28.357036+00:00 heroku[api]: Deploy 28740e1 by 95felipeg@gmail.com
2016-10-07T00:03:28.357036+00:00 heroku[api]: Release v11 created by 95felipeg@gmail.com
2016-10-07T00:03:28.543707+00:00 heroku[slug-compiler]: Slug compilation started
2016-10-07T00:03:28.543712+00:00 heroku[slug-compiler]: Slug compilation finished
2016-10-07T00:08:48.878843+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=restaurant-challenge.herokuapp.com request_id=cb9c2a83-0ebf-4d83-89a6-d273b4d70fd6 fwd="200.144.94.28" dyno= connect= service= status=503 bytes=
2016-10-07T00:08:49.400040+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=restaurant-challenge.herokuapp.com request_id=18093f32-39c7-4085-90e4-a04e84e4f9d7 fwd="200.144.94.28" dyno= connect= service= status=503 bytes=
2016-10-07T00:11:54.778061+00:00 heroku[api]: Set maintenance mode on by 95felipeg@gmail.com
2016-10-06T22:15:32.100143+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=restaurant-challenge.herokuapp.com request_id=1296ef81-571d-47e5-98dc-5d03903cc510 fwd="202.12.102.10" dyno= connect= service= status=503 bytes=
2016-10-06T22:15:33.413012+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=restaurant-challenge.herokuapp.com request_id=d141a43d-6b8c-49f6-beda-3015cb6ed095 fwd="202.12.102.10" dyno= connect= service= status=503 bytes=
2016-10-07T00:00:23.973558+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=restaurant-challenge.herokuapp.com request_id=a67f3093-7ca0-4eaa-9a49-0eb1a0d51fd8 fwd="200.144.94.28" dyno= connect= service= status=503 bytes=
2016-10-07T00:00:24.773937+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=restaurant-challenge.herokuapp.com request_id=e2566da5-e666-46ea-b8bb-e4bb74c7758b fwd="200.144.94.28" dyno= connect= service= status=503 bytes=
2016-10-07T00:03:28.357036+00:00 heroku[api]: Deploy 28740e1 by 95felipeg@gmail.com
2016-10-07T00:03:28.357036+00:00 heroku[api]: Release v11 created by 95felipeg@gmail.com
2016-10-07T00:03:28.543707+00:00 heroku[slug-compiler]: Slug compilation started
2016-10-07T00:03:28.543712+00:00 heroku[slug-compiler]: Slug compilation finished
2016-10-07T00:08:48.878843+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=restaurant-challenge.herokuapp.com request_id=cb9c2a83-0ebf-4d83-89a6-d273b4d70fd6 fwd="200.144.94.28" dyno= connect= service= status=503 bytes=
2016-10-07T00:08:49.400040+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=restaurant-challenge.herokuapp.com request_id=18093f32-39c7-4085-90e4-a04e84e4f9d7 fwd="200.144.94.28" dyno= connect= service= status=503 bytes=
2016-10-07T00:11:54.778061+00:00 heroku[api]: Set maintenance mode on by 95felipeg@gmail.com


text:
Q: CSS3 :target with only HTML style I've got a challenge I'm trying to solve.
I'm trying to create a page that has tabs to switch between content, without using Javascript or inline/external CSS. I'd like to use the :target function but the absolute only way I can use CSS in this instance is through style="" from the HTML.
Is it possible to switch between pages (like you'd see with tabs and JavaScript) with only using CSS3 inside HTML style tags for an element?
Literally, I can't even use  or
 ...
 No other way..

*

*http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_style

*http://www.w3schools.com/html/tryit.asp?filename=tryhtml_bodybgstyle


text:
Q: Spring-Data Jpa Inheritance: Keeping Entity Id's in Children Entity I'm dealing with a couple of Entities with Tree like structures that were getting more complicated so I decided to create an abstract class for it so code was a bit more mainainable:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class TreeStructure<T extends TreeStructure>
{
    @ManyToOne
    protected  T parent;

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    protected Set<T> children = new HashSet<>();
    //...

Then I have two Entities which extend it:
@Entity(name = "TreeStructureOne")
public class TreeStructureOne extends TreeStructure<TreeStructureOne>
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonProperty("TreeStructureOne_id")
    private long id;

And I basically want the database to be completely unaware of this TreeStructure abstraction and save all of the fields in each Entities tableand expected InheritanceType.TABLE_PER_CLASS to deal with that. But it seems I need to define the Id in the TreeStructure Entity at least or I get:
Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: TreeStructure
And I don't want to add an ID into the abstract class since this makes three tables in the database called: HT_TREE_STRUCTURE, HT_TREE_STRUCTURE_ONE and HT_TREE_STRUCTURE_TWO with one field ID each one.
Is there any solution to that?

A: Since TreeStructure is not an @Entity use only @MappedSuperclass
@MappedSuperclass
public abstract class TreeStructure<T extends TreeStructure> {

instead of @Entity and @Inheritance for the parent class.
You can find @MappedSuperclass in the Oracle JEE API documentation.


text:
Q: Donot wrap exceptions of Feign client Fall back method with Hystrix RunTime Exception Fallback service is wrapping ProductNotFoundException into HystrixRunTimeException.
I want to propagate custom exception as it is instead of wrapping into HystrixRunTimeException.
Below is the code snippet for reference:
@FeignClient(name = "service1", fallback = FallBackService1.class )
public interface FeignService1{
      String validateProducts(Product product);
}

class FallBackService1 implements FeignService1{
  @override
  public String validateProducts(Product product){
     throw new ProductNotFoundException("P119","Product not found");
  }
}

I have enabled
feign.hystrix.enable = true.
Please help with this. I want to propagate the exception as it is. I do not want it to be wrapped.

A: It looks impossible to tell hystrix to not wrap your custom exception in the fallback method.
What you can do is to create your custom ErrorDecoder and throw your custom exception from there. In this case, your custom exception should implement com.netflix.hystrix.exception.ExceptionNotWrappedByHystrix
otherwise hystrix will wrap it into HystrixRuntimeException.
Simple example.

*

*Create feign config with ErrorDecoder implementation. Note do not mark FeignClient1Config with the @Configuration annotation if you don't want all FeignClient to be processed by the same decoder.

import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;

public class FeignClient1Config {

    @Bean
    public ErrorDecoder customErrorDecoder() {
        return (methodKey, response) -> {
            throw new ProductNotFoundException("P119","Product not found for request " + response.request());
        };
    }
}

*Your feign client should look like this

@FeignClient(name = "service1", configuration = FeignClient1Config.class)
public interface FeignService1{
      String validateProducts(Product product);
}

The drawback of this implementation is that all methods in the FeignService1 will be processed by the same error decoder.
To overcome it you can create your own fallbackFactory and add it as a property to the @FeignClient(fallbackFactory = ...)
Or the solution I like the most is this
And do not forget your exception to implement ExceptionNotWrappedByHystrix class.


text:
Q: Error trying to build the default Android Studio app I'm trying to create an Android app, but when I create an app, just the default "hello world" app that comes when you create a new project.
But when I try to build the default app it gives me this error...Why?

One or more issues found when checking AAR metadata values:

The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.appcompat:appcompat:1.4.0.
AAR metadata file: C:\Users\Afonso.gradle\caches\transforms->3\46d15f5c58a469270eeba15db4463d05\transformed\appcompat-1.4.0\META->INF\com\android\build\gradle\aar-metadata.properties.

The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.appcompat:appcompat-resources:1.4.0.
AAR metadata file: C:\Users\Afonso.gradle\caches\transforms->3\70088de83757cd2e92dadb8b386e6adb\transformed\jetified-appcompat-resources-1.4.0\META->INF\com\android\build\gradle\aar-metadata.properties.

The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.emoji2:emoji2-views-helper:1.0.0.
AAR metadata file: C:\Users\Afonso.gradle\caches\transforms->3\6cbed90352b213553df3539e2e7f22af\transformed\jetified-emoji2-views-helper-1.0.0\META->INF\com\android\build\gradle\aar-metadata.properties.

The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.emoji2:emoji2:1.0.0.
AAR metadata file: C:\Users\Afonso.gradle\caches\transforms->3\09b79be83fba3907471fe1de63f439d3\transformed\jetified-emoji2-1.0.0\META->INF\com\android\build\gradle\aar-metadata.properties.

The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.core:core:1.7.0.
AAR metadata file: C:\Users\Afonso.gradle\caches\transforms->3\9339927e08badd09bc5459e4ba900d5f\transformed\core-1.7.0\META-INF\com\android\build\gradle\aar->metadata.properties.

The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.lifecycle:lifecycle-process:2.4.0.
AAR metadata file: C:\Users\Afonso.gradle\caches\transforms->3\0e4a425e61d135d109d64d5f17d999df\transformed\jetified-lifecycle-process-2.4.0\META->INF\com\android\build\gradle\aar-metadata.properties.

The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.lifecycle:lifecycle-runtime:2.4.0.
AAR metadata file: C:\Users\Afonso.gradle\caches\transforms->3\bca1bb61c15ab5807e64593ca04debef\transformed\lifecycle-runtime-2.4.0\META->INF\com\android\build\gradle\aar-metadata.properties.

A: If you read the error messages carefully you can understand:

The minCompileSdk (31) specified in a dependency's AAR metadata is greater than this module's compileSdkVersion (android-30).

One simple solution would be to go to gradle build(:app) and change the compileSdkVersion to 30:

Go to search and type build gradle (:app)

It would look something like this:
android {
    compileSdkVersion 31
}

After the change it should be this:
android {
    compileSdkVersion 30
}

Change the targetSdkVersion under defaultConfig to 30:
Like this:
defaultConfig {

        targetSdkVersion 30

            }

Save and run

A: Try to change your build.gradle(app) file.
Set compileSdkVersion and targetSdk to 30, and Sync your gradle file

A:
The minCompileSdk (31) specified in a dependency's AAR metadata
[...] is greater than this module's compileSdkVersion (android-30).

The minimum compile SDK version of some of your dependencies are set to 31, while your app's compile SDK is set to 30.
You can simply raise your compileSdk version in module-level build.gradle to 31:
android {
    compileSdk 31
}

Or you can leave that and instead use older versions of the dependencies you have trouble with. E.g. instead of
implementation 'androidx.appcompat:appcompat:1.4.0'

it would be
implementation 'androidx.appcompat:appcompat:1.3.1'

and so on...


text:
Q: Ergodic decomposition of the action of a subgroup Let $G$ be a countable abelian group and let $H \le G$ be a subgroup. Let $G \curvearrowright (X,\mu)$ be an ergodic measure preserving action on some probability space $(X,\mu)$. Now we know that the action $H \curvearrowright (X,\mu)$ may not be ergodic, but it has an ergodic decomposition $\mu = \int_Y\mu_y d\nu_y$ where each $\mu_y$ is ergodic for the action of $H$.
Questions:

*

*Are almost all the ergodic components $\mu_y$ isomorphic to each other (as $H$-systems)?

*If $G$ is weakly mixing then are almost all $\mu_y$ weakly mixing?

The answer seems to be yes if $H$ is finite index in $G$. I am interested in the case of $H = \mathbb{Z} \times \{0\} $ and $G = \mathbb{Z}^2$.

A: The answer to both questions is "no" - a counterexample (labeled "folklore") appears immediately prior to Question 6.6 in Austin, Tim, Extensions of probability-preserving systems by measurably-varying homogeneous spaces and applications, Fundam. Math. 210, No. 2, 133-206 (2010). ZBL1206.28023..
Here it is, essentially verbatim:
Let $G = \mathbb Z\times \mathbb Z$, let $\mathbb T = \mathbb R/\mathbb Z$ with Haar probability measure $m$, and let $X = \mathbb T^2 \times \mathbb T^2$ and $\mu=$ Haar probability measure on $X$.  Let $A:\mathbb T^2\to \mathbb T^2$ be any ergodic toral automorphism, and define an action of $\mathbb Z\times \mathbb Z$ on $X$ by $(n,m)\cdot (\mathbf x, \mathbf y) = (A^n\mathbf x, A^n(\mathbf y+m\mathbf x))$.  In other words, $G \curvearrowright (X,\mu)$ is the action generated by $A\times A$ and the map $(\mathbf x,\mathbf y)\mapsto (\mathbf x, \mathbf y+\mathbf x)$.  The action generated by $A\times A$ is ergodic (and in fact mixing), since the action generated by $A$ is mixing.  The entire action is therefore weak mixing.
Taking $H:= \{(0,m):m\in \mathbb Z\}$, the ergodic components are given by rotation $(0,m)\cdot \mathbf y = \mathbf y + m \mathbf x$ on the vertical $Y_{\mathbf x}:=\{(\mathbf x, \mathbf y): \mathbf y\in \mathbb T^2\}$.  Examining the spectrum of these components reveals that they are not (almost all) mutually isomorphic, and no component is weak mixing.


text:
Q: Wrong Min value returned from list - MS Access Query I'm using MS Access to store data that looks like this :
|EmpID    |Day1     |Day2     |Day3     |Day4    |Day5
|aa            |23        |23               |24                 |25             |
|bbb         |23              |1440    |                       |                      |            |ccc            |                       |240              |240         |300         |360
|ddd           |                  |20            |20              |20           |20
I found a way to find the Minimum value ACROSS the record (least number in the columns Day 1, 2 ,3 ,4 ,5 in a single ROW) and wrote the below query :
SELECT Minimum([Day1],[Day2],[Day3],[Day4],[Day5],[Day6],[Day7],[Day8],[Day9],[Day10],[Additional]) as [MinVal], Day1,Day2,Day3,Day4,Day5 from Tasks;
to get this result :
MinVal |Day1     |Day2    |Day3    |Day4   |Day5
23           |23            |23           |24           |25           |
5                |23            |1440      |5              |                |
80           |                 |240       |80            |300        |360
10           |                |20             |10              |20           |20
Now I'm trying to get the minimum value from the MinVal column. Expected: 5
 Actual: 10
The query I am using is :
Select min([MinVal]) as MinimumVal from ( SELECT Minimum([Day1],[Day2],[Day3],[Day4],[Day5],[Day6],[Day7],[Day8],[Day9],[Day10],[Additional]) as [MinVal] from Tasks) t ;
The data type for all fields is number.
I cannot figure out why the Min function is returning the wrong value from the list. Please help me figure this out!
Edit : I got the Minimum function from here . I had to make changes to the function given in the page because if your record has null values and only one number, it would give null as output ( does not handle comparing NULL to a number correctly). So, instead of :
 If FieldArray(I) < currentVal Then
 currentVal = FieldArray(I)
 End If
 Use :

If (FieldArray(I) < currentVal) And (IsNull(currentVal) = False) Then
 currentVal = FieldArray(I)
 ElseIf (IsNull(currentVal) = True) And (IsNull(FieldArray(I)) = False) Then
 currentVal = FieldArray(I)
 End If

A: It appears that the minimum function (found here) that you are using to compute the minimum value across the fields might not return the number/int data type. So convert your minval column to a number and then do a min..
 Select min(val([MinVal])) as MinimumVal from
        ( SELECT Minimum([Day1],[Day2],[Day3],[Day4],[Day5],[Day6],[Day7],
        [Day8],[Day9],[Day10],[Additional]) as [MinVal] from Tasks) t ;


text:
Q: Django IntegrityError while updating a record I have a model with double columns as primary key. I do a filter on it and get the records I want, change a field and save it. As I know save will update the record and does not create a new instance of the model in db. so It should be all okay but I'm stuck with an integrityError Duplicate entry '10-2' for key 'PRIMARY' when I try to save the record
Here is the code snippet:
analysis = AnalysisResult.objects.filter(request=req.request_id)
for anal in analysis:
    anal.analysisresult_path = some_string
    anal.save() #this line is where the error occurs

And here is my model:
class AnalysisResult(models.Model):

    analysisresult_path = models.CharField(db_column='analysisResult_path', max_length=255, blank=True,
                                       null=True)  # Field name made lowercase.
    detectionresult_path = models.CharField(db_column='detectionResult_path', max_length=255, blank=True,
                                        null=True)  # Field name made lowercase.
    targetcode = models.ForeignKey('TagetCode', models.DO_NOTHING,
                               db_column='targetCode_id')  # Field name made lowercase.
    request = models.ForeignKey('Request', models.DO_NOTHING, primary_key=True)

    class Meta:
        managed = False
        db_table = 'analysis_result'
        unique_together = (('request', 'targetcode'),)

A: Ah, yes, welcome to one of django's strongest opinions:  all tables/models should have a single primary key field that can be used for updates.  If you don't have this, you must write raw SQL for the update since save will assume that there is an implicit primary key field called id to use in the where clause.


text:
Q: How to hide an upload file element using javascript? Its quite wierd .
My structure is
<form name="fm">
    <input type="file" name="fl">
    <input type="text" name="st">
</form>

Now document.fm.st.hidden=true; works as expected hiding the text box but document.fm.fl.hidden=true; doesnt works , it doesnt hides the file upload element ! Why & how to work around ?

A: It sounds like this might be a case of the script running before the page is completely loaded. If you want to be absolutely sure that the page is loaded before the script runs, you can do something like this:
document.onload = function(){ // if you want it could also be window.onload
    document.fm.st.hidden = true;
    document.fm.fl.hidden = true;
};

A: Cant you just give it an id and use
document.getElementById('yourID');

other whise maybe you can make a css class for it and use Jquery
.addClass() and .removeClass()

A: if you want to keep the input's space than apply visibility = "hidden" otherwise display = "none".
get Element by name
var inputElements = document.getElementsByName("fl");
This will provide you a list of the elements which have name 'fl'.
Now if you want to hide all the elements, run a loop.
For now, it'll provide only an element.
var inputElement = inputElements[0];
I would suggest using jQuery if you want to keep using javascript for long.
now hide the element
inputElement.style.display = "none";

A: For starters, make sure your script is after your element.  The javascript you provided should work as you provided it, but if it doesn't, try the following:
<form name="fm">
    <input type="file" name="fl">
    <input type="text" name="st">
</form>

<script>
    // hides the element (it will still take up space)
    document.getElementsByName("fl").style.visibility="hidden";

    // hides the element (it does not take up any space)
    document.getElementsByName("fl").style.display="none";
</script>


text:
Q: Why is my internal field getting modified - understanding how C# references objects I have something similar to the following very simple code, but I'm getting caught out by the way objects are referenced. I'd like to understand what's going on a little more.
I'm surprised to find that _connection.Name and _connection.Enabled can be modified outside of the class.
internal class ConnectionProperties
{
    internal string Name = "Default Name";
    internal bool Enabled = true;
}

internal class Data
{
    private readonly ConnectionProperties _connection;
    internal string ConnectioName => _connection.Name;

    internal ConnectionProperties Connection()
    {
        return _connection;
    }

    internal Data()
    {
        this._connection = new ConnectionProperties();
    }

}

class Program
{
    static void Main(string[] args)
    {
        Data data = new Data();

        Console.WriteLine(data.ConnectioName);

        ConnectionProperties temp = data.Connection();
        temp.Name = "New Name";

        Console.WriteLine(data.ConnectioName);

    }
}

OUTPUT:
Default
Name New Name


text:
Q: How to use correlation argument of nlme model in rpy2 I want to estimate the model
fit <- nlme::lme(y ~ T + t, random = ~ 1 | sub, correlation = corAR1( form = ~ 1 | sub))

in rpy2. I am running the following without problems:
formula = robjects.Formula('y0 ~ T + t + c0')
random = robjects.Formula('~1|sub')
m1 = nlme.lme(formula,random=random, data=endogexog)

where endogexog is my corresponding data.
However, when I want to specify the ar1 structure of errors within subject through the correlation argument, I get an error.
correlation_formula = robjects.Formula("~ 1|sub")
m2 = nlme.lme(formula,random=random, correlation=nlme.corAR1(form=correlation_formula), data=endogexog)

WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Error in formula.default(object) : invalid formula

---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
<ipython-input-26-3653905f35ef> in <module>
      3 # The general idea is right, see https://stackoverflow.com/questions/17333351/correlation-structure-corar1-not-defined-in-rpy2-generalised-least-squares-m
      4 # how to pass it correctly with correlation argument specified?
----> 5 m2 = nlme.lme(formula,random=random, correlation=nlme.corAR1(form=correlation_formula), data=endogexog)

3 frames
/usr/local/lib/python3.7/dist-packages/rpy2/rinterface.py in __call__(self, *args, **kwargs)
    678             )
    679             if error_occured[0]:
--> 680                 raise embedded.RRuntimeError(_rinterface._geterrmessage())
    681         return res
    682

RRuntimeError: Error in formula.default(object) : invalid formula

Any idea why this could be?

A: Try using stats.asOneSidedFormula
from rpy2.robjects.packages import importr

stats = importr('stats')

# correlation_formula = robjects.Formula("~ 1|sub")
correlation_formula = stats.asOneSidedFormula("~ 1|sub")


text:
Q: Saving an image and displaying it I have an inner class named "SaveImageTask" which works in background and save a taken image from camera, then I use Intent to another class named "MainActivity2" where I want to display the image, here is the code:
 private class SaveImageTask extends AsyncTask<byte[], Void, Void> {

    @Override
    protected Void doInBackground(byte[]... data) {
        FileOutputStream outStream = null;
        try {
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File(sdCard.getAbsolutePath() + "/SelfieLightCamera");
            dir.mkdirs();
            String fileName = String.format("%d.jpg", System.currentTimeMillis());
            File outFile = new File(dir, fileName);
            outStream = new FileOutputStream(outFile);
            b = flip(BitmapFactory.decodeByteArray(data[0], 0, data[0].length));
            b.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            Log.d("pictureTaken", "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
            refreshGallery(outFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        CameraPreview.safeToTakePicture = true;
        startActivity(new Intent(MainActivity.this, MainActivity2.class));
        return null;
    }

    public Bitmap flip(Bitmap bitmap) {

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float[] mirrorY = {-1, 0, 0, 0, 1, 0, 0, 0, 1};
        Matrix matrixMirrorY = new Matrix();
        matrixMirrorY.setValues(mirrorY);
        matrix.postConcat(matrixMirrorY);
        matrix.postRotate(90);
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }
}

MainActivity2.class:
public class MainActivity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ImageView img = (ImageView) findViewById(R.id.imageView);
        img.setImageBitmap(MainActivity.b);
    }
}

However, it takes too much time, I am taking the image and then it is displaying with a delay of 5 seconds between, any way to make it more efficient?

A: Solution was displaying the image before saving it(calling the Intent to the different class before):
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {

        @Override
        protected Void doInBackground(byte[]... data) {
            FileOutputStream outStream = null;
            try {
                b = flip(BitmapFactory.decodeByteArray(data[0], 0, data[0].length));
                startActivity(new Intent(MainActivity.this, MainActivity2.class));
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath() + "/SelfieLightCamera");
                dir.mkdirs();
                String fileName = "Picture_" + String.format("%d.jpg", System.currentTimeMillis());
                File outFile = new File(dir, fileName);
                outStream = new FileOutputStream(outFile);
                b.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                outStream.flush();
                outStream.close();
                Log.d("pictureTaken", "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
                refreshGallery(outFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
            CameraPreview.safeToTakePicture = true;
            return null;
        }

        public Bitmap flip(Bitmap bitmap) {

            int w = bitmap.getWidth();
            int h = bitmap.getHeight();
            Matrix matrix = new Matrix();
            float[] mirrorY = {-1, 0, 0, 0, 1, 0, 0, 0, 1};
            Matrix matrixMirrorY = new Matrix();
            matrixMirrorY.setValues(mirrorY);
            matrix.postConcat(matrixMirrorY);
            matrix.postRotate(90);
            return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        }
    }