text:
Q: Performance with global variables vs local I am still new to Python, and I have been trying to improve the performance of my Python script, so I tested it with and without global variables. I timed it, and to my surprise, it ran faster with global variables declared rather than passing local vars to functions. What's going on? I thought execution speed was faster with local variables? (I know globals are not safe, I am still curious.)

A: The time that you are not including is the programmer time spent tracking down the bugs created when using a global has a side effect somewhere else in your program.  That time is many times greater than the time spent creating and freeing local variables,

A: Locals should be faster
According to this page on locals and globals:

When a line of code asks for the value of a variable x, Python will search for that variable in all the available namespaces, in order:

*

*local namespace - specific to the current function or class method. If the function defines a local variable x, or has an argument x, Python will use this and stop searching.

*global namespace - specific to the current module. If the module has defined a variable, function, or class called x, Python will use that and stop searching.

*built-in namespace - global to all modules. As a last resort, Python will assume that x is the name of built-in function or variable.

Based on that, I'd assume that local variables are generally faster. My guess is what you're seeing is something particular about your script.
Locals are faster
Here's a trivial example using a local variable, which takes about 0.5 seconds on my machine (0.3 in Python 3):
def func():
    for i in range(10000000):
        x = 5

func()

And the global version, which takes about 0.7 (0.5 in Python 3):
def func():
    global x
    for i in range(1000000):
        x = 5

func()

global does something weird to variables that are already global
Interestingly, this version runs in 0.8 seconds:
global x
x = 5
for i in range(10000000):
    x = 5

While this runs in 0.9:
x = 5
for i in range(10000000):
    x = 5

You'll notice that in both cases, x is a global variable (since there's no functions), and they're both slower than using locals. I have no clue why declaring global x helped in this case.
This weirdness doesn't occur in Python 3 (both versions take about 0.6 seconds).
Better optimization methods
If you want to optimize your program, the best thing you can do is profile it. This will tell you what's taking the most time, so you can focus on that. Your process should be something like:

*

*Run your program with profiling on.

*Look at the profile in KCacheGrind or a similar program to determine Which functions are taking the most time.

*In those functions:

*

*Look for places where you can cache results of functions (so you don't have to do as much work).

*Look for algorithmic improvements like replacing recursive functions with closed-form functions, or replacing list searches with dictionaries.

*Re-profile to make sure the function is still a problem.

*Consider using multiprocessing.

A: Simple Answer:
Due to Python's dynamic nature, when the interpreter comes across an expression like a.b.c, it looks up a (trying first the local namespace, then the global namespace, and finally the built-in namespace), then it looks in that object's namespace to resolve the name b, and finally it looks in that object's namespace to resolve the name c. These lookups are reasonably fast; For local variables, lookups are extremely fast, since the interpreter knows which variables are local and can assign them a known position in memory.
Interpreter knows which names inside your functions are local and it assigns them specific (known) locations inside the function call's memory. This makes references to locals much faster than to globals and (most especially) to built-ins.
Code example to explain the same:
>>> glen = len # provides a global reference to a built-in
>>>
>>> def flocal():
...     name = len
...     for i in range(25):
...         x = name
...
>>> def fglobal():
...     for i in range(25):
...         x = glen
...
>>> def fbuiltin():
...     for i in range(25):
...         x = len
...
>>> timeit("flocal()", "from __main__ import flocal")
1.743438959121704
>>> timeit("fglobal()", "from __main__ import fglobal")
2.192162036895752
>>> timeit("fbuiltin()", "from __main__ import fbuiltin")
2.259413003921509
>>>

A: When Python compiles a function, the function knows before it is called if the variables in it are locals, closures, or globals.
We have several ways of referencing variables in functions:

*

*globals

*closures

*locals

So let's create these kinds of variables in a few different functions so we can see for ourselves:
global_foo = 'foo'
def globalfoo():
    return global_foo

def makeclosurefoo():
    boundfoo = 'foo'
    def innerfoo():
        return boundfoo
    return innerfoo

closurefoo = makeclosurefoo()

def defaultfoo(foo='foo'):
    return foo

def localfoo():
    foo = 'foo'
    return foo

Dissassembled
We can see that each function knows where to look up the variable - it doesn't need to do so at runtime:
>>> import dis
>>> dis.dis(globalfoo)
  2           0 LOAD_GLOBAL              0 (global_foo)
              2 RETURN_VALUE
>>> dis.dis(closurefoo)
  4           0 LOAD_DEREF               0 (boundfoo)
              2 RETURN_VALUE
>>> dis.dis(defaultfoo)
  2           0 LOAD_FAST                0 (foo)
              2 RETURN_VALUE
>>> dis.dis(localfoo)
  2           0 LOAD_CONST               1 ('foo')
              2 STORE_FAST               0 (foo)

  3           4 LOAD_FAST                0 (foo)
              6 RETURN_VALUE

We can see that currently the byte-code for a global is LOAD_GLOBAL, a closure variable is LOAD_DEREF, and a local is LOAD_FAST. These are implementation details of CPython, and may change from version to version - but it is useful to be able to see that Python treats each variable lookup differently.
Paste into an interpreter and see for yourself:
import dis
dis.dis(globalfoo)
dis.dis(closurefoo)
dis.dis(defaultfoo)
dis.dis(localfoo)

Test code
Test code (feel free to test on your system):
import sys
sys.version
import timeit
min(timeit.repeat(globalfoo))
min(timeit.repeat(closurefoo))
min(timeit.repeat(defaultfoo))
min(timeit.repeat(localfoo))

Output
On Windows, at least in this build, it looks like closures get a little bit of a penalty - and using a local that's a default is the fastest, because you don't have to assign the local each time:
>>> import sys
>>> sys.version
'3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]'
>>> import timeit
>>> min(timeit.repeat(globalfoo))
0.0728403456180331
>>> min(timeit.repeat(closurefoo))
0.07465484920749077
>>> min(timeit.repeat(defaultfoo))
0.06542038103088998
>>> min(timeit.repeat(localfoo))
0.06801849537714588

On Linux:
>>> import sys
>>> sys.version
'3.6.4 |Anaconda custom (64-bit)| (default, Mar 13 2018, 01:15:57) \n[GCC 7.2.0]'
>>> import timeit
>>> min(timeit.repeat(globalfoo))
0.08560040907468647
>>> min(timeit.repeat(closurefoo))
0.08592104795388877
>>> min(timeit.repeat(defaultfoo))
0.06587386003229767
>>> min(timeit.repeat(localfoo))
0.06887826602905989

I'll add other systems as I have a chance to test them.


text:
Q: How to set the Timer Notification on reminder functionality in WP7? I am developing WP7 application in .net. I am new to the WP7. I have developed a diary application on WP7. In that application user can select the alphabet make the entry of Income or Payment on the selected date. The details gets saved in the XML Files. Similarly I am adding the Reminder and Note in the application. Now I also want to add the time selection on the Reminder and Note. So that user can set the specific time while adding the Reminder and Note. I want to create some type of notification popup so that it will popup on that specific time of the selected date on which the Reminder and Note has been added. If popup will be a messagebox with some text then it will also be OK. Can you please tell the way by which I should go to resolve the above issue ? How should I set the timer in my application ? How should I display the notification popup ( or messagebox ) on that specific time of the date ? Can you please provide me any code or link through which I can resolve the above issue ? If I am doing anything wrong then please guide me.

A: Currently, I don't believe that the WP7 API provides apps with any access to the calendars or reminder APIs.
As a result, I believe the only way to do this type of functionality is by implementing your own web service for push notifications - e.g. see this blog about how to show toast notifications - and then relying on the user having a data connection at the right time.
Hopefully, a new API will get opened up in the near future.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Make changes without restarting tomcat all over again I'm using spring mvc and spring data jpa with eclipse And it's very annoying that every time i make ctrl+s to my java classes my tomcat get restarting.
Also for example if i made changes in my controller why tomcat when he restart it make again connection and create bean of hibernate !.
There is not a way to deploy my project without restarting and see the changes made to my java classes ?

A: Take a look at JRebel - it's designed to do exactly what you are asking for.

A: You might take a look at spring-loaded. Jrebel has more features, but spring-loaded is open source.
https://github.com/spring-projects/spring-loaded


text:
Q: Local Server: Cannot change existing images HTML to PHP I converted a static HTML+CSS+JS website to php, only header and footer were separated, in header.php and footer.php.rest of the pages were changed from .html to .php, but when I am adding a new image and replacing it with an existing image, the image is not showing. If I replace the existing image with an image that I already had in the folder it will work but if I add a new image it won't work.
I am using apache2 local server.
I have tried clearing browser cache and also restarted the server but nothing changes.

*

*the browser console shows GET http://example.com/images/logo.png 403 (Forbidden)


text:
Q: A subbase of the weak topology of $\mathcal{P}(X)$
*

*Given a set $X$ and an indexed family $(Y_{i}, \tau_i)_{i \in I}$ of topological spaces with functions $f_{i}: X \rightarrow Y_{i}$. The initial topology $\tau$ on $X$ induced by the collection $(f_i)_{i\in I}$ is the coarsest topology on $X$ such that each
$$
f_{i}:(X, \tau) \to (Y_{i}, \tau_i)
$$
is continuous. It follows that $\{f_i^{-1} (O_i) \mid i\in I, O_i \in \tau_i\}$ is a subbase of $\tau$.

*Let $X$ be a metric space with be Borel $\sigma$-algebra $\Sigma$. Let $\mathcal{P}(X)$ be the set of probability measures on $(X,\Sigma)$. According to wikipedia, the weak topology $\tau_w$ of $\mathcal{P}(X)$ is generated by
$$
\mathcal U :=\left\{ U_{\phi, x, \delta} \,\left|\, \begin{array}{c} \phi \colon X \to \mathbb{R} \text{ is bounded and continuous,} \\ x \in \mathbb{R} \text{ and } \delta > 0 \end{array} \right. \right\}
$$
where
$$
U_{\phi, x, \delta} := \left\{ \mu \in \mathcal{P}(X) \,:\, \left| \int_{X} \phi \, \mathrm{d} \mu - x \right| < \delta \right\}.
$$
It is proved here that $\mathcal U$ is a base of $\tau_w$. It seems to me $\tau_w$ is the initial topology induced by the collection of maps
$$
\left\{L_\phi:\mu \mapsto \int_X \phi \mathrm d \mu \,\middle\vert\, \phi \colon X \to \mathbb{R} \text{ bounded and continuous}  \right\}.
$$
As such, $\mathcal U$ is indeed a subbase of $\tau_w$.

Could you confirm if my above understanding is correct?


text:
Q: Laravel return json with eloquent collection relationship values I have the following function inside the UsersApiController class :-
public function getKhatmas()
{
    $user = Auth::user();
    $khatmas = $user->khatmas;
    return response()->json($khatmas);
}

The above code give the following response :-
[
    {
        "id": 3,
        "hash": "5ec72b4913d1a",
        "type": 2,
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    },
    {
        "id": 4,
        "hash": "5ec72b7005126",
        "type": 2,
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    },
]

Relationship function in User Model file :-
public function khatmas()
    {
        return $this->hasMany('App\Khatma');
    }

App\Khatma file content :-
public function type()
    {
        return $this->belongsTo('App\KhatmaType');
    }

In above json response , ("type": 2) is the foreign key of App\KhatmaType Model .
I want instead of json response with the foreign key of KhatmaType Model, i want it to return the column "title" from App\KhatmaType to be like this :-
{
        "id": 3,
        "hash": "5ec72b4913d1a",
        "type": "this is title from App\KhatmaType Model",
        "type_text": "sample text",
        "division": 2,
        "division_variant": 1,
        "status": "active",
        "expiry_date": null,
        "is_name": 0,
        "user_id": 2,
    }

`I tried with the following :-
$khatmas = $user->khatmas->with('type');

But it return error : Method Illuminate\Database\Eloquent\Collection::with does not exist

A: Fixed by using the following query builder:-
public function getKhatmas()
{
    $user = Auth::user();

    $khatmas = Auth::user()->khatmas()
    ->select('hash','type_text','status','expiry_date','type_id')
    ->with('type')->get();

    return response()->json($khatmas);
}


text:
Q: Replace all tab characters at the beginnings of lines with 8 spaces? I just stumbled upon a problem that I find surprisingly difficult. I'd like to replace all tab characters at the beginnings of lines in all *.cc and *.h files with 8 spaces. Something like:
sed  's/\t/        /g' -i  *.cc *.h

But only for the beginnings of lines. Keep in mind that sed 's/^\t/      /g'  -i  *.cc *.h won't do as it doesn't handle the case when the line begins with multiple tabulation characters.
How can I achieve this using sed?

A: You can use following command:
sed ':label s/^\(\(        \)*\)\t/\1        /; t label' -i  *.cc *.h

You can read about branching in sed here: http://www.thegeekstuff.com/2009/12/unix-sed-tutorial-6-examples-for-sed-branching-operation/

A: Using sed
sed -r ':a s/(^ {8}*)\t/\1        /;ta'

A: Try using,
sed -e '/^\t/ s/\t/        /g'


text:
Q: Open Camera in Nexus 7 tablet I have developed a Camera application in android. It captures image using a surface view. Below is the code that I used to open camera
try {
            // attempt to get a Front Camera instance
            c = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out
                    .println("fail to connect to Front Camera");
        }
        if (c == null) {
            try {
                // attempt to get a Back Camera instance
                c = Camera.open(1);
            } catch (Exception e) {
                // TODO: handle exception
                System.out
                        .println("fail to connect to Camera   with      id   =   1");
            }
        }
        if (c == null) {
            try {
                // attempt to get a Back Camera instance
                c = Camera.open(0);
            } catch (Exception e) {
                // TODO: handle exception
                System.out
                        .println("fail to connect to Camera   with      id   =   0");
            }
        }
        if (c == null) {
            try {
                // attempt to get a Back Camera instance
                c = Camera.open();
            } catch (Exception e) {
                // TODO: handle exception
                System.out
                        .println("fail to connect to Back Camera");
                return c;
            }

Where c is an object of Camera.
It works fine in other phones except Nexus 7 Tablet. In Nexus 7, the code throws exception in all cases except the last one i.e. c = Camera.open();, but still the object c is null.
Here is the stack trace
11-22 12:36:57.559 W/System.err(7621): java.lang.NullPointerException
11-22 12:36:57.559 W/System.err(7621): at

com.MyPackage.OpenCamera.getFrontCameraInstance(OpenCamera.java:238)
11-22 12:36:57.559 W/System.err(7621): at

com.MyPackage.OpenCamera.onCreate(OpenCamera.java:123)
11-22 12:36:57.559 W/System.err(7621): at

android.app.Activity.performCreate(Activity.java:5104)
11-22 12:36:57.559 W/System.err(7621): at

android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
11-22 12:36:57.559 W/System.err(7621): at

android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
11-22 12:36:57.559 W/System.err(7621): at

android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
11-22 12:36:57.559 W/System.err(7621): at

android.app.ActivityThread.access$600(ActivityThread.java:141)
11-22 12:36:57.559 W/System.err(7621): at android.app.ActivityThread

$H.handleMessage(ActivityThread.java:1234)
11-22 12:36:57.559 W/System.err(7621): at

android.os.Handler.dispatchMessage(Handler.java:99)
11-22 12:36:57.559 W/System.err(7621): at android.os.Looper.loop

(Looper.java:137)
11-22 12:36:57.559 W/System.err(7621): at android.app.ActivityThread.main

(ActivityThread.java:5039)
11-22 12:36:57.559 W/System.err(7621): at

java.lang.reflect.Method.invokeNative(Native Method)
11-22 12:36:57.559 W/System.err(7621): at java.lang.reflect.Method.invoke

(Method.java:511)
11-22 12:36:57.559 W/System.err(7621): at

com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run

(ZygoteInit.java:793)
11-22 12:36:57.559 W/System.err(7621): at

com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-22 12:36:57.559 W/System.err(7621): at dalvik.system.NativeStart.main

(Native Method)
11-22 12:36:57.559 I/System.out(7621): Error in setting Parameter
11-22 12:36:57.609 I/ActivityManager(480): Displayed
11-22 12:36:57.679 W/System.err(7621): at

android.location.Geocoder.getFromLocation(Geocoder.java:136)
11-22 12:36:57.679 W/System.err(7621): at com.MyPackage.OpenCamera.

$MyTimmer$1.run(OpenCamera.java:336)
11-22 12:36:57.679 W/System.err(7621): java.lang.NullPointerException
11-22 12:36:57.679 W/System.err(7621): at com.MyPackage.OpenCamera.

$MyTimmer$1.run(OpenCamera.java:344)

So I can't use it to capture image.
Any solution???
Thanks...

A: When using the following code on the Nexus 7:
int cameraId = CameraInfo.CAMERA_FACING_FRONT;
The cameraId is 1, however, as you have seen, using 1 as the parameter results in an error.
I have found that using 0 instead of 1 works but the camera must be released after each use so I go ahead and call Camera.open(cameraId).release();
I realize this is ugly but it seems to solve the issue with the Nexus 7.
    int cameraId = -1;
    boolean errorFound = false;
    boolean hasFeatCamera = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);

    if (hasFeatCamera) {

            try{
                 cameraId = CameraInfo.CAMERA_FACING_BACK;
                 Camera.open(cameraId).release();
                }catch(Exception e){
                    Camera.open(0).release();
                }

    } else if(CameraInfo.CAMERA_FACING_FRONT>-1){

        try{
         cameraId = CameraInfo.CAMERA_FACING_FRONT;
         Camera.open(cameraId).release();
        }catch(Exception e){
            errorFound = true;

        }

        if(errorFound){
            try{
                Camera.open(0).release(); // Put in for Nexus 7 as  CameraInfo.CAMERA_FACING_FRONT= 1 but it only loads if the id is actually 0
                cameraId = 0;
            }catch(Exception e){
                cameraId = -1;
            }
        }
    }

    if(cameraId<0){
        Toast.makeText(this, "No camera found.",
                    Toast.LENGTH_LONG).show();
     }

A: A bit late, but maybe it helps someone.
I had the exact same problem and could NOT get the Nexus 7 camera to work with any index supplied to getCamera(idx).
I installed a camera "Kamera Nexus 7" app from the playstore. I didn't have any camera app after a reset/update.
This app worked and after i used it once, i could get the cam by using
Camera.getCamera(0);
So maybe there is an additional "unlock requirement" that is not covered in the answers here? (They did not work for me, before installing the app)


text:
Q: Writing jQuery-style function chains in AS3 and other class-based languages This isn't a specific problem I have, more a choice I could make, but I do believe the question is relevant for SO as there may be a 'proper' OO answer, as well as a performance benefit/loss to doing this. I'm working in AS3, but I believe the question would be relevant for other class-based/oo languages.
I was trying to figure a way to have Java-style multiple constructors for a class with different parameters (which is another story) but this got me thinking about jQuery, and how it chains functions by having them, where possible, return the object they are being called upon.
It doesn't always make for the neatest code with jQuery, and I guess it's a different practice to the classical approach, but I wondered if there is anything to be said for this method:
//execute chains of methods on creation, as each returns its parent class (person)
var person:Person = new Person().male('a male', 25).wakeUp().lookAround();

//Or later
person.getUp().rubEyes();

...and whether having member functions all returning an object which will often not be needed represent any significant waste/a performance issue?
It seems like a good way to save code and also represent sequences of functions in a more readable way, I wondered if anyone could help.
Thanks in advance

A: Yes, there is something to be said for person.getUp().rubEyes(): semantically it looks better. That's all.
new Person().male('a male', 25) is an entirely different case though. Male is not a verb like getUp. I would prefer: new Person({ gender: 'male', age: 25}).
Is there a significant performance hit when the returned object is not used? No. First of all, most (jit) compilers are smart enough to figure out that the object returned is never used and will therefore not execute those instructions at all. This is an optimization strategy called dead code elimination. Secondly, even if the compiler would not perform this optimization then still we are talking about a few measly clockcycles. Nothing you should worry about. In general I would advise you not to worry about these kind of performance issues at all. Better focus your optimization efforts on the parts of your code the compiler can not help you with (i.e. design, algorithms, etc).
Have fun chaining!


text:
Q: getDisplayMedia split choice window on chrome I noticed that google hangout meets provide the functionality to select if you want to share an entire monitor, application, or just a browser tab and instead of one menu, it is split into three.
I tried applying constraints like displaySurface: "monitor", but it didn't work and still provided all choices in one window. I was wondering how to achieve the same functionality in chrome as google hangouts, because according to MDN web docs

Note: Unlike most uses of constraints in media APIs, here it's solely used to define the stream configuration, and not to filter the available choices.

and this seems counterintuitive to the implementation that meet.google.com have unless there is a way to achieve this without constraints


text:
Q: Python: Numpy / Numba comparing arrays I provide a working minimal example without numba decorator. I know that numba gives me an error for a != b with a and b being arrays. Any idea how to make it work with numba?
I have also noted, that numba will work on flatten arrays i.e. a.flatten() != b.flatten(). Unfortunately, I don't want a comparison of last element of column 1 with first element with column 2. I assume, there is a way to compute strides and delete elements from the flat array, but I don't think it is either fast nor readable nor maintainable.
array2d = np.array([[1, 0, 1],
                    [1, 1, 0],
                    [0, 0, 1],
                    [2, 3, 5]])

#@numba.jit(nopython=True)
def TOY_compute_changes(array2d):
    array2d = np.vstack([[False, False, False], array2d[:-1] != array2d[1:]])
    return array2d

TOY_compute_changes(array2d)
array([[False, False, False],
       [False,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])

A: If I am getting you right, this should work:
a = np.array([
    [0, 1, 0],
    [0, 1, 0],
    [0, 1, 0],
])

b = np.array([
    [1, 0, 1],
    [0, 1, 0],
    [0, 1, 0],
])

@numba.jit(nopython=True)
def not_eq(a, b):
    return np.logical_not(a == b)

print(not_eq(a, b))

Output:
[[ True  True  True]
 [False False False]
 [False False False]]

String example:
a = np.array([['a', 'b', 'c'], ['x', 'y', 'z']])
b = np.array([['x', 'y', 'z'], ['x', 'y', 'z']])
print(not_eq(a, b))

Output:
[[ True  True  True]
 [False False False]]


text:
Q: How does Facebook detect if I block javascript on my browser? I had opened my browser setting and blocked Javascript for all websites. But when I tried to access Facebook, it says
"We're sorry, but Facebook doesn't work properly without JavaScript enabled."
My question is, how they have detected that my browser is not allowing Javascript?

A: First – you can display this message by default and remove it with JS.
Seconds – there is a HTML <noscript> tag.

A: They use the noscript element to selectively redirect.
<noscript><meta http-equiv="refresh" content="0; URL=/?_fb_noscript=1" /></noscript><


text:
Q: How to debug remote Java application through nginx reverse proxy I need to debug a remote java application running behind an nginx reverse proxy.
I get the following error:

Failed to attach to remote debuggee VM. Reason: java.io.IOException: Received invalid handshake

What should be the right nginx configuration to achieve this?
I have successfully attached vscode java debugger to the remote java application by targeting the app's host directly.
Resolver is 127.0.0.11 because I'm using nginx docker image.
My nginx config file app.xyz.com.conf in conf.d:
server {
    listen 1043;
    resolver 127.0.0.11 valid=30s;
    server_name app.xyz.com;
    include /etc/nginx/mime.types;
    location / {
        proxy_buffer_size 8k;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        set $upstream "http://java-app:1043";
        proxy_pass $upstream;
        client_max_body_size 10M;
    }
}

Thanks in advance!

A: You should declare tcp port instead http for debug java application.


text:
Q: SAX parsing - efficient way to get text nodes Given this XML snippet
<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>

In SAX, it is easy to get attribute values:
@Override
public void startElement (String uri, String localName,
              String qName, Attributes attributes) throws SAXException{
    if(qName.equals("book")){
        String bookId = attributes.getValue("id");
        ...
    }
}

But to get the value of a text node, e.g. the value of the <author> tag, it is quite hard...
private StringBuffer curCharValue = new StringBuffer(1024);

@Override
public void startElement (String uri, String localName,
              String qName, Attributes attributes) throws SAXException {
    if(qName.equals("author")){
        curCharValue.clear();
    }
}

@Override
public void characters (char ch[], int start, int length) throws SAXException
{
     //already synchronized
    curCharValue.append(char, start, length);
}

@Override
public void endElement (String uri, String localName, String qName)
throws SAXException
{
    if(qName.equals("author")){
        String author = curCharValue.toString();
    }
}

*

*I'm not sure the above sample is even working, what do you think of this approach?

*Is there a better way? (to get the text node's value)

A: That's the usual way to do it with SAX.
Just beware that characters() may be called more than once per tag. See this question for more info. Here is a complete example.
Otherwise you could give a try to StAX.

A: public void startElement(String strNamespaceURI, String strLocalName,
      String strQName, Attributes al) throws SAXException {
       if(strLocalName.equalsIgnoreCase("HIT"))
       {
            String output1 = al.getValue("NAME");
          //this will work but how can we parse if NAME="abc" only     ?
       }

   }


text:
Q: How do I get my VGA monitor to stick to 1280 x 1024 resolution? I am literally a day or two old with Xubuntu 16.04 and am learning the basics of how to get things done. I have found one way to get my monitor to (temporarily) display 1280 x 1024 but have to repeat the process with every restart.
mike@mike-OptiPlex-GX270:~$ xrandr
Screen 0: minimum 8 x 8, current 1024 x 768, maximum 32767 x 32767
VGA1 connected 1024x768+0+0 (normal left inverted right x axis y axis) 0mm x 0mm
   1024x768      60.00*
   800x600       60.32    56.25
   848x480       60.00
   640x480       59.94
VIRTUAL1 disconnected (normal left inverted right x axis y axis)
mike@mike-OptiPlex-GX270:~$ cvt 1280 1024
# 1280x1024 59.89 Hz (CVT 1.31M4) hsync: 63.67 kHz; pclk: 109.00 MHz
Modeline "1280x1024_60.00"  109.00  1280 1368 1496 1712  1024 1027 1034 1063 -hsync +vsync
mike@mike-OptiPlex-GX270:~$ xrandr --newmode "1280x1024_60.00"  109.00  1280 1368 1496 1712  1024 1027 1034 1063 -hsync +vsync
mike@mike-OptiPlex-GX270:~$ xrandr --addmode VGA1 1280x1024_60.00
mike@mike-OptiPlex-GX270:~$ xrandr --output VGA1 --mode 1280x1024_60.00

How do I make these changes permanent? I have read related threads but need step by step instructions for my specific setup.
Also, I want to continue using LightDM because the computer only has 1.5 gb ram.
Thanks in advance.

A: This thread may help you : How can I make xrandr customization permanent? . Basiquely, if you are using lighdm, follow the following steps:
Step 1: Create the script
Create a script like this:
sudo mkdir -p /opt/screen_config/
sudo touch /opt/screen_config/mycustomdesktopvideo.sh
sudo chmod +x /opt/screen_config/mycustomdesktopvideo.sh
# I don't remember xfce editor, replace maybe gedit with leafpad
sudo gedit /opt/screen_config/mycustomdesktopvideo.sh

and put in this file :
#!/usr/bin/env bash
xrandr --newmode "1280x1024_60.00"  109.00  1280 1368 1496 1712  1024 1027 1034 1063 -hsync +vsync
xrandr --addmode VGA1 1280x1024_60.00
xrandr --output VGA1 --mode 1280x1024_60.00

Then, test it:
/opt/screen_config/mycustomdesktopvideo.sh

This should resize your desktop.
Step 2: Load it at startup,
Now, edit the file /etc/lightdm/lightdm.conf with the following code, and put in the [SeatDefaults] section the line
session-setup-script=/usr/share/mycustomdesktopvideo.sh

At the end it should looks like something like this:
[SeatDefaults]
session-setup-script=/usr/share/mycustomdesktopvideo.sh

Reboot, it should work.
If it fails
If you have a bug at startup, don't re-install: press Ctrl+Alt+F2, login, and with
sudo nano /etc/lightdm/lightdm.conf

remove the line session-setup-script=.... Then press Ctrl+Alt+F7 and try to login.


text:
Q: Prevent page scrolling up on collapsing accordion section. Bootstrap 4 Its a bootstrap 4 accordion the body section is bigger than usual that's why when section collapses content below it scrolls up with it.
I'm using this code to scroll to top of clicked header and cancel the scrolling caused by collapsing of previously opened section.
but it seems to run before that collapsing previous one.
I researched on internet and unable to find a solution.
code is little lengthy sharing relevant snippet. Also populating card-body using ajax on clicking header.

shown.bs.collapse and hidden.bs.collapse are not working for me.
show.bs.collapse and hidde.bs.collapse are firing but still no working.
Thank You

A: it only occurs when the content of the card-body is longer then the browser.
simultaneously it happens only when you use data-parent.
since the card-header with the open card-body is way up the page the collapse component pushes everything below up to its position. In a way it does what it is supposed to do.
so there is a choice to make. either you have to give up closing open cards when another one is opened (not using data-parent) or use the script that scrolls the card-header to the top, which was my choice.
I know this is not the answer you expect but until someone finds a better solution these choices are the best we have.

A: I modified hidden.bs.collapse and changed it to shown.bs.collapse as well as added the event parameter to your function() immediately following the event
 $('#accordion').on('shown.bs.collapse', function(event) {

seems to have done the trick.
See working example below:

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Business Info</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="apple-touch-icon" href="">
  <link rel="shortcut icon" href="" type="image/x-icon">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

        <input class="col-12 col-md-4 form-control" type="text" name="" id="city" value="" placeholder="City" required>
        <input class="col-12 col-md-4 form-control" type="text" name="" id="keyword" value="" placeholder="Keyword" required>
        <input class="col-12 col-md-4 btn btn-primary" id="btn" type="button" value="search" />

        Show Reviews
        Show News

              <button class="btn btn-link w-100 text-left btn-expand" data-toggle="collapse" data-target="#collapse0" data-place-id="ChIJz8eQTjsFGTkRbTcXvpkUQC0" aria-expanded="true" aria-controls="collapse0">
                                Hardee's
                                Rating:
                            </button>

Hardee's [Lahore]

Address: MM Alam Rd, Block C 2 Gulberg III, LAHORE PAKISTAN, Lahore, Punjab, Pakistan
Website: https://www.hardees.com/

Alexa Rank: 126275

News

Hardee's employee robbed while making nightly deposit - The Lebanon Enterprise

The Lebanon Enterprise

Carl's Jr., Hardee's add Froot Loops Mini Donuts to menu – and they taste just like the cereal - USA TODAY

USA TODAY

Win a TV! Hardee's Super Fan Contest! - WWBT NBC12 News

WWBT NBC12 News

Hardee's hepatitis scare sent 2000 for treatment. Now, customers seek damages. - Charlotte Observer

Charlotte Observer

Man hospitalized, police investigating after stabbing at downtown Billings Hardee's - Billings Gazette

Billings Gazette

Hardees wants class action lawsuit dismissed after hepatitis A outbreak - WSOC Charlotte

WSOC Charlotte

Carl's Jr., Hardee's add Fruit Loops mini donuts to its menu - ABC Action News

ABC Action News

Hardee's launches new Froot Loops donuts - wtkr.com

wtkr.com

WANTED: Suspect who allegedly robbed Verizon store wearing Hardee's uniform - KMOV.com

KMOV.com

              <button class="btn btn-link w-100 text-left btn-expand collapsed" data-toggle="collapse" data-target="#collapse1" data-place-id="ChIJV_dJILEDGTkRy_qFDSboqXE" aria-expanded="false" aria-controls="collapse1">
                                Builder's fast food
                                Rating:
                            </button>

Builder's fast food [Lahore]

Address: Hadayatullah Block Hidayatullah Block Mustafa Town, Lahore, Punjab, Pakistan

Phone: 0321 4880266

Reviews

 Farooq Ahmad

Tower Burger is  best and economical.  taste 10/10

 Danyal Tayyub

Best burgers in mustafa town. Anyone here should try the tower burger or the special b.b.q burger. Econimical and tasty.

 Zahid Butt

They got taste

 Zain Ul-Abdien

Tower burger is a good food item here

 Abdur Rehman

They are just like my home kitchen!! Not only me but my parents and friends like their quality of services and awesome food.

News

Editorial: Elusive affordable housing - Concord Monitor

Concord Monitor

Philippines' Richest 2018: Billionaire Builders Push Ahead With Infrastructure Projects - Forbes

Forbes

Watermark has become full service waterfront builder and permit specialist - The Laconia Daily Sun

The Laconia Daily Sun

House builders sign up to NHS scheme to transform homes into healthier environments - Care Appointments

Care Appointments

Why Tech Fails Can (Sometimes) Be Inconveniently Fun - PYMNTS.com

PYMNTS.com

New College Rankings Are Out—Including Some That Are Actually Useful - The Atlantic

The Atlantic

            <button class="btn btn-link w-100 text-left btn-expand collapsed" data-toggle="collapse" data-target="#collapse4" data-place-id="ChIJF-a0kf0PGTkRO1AS0gHk19A" aria-expanded="false" aria-controls="collapse4">
                                Fresho Fast Food
                                Rating:
                            </button>

Fresho Fast Food [Lahore]

Address: mail canal bank road qazi chowk lahore، saeed block Jehangir Rd, Fatehgarh, Lahore, Punjab 5400, Pakistan

Phone: 0315 6678546

Reviews

 Huma Usman

Yummy food at reasonable price

 Ameer Hamza

Normal prices, good taste.

 Raja Aurongzeb

Good place run by four boys, very hard-working and their quality of products are very good.

 Shabbir Ahmad Nadeem

Awesome food. Fresh and delicious fast food within minutes. Good staff.

 Usman Azeem 676

Tasty fast food but bow there are going dirty

News

How to Fold the Perfect Burrito - The Manual

The Manual

How to tell if your eggs are fresh or have expired - Times of India

Times of India

3 Pepper Burrito Co. adds flavor to fast-casual Tex-Mex - The News-Press

The News-Press

The Definitive Best Time To Buy A Christmas Tree - HuffPost

HuffPost

BigBasket Ready To Launch Private Labels To Ramp Up Cosmetics And Meat Business - Inc42 Media

Inc42 Media

Steve Cahalan: Cafe opens in Gays Mills food co-op - La Crosse Tribune

La Crosse Tribune

In 3 years Bigbasket will be among the top 3 players in F&G: CEO - India Retailing

India Retailing

BigBasket to expand private labels, products in next three months - Livemint

Livemint

A: I actually had a similar problem as the poster and wasn't quite able to get the above answer to work for me as a solution. The UI might be off as I didn't add my style sheet, but you can find the unmodified code here - MDBoostrap - Accordian Example

    <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseOne"
        aria-expanded="false" aria-controls="collapseOne">

        Q: Is This An Accordian Example?
      </button>

Answer

      Yes In Fact It Is An Accordian Example I Found On The Internet

This is just a different way to apply the same effect in bootstrap. No extra JS required.


text:
Q: Access problem on JSON file in JavaScript / HTML, can not reach key/values For an HTML site, I use a JSON file from a website to fill a table.
My script looks like this:
<script>
      fetch ("[LINK]")
        .then(function (response) {
          return response.json();
        })
        .then(function(data){
          addData(data);
        })
      function addData(data){
       var table = document.getElementById("apiinventory");

       let text = "";
       for (x in data) {
          var row = table.insertRow(0);
          var cellName = row.insertCell(0);
          var cellPrice = row.insertCell(1);
          var cellAmount = row.insertCell(2);

          cellName.innerHTML = x;
          cellPrice.innerHTML = data[x].price;
          cellAmount.innerHTML = data[x].casesLeft;
          text += x;
       }
      }
    </script>

And my JSON file looks like this: (only a snippet)
{"CS20 Case": {"0": {"date": "Oct 18 2019 01: +0", "price": 5.467, "casesLeft": "55948"}, "1": {"date": "Oct 19 2019 01: +0", "price": 2.992, "casesLeft": "267246"}

I managed to display the names of the objects (CS20, Operation Phoenix Weapon Case) in my first cell, but I don't manage to get the values of date, price and casesLeft into the other cells.
Everything I try to access the key/values, I always run into "undefined" outputs instead of the actual values.
Is there anything wrong in my previous parts of the code or am I doing something wrong with my call for the value of the JSON?
Thanks in advance

A: this way
fetch ("[LINK]")
  .then( resp => resp.json() )
  .then( data => {
    addData(data['CS20 Case'])
  })

function addData(info){
  const table = document.getElementById('apiinventory')

  for (let key in info) {
    let row = table.insertRow()
    row.insertCell().textContent = info[key].date
    row.insertCell().textContent = info[key].price
    row.insertCell().textContent = info[key].casesLeft
  }
}

A: data[x] from your code has:
{"0": {"date": "Oct 18 2019 01: +0", "price": 5.467, "casesLeft": "55948"}, "1": {"date": "Oct 19 2019 01: +0", "price": 2.992, "casesLeft": "267246"}}

Hence, there is no price in data[x], rather an object itself. So, if you instead took the key 0 from the value of data[x], such as data[x][0].price, it will give you the price of the first item of the object.
You should have one more loop inside the first loop where loop through the objects inside data[x] and print each item.


text:
Q: Gatsby SPA deployed on netlify applies wrong emotion css on first load (distilled example) I managed to distil my problem into the following code. It works fine with local dev server, but breaks when deployed to Netlify.
The source repo can be found here (branch destilled-netlify-problem)
The branch is deployed here

I have a primitive Gatsby SPA with client-side routing via Reach Router.
It has two pages, /app/ and /app/team/:teamName.
The App page should always render a red background, while the Team page should always render a green background
Ant that's it - here is all the relevant code:
// src/pages/app.tsx
import React, { FC } from 'react'
import { RouteComponentProps, Router } from '@reach/router'
import { css } from '@emotion/core'
import { sharedCss } from '../styles'

const appCss = css`
  background-color: red;
`
const teamCss = css`
  background-color: green;
`

const AppPage: FC<RouteComponentProps> = () =>
App

const TeamPage: FC<RouteComponentProps> = () =>
Team

const App = () => (
  <Router>
    <AppPage path="/app/" default />
    <TeamPage path="/app/team/:teamName/" />
  </Router>
)

export default App

gatsby-node.js as suggested in Gastsby docs
// /gagsby-node.js
exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions
  if (page.path.match(/^\/app/)) {
    page.matchPath = '/app/*' // eslint-disable-line no-param-reassign
    createPage(page)
  }
}

Netlify _redirects file - the redirects seem to work as intended
// src/static/_redirects
/app/team/* /app 200

The problem:
The first load of the Team page renderes the TeamPage component (the word "Team" is visible) but on red background instead of green - somehow appCss gets applied instead of teamCss. Refreshing with f5 fixes this, turning background green. But hard-refreshing with ctrl+f5 loads the broken version again.
I noticed that when the broken page is loading, the word "App" flashes first, before changing to "Team", indicating the AppPage component got rendered first - I suppose that has something to do with the redirect. I guess Emotion doesn't handle the transition well. Is there something I can do, ideally to load TeamPage right away?

A: I solved the problem by simply wrapping one of the components in an extra div. This turned out to be sufficient to keep Emotion from confusing the two layouts. The homepage flashing persists, but that's good enough for me for now.
EDIT: Although the empty div solved the problem in the distilled example, I ran into similar css problems deeper in the component tree in my real app. The following hack worked for me, and although not optimal,I am going to settle with it for now. I simply added the following into my Homepage component:
// This is a hack to circumvent a problem with emotion. I need to first mount
// nothing, otherwise wrong css gets applied when redirected via netlify _redirects
const [show, setShow] = useState(false)
useEffect(() => {
  setTimeout(() => setShow(true), 1)
}, [])
if (!show) return null

This way Homepage never gets commited, which prevents emotion from carrying over it's styles


text:
Q: How would I implement a StackOverflow-like Markdown in PHP? What am I looking for?
I am looking for a markdown language that works similiar to the one used here on stackoverflow.
Possible solutions
I could go and write my own Markup language but I think this will be a waste of time. This is a possibility though.
What I really want to know is if the StackOverflow markdown language is opensource or if there are similiar opensource packages available for use in PHP.

A: Markdown Implementation
You should look for an already existing library that you can plug in and use.
Firstly you need to decide between two major groups of markdown implementations

*

*basic

*extended (tables etc)

Stackexchange uses what I would call basic or original markdown.
Some search terms you should explore:

*

*Basic

*

*John Gruber Markdown

*CommonMark

*PHP Markdown

*Extended

*

*Fletcher Penney MultiMarkdown

*PHP Markdown Extra

*PHP MultiMarkdown

*PHP Parsedown

I use PHP Parsedown. I find it effective but a bit quirky and intolerant.
You should note that the Markdown definition is very fractured, apart from CommonMark the markup used by the original and other implementations isn't well-defined and so different implementations will often produce different results and support different features.
Security
There are some security concerns. Markdown accessible to end-users allows them to insert arbitrary HTML which can introduce cross-site scripting and other security problems. You may need to pre-process the markup or post-process the HTML to remove problematic elements. Stackexchange allows only a limited subset of HTML for this reason.


text:
Q: SQL - Date Range Broken Down by Individual Month and Year while maintaining the ID
I need help breaking down a date range, from an existing table, into the individual month and
year of the date range while maintaining the Identification Number
assigned to that date range. Thanks!

CREATE TABLE #TEMP
(GRP_ID CHAR(8),
BILL_YR INT,
BEGIN_DT DATETIME,
END_DT DATETIME
)

INSERT INTO #TEMP
(GRP_ID, BILL_YR, BEGIN_DT, END_DT)
VALUES
('12345678','1','2019-01-01','2019-12-31'),
('12345678','2','2020-01-01','2020-12-31')

EXPECTED RESULT
GRP_ID      BILL_YR  BEGIN_DT   END_DT
12345678    1        1          2019
12345678    1        2          2019
12345678    1        3          2019
12345678    1        4          2019
12345678    1        5          2019
12345678    1        6          2019
12345678    1        7          2019
12345678    1        8          2019
12345678    1        9          2019
12345678    1        10         2019
12345678    1        11         2019
12345678    1        12         2019
12345678    2        1          2020
12345678    2        2          2020
12345678    2        3          2020
12345678    2        4          2020
12345678    2        5          2020
12345678    2        6          2020
12345678    2        7          2020
12345678    2        8          2020
12345678    2        9          2020
12345678    2        10         2020
12345678    2        11         2020
12345678    2        12         2020

A: You can join against a date dimension table.  I've included a sample Common Table Expression date dimension table - (my sample is for months instead of days).
To create a permanent Date Dimension table (also known as a calendar table), check out this post - Creating a date dimension or calendar table in SQL Server
--demo setup
CREATE TABLE #TEMP
(GRP_ID CHAR(8),
BILL_YR INT,
BEGIN_DT DATETIME,
END_DT DATETIME
)

INSERT INTO #TEMP
(GRP_ID, BILL_YR, BEGIN_DT, END_DT)
VALUES
('12345678','1','2019-01-01','2019-12-31'),
('12345678','2','2020-01-01','2020-12-31')

--common table expression date dimension
;with dates ([Date]) as (
    Select convert(date,'2019-01-01') as [Date] -- Put the start date here

    union all

    Select dateadd(month, 1, [Date])
    from dates
    where [Date] <= '2020-12-31' -- Put the end date here
)

select GRP_ID
    ,  BILL_YR
    ,  DATEPART(MONTH,[DATE]) as BEGIN_DT
    ,  DATEPART(YEAR,[DATE]) as END_DT
    from dates d
    join #temp t on d.Date >= t.BEGIN_DT
        and d.Date <= t.END_DT
option (maxrecursion 32767) -- Don't forget to use the maxrecursion option!

| GRP_ID   | BILL_YR | BEGIN_DT | END_DT |
|----------|---------|----------|--------|
| 12345678 | 1       | 1        | 2019   |
| 12345678 | 1       | 2        | 2019   |
| 12345678 | 1       | 3        | 2019   |
| 12345678 | 1       | 4        | 2019   |
| 12345678 | 1       | 5        | 2019   |
| 12345678 | 1       | 6        | 2019   |
| 12345678 | 1       | 7        | 2019   |
| 12345678 | 1       | 8        | 2019   |
| 12345678 | 1       | 9        | 2019   |
| 12345678 | 1       | 10       | 2019   |
| 12345678 | 1       | 11       | 2019   |
| 12345678 | 1       | 12       | 2019   |
| 12345678 | 2       | 1        | 2020   |
| 12345678 | 2       | 2        | 2020   |
| 12345678 | 2       | 3        | 2020   |
| 12345678 | 2       | 4        | 2020   |
| 12345678 | 2       | 5        | 2020   |
| 12345678 | 2       | 6        | 2020   |
| 12345678 | 2       | 7        | 2020   |
| 12345678 | 2       | 8        | 2020   |
| 12345678 | 2       | 9        | 2020   |
| 12345678 | 2       | 10       | 2020   |
| 12345678 | 2       | 11       | 2020   |
| 12345678 | 2       | 12       | 2020   |


text:
Q: Accessing inventory host variable in Ansible playbook In Ansible 2.1, I have a role being called by a playbook that needs access to a host file variable.  Any thoughts on how to access it?
I am trying to access the ansible_ssh_host in the test1 section of the following inventory host file:
[test1]
test-1 ansible_ssh_host=abc.def.ghi.jkl ansible_ssh_port=1212

[test2]
test2-1 ansible_ssh_host=abc.def.ghi.mno ansible_ssh_port=1212

[test3]
test3-1 ansible_ssh_host=abc.def.ghi.pqr ansible_ssh_port=1212
test3-2 ansible_ssh_host=abc.def.ghi.stu ansible_ssh_port=1212

[all:children]
test1
test2
test3

I have tried accessing the role in the following fashions:
{{ hostvars.ansible_ssh_host }}

and
{{ hostvars.test1.ansible_ssh_host }}

I get this error:
fatal: [localhost]: FAILED! => {"failed": true, "msg": "'ansible.vars.hostvars.HostVars object' has no attribute 'ansible'"}

A: You are on the right track about hostvars.
This magic variable is used to access information about other hosts.
hostvars is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1'], hostvars['test2-1'], etc.
ansible_ssh_host is deprecated in favor of ansible_host since 2.0.
So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with:
{{ hostvars['your_host_group'].ansible_host }}

A: I struggled with this, too. My specific setup is: Your host.ini (with the modern names):
[test3]
test3-1 ansible_host=abc.def.ghi.pqr ansible_port=1212
test3-2 ansible_host=abc.def.ghi.stu ansible_port=1212

plus a play fill_file.yml
---
- remote_user: ec2-user
  hosts: test3
  tasks:
   - name: fill file
     template:
       src: file.j2
       dest: filled_file.txt

plus a template file.j2 , like
{% for host in groups['test3'] %}
   {{ hostvars[host].ansible_host }}
{% endfor %}

This worked for me, the result is
abc.def.ghi.pqr
abc.def.ghi.stu

I have to admit it's ansible 2.7, not 2.1. The template is a variation of an example in https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html.
The accepted answer didn't work in my setup. With a template
{{ hostvars['test3'].ansible_host }}

my play fails with "AnsibleUndefinedVariable: \"hostvars['test3']\" is undefined" .
Remark: I tried some variations, but failed, occasionally with "ansible.vars.hostvars.HostVars object has no element "; Some of this might be explained by what they say. in https://github.com/ansible/ansible/issues/13343#issuecomment-160992631

hostvars emulates a dictionary [...]. hostvars is also lazily loaded

A: [host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar

[host_group:vars]
custom_var=asdasdasd

You can access host group vars using:
{{ hostvars['host_group'].custom_var }}

If you need a specific value from specific host, you can use:
{{ hostvars[groups['host_group'][0]].node_name }}

A: You should be able to use the variable name directly
ansible_ssh_host

Or you can go through hostvars without having to specify the host literally
by using the magic variable inventory_hostname
hostvars[inventory_hostname].ansible_ssh_host

A: I've found also a nice and simple way to address hostsvars right on one of Ansible's Github issues
Looks like you can do this as well:
 - debug:
    msg: "{{ ansible_ssh_host }}"

A: Thanks a lot this note was very useful for me!
Was able to send the variable defined under /group_var/vars in the ansible playbook
as indicated below.
tasks:
    - name: check service account password expiry
    - command:
sh /home/monit/get_ldap_attr.sh {{ item }} {{ LDAP_AUTH_USR }}


text:
Q: CakePHP downloadable PDF file This is code that I have added in my vendors/xtcpdf.php file:
<?php App::import('Vendor','tcpdf/tcpdf');

class XTCPDF  extends TCPDF {

    var $xheadertext  = 'PDF created using CakePHP and TCPDF';
    var $xheadercolor = array(0,0,200);
    var $xfootertext  = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
    var $xfooterfont  = PDF_FONT_NAME_MAIN;
    var $xfooterfontsize = 8;

    /**
    * Overwrites the default header
    * set the text in the view using
    *    $fpdf->xheadertext = 'YOUR ORGANIZATION';
    * set the fill color in the view using
    *    $fpdf->xheadercolor = array(0,0,100); (r, g, b)
    * set the font in the view using
    *    $fpdf->setHeaderFont(array('YourFont','',fontsize));
    */
    function Header()
    {

        list($r, $b, $g) = $this->xheadercolor;
        $this->setY(10); // shouldn't be needed due to page margin, but helas, otherwise it's at the page top
        $this->SetFillColor($r, $b, $g);
        $this->SetTextColor(0 , 0, 0);
        $this->Cell(0,20, '', 0,1,'C', 1);
        $this->Text(15,26,$this->xheadertext );
    }

    /**
    * Overwrites the default footer
    * set the text in the view using
    * $fpdf->xfootertext = 'Copyright © %d YOUR ORGANIZATION. All rights reserved.';
    */
    function Footer()
    {
        $year = date('Y');
        $footertext = sprintf($this->xfootertext, $year);
        $this->SetY(-20);
        $this->SetTextColor(0, 0, 0);
        $this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
        $this->Cell(0,8, $footertext,'T',1,'C');
    }
}
?>

Here is the code from my controller:
public function download($id = null) {

    if (!$id)
    {
        $this->Session->setFlash('Sorry, there was no property ID submitted.');
        $this->redirect(array('action'=>'index'), null, true);
    }
    Configure::write('debug',0); // Otherwise we cannot use this method while developing

    $id = intval($id);

    $property = $this->User->find('all',array('conditions'=>array('User.id'=>$id))); // here the data is pulled from the database and set for the view
    //$property = $this->__view($id);
    if (empty($property))
    {
        $this->Session->setFlash('Sorry, there is no property with the submitted ID.');
        $this->redirect(array('action'=>'index'), null, true);
    }

    $this->layout = 'pdf'; //this will use the pdf.ctp layout
    $this->render('download');
}

Here is the code in my views file:
<?php
App::import('Vendor','xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans'; // looks better, finer, and more condensed than 'dejavusans'

$tcpdf->SetAuthor("KBS Homes & Properties at http://kbs-properties.com");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',40));
$tcpdf->xheadercolor = array(150,0,0);
$tcpdf->xheadertext = 'KBS Homes & Properties';
$tcpdf->xfootertext = 'Copyright © %d KBS Homes & Properties. All rights reserved.';

// add a page (required with recent versions of tcpdf)  $tcpdf->AddPage();

// Now you position and print your page content  // example:   $tcpdf->SetTextColor(0, 0, 0);  $tcpdf->SetFont($textfont,'B',20);  $tcpdf->Cell(0,14, "Hello World", 0,1,'L');  // ...  // etc.  // see the TCPDF examples

echo $tcpdf->Output('sample.pdf', 'D');

?>

How can I add data so it will be visible in a PDF file and the PDF file will be downloaded?

A: Just headups. All the rest available on google too:
http://bakery.cakephp.org/articles/kalileo/2010/06/08/creating-pdf-files-with-cakephp-and-tcpdf
http://book.cakephp.org/view/1094/Media-Views


text:
Q: Adding YEAR TO MONTH interval to TIMESTAMP value I have a case where I have add YEAR TO MONTH interval to a TIMESTAMP value & to achieve this I am using it this way
SELECT (END_DATE + NUMTOYMINTERVAL(2, 'MONTH')) FROM DUAL

Above code works successfully for almost all END_DATE values except for certain values.
For Example, when END_DATE = 31-JULY-2013, Expected result for above code is 30-SEPT-2013 but it throws an error
ORA-01839: date not valid for month specified

This is because the above code returns 31-SEPT-2013 which is an invalid date.
Is there any alternate way to achieve this?
(I can use ADD_MONTHS but issue with this function it returns only DATE values & I need TIMESTAMP as return value)
Am i missing anything?

A: Since end_date does not have fractional seconds, or indeed any time component, you can use add_months and cast it to a timestamp:
select cast(add_months(end_date, 2) as timestamp) from ...

But add_months has its own quirks. If the original date is the last day of the month, you'll get the last day of the adjusted month - which is what you want if you're going to a shorter month in this case, but maybe not if you're going the other way:
with t as (
select to_timestamp('2013-07-31', 'YYYY-MM-DD') as end_date from dual
union all select to_timestamp('2013-06-30', 'YYYY-MM-DD') from dual
union all select to_timestamp('2013-02-28', 'YYYY-MM-DD') from dual
union all select to_timestamp('2012-02-29', 'YYYY-MM-DD') from dual
)
select end_date, cast(add_months(end_date, 2) as timestamp)
from t;

END_DATE                       CAST(ADD_MONTHS(END_DATE,2)AST
------------------------------ ------------------------------
2013-07-31 00:00:00.000000     2013-09-30 00:00:00.000000
2013-06-30 00:00:00.000000     2013-08-31 00:00:00.000000
2013-02-28 00:00:00.000000     2013-04-30 00:00:00.000000
2012-02-29 00:00:00.000000     2012-04-30 00:00:00.000000

Or you could create your own function to handle the bad dates, and adjust backwards until it finds a valid one:
create or replace function adjust_timestamp(orig_ts in timestamp,
  months in number)
return timestamp is
  new_ts timestamp;
  offset number := 0;
  bad_adjustment exception;
  pragma exception_init(bad_adjustment, -01839);
begin
  while new_ts is null loop
    begin
      new_ts := orig_ts - numtodsinterval(offset, 'DAY')
        + numtoyminterval(months, 'MONTH');
    exception
      when bad_adjustment then
        offset := offset + 1;
        continue;
    end;
  end loop;
  return new_ts;
end;
/

This uses an exception defined for the ORA-01839 error code to trap a bad date, and it does it in a loop so it can work backwards (via the offset) until it finds one that doesn't error.
with t as (
select to_timestamp('2013-07-31', 'YYYY-MM-DD') as end_date from dual
union all select to_timestamp('2013-06-30', 'YYYY-MM-DD') from dual
union all select to_timestamp('2013-02-28', 'YYYY-MM-DD') from dual
union all select to_timestamp('2012-02-29', 'YYYY-MM-DD') from dual
)
select end_date, adjust_timestamp(end_date, 2)
from t;

END_DATE                       ADJUST_TIMESTAMP(END_DATE,2)
------------------------------ ------------------------------
2013-07-31 00:00:00.000000     2013-09-30 00:00:00.000000
2013-06-30 00:00:00.000000     2013-08-30 00:00:00.000000
2013-02-28 00:00:00.000000     2013-04-28 00:00:00.000000
2012-02-29 00:00:00.000000     2012-04-29 00:00:00.000000

Which gives different results to the add_months version. You need to be sure what you're getting, and how you want the data to behave.

A: This is expected behavior as specified by ANSI - see this AskTom.  If you add two months to 30-JUL-2013 you'll get 30-SEP-2013, which I think is perfectly understandable.  If you add two months to 31-JUL-2013 you'll get...what?  There is no 31-SEP-2013 - only 30 days in September.  So, what's the system supposed to do?  Should it give you 30-SEP-2013?  Should it give you 01-OCT-2013?  Neither of these is correct.  You've asked it two change the month value forward by two months.  OK, it tries that and finds that the resultant date is not valid - so it throws an error.
Oh, dear.
BUT - thankfully, we are not mere mortals.  We are superior beings.  We are software developers.  We have MANUALS!!!!  WE ARE NIGH UNTO GODS!!!!!!!!!!
So, consulting the manual we find we have the ADD_MONTHS function available to us, which does pretty much what you're looking for here.  However, ADD_MONTHS only operates on DATE values, so your fractional seconds would be lost IF you didn't do some extra playing around to save them.  But, as I said, we are software developers...
Example:
DECLARE
  tsIn  TIMESTAMP := TO_TIMESTAMP('31-JUL-2013 17:31:01', 'DD-MON-YYYY HH24:MI:SS');
  tsOut TIMESTAMP;
  nFrac_secs  NUMBER;
  strBuffer   VARCHAR2(1000);
  strFrac_secs VARCHAR2(1000);
BEGIN
  tsIn := tsIn + NUMTODSINTERVAL(0.1234, 'SECOND');

  strBuffer := TO_CHAR(tsIn);
  strFrac_secs := SUBSTR(strBuffer, -10, 7);

  DBMS_OUTPUT.PUT_LINE('tsIn=' || tsIn);
  DBMS_OUTPUT.PUT_LINE('strBuffer=' || strBuffer);
  DBMS_OUTPUT.PUT_LINE('strFrac_secs=' || strFrac_secs);

  nFrac_secs := TO_NUMBER(strFrac_secs);

  DBMS_OUTPUT.PUT_LINE('nFrac_secs=' || nFrac_secs);

  tsOut := ADD_MONTHS(tsIn, 2);

  DBMS_OUTPUT.PUT_LINE('tsOut before restoring fractional seconds=' || tsOut);

  tsOut := tsOut + NUMTODSINTERVAL(nFrac_secs, 'SECOND');

  DBMS_OUTPUT.PUT_LINE('tsOut after restoring fractional seconds=' || tsOut);
END;

So, basically, if you try doing interval arithmetic Oracle follows the &^#@$# ANSI spec and plays stupid.  They then give you a function (which is, to be fair, documented) which does more-or-less what's wanted, BUT only does it on DATE values.    I think this is what's called "job security"...
:-)
Share and enjoy.

A: You can use add_months to go to the correct date, then add the fractional part of the timestamp:
SELECT CURRENT_TIMESTAMP,
       CAST(CAST(add_months(trunc(CURRENT_TIMESTAMP), 2) AS TIMESTAMP) +
            (CURRENT_TIMESTAMP -
             CAST(trunc(CURRENT_TIMESTAMP) as timestamp)) as timestamp)
FROM DUAL;

Note that you'll lose the timezone.


text:
Q: SynchronizationContext - strange behavior public static void Init()
{
    //var task = GetSource1();
    //var task = GetSource2();
    //var task = GetSource3();
    var task = MyClient();
    MessageBox.Show(task.Result);
}

private static async Task<string> GetSource1()
{
    var sourceTask = WebClient();
    sourceTask.ConfigureAwait(false);
    return await sourceTask;
}

private static async Task<string> GetSource2()
{
    var sourceTask = MyClient();
    sourceTask.ConfigureAwait(true);
    return await sourceTask;
}

private static async Task<string> GetSource3()
{
    var sourceTask = MyClient();
    sourceTask.ConfigureAwait(false);
    return await sourceTask;
}

private static async Task<string> WebClient()
{
    return await new WebClient().DownloadStringTaskAsync("http://4pda.ru").ConfigureAwait(false);
}

private static Task<string> MyClient()
{
    var t = new Task<string>(() => new WebClient().DownloadString("http://4pda.ru"));
    t.ConfigureAwait(false);
    t.Start();
    return t;
}

This code works fine. I get the source in MessageBox. However why I get deadlock when I use var task = GetSource3()? I thought that it must works because I use ConfigureAwait(false) and avoid the context switching

A: ConfigureAwait is a pure method. It returns a value but has no effect on its own. It returns a customized awaitable (ConfiguredTaskAwaitable) that you need to await:
await task.ConfigureAwait();

However, this isn't how you should handle deadlocks. It's a precaution but you should avoid blocking on asynchronous code to begin with.


text:
Q: how to display different images using grid function using tkinter? I want to display the images in the folder using grid(). But when I tried with the following code, I got the output with single image iterated.
My code:
def messageWindow():
    win = Toplevel()
    path = 'C:\Users\HP\Desktop\dataset'
    for r in range(7):
        for c in range(10):
            for infile in glob.glob(os.path.join(path,'*.jpg')):
              im = Image.open(infile)
              resized = im.resize((100, 100),Image.ANTIALIAS)
              tkimage = ImageTk.PhotoImage(resized)
              myvar=Label(win,image = tkimage)
              myvar.image = tkimage
              myvar.grid(row=r,column=c)
root = Tk()
button = Button(app, text='Images in DataSet',command = messageWindow)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 850, y = 60)
root.mainloop()

When I run this code, after 5 minutes a child window will popup, and it will display a single image like this;

But how to get all the images in the dataset? Any suggestions are welcome.
Tkanks for your support!

A: As I said in a comment, you're putting the same image in every row and column of the grid. Here's how to avoid that using the built-in divmod() function to iteratively compute the row and column for each one, based on the number of COLUMNS you want to display in each row based on the current value of image_count:
def messageWindow():
    win = Toplevel()
    path = r'C:\Users\HP\Desktop\dataset'
    COLUMNS = 10
    image_count = 0
    for infile in glob.glob(os.path.join(path, '*.jpg')):
        image_count += 1
        r, c = divmod(image_count-1, COLUMNS)
        im = Image.open(infile)
        resized = im.resize((100, 100), Image.ANTIALIAS)
        tkimage = ImageTk.PhotoImage(resized)
        myvar = Label(win, image=tkimage)
        myvar.image = tkimage
        myvar.grid(row=r, column=c)
    win.mainloop()  # Not sure if you need this, too, or not...

A: You always use the same column and row for all images in the dataset.
Try removing the row and the column for-loop. and do something like this:
      c = 0
      r = 0
      for infile in glob.glob(os.path.join(path,'*.jpg')):
          im = Image.open(infile)
          resized = im.resize((100, 100),Image.ANTIALIAS)
          tkimage = ImageTk.PhotoImage(resized)
          myvar=Label(win,image = tkimage)
          myvar.image = tkimage
          myvar.grid(row=r,column=c)
          r += 1

This should be 70 times faster :)


text:
Q: Spring boot integrationn smpp: null pointer I am trying to implement spring-boot-integration-smpp, but getting null pointer exception.
integration-context.xml
<!--smpp integration-->
<int-smpp:outbound-gateway
        id="smppIntegrationOutboundGateway"
        request-channel="toSMPPChannel"
        source-address="Indosat"
        smpp-session-ref="smppSession"
        reply-channel="fromSMPPChannel"/>

<int:service-activator ref="printService" method="print" input-channel="fromSMPPChannel">
    <int:poller fixed-delay="1"/>
</int:service-activator>

<int:gateway id="smsGateway" service-interface="com.omexit.niger.smsworker.service.SMSGateway" default-request-channel="toSMPPChannel"/>

<!-- connect to the local broker using the default user name and password -->
<bean id="rabbitConnectionFactory" class="org.springframework.amqp.rabbit.connection.CachingConnectionFactory">
    <constructor-arg value="${spring.rabbitmq.host}"/>
    <constructor-arg value="${spring.rabbitmq.port}"/>
    <property name="username" value="${spring.rabbitmq.username}"/>
    <property name="password" value="${spring.rabbitmq.password}"/>
</bean>

<bean id="smppSession" class="org.springframework.integration.smpp.session.SmppSessionFactoryBean">
    <property name="host" value="xxxx"/>
    <property name="port" value="xx"/>
    <property name="systemId" value="LBS1"/>
    <property name="password" value="Bsl04n1"/>
    <property name="systemType" value="TCP"/>
    <property name="addrTon" value="INTERNATIONAL"/>
    <property name="addrNpi" value="ISDN"/>
    <property name="autoStartup" value="true"/>
</bean>

send message
System.err.println(strMessage);
    Message<String> message = MessageBuilder.withPayload(strMessage)
            .setHeader(SmppConstants.SRC_ADDR, "xyz")
            .setHeader(SmppConstants.DST_ADDR, "6285781029162")
            .setHeader(SmppConstants.REGISTERED_DELIVERY_MODE, SMSCDeliveryReceipt.SUCCESS)
            .build();
    String res = (String) smsGateway.send(message).getPayload();
    System.err.println("Res: " +res);

Exception:
    2018-11-27 14:56:21.414 ERROR [-,,,] 24620 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.integration.smpp.outbound.SmppOutboundGateway#0': Invocation of init method failed; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    at com.mode.indosat.smsworker.SmsWorkerApplication.main(SmsWorkerApplication.java:31) [classes/:na]
Caused by: java.lang.NullPointerException: null
    at org.springframework.integration.smpp.session.SmppSessionFactoryBean$AutoReconnectLifecycle.scheduleReconnect(SmppSessionFactoryBean.java:548) ~[spring-integration-smpp-1.0.0.RELEASE.jar:na]
    at org.springframework.integration.smpp.session.SmppSessionFactoryBean$AutoReconnectLifecycle.start(SmppSessionFactoryBean.java:487) ~[spring-integration-smpp-1.0.0.RELEASE.jar:na]
    at org.springframework.integration.smpp.session.ExtendedSmppSessionAdaptingDelegate.start(ExtendedSmppSessionAdaptingDelegate.java:78) ~[spring-integration-smpp-1.0.0.RELEASE.jar:na]
    at org.springframework.integration.smpp.outbound.SmppOutboundGateway.doInit(SmppOutboundGateway.java:62) ~[spring-integration-smpp-1.0.0.RELEASE.jar:na]
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.onInit(AbstractReplyProducingMessageHandler.java:94) ~[spring-integration-core-5.1.0.RELEASE.jar:5.1.0.RELEASE]
    at org.springframework.integration.context.IntegrationObjectSupport.afterPropertiesSet(IntegrationObjectSupport.java:178) ~[spring-integration-core-5.1.0.RELEASE.jar:5.1.0.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) ~[spring-beans-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    ... 16 common frames omitted

A: Looks like a bug in the SmppOutboundGateway: we can't start session so early from the onInit(). Please, raise an issue against https://github.com/spring-projects/spring-integration-extensions project.
Meanwhile as a workaround you can inject a reconnectingExecutor property on the SmppSessionFactoryBean:
<bean id="smppSession" class="org.springframework.integration.smpp.session.SmppSessionFactoryBean">
    <property name="host" value="xxxx"/>
    <property name="port" value="xx"/>
    <property name="systemId" value="LBS1"/>
    <property name="password" value="Bsl04n1"/>
    <property name="systemType" value="TCP"/>
    <property name="addrTon" value="INTERNATIONAL"/>
    <property name="addrNpi" value="ISDN"/>
    <property name="autoStartup" value="true"/>
    <property name="reconnectingExecutor" ref="reconnectingExecutorService"/>
</bean>


text:
Q: Lost all data after compressing disk. Now what? In an attempt to solve an inherent Windows problem, I tried to compress my main partition (using windows own compressing option), like in the figure below, and then, when I reboot it says "Bootmgr is compressed".

I had to use the OS DVD to repair my boot file and then, when I finally start Windows, I receive the great surprise that I lost all my data... like EVERYTHING. And I am 200% sure that I didn't make a clean OS installation, I just recovered the boot record, nothing more, nothing less.
How come the option ruins your MBR and formats your entire drive?
Now what? Should I even care to attempt recovering files? Since they are "compressed" probably it is a goodbye forever, no recovery tool shall ever be able to recover them. What can I use?

A: I've never used this option on an entire disk but I remember from a Windows course that enabling NTFS compression on the system drive (usually C:) is not recommended.
If you want to use compression it's better to enable this on a per-folder basis, for example activating the compressing only your "large RAW pictures" folder by rightclicking -> Properties -> Advanced -> check the "Compress contents to save space". This incurs a performance overhead and usually only reduces space by 0% to 30% so it's usually a last resort option.
I suspect the missings files are due to the Windows repair, you should be able to uncompress the disk and run a file recovery software like Recuva


text:
Q: Xcode 5 command line Code Sign error Has anyone experienced the case where Xcode 5  (Build version 5A11344j)  command line tool failed to build a previously-successfully-built Project in  Xcode 4.6.3 (Build version 4H1503).
The error message is like:
"
Check dependencies
Code Sign error: No codesigning identities found: No codesigning identities (i.e. certificate and private key pairs) that match the provisioning profile specified in your build settings ("") were found.
CodeSign error: code signing is required for product type 'Application' in SDK 'iOS 7.0'
"
Any insight is greatly appreciated.  Thanks!

A: Check that you have a relevant provisional profile. The thing I always do that solve this kind of issue is clean it all.
Yep, A simple cleaning and then build can solve that. If Xcode crash after the build just rerun and clean again and then that suppose to work.
I know this answer has no logic but that works for me dozen of times maybe that would help you out.

A: Set the code signing identities and provisioning profile. Don't forget to check the bundle identifier.

A: There are many possible causes to this issue. It sounds like you may not have setup an identity certificate or that certificate is out of date (open keychain application on Mac or check the references I've added). The primary things one should check are that the Accounts Section in Xcode Preferences is configured correctly, the developer portal certificates and profiles (especially certificate expiration dates), and the local keychain application on your Mac (you may have expired certificates being used). Apple has a technical note that lists further possibilities (link).


text:
Q: conditional compilation statement in limits.h I am not able to understand the following statement from the file limits.h. What is the use of this statement and what does it accomplishes?
/* If we are not using GNU CC we have to define all the symbols ourself.
   Otherwise use gcc's definitions (see below).  */
#if !defined __GNUC__ || __GNUC__ < 2

A: It checks if your program is compiled by some other compiler than GCC, or some very old GCC version.

A: It checks whether you are not using a Gcc compiler Version 2  or Gcc some other versions.
using this pre-processor macro we can some portable codes.


text:
Q: Disabling position:fixed on scrolling when 250px from bottom of the page

$(window).scroll(function() {
  $(".lay-fixed").css("bottom", Math.max(0, 250 - $(this).scrollBottom()));
});
.lay-fixed {
  position: fixed;
  right: 30px
}

  ----widget code-----

Here, I try to disable the position:fixed element on scrolling when 250px from bottom of the page. Help me to find out the way to fix this.

A: Please try it:

$.fn.followTo = function (pos) {
    var $this = this,
        $window = $(window);

    $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 0
            });
        }
    });
};

$('.lay-fixed').followTo(250);
.lay-fixed {
  position: fixed;
  right: 30px
}

     ----widget code-----

  But I must explain to you how all
 this mistaken idea of denouncing pleasure and praising
 pain was born and I will give you a complete account of the
 system, and expound the actual teachings of the great
 explorer of the truth, the master-builder of human happiness.
 No one rejects, dislikes, or avoids pleasure itself, because
 it is pleasure, but because those who do not know how
 to pursue pleasure rationally encounter consequences
 that are extremely painful. Nor again is there anyone
 who loves or pursues or desires to obtain pain of itself,
 because it is pain, but because occasionally circumstances
 occur in which toil and pain can procure him some great pleasure.
 To take a trivial example, which of us ever undertakes
 laborious physical exercise, except to obtain some
 advantage from it? But who has any right to find fault with
 a man who chooses to enjoy a pleasure that has no annoying
 consequ
  But I must explain to you how
 all this mistaken idea of denouncing pleasure and praising pain
 was born and I will give you a complete account of the system,
 and expound the actual teachings of the great explorer of
 the truth, the master-builder of human happiness. No one rejects,
 dislikes, or avoids pleasure itself, because it is pleasure,
 but because those who do not know how to pursue
 pleasure rationally encounter consequences that are
 extremely painful. Nor again is there anyone who loves
 or pursues or desires to obtain pain of itself, because it is pain,
 but because occasionally circumstances
 occur in which toil and pain can procure him some great pleasure.
 To take a trivial example, which of us ever undertakes
 laborious physical exercise, except to obtain some advantage
 from it? But who has any right to find fault with a man who
 chooses to enjoy a pleasure that has no annoying consequ

  But I must explain to you how all
 this mistaken idea of denouncing pleasure and praising pain
 was born and I will give you a complete account of the system,
 and expound the actual teachings of the great explorer of
 the truth, the master-builder of human happiness. No one rejects,
 dislikes, or avoids pleasure itself, because it is pleasure,
 but because those who do not know how to pursue
 pleasure rationally encounter consequences that are
 extremely painful. Nor again is there anyone who loves
 or pursues or desires to obtain pain of itself, because
 it is pain, but because occasionally circumstances occur
 in which toil and pain can procure him some great pleasure.
 To take a trivial example, which of us ever undertakes laborious
 physical exercise, except to obtain some advantage from it?
 But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequ


text:
Q: Xaml Binding To Custom Class in Xamarin Forms Lets say I have a really basic class with a few properties. Eg:
public class MyClass
    {
        public MyClass()
        {
            Something = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
            OrOther = "Proin dignissim, nunc non tincidunt imperdiet, magna urna malesuada enim";
        }
        public string Something { get; set; }
        public string OrOther { get; set; }
    }

And I want to databind to this in Xaml, how would I do this?
I've tried binding directly to the object, so in my Xaml page code behind:
public partial class MainPage : ContentPage
    {
        public MyClass anInstance;
        public MainPage()
        {
            InitializeComponent();
            anInstance = new MyClass();
            BindingContext = this;
        }
    }

And then in my Xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBindingTest"
             x:Class="DataBindingTest.MainPage">

    <Label Text="{Binding anInstance.Something}"
           VerticalOptions="Center"
           HorizontalOptions="Center" />

And I've also tried setting the BindingContext on a parent control:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBindingTest"
             x:Class="DataBindingTest.MainPage">
    <StackLayout BindingContext="anInstance">
        <Label Text="{Binding Something}"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
    </StackLayout>

</ContentPage>

But it just doesn't work. I've also tried setting the bindingcontext of the page to anInstance:
 public partial class MainPage : ContentPage
    {
        public MyClass anInstance;
        public MainPage()
        {
            InitializeComponent();
            anInstance = new MyClass();
            BindingContext = anInstance;
        }
    }

And Just binding to its properties on the xaml side:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBindingTest"
             x:Class="DataBindingTest.MainPage">

        <Label Text="{Binding Something}"
               VerticalOptions="Center"
               HorizontalOptions="Center" />

</ContentPage>

But again, all I get are blank pages.
It seems that at least one of these should work.
Whats the recommended way to bind to properties on a custom class like this?
edit
Taking on board @jason comments, I've also tried this:
public MyClass anInstance
        {
            get
            {
                return _anInstance;
            }
            set
            {
                _anInstance = value;
            }
        }
        private MyClass _anInstance { get; set; }
        public MainPage()
        {
            InitializeComponent();
            anInstance = new MyClass();
            BindingContext = this;
        }

And the XAML:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBindingTest"
             x:Class="DataBindingTest.MainPage">
    <StackLayout BindingContext="anInstance">
        <Label Text="{Binding Something}"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
        <Label Text="{Binding OrOther}"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
    </StackLayout>
</ContentPage>

But again a blank page...
Same result with:
private MyClass anInstance { get; set; }
        public MainPage()
        {
            InitializeComponent();
            anInstance = new MyClass();
            BindingContext = this;
        }

And
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBindingTest"
             x:Class="DataBindingTest.MainPage">
    <StackLayout BindingContext="anInstance">
        <Label Text="{Binding Something}"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
        <Label Text="{Binding OrOther}"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
    </StackLayout>
</ContentPage>

A: You're almost there. Your property needs to be public (or protected might work. Then you're setting the binding context to this. Which is fine. For the record, I am using this code:
public MyClass AnInstance { get; set; }

public MainPage()
{
    InitializeComponent();

    AnInstance = new MyClass();
    BindingContext = this;
}

Now in your XAML, you can access it's properties like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBindingTest"
             x:Class="DataBindingTest.MainPage">
    <StackLayout>
        <Label Text="{Binding AnInstance.Something}"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
        <Label Text="{Binding AnInstance.OrOther}"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
    </StackLayout>
</ContentPage>

If you do not want the property name AnInstance prefix, set the binding context directly to the instance of the MyClass object, like this:
public MyClass AnInstance { get; set; }

public MainPage()
{
    InitializeComponent();

    AnInstance = new MyClass();
    BindingContext = AnInstance;
}

You can now use the properties belonging to the MyClass directly, like so: <Label Text="{Binding OrOther}" VerticalOptions="Center" HorizontalOptions="Center" />


text:
Q: Classification using word embeddings I'm trying to do Classification using word embeddings, but I face typeError problem.

# glove word embeddings
import numpy as np
embeddings_index = {}
with open('glove.6B/glove.6B.50d.txt', 'r') as f:
    for line in f:
        values = line.split()
        word = values[0]
        coefs = np.asarray(values[1:], dtype='float32')
        embeddings_index[word] = coefs```

# transform text (a title) to an embedding by averaging word embeddings
def get_mean_embeddings(docs,embeddings):
    means = []
    dim = len(embeddings.values()[0])
    for doc in docs :
        words = tokenizer.tokenize(doc)
        means.append(np.mean([embeddings[w] if w in embeddings else np.zeros(dim) for w in words], axis=0))
    return np.array(means)```

def get_mean_embeddings(docs,embeddings):
    dim = len(embeddings.values()[0])
    return np.array([
                np.mean([embeddings[w]
                         for w in tokenizer.tokenize(doc) if w in embeddings] or
                        [np.zeros(dim)], axis=0)
                for doc in docs
            ])

import sklearn.svm as svm
from sklearn.metrics import f1_score
clf = svm.SVC(kernel='rbf')
f1_scores = []
for g in genres:
    genre_data = balanced_data[g]
    train,test = train_test_split(genre_data,train_size = 0.6)
    train_feature_matrix = get_mean_embeddings(train['title'],embeddings)
    test_feature_matrix = get_mean_embeddings(test['title'],embeddings)
    clf.fit(train_feature_matrix,train[g])
    y_pred = clf.predict(test_feature_matrix)
    f1_scores.append(f1_score(test[g],y_pred))
    print('for "%s" , f1 score = %.2f' %(g,f1_scores[-1]))

print ('average f1 score over all genres : %.2f ' %(np.mean(f1_scores)))

expected and actual results:
for "sci-fi" , f1 score = 0.70
for "horror" , f1 score = 0.68
for "fantasy" , f1 score = 0.62
for "adventure" , f1 score = 0.66
for "thriller" , f1 score = 0.63
for "mystery" , f1 score = 0.58
for "romance" , f1 score = 0.62
for "crime" , f1 score = 0.56
for "drama" , f1 score = 0.59
for "action" , f1 score = 0.67
for "comedy" , f1 score = 0.62
for "documentary" , f1 score = 0.64
for "war" , f1 score = 0.65
average f1 score over all genres : 0.63

Error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-7c91ab021935> in <module>
      6     genre_data = balanced_data[g]
      7     train,test = train_test_split(genre_data,train_size = 0.6)
----> 8     train_feature_matrix = get_mean_embeddings(train['title'],embeddings)
      9     test_feature_matrix = get_mean_embeddings(test['title'],embeddings)
     10     clf.fit(train_feature_matrix,train[g])

<ipython-input-25-0a52cf917522> in get_mean_embeddings(docs, embeddings)
      1 def get_mean_embeddings(docs,embeddings):
----> 2     dim = len(embeddings.values()[0])
      3     return np.array([
      4                 np.mean([embeddings[w]
      5                          for w in tokenizer.tokenize(doc) if w in embeddings] or

TypeError: 'dict_values' object is not subscriptable

A: The problem is that, in Python 3, dict_values is merely a view and not a list.
If you want to get the first element lenght, you have to replace

dim = len(embeddings.values()[0])

with:

dim = len(list(embeddings.values())[0])

For more information, see: Python: how to convert a dictionary into a subscriptable array?


text:
Q: What is the volume of a smartie? According to wikipedia:

Smarties are oblate spheroids with a minor axis of about 5 mm (0.2 in) and a major axis of about 12 mm (0.5 in).

What is the volume of one smartie?

A: Calcutlate the sphere volume with the major radius and then multiply the result by minor/major.
With $r=5/2\text{ mm}$ and $R=12/2\text{ mm}$
$$V=\frac43\pi R^2r=377\;\text{mm}^3$$


text:
Q: facing issues with yahoo historical url i am trying to fetch stock price using pandas. I was wrking till last week.But i am unable to fetch data now. My question is that is it problem with yahoo URL or pandas?
raise PandasError('DataFrame constructor not properly called!')
pandas.core.common.PandasError: DataFrame constructor not properly called!
I tried the URL in browser, but it is not working.

A: They've changed their url and now use cookies protection (and possibly javascript)
I could not get anywhere with cookie browsing a CookieJar so I ended up using dryscrape to "fake" a user download
import dryscrape
from bs4 import BeautifulSoup
import time
import datetime
import re

#we visit the main page to initialise sessions and cookies
session = dryscrape.Session()
session.set_attribute('auto_load_images', False)
session.set_header('User-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95     Safari/537.36')
session.visit("https://finance.yahoo.com/quote/AAPL/history?p=AAPL")
response = session.body()

#get the dowload link
soup = BeautifulSoup(response, 'lxml')
for taga in soup.findAll('a'):
    if taga.has_attr('download'):
        url_download = taga['href']
print(url_download)

#now replace the default end date end start date that yahoo provides
s = "2017-02-18"
period1 = '%.0f' % time.mktime(datetime.datetime.strptime(s, "%Y-%m-%d").timetuple())
e = "2017-05-18"
period2 = '%.0f' % time.mktime(datetime.datetime.strptime(e, "%Y-%m-%d").timetuple())

#now we replace the period download by our dates, please feel free to improve, I suck at regex
m = re.search('period1=(.+?)&', url_download)
if m:
    to_replace = m.group(m.lastindex)
    url_download = url_download.replace(to_replace, period1)
m = re.search('period2=(.+?)&', url_download)
if m:
    to_replace = m.group(m.lastindex)
    url_download = url_download.replace(to_replace, period2)

#and now viti and get body and you have your csv
session.visit(url_download)
csv_data = session.body()

#and finally if you want to get a dataframe from it
import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd
df = pd.read_csv(StringIO(csv_data), index_col=[0], parse_dates=True)
df


text:
Q: Ruby regex to remove all consecutive letters from string Here is the problem (from Codeforces)
Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu".
Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something!
Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.
Here is my solution..  For some reason it fails an extremely large test case.  Mine seems to get rid of more letters than it is supposed to.  Is this regular expression incorrect?
str = gets.chomp

while str =~ /(.)\1/
  str.gsub!(/(.)\1+/,'')
end

puts str

EDIT -- This solution doesn't work because it gets rid of all consecutive groups of characters.  It should only get rid of duplicates.  If I do it this way, which I believe to be correct, it times out on extremely large strings:
str = gets.chomp

while str =~ /(.)\1/
  str.gsub!(/(.)\1/,'')
end

puts str

A: Why does it have to be a regular expression?
'foobar'.squeeze
=> "fobar"

"hhoow aaaare yyoouu".squeeze
=> "how are you"

squeeze is a useful tool for compressing runs of all characters, or specific ones. Here are some examples from the documentation:

"yellow moon".squeeze                  #=> "yelow mon"
"  now   is  the".squeeze(" ")         #=> " now is the"
"putters shoot balls".squeeze("m-z")   #=> "puters shot balls"

If "aab" becomes "b", then you're not following the example given in the question, which is "hhoow" turns into "how". By your statement it would be "w", and "yyoouu" would be "". I think you're reading too much into it and not understanding the problem based on their sample input and sample output.

A: ha, harder than I thought when I first read. What about
s = "hhoow aaaareer yyoouu"
while s.gsub!(/(.)\1+/, '')
end
puts s

which leaves s == 'w' if i understand the problem correctly.


text:
Q: Как анимировать border input'а? Есть вот такая форма:

Хочу, чтобы при нажатии на input Имя и E-mail плавно появлялись остальные бордеры, но не знаю как реализовать задумку. Сама проблема в том, что где-то видел как бордеры от нижнего по бокам поднимаются, а потом соединяются сверху в середине и хотелось бы сделать также.
Как такое реализовать?

A: Один из вариантов - использовать анимацию градиента:

.ani-border {
  padding: 1em;
  border: none; outline: 2px solid transparent;
  background-image:
  linear-gradient(to bottom, #cacaca 1px, transparent 1px),
  linear-gradient(to bottom, #cacaca 1px, transparent 1px),
  linear-gradient(to right, #cacaca 1px, transparent 1px, transparent calc(100% - 1px), #cacaca calc(100% - 1px)),
  linear-gradient(to top, #cacaca 1px, transparent 1px);
  background-position: -100% 0%, 200% 0%, 0% 100%, 0% 100%;
  background-size: 50% 100%, 50% 100%, 100% 1px, 100% 100%;
  background-repeat: no-repeat;
  transition: background-size .4s ease-out .6s, background-position .6s ease-in;
}

.ani-border:focus {
  background-position: 0% 0%, 100% 0%, 0% 100%, 0% 100%;
  background-size: 51% 100%, 51% 100%, 100% 100%, 100% 100%;
  transition: background-size .4s ease-in, background-position .6s ease-out .4s;
}
<input class="ani-border" placeholder="E-mail">