text:
Q: C does not run until I use the quit command fellow programmers. I am pretty new to this area that is why I may be having my problem.
I am told to write a program that finds the area and circumference of a circle. One condition, display the output to 5 decimal places. the output should look like this.
The radius of the circle is ________.
The diameter of the circle is_______.
The area of the circle is__________.
The circumference is____________.
here is my code that I wrote for this problem.
#include<stdio.h>
    int main()
    {
        float r, area, circ, diam, pi = 3.14159;

        printf("Enter the radius please");
        scanf("%f\n", &r);

        printf("The radius of the circle is %0.5f\n", r);

        diam = 2 * r;
        printf("The diameter of the circle is %0.5f\n", diam);

        area = pi * r * r;
        printf("The area of the circle is %0.5f\n", area);

        circ = 2 * pi * r;
        printf("The circumference of the circle is %0.5f\n", circ);

        return 0;
    }

The code runs and showing me this in the terminal
Enter the radius please4

I placed 4 as a testing sample. This is when the program just stops working. I type q and hit enter. This is when the rest of the output shows up like so.
The radius of the circle is 4.00000
The diameter of the circle is 8.00000
The area of the circle is 50.26544
The circumference of the circle is 25.13272

A: The problem is in your scanf format string:
scanf("%f\n", &r);

By putting \n in the format string, it consumes any newline character that you enter and waits for a character that isn't a newline.
Remove \n from the format specifier and it will work as expected:
scanf("%f", &r);

A: Najik,
Are you sure that you want to have a "\n" in the scanf ?
I think for what you want you need to remove it.
Before:
scanf("%f\n", &r);

After:
scanf("%f", &r);

This will ensure the scanf function is finished shortly after entering the number and pressing Enter.
Hope I had help you.


text:
Q: Django model order_by based on another model queryset length I have 2 models:
models.py
class Post(models.Model):
    title = models.CharField(max_length=255)
    desc = models.CharField(max_length=500)
    content = models.TextField()
    uploadedBy = models.ForeignKey(User, on_delete=models.CASCADE)

LIKE_CATEGORIES = (
    ("LIKE", "LIKE"),
    ("DISLIKE", "DISLIKE")
)

class PostLike(models.Model):
    _type = models.CharField(max_length=200, choices=LIKE_CATEGORIES, blank=True, null=True)

    content = models.ForeignKey(
        Post, on_delete=models.CASCADE)

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    created = models.DateTimeField(auto_now_add=True)

I want to order Post based on number of likes a post has. Number of likes a post has is the count of PostLike objects having _type="LIKE",content=post_object.
How can I order Post specifically based on number of likes?

A: You can annotate each Post with a Count of related PostLike objects, this can have a filter to only count the related objects that satisfy a condition. Then order by the annotation
from django.db.models import Count, Q
Post.objects.annotate(
    likes=Count('postlike', filter=Q(postlike___type="LIKE"))
).order_by('-likes')

I'm not sure having a field with an underscore prefix is the best idea, it may mess up the ORM and other parts of the Django internals

A: This will restrict your filter to Post with LIKE and also rank it
from django.db.models import Count
Post.objects.filter(postlike___type='LIKE').annotate(likes=Count('postlike')).order_by('-likes')

Or

from django.db.models import Count
Post.objects.filter(postlike___type='LIKE').annotate(Count('postlike'))[::-1]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Refactor Laravel Routes I am having partial success refactoring common laravel routes to a class. Currently I error looking for the controller.
Here is the basic pattern I am refactoring. I will need the same pattern for vendors, users, terminals etc
Route::group(['middleware' => ['csrf','DashboardAuthenticate'], 'namespace' => 'App\Http\Controllers'], function () {

    Route::get('vendors/', 'VendorController@index');
    Route::get('vendors/create', 'VendorController@create');
    Route::get('vendors/{id}', 'VendorController@show');
    Route::post('vendors/search', 'VendorController@search');
    Route::put('vendors/', 'VendorController@update');
    Route::delete('vendors/', 'VendorController@destroy');

    Route::get('roles/', 'RoleController@index');
    Route::get('roles/create', 'RoleController@create');
    Route::get('roles/{id}', 'RoleController@show');
    Route::post('roles/search', 'RoleController@search');
    Route::put('roles/', 'RoleController@update');
    Route::delete('roles/', 'RoleController@destroy');

    Route::get('users/', 'UserController@index');
    Route::get('users/create', 'UserController@create');
    Route::get('users/{id}', 'UserController@show');
    Route::post('users/search', 'UserController@search');
    Route::put('users/', 'UserController@update');
    Route::delete('users/', 'UserController@destroy');

    Route::get('terminals/', 'TerminalController@index');
    Route::get('terminals/create', 'TerminalController@create');
    Route::get('terminals/{id}', 'TerminalController@show');
    Route::post('terminals/search', 'TerminalController@search');
    Route::put('terminals/', 'TerminalController@update');
    Route::delete('terminals/', 'TerminalController@destroy');
});

To refactor I made a class that looks like: (the CIRoute class file is under App\Classes\Routes namespace)
class CIRoutes
{
    public static function addRoutes($name)
    {
        $n2 = ucfirst($name);
        Route::get($name.'s/', $n2.'Controller@index');
        Route::get($name.'s/create', $n2.'Controller@create');
        Route::get($name.'s/{id}', $n2.'Controller@show');
        Route::post($name.'s/search', $n2.'Controller@search');
        Route::put($name.'s/', $n2.'Controller@update');
        Route::delete($name.'s/', $n2.'Controller@destroy');
    }
}

Then I create the route:
CIRoutes::addRoutes('vendors');

I thought this was working fine, but I was mistaken. Currently php artisan route:list comes back with Class App\Http\Controllers\RolesController does not exist which it does - i mean it works fine without the refactor.
How can I refactor the common route pattern?

A: I think it's a better option to store your routes in the routes/web.php file instead of a class, and use the group method to organize them instead.
Route::group(['prefix' => 'vendors'], function () {

    Route::get('/', function ()    {
        // Matches The "/vendors/" URL
    });
    Route::get('/create', function ()    {
        // Matches The "/vendors/create" URL
    });

});

Group also allows for middleware, sub-domain and namespace routing.
Next, since your class is creating a typical CRUD route, you can simply use:
Route::resource('vendors', 'VendorsController');

To create the following routes:
Verb        URI                     Action        Route Name
GET         /vendors                index         vendors.index
GET         /vendors/create         create        vendors.create
POST        /vendors                store         vendors.store
GET         /vendors/{vendor}       show          vendors.show
GET         /vendors/{vendor}/edit  edit          vendors.edit
PUT/PATCH   /vendors/{vendor}       update        vendors.update
DELETE      /vendors/{vendor}       destroy       vendors.destroy

Note that Laravel automatically maps all the routes in routes/web.php to your 'web' middleware and the App\Http\Controllers namespace in the App\Providers\RouteServiceProvider class.
/**
 * Define the "web" routes for the application.
 *
 * These routes all receive session state, CSRF protection, etc.
 *
 * @return void
 */
protected function mapWebRoutes()
{
    Route::group([
        'middleware' => 'web',
        'namespace' => $this->namespace,
    ], function ($router) {
        require base_path('routes/web.php');
    });
}

So if you still want to use a class to define your routes, you will have to group the routes in your class and assign them the App\Http\Controllers namespace and the 'web' middleware.
The web middleware makes sure that these routes provides features like session state and CSRF protection.
So you could probably (I haven't tested it) do something like:
public static function addRoutes($name)
{

    Route::group([
        'middleware' => 'web',
        'namespace' => 'App\Http\Controllers',
    ], function () use ($name) {

        $n2 = ucfirst($name);
        Route::get($name.'s/', $n2.'Controller@index');
        Route::get($name.'s/create', $n2.'Controller@create');
        Route::get($name.'s/{id}', $n2.'Controller@show');
        Route::post($name.'s/search', $n2.'Controller@search');
        Route::put($name.'s/', $n2.'Controller@update');
        Route::delete($name.'s/', $n2.'Controller@destroy');

    });

}


text:
Q: Ruby Mysql2: different results using count method I'm using .count method in a mysql2 query results:
My code:
  require "mysql2"

  hostname='db.xxxxx.xxx'
  port='3306'
  username='xxxxxx'
  password='xxxxxxxxxxxxxxxxxxxxxxxxxx'
  database='xxx'

  dbh = Mysql2::Client.new(:host=> hostname, :username=> username, :password=> password, :database=> database, :port=> port.to_f, :database_timezone=> :utc, :application_timezone => :local)

  results=dbh.query("SELECT * FROM xxx")
    p results.count
    i=0
    results.each do |result|
        i=i+1
    end

    p results.count

With the first results.count I obtain the number of SELECT results rows as expected. But for the second one, I obtain (sometimes!) a different value:

My results:
$ ruby test_count.rb
4942
4942

$ ruby test_count.rb
4942
24773520

$ ruby test_count.rb
4942
37442208

My config:
$ rvm --version
rvm 1.13.4 (stable) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]

$ ruby --version
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]

$ gem list

*** LOCAL GEMS ***

Ascii85 (1.0.1)
bundler (1.1.3)
curb (0.8.0)
mime-types (1.18)
mysql (2.8.1)
mysql2 (0.3.11)
pdf-reader (1.1.1)
prawn (0.12.0)
prawn-core (0.8.4)
rake (0.9.2.2)
ruby-filemagic (0.4.2)
ruby-rc4 (0.1.5)
rubygems-bundler (0.9.2)
RubyInline (3.11.2)
rvm (1.11.3.3)
ttfunk (1.0.3)
ZenTest (4.8.0)

Someone have any idea why is this happen?
Thanks

A: Check your = versus ==. Also, the first results is an array. If you change to a string by doing some sort of .to_s or join and putting it back in the same variable, eg, results = results.join, then length would change. If you add elements to the array by mistake using results += results + another_array, then your count will increas fast. Best is to post your real code here. I know because I have done some of these at one time or another.


text:
Q: std container for C-style array Is there an std container for C-style arrays with variable size?
For example, I have the following code
int size = 5;    // This is not a constant in general
int *my_array = SpecialAllocationFunction(size);

I want to be able to access this array with a C++, std-style container. Something that has iterators and functions like: size, begin, end, ...
I know that I can use std::array if my_array has a constant size. I also can write one myself, but I feel there bound to be something ready-made.

A: As @NathanOliver and @utnapistim said in the comments, gsl::span works. Since I don't want to include this library I ended up writing a "trivial wrapper" myself. Included below for others looking for an answer (and my future self)
template<class T>
class span {
public:
    inline span() : _data(0), _size(0) {}
    inline span(T* d, size_t s) : _data(d), _size(s) {}
    inline T& operator[](size_t index) { return _data[index]; }
    inline const T& operator[](size_t index) const { return _data[index];}
    inline size_t size() const { return _size; };
    inline T* begin() { return _data; }
    inline const T* begin() const { return _data; }

    inline T* end() { return _data+_size; }
    inline const T* end() const { return _data+_size; }
protected:
    T* _data;
    size_t _size;
};

A: Using a custom allocator, it is possible to build a vector with a size known only at run time (so no std::array possible), wrapping an existing array. It is even possible to keep pre-existing values by overriding the special construct method(*).
Here is a possible implementation:
/**
 * a pseudo allocator which receives in constructor an existing array
 *  of a known size, and will return it provided the required size
 *  is less than the declared one. If keep is true in contructor,
 *  nothing is done at object construction time: original values are
 *  preserved
 * at deallocation time, nothing will happen
 */
template <class T>
class SpecialAllocator {
    T * addr;
    size_t sz;
    bool keep;
public:
    typedef T value_type;
    SpecialAllocator(T * addr, size_t sz, bool keep):
        addr(addr), sz(sz), keep(keep) {}
    size_t max_size() {
        return sz;
    }
    T* allocate(size_t n, const void* hint=0) {
        if (n > sz) throw std::bad_alloc();  // throws a bad_alloc...
        return addr;
    }
    void deallocate(T* p, size_t n) {}
    template <class U, class... Args>
    void construct(U* p, Args&&... args) {
        if (! keep) {
            ::new((void *)p) U(std::forward<Args>(args)...);
        }
    }
    template <class U>
    void destroy(U* p) {
        if (! keep) {
            p->~U();   // do not destroy what we have not constructed...
        }
    }

};

It can then be used that way:
int size = 5;    // This is not a constant in general
int *my_array = SpecialAllocationFunction(size);

SpecialAllocator<int> alloc(my_array, size);
std::vector<int, SpecialAllocator<int> > vec(size, alloc);

From that point, vec will be a true std::vector wrapping my_array.
Here is a simple code as demo:
int main(){
    int arr[5] = { 5, 4, 3, 2, 1 };
    SpecialAllocator<int> alloc(arr, 5, true); // original values will be preserved
    std::vector<int, SpecialAllocator<int> > vec(5, alloc);
    for(auto it= vec.begin(); it != vec.end(); it++) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    try {
        vec.push_back(8);
    }
    catch (std::bad_alloc& a) {
        std::cout << "allocation error" << std::endl;
    }
    return 0;
}

It will successfully output:
5 4 3 2 1
allocation error

(*) BEWARE: Construction/destruction may be involved in different places: push_back, emplace_back, etc. Really think twice about your real use case before using no-op construct and destroy methods.


text:
Q: Samsumg EditText input gif will crash
java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider uri
content://com.samsung.android.honeyboard.provider/root/data/user/0/com.samsung.android.honeyboard/temp_content/com.samsung.android.icecone.sticker/5f3235a4-e1db-4d5a-acd8-98df17919758.gif
from pid=31712, uid=1000 requires the provider be exported, or
grantUriPermission() at
android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:912)


text:
Q: Python append performance I'm having some performance problems with 'append' in Python.
I'm writing an algorithm that checks if there are two overlapping circles in a (large) set of circles.
I start by putting the extreme points of the circles (x_i-R_i & x_i+R_i) in a list and then sorting the list.
class Circle:
def __init__(self, middle, radius):
    self.m = middle
    self.r = radius

In between I generate N random circles and put them in the 'circles' list.
"""
Makes a list with all the extreme points of the circles.
Format = [Extreme, left/right ~ 0/1 extreme, index]
Seperate function for performance reason, python handles local variables faster.
Garbage collect is temporarily disabled since a bug in Python makes list.append run in O(n) time instead of O(1)
"""
def makeList():
    """gc.disable()"""
    list = []
    append = list.append
    for circle in circles:
        append([circle.m[0]-circle.r, 0, circles.index(circle)])
        append([circle.m[0] + circle.r, 1, circles.index(circle)])
    """gc.enable()"""
    return list

When running this with 50k circles it takes over 75 seconds to generate the list. As you might see in the comments I wrote I disabled garbage collect, put it in a separate function, used
append = list.append
append(foo)

instead of just
list.append(foo)

I disabled gc since after some searching it seems that there's a bug with python causing append to run in O(n) instead of O(c) time.
So is this way the fastest way or is there a way to make this run faster?
Any help is greatly appreciated.

A: Your performance problem is not in the append() method, but in your use of circles.index(), which makes the whole thing O(n^2).
A further (comparitively minor) improvement is to use a list comprehension instead of list.append():
mylist = [[circle.m[0] - circle.r, 0, i]
          for i, circle in enumerate(circles)]
mylist += [[circle.m[0] + circle.r, 1, i]
           for i, circle in enumerate(circles)]

Note that this will give the data in a different order (which should not matter as you are planning to sort it anyway).

A: I've just tried several tests to improve "append" function's speed. It will definitely helpful for you.

*

*Using Python

*Using list(map(lambda  -  known as a bit faster means than for+append

*Using Cython

*Using Numba - jit

CODE CONTENT : getting numbers from 0 ~ 9999999, square them, and put them into a new list using append.

*

*Using Python
import timeit

st1 = timeit.default_timer()

def f1():

    a = range(0, 10000000)

    result = []
    append = result.append

    for i in a:
        append( i**2 )

    return result

f1()

st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))

RUN TIME : 3.7 s

*Using list(map(lambda
import timeit

st1 = timeit.default_timer()

result = list(map(lambda x : x**2 ,  range(0,10000000) ))

st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))

RUN TIME : 3.6 s

*Using Cython

*

*the coding in a .pyx file
def f1():
    cpdef double i
    a = range(0, 10000000)
result = []
append = result.append

for i in a:
    append( i**2 )

return result

and I compiled it and ran it in .py file.

*

*in .py file
import timeit
from c1 import *

st1 = timeit.default_timer()

f1()

st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))

RUN TIME : 1.6 s

*Using Numba - jit
import timeit
from numba import jit

st1 = timeit.default_timer()

@jit(nopython=True, cache=True)
def f1():

    a = range(0, 10000000)

    result = []
    append = result.append

    for i in a:
        append( i**2 )

    return result

f1()

st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))

RUN TIME : 0.57 s

CONCLUSION :
As you mentioned above, changing the simple append form boosted up the speed a bit. And using Cython is much faster than in Python. However, turned out using Numba is the best choice in terms of speed improvement for 'for+append' !

A: Try using deque in the collections package to append large rows of data, without performance diminishing. And then convert a deque back to a DataFrame using List Comprehension.
Sample Case:
from collections import deque

d = deque()
for row in rows:
 d.append([value_x, value_y])

df = pd.DataFrame({'column_x':[item[0] for item in d],'column_y':[item[1] for item in d]})

This is a real time-saver.

A: Instead of
for circle in circles:
    ... circles.index(circle) ...

use
for i, circle in enumerate(circles):
    ... i ...

This could decrease your O(n^2) to O(n).
Your whole makeList could be written as:
sum([[[circle.m[0]-circle.r, 0, i], [circle.m[0]+circle.r, 1, i]] for i, circle in enumerate(circles)], [])

A: If performance were an issue, I would avoid using append. Instead, preallocate an array and then fill it up. I would also avoid using index to find position within the list "circles". Here's a rewrite. It's not compact, but I'll bet it's fast because of the unrolled loop.
def makeList():
    """gc.disable()"""
    mylist = 6*len(circles)*[None]
    for i in range(len(circles)):
        j = 6*i
        mylist[j] = circles[i].m[0]-circles[i].r
        mylist[j+1] = 0
        mylist[j+2] = i
        mylist[j+3] = circles[i].m[0] + circles[i].r
        mylist[j+4] = 1
        mylist[j+5] = i
    return mylist


text:
Q: Validation logic for adjacent checkboxes guys!
I have something like that:

I need to write some validation logic. The main rule - user can select only adjacent checkboxes. For example 1;2;3 or 2;3 or 3;4 and etc. (don't choose 1;3 or 1;2;4 and etc(without gaps)).
And I have no idea,how can I implement that algorithm simply.
I Use MVVM approach and this is part of my ViewModel class(short):
public bool FirstIsCheck {get;set;}
public bool SecondIsCheck {get;set;}
public bool ThirdIsCheck {get;set;}
public bool FourthIsCheck {get;set;}

A: Thanks to all for good ideas, especially about "range".
I like 2 combobox(from/to) variant, and after them i had seen on slider control with 2 thumbs(f.e. RangeSlider in http://avaloncontrolslib.codeplex.com/ )
But in my solution I will use another approach(Only because i have 4 elements):
User select some checkboxes(correct or incorrect) and after that(when he try to save changes, f.e.) he may to see error message.
IsChecked values will be added in a collection and we find Max of Min values + check them.
(in that example i use string to save final result)

        string temp = "";
        List<int> range = new List<int>();
        if (FirstIsCheck) { temp += 1 + ";"; range.Add(1); }
        if (SecondIsCheck) { temp += 2 + ";"; range.Add(2); }
        if (ThirdIsCheck) { temp += 3 + ";"; range.Add(3); }
        if (FourthIsCheck) { temp += 4 + ";"; range.Add(4); }

        Result = temp;

        if(range.Count>1)
        {
            var max = range.Max();
            var min = range.Min();

            if (max - min == 2 && range.Count != 3) throw new Exception();
            if (max - min == 3 && range.Count != 4) throw new Exception();
        }

In my case it works, but if you have more elements that approach will be ugly. (and you must think about use some slider controls, or  2 combobox/TextBox from-to fields)


text:
Q: No value passed to the slots but Original Value is passed in the bot I am using Amazon lex with AWS lambda as a validation Codehook. When I was trying to pass a value with a response card dynamically generated, it is showing null value in the AppointmentTime Slot but the original value is showing value in slotDetails.
Here is the request sent through lex:
{
"messageVersion": "1.0",
"invocationSource": "DialogCodeHook",
"userId": "prwna44b91sbr4w7d2pwwva59anaqzqx",
"sessionAttributes": {
    "store_id": "26",
    "address": "Quark Atrium, A‐45, Phase VIII Extension,Industrial Focal Point,Sahibzada Ajit Singh Nagar, Punjab 160071,India",
    "closingTime": "19:00:00",
    "city": "Mohali",
    "phone": "9718409751",
    "bookingDateTime": "2018-05-27T21:25:46+05:30",
    "openingTime": "10:00:00",
    "state": "PB",
    "email": "bhuvnesh.kumar@sourcefuse.com",
    "zip_code": "44545"
},
"requestAttributes": null,
"bot": {
    "name": "ScheduleRide",
    "alias": "$LATEST",
    "version": "$LATEST"
},
"outputDialogMode": "Text",
"currentIntent": {
    "name": "BookAppointment",
    "slots": {
        "CustomerAgreement": null,
        "DropLocationPrompt": "yes",
        "PickupAddress": "Unnamed Road, Industrial Area, Sector 74, Sahibzada Ajit Singh Nagar, Punjab 140308, India",
        "RequiredService": null,
        "AppointmentTime": null,
        "DropAddress": null,
        "PhoneNumber": null,
        "AppointmentDate": "2018-05-28"
    },
    "slotDetails": {
        "CustomerAgreement": {
            "resolutions": [],
            "originalValue": null
        },
        "DropLocationPrompt": {
            "resolutions": [
                {
                    "value": "yes"
                }
            ],
            "originalValue": "yes"
        },
        "PickupAddress": {
            "resolutions": [],
            "originalValue": "Unnamed Road, Industrial Area, Sector 74, Sahibzada Ajit Singh Nagar, Punjab 140308, India"
        },
        "RequiredService": {
            "resolutions": [],
            "originalValue": null
        },
        "AppointmentTime": {
            "resolutions": [
                {
                    "value": "00:00"
                },
                {
                    "value": "12:00"
                }
            ],
            "originalValue": "14:00:00"
        },
        "DropAddress": {
            "resolutions": [],
            "originalValue": null
        },
        "PhoneNumber": {
            "resolutions": [],
            "originalValue": null
        },
        "AppointmentDate": {
            "resolutions": [],
            "originalValue": "28 may"
        }
    },
    "confirmationStatus": "None"
},
"inputTranscript": "14:00:00"

}
Here is the request passed to the lex, see the AppointmentTime in the slots object, it is showing null and in the slotDetails object, it is showing value. Here is the array of buttons which i pass from the response card object:
 [ { text: '1:00 PM', value: '13:00:00' },
   { text: '1:30 PM', value: '13:30:00' },
   { text: '2:00 PM', value: '14:00:00' },
   { text: '2:30 PM', value: '14:30:00' },
   { text: '3:00 PM', value: '15:00:00' },
   { text: '3:30 PM', value: '15:30:00' },
   { text: '4:00 PM', value: '16:00:00' },
   { text: '4:30 PM', value: '16:30:00' },
   { text: '5:00 PM', value: '17:00:00' },
   { text: '5:30 PM', value: '17:30:00' },
   { text: '6:00 PM', value: '18:00:00' },
   { text: '6:30 PM', value: '18:30:00' } ]

Here is the function of buildResponseCard:
  function buildResponseCard(title, subTitle, options){
let buttons = null;
console.log(options);
let genericAttachments = [];
if (options != null){
    buttons = [];
    for(let i = 0; i < (options.length); i++){
        buttons.push(options[i]);
        if(i%3 === 2){
            genericAttachments.push({
             title,
             subTitle,
             buttons
            });
            buttons = [];
        }
    }
}
return {
    version: 1,
    contentType: "application/vnd.amazonaws.card.generic",
    genericAttachments
};
}

The reason I want AppointmentTime slot value on slot object to be shown on is that whenever the value in the slot is invalid through validation, I will set it to null and will callback it through lambda function and i will not be able to callback the slotDetails object in the response.
Can anyone tell me how can i achieve this?

A: For the AMAZON.TIME built-in slot:

When a user enters an ambiguous time, Amazon Lex uses the slotDetails attribute of a Lambda event to pass resolutions for the ambiguous times to your Lambda function. ... In this case, the value in the slots map is null, and the slotDetails entity contains the two possible resolutions of the time.

Your input of "14:00:00" is not understood as an unambiguous time, and Lex tries to resolve it to either noon or midnight, which is obviously wrong. This is probably because the Lex Time slot is expecting only hours and minutes (hh:mm) but not seconds (hh:mm:ss).
So if it is possible for you, one solution is to remove the seconds digits from your time values. For example:
[ { text: '1:00 PM', value: '13:00' }, ... ]

However, if you must have the seconds in the time value, then you can simply find the time the user selected from the inputTranscript value and do your validation of it from there.
var userInput = event.inputTranscript;

EDIT:
Another option is to ignore Lex's suggested resolutions and get the slot-details original-value. Like this:
var timeValue = event.currentIntent.slotDetails.AppointmentTime.originalValue;

And then set the AppointmentTime slot yourself. Like this:
event.currentIntent.slots.AppointmentTime = timeValue;


text:
Q: draw string in GLUT I'm trying to draw string in GLUT. I need to convert int value to unsigned char* before I can use it in glutBitmapString. But when I do like this
glBegin(GL_POINTS);
    glRasterPos2i(15, 20);
    char text[10];
    sprintf(text, "%d", 5);
    glutBitmapString(GLUT_BITMAP_HELVETICA_18, (unsigned char*)text);
glEnd();

There is not text on the screen. But in debugger text contains value of 5.
What is wrong?

A: Don't know if this helps, but I personally use:
std::uint32_t Base = 0;

void SetupFonts(int FontSize)
{
    HFONT Font = CreateFont(-MulDiv(FontSize, GetDeviceCaps(DC, LOGPIXELSY), 72), 0, 0, 0, FW_BOLD, false, false, false, ANSI_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_DONTCARE | DEFAULT_PITCH, "Arial");
    HFONT OldFont = static_cast<HFONT>(SelectObject(DC, Font));
    wglUseFontBitmaps(DC, 32, 96, Base);
    //wglUseFontBitmaps(DC, 32, 96, Base); //May or may not need this line twice.
    SelectObject(DC, OldFont);
    DeleteObject(Font);
}

template<typename... Args>
void Print(float X, float Y, float R, float G, float B, const char* Text, Args... args)
{
    using namespace std;
    std::size_t Position = 0;
    std::string Container(Text);
    std::vector<std::string> Arguments;
    std::initializer_list<int> {(Arguments.push_back(to_string(args)), 0)...};

    for (auto it = Arguments.begin(); it != Arguments.end(); ++it)
    {
        if ((Position = Container.find("%")) != std::string::npos)
        {
            Container.replace(Position, 1, *it);
        }
    }

    glColor3f(R, G, B);
    glRasterPos2f(X, Y);
    glPushAttrib(GL_LIST_BIT);
    glListBase(this->Base - 32);
    glCallLists(Container.size(), GL_UNSIGNED_BYTE, Container.data());
    glPopAttrib();
    glFlush();
}

if (Base == 0) SetupFonts(12);
Print(200, 200, 1.0f, 0.0f, 0.0f, "Hello %", "World");
Print(200, 250, 0.0f, 1.0f, 0.0f, "Your FPS is: %", CalculateFPS());

etc..
Draws text that looks like:


text:
Q: How do I hook up a referencing outlet in Interface Bulider for a UIImage? I want to access a UIImage programmatically... i.e. myImage.hidden = TRUE; etc.  I can do this fine for UILabel but when I repeat the process for UIImage it doesn't work.  Specifically when I drag the blue line in Interface Builder over the icon I don't get a popup menu like I do when using UILabel.
Perhaps using UIImageView instead of UIImage?
Thanks!

A: An UIImage is not a view that can be added via Interface Builder.  In order to display a UIImage you either need to override the drawRect method of whatever view you want to display it in, or use a UIImageView.
Using a UIImageView will allow you to set it as an IBOutlet and reference it in your controller.


text:
Q: Setting two different value on an enum variable I have been trying to assign value on the enum variable but I couldn't succeed it.
So what I want is THIS to have two values of optionOne and optionTwo.
So that A.valueOf("THIS"); will bring value A.getOptionOne() of 2 and A.getOptionTwo() of 4.
From Eclipse I get an error line
"The nested type A cannot hide an enclosing type" on
<< public enum A {THIS("2","4"), IS("4","7"), REAL("12.5","29")}; >>

I want some advise :(
//edit : I will work on the error message it really isn't related, I want to get a guide of methodology of setting two different values on a single enum variable.
public class A {

    public enum A {THIS("2","4"), IS("4","7"), REAL("12.5","29")};

    private final String optionOne;
    private final String optionTwo;

    private A(String optionOne, String optionTwo){
        this.optionOne= optionOne;
        this.optionTwo= optionTwo;
    }

    public String getOptionOne(){
        return optionOne;
    }

    public String getOptionTwo(){
        return optionTwo;
    }
}

A: The error message is telling you exactly what's wrong: your enum definition is hiding the name of identically-named class that it's in.
Java's enums are a special type of class, in which the enum constants are the only allowed instances. Therefore, you don't have to enclose your enum in another class. Just provide the methods inside the enum definition:
public enum A {
    THIS("2","4"), IS("4","7"), REAL("12.5","29");

    private final String optionOne;
    private final String optionTwo;

    A(String optionOne, String optionTwo){
        this.optionOne= optionOne;
        this.optionTwo= optionTwo;
    }

    public String getOptionOne(){
        return optionOne;
    }

    public String getOptionTwo(){
        return optionTwo;
    }
}

public void test() {
    System.out.println(A.valueOf("THIS").getOptionOne()+ " - "+A.valueOf("THIS").getOptionTwo());
}

A: I think you have a misunderstanding of how nested types work in Java. In your example you have a class called 'A' with a nested enum also called 'A'. Even if Java allowed this name clash (it doesn't), it would be confusing. Which 'A' would we be talking about in a given situation?
Anyway, you don't need any nesting in this situation, you just need a regular enum defined like so:
public enum A
{
    FOO("1","2"), BAR("2","3");

    private final String optionOne;
    private final String optionTwo;

    A(String one, String two)
    {
        this.optionOne = one;
        this.optionTwo = two;
    }

    public String getOptionOne(){
        return optionOne;
    }

    public String getOptionTwo(){
        return optionTwo;
    }
}

You can then say:
A.FOO.getOptionOne(); //1
A.FOO.getOptionTwo(); //2

A.BAR.getOptionOne(); //3
A.BAR.getOptionTwo(); //4

You may find it useful to read up on enum definitions.


text:
Q: Parsing Unicode Strings in LinkedIn JSON Responses using Scribe and FasterXML Jackson Hi I am developing a Java application using Scribe to integrate with Linkedin and make RestFul calls. I use FasterXML Jackson Json Parser library to parse the LinkedIn API responses in JSON.
I would like to check how I can parse Unicode characters in the response from LinkedIn when using the Jackson parser. When i do it the normal API call and print it out I see see ????? for those values that are returned in Unicode format.

A: Unicode characters are handled by Jackson. But code that prints out content may not be using UTF-8 encoding; make sure you check out actual character codes and NOT rely on what you see on your console window. Console may be using incorrect encoding, for example, or not have fonts to display all Unicode characters.
Alternatively service may be sending incorrectly encoded content. To verify this, you must check out actual bytes sent and see if they are properly UTF-8 encoded.


text:
Q: is there a way I can get the value of method parameter belong import class at debug stage I use eclipse to develop java program. About the below code segment:
public class Boot {
    public static void main(String[] args){
        int[] arr = {1,24,2,12};
        Arrays.sort(arr);////////make breakpoint!!!!!!!!!!!!
        System.out.println(arr);
    }
}

I make a breakpoint at Arrays.sort(arr); And when I debug this code segment, the thread will be suspended at this breakpoint, then I move the mouse on (arr) it will display {1,24,2,12} as this.
Then I step into this method Arrays.sort(arr) and of course I come into the sort method of Arrays .

Then my question come, I move the mouse on int[] a (the parameter of this method) it dont display the content of a which should be {1,24,2,12} this is the info it display

my question is that whether there exist a way I can see the content of a {1,24,2,12}
or that is to say whether there exist a way by which we can see the value of variable belong to import class.

A: Use the Variables view in eclipse debugger mode.
And here's an explanation of why you're not able to see the values on mouse over: https://stackoverflow.com/a/271543/2061329


text:
Q: Play Login not catching CSRF token I'm doing some simple login validation on my Play! 2.6 framework web app, and it seems to not pick up the CSRF token that I include on the view.loginForm:
@import helper.CSRF

@(loginform: Form[UserLoginData])(implicit messages: MessagesProvider, request: RequestHeader)

@main() {
        <div class="row">
            <form method="post" class="col-md-6" id="loginform" autocomplete="on">
               @CSRF.formField
            <input type="text id="userName">
             <!-- other inputs and submit button-->
             </form>
        </div>
}

and then my conf.routes handles the POST'ing by:
POST    /login                      controllers.LoginRegController.attemptLogin
And here's the method in the LoginRegController :
def attemptLogin() = Action {
        implicit request: Request[AnyContent] => {
          loginform.bindFromRequest().fold(
            formWithErrors => BadRequest(views.html.login(formWithErrors)),
            successfulForm => {
              // check DB for valid inputs
                val userName = //retrieved from form
                Ok(views.html.afterLogin.dashboardviews.dashboard())
                  .withSession(request.session + ("authenticated" -> "true") + ("username" -> userName))
                  .withHeaders(SecurityHeadersFilter
                    .CONTENT_SECURITY_POLICY_HEADER -> " .fonts.googleapis.com ")
            }
          )
        }
      }

As soon as the user hits submit, it gets taken to the framework's default Authorized page, and I see on my console that it has failed the CSRF check:

[warn] p.filters.CSRF - [CSRF] Check failed because no token found in
  headers

I'm thinking that there's a similar problem as mentioned in this answer here in that the session is being refreshed, but I would think it would have the token in the request itself, pass the test, and then load up a new session. Any ideas how to fix, or how to grab the token and "insert" it where necessary here in the Controller method?


text:
Q: How to have getElementsByClassName target all tagged elements - and is there a better alternative? I'm sorry, I think the answer to this will have been posted, but I've looked and I'm struggling to apply it.
I'm using this FitText non-library alternative posted by RobG (https://stackoverflow.com/a/15488590/1490943). It's great, but I want to apply it to a number of elements, not just one. I'm piecing together how to replace getElementById...
window.onload = function() {
  function doResize() {resize(document.getElementById('d0'), 5);}
  window.onresize = doResize;
  doResize();
}

(http://jsfiddle.net/cgwM4/)
... with getElementsByClassName...
window.onload = function() {
  function doResize() {resize(document.getElementsByClassName('d0')[0], 5);}
  window.onresize = doResize;
  doResize();
}

(http://jsfiddle.net/cgwM4/2/)
... but I can't figure out how to target all elements tagged with that class rather than just specific ones. And I'm wondering if there's an alternative that will work in earlier MSIE - a way of getting all with that class, without using ClassName.
I'm really sorry to be ignorant about this. It'll be obvious, but I don't know where to start... Thank you for having a look.

A: All you have to do is loop through them:
function doResize() {
    var qsa = document.querySelectorAll(".d0"), l = qsa.length, i;
    for( i=0; i<l; i++) resize(qsa[i],5);
}

Note that I used querySelectorAll instead of getElementsByClassName - this enables support in IE8. If you really need older than that, you might want to use a name attribute instead, because even ancient IE supports getElementsByName.


text:
Q: How do you edit and test SCSS instantly on browser? Despite cool feature SCSS/Compass brought into my production routine, it still bugs me a bit as to how long it takes to edit a line of css and test them on browser. (That's mostly what my team says but being responsible for developing workflow, I can't just ignore this.)
To be specific about what 'long process' it's taking, they are:

*

*Copying 'tested' lines from inspector (such as Chrome developer tool) to text editor to update SCSS file (More than a few seconds)

*Uploading compiled CSS file to remote server (4+ seconds)

*Refreshing browser for testing (sub-second)

And it's bugging me to repeat this every single time.
As to why I'm so bothered with them, before SCSS I used to do:

*

*Edit a line on inspector (which automatically updates local files, which also leads browser to update style from local css file) (sub-second, even without any mouse clicking or keyboard stroke)

I'm thinking about building server locally, on top of Docker to emulate nearly identical environment to the production server, so that 2. (Uploading file to server) part would be solved.
As I code style only sometimes, I can work with it, but someone who works on them everyday is being frustrated so much to the point they are not willing to learn SCSS yet. (Which I think it is ridiculous concerning the huge time they will be saving just by saving a bunch of reusable lines, etc. However they also have to keep the time given project allows them to spend while learning SCSS.)
It seems like nobody is typing pure CSS code by hand today, so this question might be kind of outdated, and probably that's why I wasn't quite successful at finding somebody complaining about this. However I thought it's cool to know anybody's method or just thought around this. Any recommendation? If the answer was "Just get used it.", then I can work with it too.

A: Assuming that you can set an environment with sass "watching" the changes of the files and generate a source map, you can make a workflow like this:

*

*Edit the source sass files from within chrome

*Sass generate the css file

*The css file is reloaded and the browser pick up the changes.

https://developers.google.com/web/tools/setup/setup-preprocessors
I personally don't like this workflow because usually, the final code is more unorganized but for small changes in the code, it can work.
I've tested on chrome v67, my configuration is something like this:

*

*I have a sass build watcher (configured to generate source maps)

*I have browsersync configured for auto reload/inject the CSS (https://browsersync.io/)

*I have Enable CSS source maps checkbox checked on the devtools settings

*I have a workspace set on chrome which points to my sass folder

And the workflow:

*

*Go to the Elements tab and inspect some element

*Jump to the source panel

*Edit the source file (on chrome)

*Save the file

It seems like nobody is typing pure CSS code by hand today

Well, I don't know about that, I think that more and more people are going back to write pure CSS.


text:
Q: Conditionally extracting digits from patterns from strings in R I'd like to extract digits from strings if the string has both a "..1.." and "..0.." pattern in it. If the string has both these patterns, I'd like to extract all digits that are a part of a "..(any digit).." pattern in that string.
The result of my attempt is different from my expected result, see below code.
 # Load packages
library(stringr)
library(dplyr)

# Load toy dataset
film = data.frame(var=c("grey..0..yellow..1..", "grey..0..brown..1..", "grey0brown1", "grey..a..brown..3..", "grey..a0..red..1...", "grey..0..blue..1...brown..2..", "3grey..0..purple..1...brown..2..", "3grey..0..purple..1...brown..2..brown..3.."))

# Attempt
for (i in film$var)
  if(str_detect(i, "[.][.]0[.][.].+[.][.]1[.][.]")){               # if entries feature both "..0.." AND "..1.." patterns
film$var2 = str_extract_all(i, "([.][.][:digit:][.][.])+") %>%     # extract any  "..(any digit).." patterns
  str_extract_all(., "[:digit:]+")                                 # further extract the digits out of those already extracted patterns
  }

#Expected result
film$expected_var = c("0, 1", "0, 1", "", "", "", "0, 1, 2", "0, 1, 2", "0, 1, 2, 3")

Thought it'd be nice to use stringr as it's makes for very readable code. Not sure where I've gone wrong though. Thanks for any help!

A: I'm horrible with regex --- so I'm sure there's a better way. Here's one approach:
x <- str_extract_all(film$var, "(?<=\\.\\.)\\d(?=\\.\\.)")
newvar <- sapply(x, function(y) paste0(y, collapse = ', '))
newvar[!(grepl("0", newvar) & grepl("1", newvar))] <- ""
cbind(film, newvar)

                                         var expected_var     newvar
1                       grey..0..yellow..1..         0, 1       0, 1
2                        grey..0..brown..1..         0, 1       0, 1
3                                grey0brown1
4                        grey..a..brown..3..
5                        grey..a0..red..1...
6              grey..0..blue..1...brown..2..      0, 1, 2    0, 1, 2
7           3grey..0..purple..1...brown..2..      0, 1, 2    0, 1, 2
8 3grey..0..purple..1...brown..2..brown..3..   0, 1, 2, 3 0, 1, 2, 3

Please let me know if this would meet your needs. I hope someone can provide a better answer.


text:
Q: SSH into GKE private cluster node I need to install a plugin on every node in my private-cluster.
I've tried to add an external IP with:
gcloud compute instances add-access-config gke-private-cluster-nodename

It works, but then SSH into the node
(IP registered in cluster Authorized networks)
 gcloud compute ssh gke-private-cluster

"I get: Operation timed out"
Same when I try in the Compute-engine console but with error:
"We are unable to connect to the VM on port 22"
Is it some firewall rule that has to be enabled? Any hint would be helpful!

A: You cannot install things on GKE nodes.
GKE nodes use an OS image with a read-only filesystem that doesn't allow you to install things https://cloud.google.com/container-optimized-os/docs/.
Not only it's a bad idea, your nodes are "temporary". When GKE automatically upgrades your Kubernetes node versions, all your VMs will be replaced with new VMs so SSHing them and trying to install things to them one by one just going to work for a few days.
To answer your question, by definition, "private clusters" aren't accessible from the internet. You should have a "bastion node" in that VPC network which you can SSH in then to access the private nodes. https://cloud.google.com/solutions/connecting-securely#bastion


text:
Q: Set Lookup and User Field Types when Migrating to Sharepoint online using Migration API I am in the process of writing a c# code to migrate set of files to Sharepoint online(o365) using migration API and I have successfully done migration using the approach mentioned in the below link.
http://case.schollaart.net/2016/03/10/office365-migration-using-c-sharp.html
But I am unable to update complex field types such as Lookup fields and User type fields in a document library.
Is there any suggestion or approach recommended for this scenario?

A: You can use SharePoint CSOM library to update lookup and person fields, please check this demo, Project is a lookup field and CurrentUser field is person field which is set to current user:
    using (var ctx = new ClientContext(@"http://sp2016/sites/test"))
    {

        var list = ctx.Web.Lists.GetByTitle("myList");
        var item = list.GetItemById(4);

        item["Title"] = "test";
        var currentUser = ctx.Web.CurrentUser;
        ctx.Load(item);
        ctx.Load(currentUser, user => user.Id);
        ctx.ExecuteQuery();
        FieldUserValue uservalue = new FieldUserValue();
        uservalue.LookupId = currentUser.Id;
        item["CurrentUser"] = uservalue;
        FieldLookupValue lv = new FieldLookupValue();
        lv.LookupId = 1;
        item["Project"] = lv;
        item.Update();
        ctx.ExecuteQuery();
    }


text:
Q: Prove that there exist infinitely many positive integers $n$ such that $a_{n}$ is divisible by $n$ Let $\{a_{n}\}$be a sequence defined by $$a_{0}=0,a_{1}=a_{2}=1,a_{n+3}=a_{n+2}+a_{n+1}+a_{n}$$
Prove that there exist infinitely many positive integers $n$ such that $a_{n}$ is divisible by $n$
I try:let $a,b.c$ be the set of all roots of $X^3-X^2-X-1\in \Bbb{Q}[x]$, we can take $(s,t,u)\in \Bbb{C}^3$, such that $$a_{n}=sa^n+tb^n+uc^n$$ for all $n\in \Bbb{Z}$

A: $\DeclareMathOperator*{\lcm}{lcm}$We will need a few theorems from "Some properties of a generalized Fibonacci sequence modulo $m$", M.E. Waddill (1978). Let's denote $h(x)$ the Trisano period of the $a_n$ sequence taken modulo $$. To begin with, a few empirical observations:
$$\begin{aligned}
 h(3) &= 13\\
 h(13) &= 168
\end{aligned}$$
Also
$$\begin{align*}
a_{13\cdot 3} &\equiv 0 \pmod{h(3)}\\
a_{13\cdot 3} &\equiv 0 \pmod{h(13)}
\end{align*}$$
This allows us to derive
$$\begin{align*}
a_{13\cdot 3} &\equiv 0 \pmod{\lcm(h(3),h(13))}\\
&\equiv 0 \pmod{h(13\cdot 3)} &\text{(see Waddill Theorem 4)}
\end{align*}$$
And $39|a_{39}$ follows.
The general form for $13\cdot 3^{1+6k}$ with $k$ non-negative integer (as conjectured in the question's comments) poses no major difficulties. We know that
$$a_{13\cdot 3^{1+6k}} \equiv 0 \pmod{h(3^{1+6k})} \tag{1}$$
is true because
$$\begin{aligned}
h(3^{1+6k}) &= 3^{6k}h(3) &\text{(see Waddill Theorem 8)}\\
&= 13\cdot 3^{6k} &\text{which divides $13\cdot 3^{1+6k}$.}
\end{aligned}$$
Taking into account that $3^m$ has period $6$ when taken modulo $168$, we also have
$$a_{13\cdot 3^{1+6k}} \bmod{h(13)} = a_{13\cdot 3} \bmod{h(13)} = 0\tag{2}$$
So we can claim that
$$\begin{align*}
a_{13\cdot 3^{1+6k}} &\equiv 0 \pmod{\lcm(h(3^{1+6k}),h(13))}\\
&\equiv 0 \pmod{h(13\cdot 3^{1+6k})}
\end{align*}$$
and conclude that
$$13\cdot 3^{1+6k} | a_{13\cdot 3^{1+6k}}$$
for all non-negative integer $k$.

On the topic of finding $h(p)$ for $p$ prime: Trisano periods exist for all $p$ (that's Waddill's Theorem 1), however they are no more predictable than Pisano periods are for Fibonacci sequences. One can only compute as many terms as needed to find the first reoccurrence of the first terms. For small primes, using a spreadsheet is fast and simple:

Column A for the indices, column B for the sequence itself, cell D1 for the modulus. Then you copy A4:B4 down a few hundred times, and you will find a new occurrence of $0,1,1$ at index $168$.


text:
Q: Vue - Retornar información de un componente hijo al padre por propiedades
Tengo un problema con mi componente hijo(azul) y la comunicación al padre, debido al que el componente children tiene la herramientas de filtro de "mi tabla" necesito pasar los datos capturados al padre, que es el contenedor de mi tabla.
mi componente padre:
<template>
  <busqueda /> //color azul

Componente hijo:
return {
          filter:{
          col: null,
           text: ''
        },
         orderBy: {
            col: null,
            type: 'asc'
         },
         total: 20
       }

he visto varias formas de hacerlo, sin embargo no se como retornar toda la información.
La mejor manera para mi seria que estuviera de la siguiente forma:
<busqueda :filterBy="modelo_1" :orderBy="modelo_2" />

y de esta manera ya tengo controlado cada uno de los <select> de busqueda.
¿Alguien sabe como puedo hacer eso?

A: Hay dos maneras sanas de hacerlo y como 200 maneras terribles. De las primeras:
1.- Escuchar a un evento del hijo:
en el padre:
<template>
  <busqueda v-on:tengo_resultados="onResultados">
</template>

en el hijo
export default {
   methods: {
      async buscarDatos(parametros) {
         let datos = await axios.get(...);
         this.$emit('tengo_resultados', datos);
      }
   }
 }

Básicamente, el primer parámetro que le pasas a $emit ('tengo_resultados') es el nombre del evento que el padre escucha. El segundo parámetro (datos) será lo que reciba la función con que el padre reaccionará al evento del hijo.
2.- Pasarle una función "callBack" al hijo
Si lo primero era como llevar a tu hijo hijo al parque y vigilarlo para que, si se cae, reaccionar.
Por la contraparte, pasarle una función es como pasarle un walkie-talkie al niño y decirle: "cuando te caigas, llámame". Lo encuentro más elegante.
en el padre:
<template>
  <busqueda :avisar="onResultados">
</template>

En el padre se ve casi igual, pero ahora el hijo debe invocar la función que recibe como prop
export default {
   props: ['avisar'],
   methods: {
      async buscarDatos(parametros) {
         let datos = await axios.get(...);
         this.avisar(datos);
      }
   }
 }

Nótese que el hijo no tiene idea de cómo se llama el listener del padre. Él sólo sabe llamar a "avisar".
Por convención, recuerda que estos métodos pasan de kebab-case a camelCase
Dejo un ejemplo de ambos approach

Vue.component('hijoMenor', {
  template: `
   <button v-on:click="gritar">
    Click: se cae mi hijo menor
   </button>
  `,
  methods: {
    gritar: function() {
      this.$emit('se_cae', 'hijo menor')
    }
  }
});
Vue.component('hijoMayor', {
  template: `
   <button v-on:click="llamar">
      Click: se cae mi hijo mayor
   </button>
  `,
  props: ['cuandoSeCaiga'],
  methods: {
    llamar: function() {
      this.cuandoSeCaiga('hijo mayor')
    }
  }
});

var vm = new Vue({
  el: '#app',

  data: function() {
    return {

      mensaje: 'Llevé a mis hijos a la plaza'
    }
  },
  methods: {
    TengoQueLevantarlo: function(cual) {
      this.mensaje = ('Escuché que se cayó mi ' + cual + ', Tengo que levantarlo');
    },
    MeAvisaPorRadio: function(cual) {
      this.mensaje = ('Me acaba de llamar mi ' + cual + ' para avisarme que se cayó');
    }
  }
})

    {{mensaje}}

  <hijo-menor v-on:se_cae="TengoQueLevantarlo"></hijo-menor>
  <hijo-mayor :cuando-se-caiga="MeAvisaPorRadio"></hijo-mayor>

No voy a ahondar en los métodos terribles, pero he visto usar vuex para este caso de uso... sólo porque el desarrollador era fan de vuex. También solía ser común generar una instancia vacía de Vue y usarlo como bus de eventos desde y hacia todos los componentes.


text:
Q: How to get parameters value in model from views form in rails? Here is my new.html.erb
<%= form_for :simulation, url: simulations_path do |f|  %>

  <%= f.label :Name %>

      <%= f.text_field :name, class: 'form-control' %>

<%= f.label :'Rendering Option' %>

  <%= select_tag(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>

   <%= f.submit 'Submit', class: 'btn btn-primary' %>

simulations_controller.rb
class SimulationsController < ApplicationController
 def index
  @simulations = Simulation.all
 end

 def new
 end

 def create
   @simulation = Simulation.new(simulation_params)
   @simulation.save
   redirect_to @simulation
 end

 def show
    @simulation = Simulation.find(params[:id])
 end

end
Simulation.rb (Model class)
class Simulation < ActiveRecord::Base
  belongs_to :user
end

Schema.rb
 create_table "simulations", force: :cascade do |t|
  t.string   "name"
  t.boolean  "is_random"
 end

I am not able to set the :is_random value in database while rest is fine. What I am doing wrong here? I checked the value in sqlite database and there was null entry in is_random column.

A: You need to permit attributes while doing mass assignment. You could write it as :
<%= f.select(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>

or
<%= select_tag("simulations[:is_random]", options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>

With your syntax, the value is inside the params hash as {..., is_random: true,..}, that's why inside the strong parameter filtering method you are not getting it. If you use now the suggested solutions, you will get it the value inside the params hash like {..., simulations: { is_random: true,..}, ...}.
You can inspect all these from the the development.log file, while making the request.

A: You need to use form object select method like bellow:
<%= f.select(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>

A: Using f.select (suggested above) should fix your problem. If you look at the generated html, you will see this field with a name of "is_random". It should be "simulations[is_random]". When you pull the form field values from the params object like this params[:simulations] all form fields with names in the form of "simulations[name]" will be included. Using the form builder object names the form fields correctly.
Hope this helps!

A: You can also use <%= debug params %> to inspect what's in params, it's very helpful.


text:
Q: Execution failed for task ':app:lintVitalRelease' - ':video_player_android:debugUnitTestRuntimeClasspath' When i try to generate the signed APK i am getting this below error.
Execution failed for task ':app:lintVitalRelease'.
> Could not resolve all artifacts for configuration ':video_player_android:debugUnitTestRuntimeClasspath'.
   > Failed to transform bcprov-jdk15on-1.68.jar (org.bouncycastle:bcprov-jdk15on:1.68) to match attributes {artifactType=processed-jar, org.gradle.category=library, org.gradle.libraryelements=jar, org.gradle.status=release, org.gradle.usage=java-runtime}.
      > Execution failed for JetifyTransform: /Users/elamparithibalakrishnan/.gradle/caches/modules-2/files-2.1/org.bouncycastle/bcprov-jdk15on/1.68/46a080368d38b428d237a59458f9bc915222894d/bcprov-jdk15on-1.68.jar.
         > Failed to transform '/Users/elamparithibalakrishnan/.gradle/caches/modules-2/files-2.1/org.bouncycastle/bcprov-jdk15on/1.68/46a080368d38b428d237a59458f9bc915222894d/bcprov-jdk15on-1.68.jar' using Jetifier. Reason: IllegalArgumentException, message: Unsupported class file major version 59. (Run with --stacktrace for more details.)
           Suggestions:
            - Check out existing issues at https://issuetracker.google.com/issues?q=componentid:460323&s=modified_time:desc, it's possible that this issue has already been filed there.
            - If this issue has not been filed, please report it at https://issuetracker.google.com/issues/new?component=460323 (run with --stacktrace and provide a stack trace if possible).

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

But i can able build the signed Bundle file. This is not the first time i am generating the apk for this app. But dont know y i got this error.
can someone please help me on this.

A: Adding this in the gradle.properties fixed my issue.
android.jetifier.blacklist=bcprov-jdk15on


text:
Q: Precisamos chamar cancelAnimationFrame para os frames anteriores ao atual do requestAnimationFrame? Tenho trabalhado com animação e estudando e lendo bastante achei esse método com a melhor performance entre outros existente, tanto para uso no computador quanto para Smartfones, abusurdamente eficiente.
Minha duvida é se esta correto chamar o cancelAnimationFrame para o frame anterior caso tenha atraso ou não é necessário colocar esta linha de cancelamento e por que?
Explicando a lógica:
/*
  CRIO VARIAVEL
raf: int, valor do id do raf antigo/atual executando
*/
/*
  CRIO VARIAVEL
tempo: float, armazena o valor do DOMHighResTimeStamp que e temporizado a cada raf executado, valores flutuantes podem representar microssegundos/miilesegundos dependendo do navegador, esse valor deve ser usado com o tempo atual para as comparacoes do scorpo e tempo de execusao
*/
/*
  Funcao:       fc_loop_infinito_raf (arg)
  Descricao:    Loop infinito com requestAnimationFrame com gestao do id e tempo do frame anterior/atual, deleto o frame antigo caso encontre atraso e executa o frame atual para tentar manter a performance
  Criacao:    20/1/2019
  Atualizada:   3/3/2019
https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
requestAnimationFrame: funcao, metodo informa ao navegador que voce deseja executar uma animação e solicita que o navegador chame uma funcao especificada para atualizar uma animação antes da proxima repintura. O método recebe um retorno de chamada como um argumento a ser chamado antes da repintura.
arg: de "function fc_loop_infinito_raf (arg), e agora um DOMHighResTimeStamp fornecido pelo raf
https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp
logica e pratica retirada de:
https://developer.mozilla.org/en-US/docs/Games/Anatomy
*/
;{

  let

  raf = 0,

  tempo = 0,

  fc_loop_infinito_raf = function (arg) {

    // CONDICAO CANCELA OS FRAMES ANTIGOS
    if (arg > tempo) {

      console.log ('CANCELO RAF '+ raf);

      // CANCELA O FRAME ANTERIOR CASO TENHA OCORRIDO ATRASO
      window.cancelAnimationFrame (raf);

    }

    raf = window.requestAnimationFrame (fc_loop_infinito_raf);

    tempo = (arg !== undefined ? arg : 0);

    // FUNCAO DE ATUALIZACAO

    // FUNCAO DESENHA

    console.log ('EXECUTA RAF '+ raf +' - '+ tempo);

  };

  // INICIO CICLO DO RAF
  fc_loop_infinito_raf ();

}

ou assim seria o correto? (caso sim, por que?)
   ;{

      let

      raf = 0,

      tempo = 0,

      fc_loop_infinito_raf = function (arg) {

        raf = window.requestAnimationFrame (fc_loop_infinito_raf);

        tempo = (arg !== undefined ? arg : 0);

        // FUNCAO DE ATUALIZACAO

        // FUNCAO DESENHA

        console.log ('EXECUTA RAF '+ raf +' - '+ tempo);

      };

      // INICIO CICLO DO RAF
      fc_loop_infinito_raf ();

    }

Existe essa pergunta parecida no stack inglês porem sem resposta!
https://stackoverflow.com/questions/52508261/do-we-need-to-clear-a-timeout-when-using-requestanimationframe-polyfill

A: Primeiro você precisa entender o que o seu segundo exemplo, o mais simples, faz, aí você vai entender que o primeiro exemplo não faz sentido. Depois de ler minha resposta, sugiro que releia o artigo que você linkou na MDN, inteiro. Se o problema for o inglês, tem uma versão em português também.
Quando você chama requestAnimationFrame e passa um callback, você está pedindo para o browser executar esse callback logo antes da próxima operação de repaint, que é quando ele (re)desenha o conteúdo da página na tela. A execução do callback é uma operação assíncrona; não ocorre no momento da chamada de requestAnimationFrame, e sim mais tarde (a critério do "fôlego" do browser).
Cada chamada do seu callback corresponde a um único frame da animação, o "frame atual". E o próprio callback agenda a próxima chamada do callback – o processamento do "próximo frame" – chamando novamente requestAnimationFrame e passando a si mesmo. Se o "frame atual" é quem agenda a execução do "próximo frame", é consequência lógica o "frame atual" só foi processado porque foi agendado durante o processamento do "frame anterior".
Agora vejamos o que você perguntou:

Minha dúvida é se está correto chamar o cancelAnimationFrame para o frame anterior caso tenha atraso, ou [se] não é necessário (...)

Percebe que isso não faz sentido? Na hora que você quer chamar cancelAnimationFrame, já é tarde demais, o "frame anterior" – mais precisamente, a execução anterior do seu callback – já terminou, você não tem como cancelar mais nada. O cancelAnimationFrame não serve para resolver questões de performance, serve para interromper o loop de animação, desagendando a próxima execução agendada.
Eu entendi que você está explorando soluções de performance. O problema é que não existe resposta única, abstrata, "esse jeito é sempre melhor e pronto". Depende do que você está fazendo, mais precisamente no que é feito nas partes do seu código que calculam o estado da animação, e nas que propriamente desenham o frame. O artigo que você linkou mostra algumas maneiras de se lidar com isso – e nenhuma delas usa cancelAnimationFrame.


text:
Q: VIM in GNU screen in Mac Terminal.app scrambled text Trying to use Vim in Mac's Terminal.app but it's unusable, terminal is only refreshing line or column where the cursor is, so scrolling is quite bizarre. Text is being updated only on the line where the cursor is, but the rest is not changing. Very weird behavior, I've seen this on linux too, with nvidia driver, the bufferes somehow were not updated. It's driving me crazy, and forces me to use MacVim all the time.
The weird factor here, it only happens when I run Vim inside GNU screen, otherwise it works just fine.

A: try MacVim :)


text:
Q: Postgres index is not used I have an over 30s query that looks like this
select
     coalesce(sum("paidInstallment"-(plafond/tenor*frequency)),0)
from
    account_transaction_debit atd
    join r_account_transaction_debit ratd on atd.id = ratd."accountTransactionDebitId" and atd."deletedAt" isnull and ratd."deletedAt" isnulland atd."type" = 'INSTALLMENT'
    join account a on a.id = ratd."accountId" and a."deletedAt" isnull and a.id = 4735
    join r_account_transaction_debit_installment ratdi ratd."accountTransactionDebitId" =  atd.id and ratdi."deletedAt" isnull
    join installment i on i.id = ratdi."installmentId" and i."deletedAt" isnull
    join r_loan_installment rli on i.id = rli."installmentId" rli."deletedAt" isnull
    join loan l on l.id = rli."loanId" and l."deletedAt" isnull
where
   atd."createdAt"::date between date_trunc('week',current_date) and current_date;

This is the index that is expected to be used (n.b.: "createdAt" type is timestamp with timezone)
CREATE UNIQUE INDEX
account_transaction_debit_deletedAt_type_createdAtDate_id_idx
ON account_transaction_debit ("deletedAt","type",my_to_char("createdAt"),id);

and my_to_char function looks like
CREATE OR REPLACE FUNCTION my_to_char(some_time timestamptz)
  RETURNS text
AS
$BODY$
    select to_char($1, 'yyyy-mm-dd');
$BODY$
LANGUAGE sql
IMMUTABLE;

and finally the explain (analyze, verbose, buffers) results
Aggregate  (cost=17943983.42..17943983.43 rows=1 width=32) (actual time=3020772.135..3020772.135 rows=1 loops=1)
  Output: COALESCE(sum((i."paidInstallment" - ((l.plafond / (l.tenor)::numeric) * (i.frequency)::numeric))), '0'::numeric)
  Buffers: shared hit=84541, temp read=25220 written=25092
  ->  Nested Loop  (cost=157262.23..8369328.64 rows=638310318 width=18) (actual time=3520.565..593472.501 rows=3168056628 loops=1)
        Output: i."paidInstallment", l.plafond, l.tenor, i.frequency
        Buffers: shared hit=84541, temp read=25220 written=25092
        ->  Nested Loop  (cost=125695.82..280946.58 rows=1384621 width=22) (actual time=1266.622..6543.090 rows=1496484 loops=1)
              Output: i."paidInstallment", i.frequency, l.plafond, l.tenor, a.id
              Buffers: shared hit=53058, temp read=25012 written=24886
              ->  Index Scan using account_id_idx on public.account a  (cost=0.29..8.31 rows=1 width=4) (actual time=0.012..0.518 rows=1 loops=1)
                    Output: a.id, a."totalDebit", a."totalCredit", a."totalBalance", a."createdAt", a."updatedAt", a."deletedAt", a."oldId", a.threshold
                    Index Cond: (a.id = 4735)
                    Filter: (a."deletedAt" IS NULL)
                    Buffers: shared hit=93
              ->  Hash Join  (cost=125695.53..267092.07 rows=1384621 width=18) (actual time=1266.608..6240.859 rows=1496484 loops=1)
                    Output: i."paidInstallment", i.frequency, l.plafond, l.tenor
                    Hash Cond: (rli."loanId" = l.id)
                    Buffers: shared hit=52965, temp read=25012 written=24886
                    ->  Hash Join  (cost=120652.07..228476.25 rows=1434437 width=14) (actual time=1224.901..4429.943 rows=1496484 loops=1)
                          Output: i."paidInstallment", i.frequency, rli."loanId"
                          Hash Cond: (ratdi."installmentId" = i.id)
                          Buffers: shared hit=49833, temp read=21586 written=21462
                          ->  Hash Join  (cost=52321.11..118507.38 rows=1493212 width=12) (actual time=552.083..1704.683 rows=1496484 loops=1)
                                Output: ratdi."installmentId", rli."installmentId", rli."loanId"
                                Hash Cond: (ratdi."installmentId" = rli."installmentId")
                                Buffers: shared hit=21624, temp read=9403 written=9341
                                ->  Seq Scan on public.r_account_transaction_debit_installment ratdi  (cost=0.00..25809.68 rows=1511094 width=4) (actual time=0.010..303.506 rows=1496491 loops=1)
                                      Output: ratdi."installmentId"
                                      Filter: (ratdi."deletedAt" IS NULL)
                                      Rows Removed by Filter: 8502
                                      Buffers: shared hit=10606
                                ->  Hash  (cost=26774.97..26774.97 rows=1557051 width=8) (actual time=551.360..551.360 rows=1529141 loops=1)
                                      Output: rli."installmentId", rli."loanId"
                                      Buckets: 131072  Batches: 32  Memory Usage: 2897kB
                                      Buffers: shared hit=11018, temp written=5047
                                      ->  Seq Scan on public.r_loan_installment rli  (cost=0.00..26774.97 rows=1557051 width=8) (actual time=0.010..267.452 rows=1529141 loops=1)
                                            Output: rli."installmentId", rli."loanId"
                                            Filter: (rli."deletedAt" IS NULL)
                                            Rows Removed by Filter: 17031
                                            Buffers: shared hit=11018
                          ->  Hash  (cost=43020.87..43020.87 rows=1456007 width=14) (actual time=672.617..672.617 rows=1510902 loops=1)
                                Output: i."paidInstallment", i.frequency, i.id
                                Buckets: 131072  Batches: 32  Memory Usage: 3244kB
                                Buffers: shared hit=28209, temp written=6413
                                ->  Seq Scan on public.installment i  (cost=0.00..43020.87 rows=1456007 width=14) (actual time=0.010..360.023 rows=1510902 loops=1)
                                      Output: i."paidInstallment", i.frequency, i.id
                                      Filter: (i."deletedAt" IS NULL)
                                      Rows Removed by Filter: 24993
                                      Buffers: shared hit=28209
                    ->  Hash  (cost=3845.53..3845.53 rows=68875 width=12) (actual time=41.500..41.500 rows=69253 loops=1)
                          Output: l.plafond, l.tenor, l.id
                          Buckets: 131072  Batches: 2  Memory Usage: 2655kB
                          Buffers: shared hit=3132, temp written=151
                          ->  Seq Scan on public.loan l  (cost=0.00..3845.53 rows=68875 width=12) (actual time=0.005..25.918 rows=69253 loops=1)
                                Output: l.plafond, l.tenor, l.id
                                Filter: (l."deletedAt" IS NULL)
                                Rows Removed by Filter: 2611
                                Buffers: shared hit=3132
        ->  Materialize  (cost=31566.41..109504.70 rows=461 width=4) (actual time=0.002..0.130 rows=2117 loops=1496484)
              Output: ratd."accountId"
              Buffers: shared hit=31483, temp read=208 written=206
              ->  Hash Join  (cost=31566.41..109502.39 rows=461 width=4) (actual time=2253.937..2295.318 rows=2117 loops=1)
                    Output: ratd."accountId"
                    Hash Cond: ((atd.id)::double precision = ratd."accountTransactionDebitId")
                    Buffers: shared hit=31483, temp read=208 written=206
                    ->  Seq Scan on public.account_transaction_debit atd  (cost=0.00..77463.04 rows=7467 width=4) (actual time=2048.273..2078.574 rows=20319 loops=1)
                          Output: atd.id
                          Filter: ((atd."deletedAt" IS NULL) AND (atd.type = 'INSTALLMENT'::text) AND ((atd."createdAt")::date <= ('now'::cstring)::date) AND ((atd."createdAt")::date >= date_trunc('week'::text, (('now'::cstring)::date)::timestamp with time zone)))
                          Rows Removed by Filter: 1496536
                          Buffers: shared hit=20688
                    ->  Hash  (cost=30009.74..30009.74 rows=94854 width=8) (actual time=205.009..205.009 rows=102568 loops=1)
                          Output: ratd."accountTransactionDebitId", ratd."accountId"
                          Buckets: 131072  Batches: 2  Memory Usage: 3021kB
                          Buffers: shared hit=10795, temp written=175
                          ->  Seq Scan on public.r_account_transaction_debit ratd  (cost=0.00..30009.74 rows=94854 width=8) (actual time=17.923..180.127 rows=102568 loops=1)
                                Output: ratd."accountTransactionDebitId", ratd."accountId"
                                Filter: ((ratd."deletedAt" IS NULL) AND (ratd."accountId" = 4735))
                                Rows Removed by Filter: 1414286
                                Buffers: shared hit=10795
Planning time: 1.181 ms
Execution time: 3020772.395 ms

I've searched for the solution but nothing solves my issue, is there any option that I should try?

A: In general an index is only used if the expression in the where clause matches exactly the index expression. Plus leading columns of the index are preferred.
You do not use my_to_char("createdAt") in where clause but the expression `"createdAt"::date.
You would need to define an index on "createdAt"::date - which is a better choice anyway as that makes the index smaller. A date is stored in 4 bytes, the character representation takes up 10 bytes.
As you only reference "createdAt"::date in your query, that expression should also be the leading expression of an index. Even if you changed your unique index to use "createdAt"::date it would most probably not be used.
The following index should help:
CREATE INDEX ON account_transaction_debit ( ("createdAt"::date) );

As you have join conditions on deletedAt and type a partial index might even be better:
CREATE INDEX ON account_transaction_debit ( ("createdAt"::date), type )
where "deletedAt" is null;

Edit
You forgot to mention that you are using a timestamp with time zone column which complicates things (which is a nice example why it's always a good idea to include the create table statements).
You can still work on date value, but you will need to change your function, query and index:
CREATE OR REPLACE FUNCTION get_date(some_time timestamptz)
  RETURNS date
AS
$BODY$
    select some_time::date
$BODY$
LANGUAGE sql
IMMUTABLE;

Then you can create this index:
CREATE INDEX ON account_transaction_debit ( (get_date("createdAt")), type )
where "deletedAt" is null;

and then use the following condition in your query:
where get_date(atd."createdAt") between date_trunc('week',current_date) and current_date;


text:
Q: Using MCMC to calculate log likelihood I have an analytical solution to finding $p(y|\beta)$ and $p(\beta)$. My goal is to find $\log p(y)$. However, the integral $\int p(y|\beta)p(\beta)\,d\beta$ is not analytical.
I did manage to use a Metropolis Hastings algorithm (using $p(y|\beta)$ and $p(\beta)$) to get a posterior sample from $p(\beta|y)$. Now I'm not sure if this posterior sample is supposed to even help me to get $\log(y)$ but if it does how?
I am basing this off the fact that you could get a lower bound on the log likelihood by using $$\log(y) > \frac{1}{N}\sum_{\beta\in\beta_s} p(y|\beta)p(\beta) $$ where $\beta_s$ is the sampled beta from the posterior. The above result is thanks to the EM algorithm where you set $q(\beta)=p(\beta|y)$.
Edit: Perhaps I might be looking at it all wrong, maybe some numerical integration technique will be better. This function is unimodal.


text:
Q: Using current_user to customize ActionCable channel submittion I'm making instant commenting with Rails 5. Using Rails *.js.erb, which is comfortable for this size of project. Also use ActionCable to deliver new comments to users. The thing is that I want ActionCable to send rendered comments/_comment.html.haml directly to client to evaluate this code in browser. In common case it's totally achivable. But in erb template of comment I have to deal with current_user to add delete link if current_user.admin? The problem is when I invoke CommentsChannel.broadcast_to and render _comment.html.haml renderer do not now current_user.
Question is how can I render _comment.html.haml and submit it to each separate subscription defined by current user, using current user from this subscription?
Devise is used for authentication.
comments/_comment.html.haml
%div[comment]
  .details
    %span.author= comment.user.email
    %span.time= l comment.created_at, format: :short
  = comment.body
  = link_to t('common.reply'), comment, class: 'reply-link'
  = link_to t('common.delete'), comment, method: :delete, remote: true if current_user.admin?
  = render 'comments/form', comment: comment.commentable.comment_threads.build, parent: comment

  - if comment.children.any?
    .child-comments
      = render comment.children.sort_by { |c| c.created_at }.reverse

application_cable/connection.rb
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    def find_verified_user
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

broadcast_comment_job.rb
class BroadcastCommentJob < ApplicationJob
  queue_as :default

  def perform(comment)
    CommentsChannel.broadcast_to \
      comment.commentable,
      comment: render_comment(comment)
  end

  private

  def render_comment(comment)
    CommentsController.render(partial: 'comment', locals: { comment: comment })
  end

end

comment.rb
class Comment < ActiveRecord::Base
  ...
  after_create_commit { BroadcastCommentJob.perform_now(self) }
  ...
end


text:
Q: Change instruction for apache config for linux into config for windows I was given a tutorial on setting up apache2 and php to work with a java CMS called liferay. the problem is that the instructions were written for linux. Can someone help me change these to work with windows environment?
ssh into the server.

cd /var/www/

sudo mkdir directory name

sudo nano (or vim if you prefer) index.php

Enter this into the text editor.

<?php
         echo "Hello World!";
?>

cd /etc/apache2/sites-enabled/

sudo nano (or vim if that's your preference) 000-default

Make sure the first item on the page looks like this...

NameVirtualHost *:80

Make sure the <VirtualHost> directive looks like this...

<VirtualHost *:80>

Save and exit the file.

sudo nano liferay.conf

Make sure the <VirtualHosts> directive looks like this...

Add an alias inside the <VirtualHost> tag.

Alias /apps "/var/www/apps"

Add a <Directory> directive inside the <VirtualHost> tag. It should look like this...

<Directory "/apps/">

 Options FollowSymLinks

      AllowOverride None
      Order allow,deny
      Allow from all
      ProxyPass [http://localhost:80/apps/]
</Directory>

Save and exit the file.

Restart the server

/etc/init.d/apache2 restart

things like the directory site-enabled don't exist, etc. so am having a hard time here.
Thanks a lot!
Jonesy

A: The file you are looking for is httpd.conf, probably in "conf" directory of the apache installation. You can also check httpd-vhost.conf into "conf/extra" directory.


text:
Q: Trying to add elements to a list inside "for" loop overwrites the same value each time Given the following:
data = response.json()
for result in data['results']:
    for field in result['custom_fields']:
        if field['id'] == some_id_field:
            print(field['value'])

Returns:
11111
22222
33333
44444
55555
66666
77777

However, I wanted to store the output as list in a separate variable to use later so I did this:
data = response.json()
for result in data['results']:
    for field in result['custom_fields']:
        if field['id'] == some_id_field:
            var_for_later = field['value']
            var_for_later = var_for_later.splitlines()
            var_for_later = var_for_later

But instead, it only returns the first element in the array:
11111

Instead of ['11111','22222','33333','44444','55555','66666','77777']
Why is field['value'] now only storing the first element when assigned to a variable?

A: You are assigning the value to a variable, not appending it to list. In order to store the values in list, you need to update your code to create an empty list before the for loop and append the field['value'] to list by using list.append() method. Hence, your code will become:
data = response.json()

my_list = []  # creating empty list
for result in data['results']:
    for field in result['custom_fields']:
        if field['id'] == some_id_field:
            my_list.append(field['value'])  # Appending items to the list

which will return you the my_list as list in your desired format as:
[11111, 22222, 33333, 44444, 55555, 66666, 77777]

A: Try this:
yourdata = []
data = response.json()
for result in data['results']:
    for field in result['custom_fields']:
        if field['id'] == some_id_field:
            yourdata.append(field['value'])

print(yourdata)

I guess you're pretty new to Python, so I suggest you to watch some tutorials or search for documentation on the internet. E.g. w3schools
Why didn't your code work?
Have a look at this line: var_for_later = var_for_later It does absolutely nothing. Also, you overwrite var_for_later in every iteration. So it should technically return '77777' and not '11111' in the end.
Are you sure this is the output that corresponds to this code?
Btw, do you really have multiple entrys with the same id?

A: Earlier you were printing one field at a time, but then you started replacing the same variable in every loop which is why it jas only one value. var_for_later only exists within that for loop. In stead create your final list outside the loop and append values in every iteration.
out = []
data = response.json()
for result in data['results']:
    for field in result['custom_fields']:
        if field['id'] == some_id_field:
            out.append(field['value'])


text:
Q: Get correct path for sparkdid.cassandra.connection.config.cloud.path in AWS EMR I checked the entire web. but could not found the solution.
I am trying to connect astra cassandra using bundle in AWS EMR its able to download the bundle file but not loading it.
spark.conf.set("sparkdid.cassandra.connection.config.cloud.path", "secure-connect-app.zip")
this is how I am giving path I know this is wrong path since its not loading the correct config returning connection refused with localhost.
I don't what is the correct path in EMR.

A: If you look into documentation, then you see that the file could be either specified as URL of file on S3, or you can use —files option when submitting with spark-submit or spark-shell , then it will be available as just a file name, like you're doing


text:
Q: Is it possible for Google Places API to notify users of any quiet locations within close proximity? I would like to ask whether Google Places API is able to notify users of any quiet places within their region?
I am creating an application which is targeted towards people with hearing loss and one of the features of the application is to enable users with hearing loss to locate a quiet place in order to rest their ears. For instance, if a user is currently in a club for extended periods of time and requires a quiet place to rest his ears away from the loud music, the app will be able to direct the user to the desired location quickly and efficiently.

A: Try using geofencing and notify user if he/she reach near by such loactions

Example1 , Example2 , Example3 Example4 ,
  Example5


text:
Q: Challenges with Key with Gaps? I had a mistake with a trigger which resulted in errors in PostgreSQL 9.4.3 on x86_64-unknown-linux-gnu, compiled by gcc (Debian 4.9.2-10) 4.9.2, 64-bit.
Each time during the error, the primary key of SERIAL increased.
After fixing the bug, the table measurements is
 measurement_id | measurement_size_in_bytes |             time
----------------+---------------------------+-------------------------------
              1 |                     77777 | 2015-07-14 18:29:56.858703+03
              2 |                       888 | 2015-07-14 18:29:56.882552+03
              3 |                       888 | 2015-07-14 18:30:15.505957+03
              4 |                       888 | 2015-07-14 18:41:01.878106+03
             39 |                     77777 | 2015-07-15 12:11:21.21391+03
             40 |                     77777 | 2015-07-15 12:11:59.551973+03
             41 |                     77777 | 2015-07-15 12:12:05.48982+03
             42 |                     77777 | 2015-07-15 12:13:02.402053+03
             43 |                     77777 | 2015-07-15 12:13:02.419412+03
             44 |                       888 | 2015-07-15 12:13:02.434728+03
         ...

where the amount of error statements has been 35 (= 39-4).
This jump in IDs may become a challenge later when I want to integrate this table with a partial index where order matters.
Table
CREATE TABLE measurements
    (
        measurement_id SERIAL PRIMARY KEY NOT NULL,
        measurement_size_in_bytes INTEGER NOT NULL,
        time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
        CONSTRAINT no_duplicate_measurements UNIQUE (time)
    );

What are the challenges of keys with gaps?

A: What you see is completely normal and expected.

Note: Because smallserial, serial and bigserial are implemented using sequences, there may be "holes" or gaps in the sequence of
  values which appears in the column, even if no rows are ever deleted.
  A value allocated from the sequence is still "used up" even if a row
  containing that value is never successfully inserted into the table
  column. This may happen, for example, if the inserting transaction
  rolls back.

Unless you really need a gapless series of values, you don't have to worry about it.  This is how most (well over 99%, I guess) database tables work.
If you need it, be careful if you have concurrent inserts on the table - you will need some locking to exclude the possibility of choosing the same value by two or more sessions running in parallel.


text:
Q: Change dotenv configuration when deploying to Heroku/production? I have an ajax call that relies on an API key as part of the request URL. I am using dotenv to hide that key. It works fine when I run it locally, but once deployed on Heroku, it gives me back a:
Uncaught TypeError: Cannot read property '________' of null

It looks as though it's returning null back (but it's totally fine in development). I'm wondering if I have to change any of the settings relating to dotenv when pushing up to Heroku / for production?
Thanks!

A: I am assuming you are referring to the file named .env as dotenv. Every variable in that file that you need on Heroku must be defined in Heroku config vars : https://devcenter.heroku.com/articles/config-vars
The .env file is an easy way to replicate the Heroku config vars locally. That way your code is prepared to read configuration data from config vars. For code running on Heroku you need to set the heroku config vars.


text:
Q: Can you use Amazon's MSK on EKS? I'm looking at the possibly of replacing/moving our existing Apache Kafka set up (version 2.1.0) to Amazon's MSK and for it work on EKS.
I've been looking around to see if this is actually possible and if someone has done this or attempted it but so far I've only seen reference to using Apache Kafka on EKS. Does anyone know if it is possible/makes sense to use MSK on EKS?
Many thanks.

A: Amazon MSK provides fully-managed Kafka clusters, which means that from your side, you do not have to operate the cluster at all. Broker and Zookeeper nodes are packaged, deployed, created, updated and patched for you.
This step-by-step tutorial illustrates the creation of a cluster.

A: The answer is not, MSK is a fully managed service provided by AWS, you cannot install managed service :-) but you can run your own Kafka cluster on top of Kubernetes cluster in AWS, eg. on EKS service while installing a Kafka Operator:
https://banzaicloud.com/docs/supertubes/kafka-operator/

A: I haven't done it for MSK before but surely done it for AWS Aurora Postgres. Not sure why you can't define your external persistence (in this case MSK) as a service with no selector then manually register an Endpoint object pointing to the MSK host.
https://kubernetes.io/docs/concepts/services-networking/service/#services-without-selectors


text:
Q: What is the surface tension of liquids in space? I mean does surface tension exists in space on liquids?
Let's take an example if I have to write something using ballpen in space and space does not have gravity. Does it works because of the surface tension?

A: Surface tension does exist "in space", which I take you to mean "without gravity". Surface tension in liquids is simply the attractive interactions between the molecules of a liquid. That exists whether there is gravity or not. I think most pens will not work well without being in the proper orientation in gravity, though. If you try using a normal ballpoint pen and write on a paper on the ceiling, you'll probably find that it won't work because gravity is pushing the ink in the wrong direction.


text:
Q: How do you edit styles in WPF 4.5 under Windows 7? I just realised that Blend for Visual Studio 2012 does not support WPF apps under W7.
Once I opened a window I can only see raw XAML.
I need to edit a style for a chart dataseries System.Windows.Controls.DataVisualization.Charting. I normally use Blend for these kind of tasks - because it pulls default styles from somewhere and gives it to you in a blink of an eye.
now I am stuck.. what would you guys do?
P.S. here is nice summary for future references: http://blendinsider.com/technical/available-now-blend-for-visual-studio-2012-2012-08-15/
(scroll down to see the table what version supports what)

A: You need to use the Blend Preview that supports WPF apps.

*

*http://expression.microsoft.com/en-us/jj154135

*How can I design an animation with a WPF project in Visual Studio 2012?
Visual Studio 2012 Update 2 will have a released version of Blend which supports WPF...in the meantime use the preview one.

*

*http://www.microsoft.com/expression/


text:
Q: Getting author to view correct story in laravel I'm using Laravel 7 and I'm  trying to create a site where the user can login if they have a token. I seem to have that almost working in that if you don't
have a token you can't access the page and if you put in a token that isn't in the database then it throws out an error.
The problem I'm having is that a user can still view a page they not meant to. For example I have Story 1 and Story 2, Author 1 can
view both Story 1 and 2, but Author 2 can only view Story 2.
The issue is that Author 2 can view both Story 1 and Story 2, which is wrong they only supposed to see Story 2.
I wanted to use middleware for this but I kind of hit a brick wall and not sure what next to do.
My tables
Story Table
id | title
1  | Story 1
2  | Story 2

Author Table
id | name
1  | Author 1
2  | Author 2

author_story table
id | author_id | story_id
1  |    1      |    1
2  |    1      |    2
3  |    2      |    2

My Story.php
protected $fillable = ['title'];

public function authors()
{
    return $this->belongsToMany('App\Author');
}

My Author.php
protected $fillable = ['name'];

public function stories()
{
    return $this->belongsToMany('App\Story');
}

My ViewStory.php (middleware)
if(Auth::check())
{
    return $next($request);
}else{
    abort(401);
}

A: Do you get any error?
I think you should use hasMany relation in my author model:
return $this->belongsToMany('App\Story',story_id, id);


text:
Q: How to make a @ManyToOne field mandatory in JPA2? I am designing the persistence repository for an app.
I am new to Hibernate+JPA2 and I am having trouble creating more complex relationships in this case a Foreign mandatory key.
An example (just wrote on notepad, so it's not exactly this.)
I have a Top Class called Person which can hold several Posts (another class).
If I map my top class like this
@Entity
@Table(name="tb_people")
public class Person{
    @Id
    @GeneratedValue
    public long         id;

    @OneToMany(mappedBy="person")
    List<Post>          listOfPosts;

    .
    . more code
    .

}

@Entity
@Table(name="tb_posts")
public class Post{

    @Id
    @GeneratedValue
    public long         id;

    @ManyToOne
    @JoinColumn(name = "person_id")
    Person              person;

    .
    .more code
    .

}

How can I using annotations make the person field in Post mandatory ?
I tryed with @Column(nullable=false) but I get an exception telling me I cannot use that annotation on a @ManyToOne Collection.
Thank you !

A: You have to use @JoinColumn(name=..., nullable=false) not @Column
See the complete API

A: Or you can just use @NotNull from javax.validations.constraints package.

A: It should be enough to just use @ManyToOne(optional = false)


text:
Q: what is the port number of the server on the android mobile phone not on AVD to can allow client to connect? I had succeeded in developing this on AVD through eclipse but i want to do it on the mobile android phones.
But they can't connect to each other while testing on mobiles.
So, my question is "how to set the ports"
On AVD's , i gived the server port no. 2000 while client is connected to 1000, so i had redirected the ports through "telnet localhost" but on android phones i can't do this "telnet"
So, please help how to set IP and ports while developing on phones not virtual devices.
Thanks