text:
Q: What happens when the index size of my Mysql instance exceeds the innodb_buffer_pool_size? I am using Amazon's RDS db.m1.small.
innodb_buffer_pool_size is set to 1125.00 MB.
Current index size is 1110.00 MB and growing slowly but steadily.
I do not need more hard drive space.
I want to know if it is necessary to upgrade to a larger instance (db.m1.medium) in order to keep my app working smoothly. Is it important that the index fits into memory? What should be my next steps?

A: It isn't the index size... it's the data and indexes.  The InnoDB Buffer Pool:

...holds cached InnoDB data for both tables and indexes
— http://dev.mysql.com/doc/refman/5.6/en/glossary.html#glos_buffer_pool
The larger the buffer pool, the more InnoDB acts like an in-memory database, reading data from disk once and then accessing the data from memory during subsequent reads. The buffer pool even caches data changed by insert and update operations, so that disk writes can be grouped together for better performance.
— http://dev.mysql.com/doc/refman/5.6/en/innodb-buffer-pool.html

Conversely, the smaller the buffer pool, the less InnoDB acts like an in-memory database.
In an ideal world, your buffer pool is larger than data size plus index size plus a little bit of overhead, because InnoDB does nothing to a page from a tablespace without storing that page in the buffer pool, it follows that when the pool is full, something less recently used gets evicted from the pool.  Practicality, of course, often necessitates something smaller than the ideal, and the key to appropriate sizing is the working data set.  The more infrequently-accessed data you have on your server, the fewer potential performance issues you should expect from an undersized pool.
There is, of course, no formula for this... familiarity with your unique working data set is the only "tool" you can use... but SHOW STATUS LIKE '%buffer%'; will give you the counters.
Note that Innodb_buffer_pool_pages_free is only an indication of completely unused space in the pool... it's not an emergency situation or even intensely meaningful if this value is very low or 0, because there is no process to spontaneously evict pages from the pool even when they are old and idle... but as long as they aren't "dirty" then replacing one page with something else is essentially no different in cost than loading a page into free space.  Zero free only means that at some point since the server was started, the total data and indexes read into the pool exceeded the size of the pool and there have not been enough deletions or tables dropped since the last peak to free up any pages.  Note also that running a backup will tend to fill an undersized pool, relatively harmlessly, depending on what's been loaded into the pool by the prior workload.


text:
Q: Datatables Responsive in a flexbox hierarchy overflow in recent browsers The problem
We use Datatables Responsive to display a table within a Bootstrap cell. It works fine. At least, we thought so, but lately discovered that, in later browsers, the table largely overflows the screen.
About the overflow: some columns are collapsed, but clearly not enough. We have some older versions of the code where columns are hidden when we drop below a threshold point (which is far after it should be). This is no longer the case but we had some radical changes (in both stylesheets and JavaScript) that code comparison flew out of the window.
To be precise:

*

*Works fine

*

*Chrome 47

*IE11

*Overflows

*

*Chrome 52

*Chromium 54

*Firefox ESR 47 & 52

We are in a corporate environment so we have limited choice in the browsers we have and this is all I can test.
The configuration
The datatables is set this way:
HMTL

JavaScript
$table.DataTable({
    language: {emptyTable: this.i18n.no_data},
    data: content,
    columns: columns,
    responsive: true
});

(I'm sorry, I cannot easily reproduce a case)
What I've tried
Go back to the basics
I removed as much as the options as I could from the configuration and see if the default Datatables configuration was better (spoiler alert: it was not). I also tried deactivating responsive but overflow still occurs.
I also moved the table as close to top-level as I could but that did not change anything.
We also wrote our own stylesheet but adding the original one doesn't change anything.
Tinker
After browsing all the possibly relevant solutions I saw on SO (div.table-responsive doesn't work and I already have the viewport <meta/>), I browsed the Datatables API and tinkered with some options we hadn't set yet (autoWidth, for instance).
I noticed no interesting change.
Listening
I added some listeners on Datatables events. Whether Responsive works or not, column-sizing is fired. In more modern browsers however, responsive-resize is not.
Check Chrome's changelog
I tried but only found a list of security fixes. Which is not what I need.
What next?
I've got no clue about how to solve this. Even if I don't get a solution, a new investigation lead would be great!
[Edit 2017-10-06] Clues
I'm still investigating, but moving the table around in the DOM, I found which element was the first to show problems. It had a display: flex; flex: 1 0 auto; style. Removing it fixed the problem.
I must now investigate with the full DOM tree but I'm afraid this is related to flexbox. This post on Datatables' forum seems to support this, but the proposed solution (add overflow: hidden to the table's parent) doesn't do the trick for me. Going on with my search.

A: The flexbox display style can break jQuery DataTable rendering. You'll have to inspect all parents containers that have the display: flex property and temporarily disable the display type one by one to find which container is causing this issue.
I think flex-shrink:1 is a possible cause of your problem.

A: Add overflow: hidden to the closest flex element in the DOM hierarchy it should solve the issue

A: Adding min-width: 0; to the content class of my site solved this issue for me.
I got it from here:
https://datatables.net/forums/discussion/46383/responsive-does-not-work-inside-flexbox

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interfaz COM no encontrada en PHP Estoy queriendo utilizar la libreria pyFEPDF, que genera un pdf de factura con formato para Argentina, y obtengo este error:
Fatal error: Uncaught Error: Class 'COM' not found in /home/u390048254/domains/engrasecornalo.com/public_html/views/modules/facta/imprimeA.php:25
En algunos temas lei que hay que habilitar la extension COM en php.ini:

[COM_DOT_NET]
extension=php_com_dotnet.dll

Peromi aplicacion esta en un webhosting. Y no creo tener accesos al php.ini.
Pero que puede ser? De que manera puedo resolverlo?
Aqui una parte del codigo:
 error_reporting(E_ALL);
 ini_set('display_errors', '1');
 $HOMO = true;   # homologación (testing / pruebas) o producción
 $CACHE = "";    # directorio para archivos temporales (usar por defecto)

try {

# Crear objeto interface Web Service Autenticación y Autorización
$PyFEPDF = new COM('PyFEPDF');

# CUIT del emisor
$PyFEPDF->CUIT = "33693450239";

# Establezco los valores de la factura a generar:
$fecha = date("d/m/Y");
$tipo_cbte = 1;                 # 1: factura A, 6: Factura B, 11: Factura C, 19 Factura E
$punto_vta = 1;
$cbte_nro = 123;
 ....demas codigo

y el error esta aqui:
   $PyFEPDF = new COM('PyFEPDF');


text:
Q: Listen to actions/mutations from within a vuex modules I have a vuex store with several modules, and I want to be able to listen to "global" dispatch or commit calls (aka actions and mutations) from within a module. For example, in an auth module there are actions like login and logout. Whenever those actions are dispatched, I want another module ui to also perform some action, like setting a language based on the logged in user.
I know I can just dispatch the ui actions from within the login and logout actions in the auth module. But I'd rather have it the other way around, so that ui is listening to the events (actions and/or mutations) dispatched in auth. This way I can easily create side effects without changing the "original" vuex module.
Maybe I need to use watches, but some actions don't alter state so I can't always use them. Creating a plugin is also an option, but I don't want to create an extra plugin each time I want to create such a side effect.
So my question; from within a vuex module, how can I listen to actions/mutations dispatched from other modules?

A: I created a vuex plugin for myself which can will trigger all refresh action in all stores. But you can do anything else where I called the refresh.
Plugin:
const onModuleAValueChange= (store) => {
    store.watch(
        state => state.moduleA.value,
        (val, oldVal) => {
            // Don't do anything on init state
            if (!oldVal) return;

            // This will trigger all refresh actions on all store. But you can add anything here
            // Essentially does:
            // store.dispatch(`moduleA/refresh`);
            // store.dispatch(`moduleB/refresh`);
            // store.dispatch(`moduleC/refresh`);
            for (let state in store.state) {
                const action = `${state}/refresh`;
                // If the store does not have an refresh action ignore
                if (store._actions[action]) store.dispatch(`${state}/refresh`);
            }

            // Additional action
            store.dispatch(`moduleC/moduleC_Action`);
        }
    );
};

Store core:
export const store = new Vuex.Store({
    modules: {
        moduleA,
        moduleB,
        moduleC
    },
    plugins: [onModuleAValueChange]
});


text:
Q: Angular material tabs I'm on a situation where I'm using tabs from angular-material : https://material.angularjs.org/latest/demo/tabs
Let's suppose I have a tabs with 2 cols. From the second cols I call a modal in order to submit actions. when I close the modal, I use $route.reload to refresh my view. The problem is that after $route.reload , it will come back to the first col and not remain in the second call where I was.
Is there a hack to fix this situation ?

A: In your config:
$routeProvider.when('/mypage/tab2', {
            templateUrl: '/mypage/tab2data.html',
            controller: 'pageCtrl',
            title: 'Add New Courses'
            }
        });

In your material tab:
<md-tab label="tab1e" ng-click="tab2()"></md-tab>

Now in your controller, define the function:
$scope.tab2 = function(){
    $location.path('/mypage/tab2');
}

Now when you click your tab2, url will change, you'll able to bookmark it, so it won't redirect to default tab.


text:
Q: formatting date in ruby I have a date in the format 05/22/2011 13:10 Eastern Time (US & Canada)
How can I convert that into a date object? This is what I used to parse the date from sting but I'm getting invalid date error.
str = "05/22/2011 13:10 Eastern Time (US & Canada)"
Date.strptime(str, "%d/%m/%Y %H:%M:%S %Z")

A: Your sting: 05/22/2011 13:10 Eastern Time (US & Canada).
Here is a number of mistakes in your pattern:

*

*Month is a first argument

*Day is a second

*Here is no any seconds in your time, only hours and minutes

Also your string includes Date and Time as well, so you'd better to use DateTime class instead of Date class:
Date.strptime(str, "%m/%d/%Y %H:%M %Z")
#=> Sun, 22 May 2011

or
DateTime.strptime(str, "%m/%d/%Y %H:%M %Z")
#=> Sun, 22 May 2011 13:10:00 -0500

To work with datetime you should require it first:
require 'date'
dt = DateTime.strptime("05/22/2011 13:10 Eastern Time (US & Canada)", "%m/%d/%Y %H:%M %Z")
#=> #<DateTime: 353621413/144,-5/24,2299161>
dt.to_s
#=> "2011-05-22T13:10:00-05:00"
dt.hour
#=> 13
...

A: There are 2 bugs in your call to Date.strptime
1) The date and month are reversed
2) There is no seconds field in your string


text:
Q: Are CSS Generated Content acceptable in terms of SEO? I run an online literary journal which leads to an indexing problem--our content is not "about" literature -- it is literature. As such, Google is really bad at identifying what's going on, and due to the very low keyword density we have to try and work with, I've been looking for ways to slash interface text and turn it into iconography where possible.
I've been looking for a way to do the same with our post dates, but it's been a long search. I stumbled across the idea of using CSS generated content content:attr(id) to substitute the ID attribute of an invisible image into the page itself.
This works on the display level, however, I haven't been able to track down anything conclusive on whether this interface-only text will still get indexed, or whether we'll be able to move away from months and days of the week being our most-frequent keywords. I know Google will still see it; anyone know if it'll "count"?

A: As far as I'm aware, the 'best' way to ensure something is hidden from a search engine is to either load it via AJAX or (shudder) include it with flash.
If you feel that the non-content aspects of your site are adversely affecting your site's standing in the various search engines, you could load these elements via AJAX.
Only if you really think these elements are seriously affecting your position.
Below is an image describing areas of this page that one could conceivably post-load via AJAX, if one was overly concerned about their impact on SEO:

I know this doesn't specifically answer your question, it's a suggestion for an alternative way to tackle your issue.


text:
Q: What's the strategy of storing User info in ASP.NET MVC4 Now I'm reading a book and in the book it says:
"Both Session State and Application state are used for storing a small amount of insecure global information that does not change frequently"
Based on that I have five questions:

*

*In MVC4 we can access session by HttpContext.Session, what's the difference
between this and HttpContext.Current.Session?

*What's application status used for?

*What's the practical difference between Session and Application state?

*For which user info we cannot store in session but only store in server database?

*Many many browser side cookies have been disabled, does that mean cookie are no longer in use when developing web application?
I hope this is not only helpful to me but also will help others who see this
Any suggestion are welcomed!

A: *

*There is no difference. Use HttpContext.Current.Session when you are not on a view.

*For storing application-wide information that applies to all users. There is only one at a time and the values are the same for all users.

*Sessions are at a user level. Application is system-wide. If you need to keep information specific to a user, use session. If the value will be the same for all users, use Application.

*Not sure what you mean

A: *

*They both point to the same object.

*ApplicationState if for sharing data between different Session objects which are tied to a concrete user session

*I stated the main difference under the previous point. To elaborate: objects stored in Session are only accesible to requests that are run under that session (they have session cookie or identification string in url). Objects stored in Application, on the other hand, are available everywhere (for instance in global.asax) and are not dependent on current user.

*It depends on your paranoia level. I would not store credit card information or social security number or passwords in an unencrypted format in Session. On the other hand I would not store them unencrypted on the database as well. SessionState can, by the way, be configured to reside in database and thus be shared between different machines.

*ASP.NET functions better with cookies. There are ways of making it work without cookies, but it will involve a lot of work.


text:
Q: Find arrays that are fully represented in a flat array with many values This is the third time that I'm posting about this topic. User Baba helped me everytime. Since the SO website has not a user message system -unfortunately- I'm asking a question within a post. Again.
With the help of the user Baba, we have managed to create a function that checks whether an array contains another array, but the function determines it multiple times and creates an index list. What the function lacks and I need to know is that the function does not return -1 in the exceptions like expected. Function may return values that are not related, and the function is not consistent. We simply need to check which arrays are matched with the main array($leftArray) and return the index's of those arrays. If there is not any matched array, the function have to return -1.
Please review this code and help me:
<?php
$leftArray = array(7,6,14,15,8,0,1,4,5,9);
//contains $GroupOfFour[6] and $GroupOfFour[1], and some excess
//numbers. Function should return array(6,1), If there is not a
//matching case the function should return -1.
//i've realised that the exception cases and the multiple
//grouping does not work.

$GroupOfFour = array (
                     array(3,2,7,6),
                     array(7,6,15,14),
                     array(15,14,11,10),
                     array(1,3,5,7),
                     array(5,7,13,15),
                     array(13,15,9,11),
                     array(0,1,4,5),
                     array(4,5,12,13),
                     array(12,13,8,9),
                     array(0,4,12,8),
                     array(1,5,13,9),
                     array(3,7,15,11),
                     array(2,6,14,10),
                     array(0,1,3,2),
                     array(4,5,7,6),
                     array(12,13,15,14),
                     array(8,9,11,10),
                     array(0,2,8,10),
                     array(0,1,8,9),
                     array(1,3,9,11),
                     array(3,2,11,10),
                     array(0,4,2,6),
                     array(4,12,6,14),
                     array(12,14,8,10)
                     );

function searchFourTerms($leftArray, $GroupOfFour) {
    global $GroupOfFour, $leftArray;
    $len4 = count($leftArray);
    $len4_carry = count($leftArray);
    $list4 = array();
    for($i4 = 0; $i4 < count($GroupOfFour); $i4 ++) {
        $intercept4 = array_intersect($GroupOfFour[$i4], $leftArray);
        $len4 = count($intercept4);
        if (count($intercept4) % 4 == 0) {
            $list4[$i4] = $len4;
        }
    }
    arsort($list4);
    if (empty($list4) || ($len4_carry<4))
        return - 1;
    return key($list4);
}

?>

A: key($list4) will only return the current index of list4. In your case it would return 18.
Try this, it worked for me. Instead of returning key($list4) I returned an array of matching indexes.
function searchFourTerms($la, $gof) {
$i3=0;
if(count($la)<4){
    return -1;
}
$list4 = array();
for($i4 = 0; $i4 < count($gof); $i4++) {
    $intercept4 = array_intersect($gof[$i4], $la);
    $len4 = count($intercept4);
    if(count($intercept4)==4) {
        $list4[$i3] = $i4;
        $i3++;
    }
}
if (empty($list4)){
    return - 1;
}
$list5= array();
$i7=0;
for($i4=0; $i4<count($list4); $i4++){
    $i6=0;
    for($i5=0; $i5<count($list4); $i5++){
        if($i4!=$i5){
            $i6+=count(array_intersect($gof[$i4], $gof[$i5]));
        }
    }
    if($i6<count($gof[$i4])){
        $list5[$i7]=$list4[$i4];
        $i7++;
    }
}
return $list5;
}

if $leftArray = array(0,1,3,2,7,6,8,9), doing a var_dump on the returned array prints the following array, which excludes [13] since it contains all duplicates from [0] and [18]:
array(2) {
[0]=>
int(0)
[1]=>
int(18)
}

A: This is all you need to return more than 1 keys
var_dump(searchFourTerms($leftArray, $GroupOfFour));

Output (All Groups use array_slice to pick any 2)
array
  0 => int 18
  1 => int 1
  2 => int 14
  3 => int 6
  4 => int 20

Your modified Function
function searchFourTerms($leftArray, $GroupOfFour) {
    $len4 = count($leftArray);
    $len4_carry = count($leftArray);
    $list4 = array();
    for($i4 = 0; $i4 < count($GroupOfFour); $i4 ++) {
        $intercept4 = array_intersect($GroupOfFour[$i4], $leftArray);
        $len4 = count($intercept4);
        if (count($intercept4) % 4 == 0) {
            $list4[$i4] = $len4;
        }
    }
    arsort($list4);
    if (empty($list4) || ($len4_carry < 4))
        return - 1;
    return array_keys($list4);
}

A: I have renamed the input variables and reduced the volume of data in the MCVE.
You only need to perform iterated array_intersect() calls.  If the output array is not declared, return -1.
Code: (Demo)
$haystack = [7, 6, 14, 15, 8, 0, 1, 4, 5, 9];
$needles = [
    [3, 2, 7, 6],
    [7, 6, 15, 14],
    [15,14,11,10],
    [1,3,5,7],
    [5,7,13,15],
    [13,15,9,11],
    [0,1,4,5],
    [4,5,12,13],
];

function getIndexOfMatchingArrays(array $needles, array $haystack) {
    if (!$haystack) {
        return -1;
    }
    foreach ($needles as $index => $needle) {
        if ($needle === array_intersect($needle, $haystack)) {
            $fullMatch[] = $index;
        }
    }
    return $fullMatch ?? -1;
}

var_export(
    getIndexOfMatchingArrays($needles, $haystack)
);

Output:
array (
  0 => 1,
  1 => 6,
)


text:
Q: While с двумя условиями в Python Используя цикл, запрашивайте у пользователя число, пока оно не станет больше 0, но меньше 10.
После того, как пользователь введет корректное число, возведите его в степень 2 и выведите на экран.
while True:
    number = int(input("Введите число от 0 до 10 "))
    if number  < 0 and number > 10:
        print('Число должно быть от 0 до 10')
    else:
        break

print(number,'во второй степени равно', number**2)

Выходит из цикла при любом варианте. Что делаю не так?

A: Используйте or, а не and(ведь число не может быть одновременно больше 10 и меньше 0):
while True:
    number = int(input("Введите число от 0 до 10 "))
    if number  < 0 or number > 10:
        print('Число должно быть от 0 до 10')
    else:
        break

print(number,'во второй степени равно', number**2)

A: if number<10 and  number>0:

A: Более короткая запись:
if not (0 < number < 10):

A: while True:
    number = int(input("Введите число от 0 до 10 "))
    if number  < 0 or number > 10:
        print('Число должно быть от 0 до 10')
    else:
        break

print(number,'во второй степени равно', number**2)

Просто поменяйте and на or


text:
Q: How to get index value as an id to div? Currently I am using Angular 2.0. I have an array called addExtra: number[] = [0,1,2,3];.
My HTML code is as follows:

            <button class="btn btn-danger btn-delete"
            (click)='delete(val)'>

            </button>
            Draw
            <input id="isCheckBox" id=val type="checkbox" class="setCheckbox" (change)="isChecked($event)" style="vertical-align: text-bottom;" />

How do I get the val meaning 0, 1, 2, 3 as id to the checkbox.

A: <input id="{{val}}" type="checkbox" class="setCheckbox" (change)="isChecked($event)" style="vertical-align: text-bottom;" />

A:

                <button class="btn btn-danger btn-delete"
                (click)='delete(val)'>

                </button>
                Draw
                <input id="isCheckBox" id={{i}} type="checkbox" class="setCheckbox" (change)="isChecked($event)" style="vertical-align: text-bottom;" />

A: You can't have 2 id for a html tag.
<input id={{val}} type="checkbox" class="setCheckbox" (change)="isChecked($event)" style="vertical-align: text-bottom;" />


text:
Q: Using the same progressbar in tkinter for several computation I wish to know how is the best method to use the same progressbar (determinate and indeterminate). In this example the same progressbar is used for a indeterminate, for a determinate, and function-indeterminate computation. When i run the code only the last progressbar is showed.
from Tkinter import *
import ttk
import tkFileDialog
import time

def foo(m, n, self_from_class):
    for i in xrange(m):
        i * n
        self_from_class.pbar_f.step(1)
        self_from_class.update()
        time.sleep(0.1)
    return i

class MainWindow(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("ProgressBar example")
        self.master.minsize(200, 100)
        self.grid(sticky=E+W+N+S)

        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

        self.start = Button(self, text='Start', command=self.start, activeforeground="red")
        self.start.grid(row=0, column=0, pady=2, padx=2, sticky=E+W+N+S)

        self.pbar_ind = ttk.Progressbar(self, orient="horizontal", length=300, mode="indeterminate")
        self.pbar_ind.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)

        self.pbar_det = ttk.Progressbar(self, orient="horizontal", length=300, mode="determinate")
        self.pbar_det.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)

        self.pbar_f = ttk.Progressbar(self, orient="horizontal", length=300, mode="indeterminate")
        self.pbar_f.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)

    def start(self):
        for i in xrange(10):
            self.pbar_ind.step(1)
            self.update()
            # Busy-wait
            time.sleep(0.1)
        for i in xrange(10):
            self.pbar_ind.step(1)
            self.update()
            # Busy-wait
            time.sleep(0.1)
        res = foo(10, 2, self)

if __name__=="__main__":
   d = MainWindow()
   d.mainloop()

UPDATE - my not elegant solution is:
class MainWindow(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("ProgressBar example")
        self.master.minsize(200, 100)
        self.grid(sticky=E+W+N+S)

        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

        self.start = Button(self, text='Start', command=self.start, activeforeground="red")
        self.start.grid(row=0, column=0, pady=2, padx=2, sticky=E+W+N+S)

        self.pbar_f = ttk.Progressbar(self, orient="horizontal", length=300, mode="indeterminate")

        self.pbar_det = ttk.Progressbar(self, orient="horizontal", length=300, mode="determinate")

        self.pbar_ind = ttk.Progressbar(self, orient="horizontal", length=300, mode="indeterminate")
        self.pbar_ind.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)

    def start(self):
        for i in xrange(10):
            self.pbar_ind.step(1)
            self.update()
            # Busy-wait
            time.sleep(0.1)
        self.pbar_ind.grid_forget()
        self.pbar_det.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)
        for i in xrange(10):
            self.pbar_det.step(1)
            self.update()
            # Busy-wait
            time.sleep(0.1)
        self.pbar_det.grid_forget()
        self.pbar_f.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)
        res = foo(10, 2, self)

A: If you put all widgets in one cell - they have the same column and row - then you put them one over another. Last one is on the top and you see it.
You can use only one Progressbar widget - for all computation.
You can have few Progressbars and use grid/grid_forget to show one and hide anothers.
You can put Progressbars in different cells and have all on the screen.

EDIT:
example with grid_forget
from Tkinter import *

#-----------------------------------

def on_press():
    global visible

    if visible == 1:
        l1.grid_forget()
        l3.grid(row=0,column=3)
        visible = 3
    else:
        l1.grid(row=0,column=0)
        l3.grid_forget()
        visible = 1

#-----------------------------------

master = Tk()

l1 = Button(master, text='press there >>')
l1.grid(row=0,column=0)

l2 = Button(master, text='change', command=on_press)
l2.grid(row=0,column=1)

l3 = Button(master, text='<< press there')
#l3.grid(row=0,column=3)

visible = 1

master.mainloop()


text:
Q: Why the Minimum matching is wrong? <?php
    $str='00160.Day';
    $pattern = "/(.+?)('.Day')/i";
    $replacement = "\${1}";
    print preg_replace($pattern, $replacement, $str);
?>

Why the output is 00160.Day ,not 00160?What is the matter with my Minimum matching  regular expression?

A: Single Quote ' around day is cause of unexpected output. . should also be escaped. Use below pattern.
"/(.+?)(\.Day)/i";


text:
Q: Repeated and unique in hash-like things The repeated method takes a function as an argument for normalizing the elements before finding out which ones are repeated. However, I can't seen to make it work with values. For instance:
%(:a(3),:b(3),:c(2)).repeated( as=> *.values ).say

Returns an empty list, while I was expecting the pairs :a(3) and :b(3), same as
%(:a(3),:b(3),:c(2)).repeated( as=> .values ).say

In this case, for instance, it seems to work as expected:
(3+3i, 3+2i, 2+1i).unique(as => *.re).say  # OUTPUT: «(3+3i 2+1i)␤»

Any idea of what I'm missing here?

A: .values is a method for returning all of the values of a container.
Since it is a List method, if you call it on a singular value it pretends it is a List containing only that value.
say 5.values.perl;
# (5,)

The as named parameter of .repeated gets called on all of the singular values.
%(:a(3),:b(3),:c(2)).repeated( as=> *.perl.say );
# :a(3)
# :b(3)
# :c(2)

So by giving it the *.values lambda, it is effectively not doing anything useful.

The method you were looking for is .value. Which is a method on a Pair.
%(:a(3),:b(3),:c(2)).repeated( as=> *.value ).say
# (a => 3)


text:
Q: Why is the first value of a Rails find_or_create_by block always nil in database? I am using a find_or_create_by block.
If a TrainingEvent record with the webinar_id that's being passed as an argument is not found, Rails should create a new TrainingEvent with all of the attributes passed in the block.
Rails creates the record but the first attribute is always nil in the database.
Rails 5.2.0
ruby 2.4.1p111
TrainingEvent.find_or_create_by(webinar_key: '2345') do |training_event|
  training_event.start_date_time = '2018-07-04 12:00:00',
  training_event.end_date_time = '2018-07-04 13:00:00',
  training_event.published = true,
  training_event.hidden_from_list = false,
  training_event.training_template_id = 349,
  training_event.organizer_key = '6789'
end

start_date_time is not in the SQL and ends up being nil in the database. No matter which attribute is first in the block, the value is always nil.

A: The commas that mu is too short spotted are what's actually causing the problem here.
This is interpreted by Ruby as trying to assign an array to start_date_time with a side effect of setting all the other attributes along the way. As this isn't a valid value for the field it ends up remaining as nil.
It looks like this stems from a slight misunderstanding:

Rails should create a new TrainingEvent with all of the attributes passed in the block

The block isn't for passing a list of attributes. The block is code which in the case of create is passed the new model object so that you can do anything you'd like with it prior to it being saved. Remove the commas and you'll be fine!

If you're curious, here's a simpler example that demonstrates how your code is being interpreted:
> x = 1, y = 2

This results in x having the array value [1, 2] and y having the value 2


text:
Q: Deleting Video File in Android I want to the delete the file after compression is done. I have used the code to delete the file. But when I check in the Gallery the video file is still there but it doesn't play shows error Media not Supported. Here is my code.
if (compressed) {
              snackbar = TSnackbar
                        .make(coordinatorLayout,"Video Compressed Successfully",TSnackbar.LENGTH_SHORT);
                snackbar.show();
                //Delete File from Location.
                File videoFile = new File(mediaFile.getPath());
                if(videoFile.exists())
                {
                    boolean del =  videoFile.delete();
                }

            }

This is mediaFile
 mediaFile = new File(path + "VID_" + timestamp + ".mp4");

This is the storage directory
File mediaStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appName);

A: Try this
getContentResolver().delete(Uri.parse(mediafile.getPath()),null,null);


text:
Q: windows service failing while sending report as PDF with System.Net.WebException: The request failed with HTTP status 401: Unauthorized I am trying to send SSRS report as PDF from a windows service. This works fine for me on my local machine and staging setup, but I get below error on production environment. This seems to be some permission issue to me but I am not able to pinpoint the exact issue. Below is error looged in windows service logs:
<log4j:event logger="MyProjectNamespace.Logger" timestamp="1352927717254" level="ERROR" thread="377">
    <log4j:message>The request failed with HTTP status 401: Unauthorized.  </log4j:message>
    <log4j:properties>
        <log4j:data name="log4net:UserName" value="NT AUTHORITY\SYSTEM" />
        <log4j:data name="log4jmachinename" value="<My server machine name>" />
        <log4j:data name="log4japp" value="<My windows service exe name>" />
        <log4j:data name="log4net:HostName" value="<My host name>" />
    </log4j:properties>
    <log4j:throwable>

System.Net.WebException: The request failed with HTTP status 401: Unauthorized.     at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)     at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
From stacktrace, line which is producing error is below:
    Rse2005.ExecutionInfo ei = rsExec.LoadReport(reportPath, historyID);

here "rsExec" is object of type "Rse2005.ReportExecutionService", historyId is NULL

My code to create report PDF is below:
private static void RenderReport(string reportFormat, string reportPath, string parameterLanguage, Rse2005.ParameterValue[] rptParameters, string outputFilePath)
        {
            string historyID = null;
            string deviceInfo = null;
            string encoding = String.Empty;
            string mimeType = String.Empty;
            string extension = String.Empty;
            Rse2005.Warning[] warnings = null;
            string[] streamIDs = null;

            Rse2005.ReportExecutionService rsExec = new Rse2005.ReportExecutionService();
            rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Rse2005.ExecutionInfo ei = rsExec.LoadReport(reportPath, historyID);
            rsExec.SetExecutionParameters(rptParameters, parameterLanguage);
            Byte[] results = rsExec.Render(reportFormat, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);

            File.WriteAllBytes(outputFilePath, results);
        }

this method gets reportPath like "folderName/reportName".
I am also displaying the same report using reportViewer control from a webApp (on same server) and there it works perfectly.
My report server, windows service and webApp are all on same server
I tried to give user "NT AUTHORITY\SYSTEM" permissions in report site settings and changing reportPath to full path with server name (like http:///reportserver/folderName/ReportName), but these didn't helped. Please suggest what else I can check and fix. Thanks.

A: NT Authority\System is a local system account. It cannot access resources on another machine, and sometimes local resources are secured to keep this account from access. So if you are giving this account permissions on a different machine (such as the SQL server), then it's not really the same account as the one running your service.
Try running your service with a domain user's credentials. Set that user up with the appropriate permissions in SSRS.


text:
Q: Consuming implicit from consuming class I'm looking for the best syntax for having contained classes pick up the implicits exposed by their containing classes?
The scenario I have has two dependencies abstracted for testing: The creation of the application's actorsystem, and a webclient that happens to require the actorsystem as well:
trait Core {
  implicit def system: ActorSystem
}

trait WebClient {
  implicit def system: ActorSystem
}

trait Api extends WebClient {
  ...
}

trait Server extends Core {
  def api: Api
  val service = system.actorOf(Props(new Service(api)))
}

Now, i create a new App which provides the actorsystem and api, but the Api needs an implicit actorsystem, and the only way I've figured out is to manually provide it like this:
object ServerApp extends App with Core {

  implicit val system = ActorSystem("foo")

  val api = new Api {
    override implicit def system = implicitly[ActorSystem]
  }

}

Is there a better syntax for having WebClient pick up the implicit from Core? I can't have it extend Core, since it is contained by the Core implementation and required as a dependency for something else that is contained there. But override implict def system = implicitly[ActorSystem] seems rather hamfisted for something that should be, er, implicit

A: You're shadowing the implicit value since they have the same name.
You might consider
class Api()(implicit val system: ActorSystem)

and
val api = new Api


text:
Q: Wait until operations in CustomKeywords finish to continue, Katalon Studio I have a script using groovy in Katalon Studio. Basically the pseudocode is
 1. OpenBrowser
 2. Login
 3. Get urls on page.
 4. Foreach urls
     a. Check(url)
 5. CloseBrowser

The CustomKeywords Check navigate to the url and do some checks in this page
I got usually around 200 url, and the check for the first 5 or 7 url works ok(it depends on speed of connection), but despite a certain moment, the check fails for the rest of the urls. I notice that when the script navigates to a url, the next url opens too fast, and for that reason, the check fails.
I tried to set a delay for Delay between actions in the Project Settings but take to much time in step 3 isn't the idea.

*

*How can I wait until step 4.a is finished to iterate to the next url?

*Is a sleep after step 4.a to assure that it finished necessary? Is it a good practice?

Fragment of step 4
for (def url: urls) {
    CustomKeywords.'com.utilities.CommonUtilities.Check'(href)
}

Any suggestion is welcome

A: You can use any of the Wait commands in Katalon to wait for some element's presence or non-presence.
WebUI.waitForElementAttributeValue()
WebUI.waitForElementClickable()
WebUI.waitForElementHasAttribute()
WebUI.WaitForElementNotClickable()
WebUI.WaitForElementNotHasAttribute()
WebUI.WaitForElementNotPresent()
WebUI.WaitForElementNotVisible()
WebUI.WaitForElementPresent()
WebUI.WaitForElementVisible()

After that, you could still add a WebUI.delay() if needed.


text:
Q: Chrome Media Query w/ Scrollbars Change Chrome used to improperly exclude the scroll bar in its media queries. This means that with 1000px of visible space and a 17px scroll bar, other browsers would report 1017px as a width so far as Media Query is concerned, but webkit browsers (such as Chrome and Safari) did not do this.
These browsers could hit a specific size where a scroll bar would appear in one resolution, then change resolutions to another where it would appear, then it would go back to when it didn't... the solution caused an ugly blank space to appear where the scroll bar should, but it did not. It came out looking like a glitch, and the DOM resize events did not fire properly so it was not something you could react to properly in JS.
However, now in Chrome 29, this appears to have changed. Now they are going off of how the specification works and including the scroll bar in their media query calculations... just like Firefox and Internet Explorer (and how the specification says they should have all along). This fixes the bugs, but causes another problem in that the JS to try to detect the Chrome/Safari issue now will have false positives, because it is not a concern with newer versions of Chrome and I assume eventually Opera and Safari as well.
In light of all of this, I cannot find any information anywhere on when this was fixed in either Chrome or Webkit. I hate having to resort to browser version testing in my JS to work around these flaws, but I am just guessing blindly on Chrome 29+ for the moment as a temporary patch and would love an authoritative answer... I have tested in Safari 6.0.5, but the old method is still being used...
Does anybody know in what version of Chrome and/or Webkit this was fixed?

A: Chrome is no longer using the webkit engine as of Chrome v. 28 it now uses the Blink Rendering Engine. So no need to be detecting this for chrome unless you need it for previous versions.
For more on Blink: Blink Documnetation
For more on the Release: Next Web Article on Webkit/Blink Switch


text:
Q: How do class methods affect instance variables in Python? I've read throughly many posts here on the difference between class methods and instance methods. I understand them conceptually, but now I'm trying to figure out the more subtle nuances. In the example below, if I call User.createUser('xyz'), where does userId get stored? does it go to (*) below, i.e. on the instance? Or would it be as if I inserted userId = None where I have the comment # placeholder and the userId passed in from User.createUser('xyz') then assigns the class variable userId with 'xyz'?
class User():

    # placeholder

    def __init__(self, userId):
        self.userId = userId # (*)

    @classmethod
    def createUser(cls, userId):
        if not isValid(userId): # isValid may or may not be part of the class
            return False
        else:
            return cls(userId)

    # ... other methods

A: Your classmethod createUser returns a new instance of the User object.  The parameter passed to it is stored as an attribute on this new User instance.

A: The userId parameter is stored in the __init__ method.
The call to cls(userId) is equivalent to a call to User(userId)

A: In your case, neither. The return cls(userId) returns a new object*, and the userId is assigned to the self of the new object. So, it's neither a class nor an instance variable, it's an instance variable of another object.


text:
Q: Showing convolution improves smoothness I want to show that for the $2\pi$-peroidc, integrable function, the convolution operation improves the smoothness, the convolution for my cases is only defined over the complex unit circle, that is
$$ (f *g)(x) = \frac{1}{2\pi}\int_{-\pi}^{\pi} f(\tau)g(x - \tau)\,d\tau$$
Now, suppose that $f,g$ are both $2\pi$-peroidc, integrable function defined over the complex unit circle, with $f \in C^{m}$, and $g \in C^{n}$. Let $h(x) = (f *g)(x)$, I want to show that $h \in C^{m+n}$. My approach is simple, begin with a bases cases that $f \in C^{1}$, and $g \in C^{0}$. Then, using the commutativity of convolution, we have
$$
\begin{align}
h'(x) = (f *g)'(x) = (g *f)'(x) &= \frac{d}{dx} \bigg[\frac{1}{2\pi}\int_{-\pi}^{\pi} g(\tau) f(x - \tau)\,d\tau \bigg]\\
&= \frac{1}{2\pi}\int_{-\pi}^{\pi} g(\tau) \frac{d}{dx}f(x - \tau)\,d\tau\\
&= \frac{1}{2\pi}\int_{-\pi}^{\pi} g(\tau) f'(x - \tau)\frac{d}{dx}(x - \tau)\,d\tau\\
&= \frac{1}{2\pi}\int_{-\pi}^{\pi} g(\tau) f'(x - \tau)\,d\tau
\end{align}
$$Since differentiation is over $x$, the dummy variable $\tau$ inside the integral is not touched, and $f$ and $g$ are always interchangeable. So, the first order derivative for $h(x)$ exist.
Then, suing the induction to extend to $f \in C^{m}$, and $g \in C^{n}$ cases, would this be vaild approach? All my concern here is the well-definedness of the derivative of the convolution. I direct give the derivative of the convolution but do not show that it is well defined, would this be a problem? Thanks for any help.


text:
Q: Migration error when using jSON field on MariaDB After trying to add a new jSon column to my Users table, I am getting an error related to field size. I blame MariaDB because they can't see the future, but is there a way to override this error without changing my field type to BLOB or TEXT?
Here is my up method in the migration:
public function up(){
  Schema::table( 'users', function( Blueprint $table ){
    $table->json( 'options' )->nullable();
  } );
}

This is the error I get:
In Connection.php line 669:

  SQLSTATE[42000]: Syntax error or access violation: 1118 Row size too large. The maximum row siz
  e for the used table type, not counting BLOBs, is 8126. This includes storage overhead, check t
  he manual. You have to change some columns to TEXT or BLOBs (SQL: alter table `users` add `opti
  ons` json null)

In PDOStatement.php line 129:

  SQLSTATE[42000]: Syntax error or access violation: 1118 Row size too large. The maximum row siz
  e for the used table type, not counting BLOBs, is 8126. This includes storage overhead, check t
  he manual. You have to change some columns to TEXT or BLOBs

In PDOStatement.php line 127:

  SQLSTATE[42000]: Syntax error or access violation: 1118 Row size too large. The maximum row siz
  e for the used table type, not counting BLOBs, is 8126. This includes storage overhead, check t
  he manual. You have to change some columns to TEXT or BLOBs


text:
Q: How much of Metropolis is Toronto? Joe Shuster was the co-creator and original artist of Superman.  Shuster was born and raised in Toronto, where he was a paper boy for The Toronto Star.  (For those of you who know Toronto well, he lived in and around Kensington Market.)

In the original version Superman's mild-mannered alter ego, Clark Kent, worked for The Daily Star, which was patterned after The Toronto Star. The newspaper's name in the strip was changed later to The Daily Planet.

(Source)
To clarify the preceding passage, I should add that The Toronto Star  was The Toronto Daily Star  when Shuster was growing up.

Superman co-creator Joe Shuster modeled the look of Metropolis after his home town of Toronto, Ontario, Canada (though Metropolis was never depicted as a Canadian city).

(Source)
Other than the Daily Planet, are there any other specific Toronto landmarks that are seen or referenced, either in name or appearance, within Metropolis in the comics?

A: TL;DR:  Not much.

Metropolis was modeled on Toronto and Cleveland, but bears little resemblance to either. In fact, Shuster's Metropolis looks like no city on earth - it is just a vague art-deco shape in the background.

Shuster did talk about Toronto:

"Cleveland was not nearly as metropolitan as Toronto was, and it was not as big or as beautiful. Whatever buildings I saw in Toronto remained in my mind and came out in the form of Metropolis. As I realized later on, Toronto is a much more beautiful city than Cleveland ever was." Pausing for a moment, Shuster chuckles and adds, "I guess I don't have to worry about saying that now."

But compare his drawings to the actual cities of Cleveland and Toronto at that time:

Cleveland in the 1930's

Toronto in the 1930's
And you'd be hard pressed to see any similarities to Shuster's Metropolis.
The one clear connection to Toronto was quickly retconned out of the story, when the "Daily Star" (named after the Toronto Daily Star) became the "Daily Planet".

The Toronto Daily Star

The Daily Star

First appearance of The Daily Planet, in a February 26, 1942 Fleischer Superman short

First comic book appearance of The Daily Planet, Superman #19, 1942


text:
Q: jQuery navigation mega menu by click not hover I've got a navigation menu that I would like to have certain links display a sub-menu underneath, here is the general layout http://jsfiddle.net/hcharge/HGtTz/
Before I've used jQuery hoverintent to display the menu beneath, however this time I would like it to display without the hover and by click and to be able to navigate with the keyboard by tabbing.
I'm very new to jQuery and I've tried to get the menu displaying without any luck, is somebody able to point me in the right direction?  I'm sure this is pretty simple, with a display none on the dropdown-inside and then slidedown with a click or something?
The menu also needs to close if you click outside the box or another link.  Thanks very much.

A: Is this for accessibility purposes?
If so try tabindex
http://www.w3schools.com/tags/att_standard_tabindex.asp

A: use tabindex and jquery to bind on focus event than trigger whatever you want
$("li a").focus(function() {
    $(this).parent().find('ul').slideDown(200); // example of targeting nested UL with slide down animation
});

it should work like this
and then use blur event to hide that submenu
$("li a").blur(function() {
        // your code here to hide submenu
    });

to enable click event:
$("li a").click(function() {
   // target all opened submenus and hide them by its class name
   $("ul.active-submenu").slideUp(200).removeClass("active-submenu");
   // adds class to submenu so you can determine easily which is active
   $(this).parent().find('ul').slideToggle(200).toggleClass('active-submenu');
});

A: jsfiddle.net/hcharge/HGtTz
The following link is the solution for above issue
jsfiddle.net/HGtTz/23/


text:
Q: JSON in Python error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I am trying to extract text from a JSON file in python, but I am receiving the following error:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The code I am trying to run:
import json

with open('file.json', encoding="utf-8") as json_file:
    thing = json.load(json_file)
    print(thing['text'])

The JSON file: (a shortened example of what I'm using)
{
  "resources": "https://www.example.com",
  "id": 1,
  "joined": [],
  "text": "Hello.\n The dog sat. \n\n The cat ran",
  "urls": [
    "https://www.example.com",
    "https://www.example.com",
    "https://www.example.com"
  ]
}

I would appreciate any suggestions for how to solve this error. (I've seen a few similar questions, but they seem to deal with API issues. Apologies if I'm missing something!)
(I am new to stack overflow and JSON, so I sincerely apologize if this is not a good question!)

A: I received an error concerning control characters. This was solved with double slashes.
Try this code:
ss = '''
{
  "resources": "https://www.example.com",
  "id": 1,
  "joined": [],
  "text": "Hello.\\n The dog sat. \\n\\n The cat ran",
  "urls": [
    "https://www.example.com",
    "https://www.example.com",
    "https://www.example.com"
  ]
}
'''.strip()

with open('file.json','w') as f: f.write(ss)  # write test file

#####################

import json

with open('file.json', encoding="utf-8") as json_file:
    thing = json.load(json_file)
    print(thing['text'])

Output
Hello.
 The dog sat.

 The cat ran


text:
Q: ref.push().key & ref.child (Type mismatch) I'm having a problem in this tutorial...
https://www.youtube.com/watch?v=I485b7LzYkM
There are three items. An editText, a ratingBar, and a button. When you click on the button the rating is sent to the database. But I'm having issues with "heroId." Under ref.child(heroId) I get the error "Type mismatch: inferred type is String? but String was expected" for heroId. Any ideas?
Here is the code below:
class MainActivity : AppCompatActivity() {

    lateinit var editTextName: EditText
    lateinit var ratingBar: RatingBar
    lateinit var buttonSave: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        editTextName = findViewById(R.id.editTextName)
        ratingBar = findViewById(R.id.ratingBar)
        buttonSave = findViewById(R.id.ratingBar)

        buttonSave.setOnClickListener {
            saveHero()
        }
    }

    private fun saveHero() {
        val name = editTextName.text.toString().trim()

        if (name.isEmpty()) {
            editTextName.error = "Please enter a name"
            return
        }

        val ref = FirebaseDatabase.getInstance().getReference("heroes")
        val heroId = ref.push().key

        val hero = Hero(heroId, name, ratingBar.numStars)

        ref.child(heroId).setValue(hero).addOnCanceledListener {
            Toast.makeText(applicationContext, "Hero saved", Toast.LENGTH_LONG).show()
        }

    }
}

Thank you!

A: Your val heroId = ref.push().key snippet uses the DatabaseReference.getKey() method, which returns a String? - so an optional string.
The DatabaseReference.child() method requires a String - so a non-optional string.
So you'll need to ensure the optional string really has a value. Since you generate it client-side, that is guaranteed by the code already, so you can hard-cast it:
val heroId = ref.push().key!!

To learn all about dealing with these optional types and null-safety, I recommend spending some time in the Kotlin documentation on null safety.


text:
Q: Group multi dimensional array using crossfilter I want to make multi level array filtering using crossfilter ans d3.
App.js looks like below.
    var region = [{
            "code" : "New-York",
            "id"   : 1,
            "centre" : [{
                "name": "xxx",
            "id" : 11
                },{
                "name": "yyy",
                "id" : 12,
                },{
                "name": "zzz",
                "id" : 13,
                }]
            },{
            "code" : "Florida",
            "id"   : 2,
            "centre" : [{
                "name": "aaa",
                "id" : 21
                },{
                "name": "bbb",
                "id" : 23,
                }]
            },{
            "code" : "Tennessee",
            "id"   : 3,
            "centre" : [{
                "name": "ccc",
                "id" : 31
                }, {
                "name": "ddd",
                "id" : 32,
                }, {
                "name": "eee",
                "id" : 33,
                }, {
                "name": "fff",
                "id" : 34,
                }]
            },{
            "code" : "Jersey",
            "id"   : 3,
            "centre" : [{
                "name": "ccc",
                "id" : 31
                }, {
                "name": "ddd",
                "id" : 32,
                }, {
                "name": "eee",
                "id" : 33,
                }, {
                "name": "fff",
                "id" : 34,
                }]
            }
        ];

$(document).ready(function() {

    var i, allCodeDimensionGroups, currentSet, currentSetSum;
        regionCrossfilter = crossfilter(region);
        regionsCount = regionCrossfilter.groupAll().value();

        codeDimension = regionCrossfilter.dimension(
        function(regiion) {
        //return region.centre[0].id;
        return regiion.code;
        }),

        codeDimensionGroup = codeDimension.group(),
        table = $('#outputTable'),
        header = $('#outputTable > thead > tr'),
        valuesRow = $('#outputTable > tbody > tr');

    function appendRegionData(region, value) {
        //Adds header cell and value beneath it
        header.append('' + region + '	');
        valuesRow.append('' + value + '	')
    }

    appendRegionData('Region', regionsCount);

    allCodeDimensionGroups = codeDimensionGroup.all();
    //ee
    for (i = 0; i < allCodeDimensionGroups.length; i += 1) {
        codeDimension.filter(allCodeDimensionGroups[i].key);
        currentSet = codeDimension.top(Infinity);

        appendRegionData(allCodeDimensionGroups[i].key, currentSet);
    }

    //Reset the filters when you are done
    codeDimension.filterAll();
});

Can we show the results as below in a table.
     New-York       Florida        Jersey
       xxx            aaa            ccc
       yyy            bbb            ddd
       zzz                           eee
                                     fff

How can we do this using crossfilter js and d3 js.
Any help would be accepted.
Thanks in advance.

A: To obtain the specified result you do not require d3.js, just crossfilter.js. For utility, I have also included jQuery in my answer to easily select and append elements.
Considering that you have already downloaded the jquery and crossfilter .js files, this is the HTML markup:
<!DOCTYPE html>

    <title>Crossfilter Output</title>

and here is the 'app.js' file content that will generate your result:
var region = [{
            code : 'New-York',
            id   : 1,
            centre : [{
                name: 'xxx',
                id : 11
                },{
                name: 'yyy',
                id : 12,
                },{
                name: 'zzz',
                id : 13,
                }]
            },{
            code : 'Florida',
            id   : 2,
            centre : [{
                name: 'aaa',
                id : 21
                },{
                name: 'bbb',
                id : 23,
                }]
            },{
            code : 'Tennessee',
            id   : 3,
            centre : [{
                name: 'ccc',
                id : 31
                }, {
                name: 'ddd',
                id : 32,
                }, {
                name: 'eee',
                id : 33,
                }, {
                name: 'fff',
                id : 34,
                }]
            }
        ];

$(document).ready(function() {
    var i, allCodeDimensionGroups, currentSet, currentSetSum
        regionCrossfilter = crossfilter(region);
        regionsCount = regionCrossfilter.groupAll().value();
        codeDimension = regionCrossfilter.dimension(
        function(region) {
            return region.code;
        }),
        codeDimensionGroup = codeDimension.group(),
        table = $('#outputTable'),
        header = $('#outputTable > thead > tr'),
        valuesRow = $('#outputTable > tbody > tr');
    function appendRegionData(region, value) {
        //Adds header cell and value beneath it
        header.append('' + region + '	');
        valuesRow.append('' + value + '	')
    }

    appendRegionData('Region', regionsCount);
    allCodeDimensionGroups = codeDimensionGroup.all();
    for (i = 0; i < allCodeDimensionGroups.length; i += 1) {
        codeDimension.filter(allCodeDimensionGroups[i].key);
        currentSet = codeDimension.top(Infinity);
        currentSetSum = 0;
        for(j = 0; j < currentSet.length; j += 1) {
            currentSetSum += currentSet[j].centre.length;
        }
        appendRegionData(allCodeDimensionGroups[i].key, currentSetSum);
    }
    //Reset the filters when you are done
    codeDimension.filterAll();
});


text:
Q: xdotool: what are "class" and "classname" for a window? In light of https://unix.stackexchange.com/a/254854/674 and https://unix.stackexchange.com/questions/458895/how-can-i-bring-a-background-gui-job-to-the-front-of-my-desktop, there is an example from manpage of xdotool
# Activate google-chrome when you move the mouse to the bottom-left corner:
xdotool behave_screen_edge bottom-left search --class google-chrome windowactivate

The manpage says

--class Match against the window class.
--classname Match against the window classname.

What are "class" and "classname"?
What possible values do they have?
How can I find out the class and classname of a window?
Thanks.

A: Under X11 windows have  XWindowdAttributes structure and XClassHint structures  properties from which applications get information about windows. Specifically the last one is responsible for the WM_CLASS property, two comma-separated strings, which can be seen easily via xprop command. For instance, Chrome has
WM_CLASS(STRING) = "google-chrome", "Google-chrome"

These two are documented as:

*

*A string that names the particular instance of the application to which the client that owns this window belongs. ...

*A string that names the general class of applications to which the client that owns this window belongs. Resources that are specified by
  class apply to all applications that have the same class name....

Thus, for example Hangouts extension for Chrome, has same class name, but different instance name:
$ xprop | grep 'CLASS'
WM_CLASS(STRING) = "crx_nckgahadagoaajjgafhacjanaoiihapd", "Google-chrome"

This allows tools such as xdotool search all windows of particular application type, or specific window instance. For instance, this also can be useful property for something like docks that group windows under the same icon of an application.
In particular for xdotool, classname corresponds with the first string, and class corresponds the second string. In my example with Chrome and Hangouts apps:
$ xdotool search -classname crx_nckgahadagoaajjgafhacjanaoiihapd
96469129

$ xdotool search -class Google-chrome
96469069
109051905
109051907
96468993
96469129
109051912
109051924

This also can be apparent from looking at the source code. Let's focus on classname for example. In the cmd_search.c we have a search struct built up, which has a search mask property(lines 171 to 173).
This gets passed to xdo_search_windows function defined in xdo_search.c , which in turn calls check_window_match, that in turn goes to  _xdo_match_window_classname, which finally ends up retrieving both structures mentioned in the beginning of this answer with the standard Xlib functions XGetWindowAttributes and XGetClassHint.

Side note: Gtk apps apparently always create a small parent window with a child window, which means you may get confusing results when searching for a specific window.


text:
Q: Лучшая программа для модификации http траффика на лету? Недавно мне была поставлена лёгкая на первый взгляд задача.
Дано: JAR-приложение без исходников, которое падает при запуске с ошибкой из-за того что автор забросил проект.
Задача: Подменить один файл "на лету", который запрашивает софт из сети, и таким образом оживить ее.
Решение: Берем Fiddler,Charles и кормим ее недостающим файлом из моего сайта, при этом она обращается по адресу: avtorpage.com/dl/update.lst, а файл отдается с адреса mypage.com/dl/update.lst, но вся проблема в том, что общается она посредством Socket http соединения, из-за этого две вышеуказанных тулзы не видят ее.
Вопрос: Что же делать ?
Декомпилировать не вариант, накрыто Зельдой и не хочу нарушать права разработчика.


text:
Q: Angular - Como reutilizar informações de um componente em outro para realizar condição? Eu tenho um menu no meu componente html da seguinte forma: (MenuComponent.html)

<aop-drogaria-rosario></aop-drogaria-rosario>

 <aop-drogaria-sao-paulo></aop-drogaria-sao-paulo>

<aop-drogaria-santa-marta></aop-drogaria-santa-marta>

  <aop-drogaria-demais></aop-drogaria-demais>

E no TypeScript desse componete,(MenuComponent.ts) tenho funções que ativam esse menu e atribuem seus respectivos ID para a apresentação na tela:
public items: MenuItem[];
public itemAtivado: MenuItem;

ngOnInit() {

this.items = [
  {label: 'ROSARIO',  id: 'ROSARIO'},
  {label: 'SAO PAULO',  id: 'SP'},
  {label: 'SANTA MARTA', id: 'SM'},
  {label: 'DEMAIS', id: 'DEMAIS'},
];
}

ativarMenu()
this.itemAtivado = this.menu['activeItem'];

 }
menuAtivado() {
return this.itemAtivado != null ? this.itemAtivado.id : 'ROSARIO';

}
O menu funciona fielmente. Quando clico na aba de Drogaria Rosario por exemplo, é exibido o componente  (DrogariaRosario.component.html) e se eu clicar na aba de SP é exibido o  (DrogariaSaoPaulo.component.html). O que acontece é que todos os componentes tem dentro deles embutido a reutilização de um outro componente chamado Drogarias  (Drogarias.component.html). Dentro dele há um html que organiza todos esses componentes. Ou seja se eu for em qualquer um dos componentes de remedios, dentro deles terá um . Que os leva até o seguinte código html reutilizado para todas as drogarias:

   Nome do Remédio:{{remedio.nome}}

   Data de Fabricação:{{remedio.data}}

   Descrição do Remédio:{{remedio.descricao}}

  Informação nutricional:{{remedio.informacaoNutricional}}

O que preciso saber é como limitar algumas informações para cada menu que for clicado, por exemplo. Se eu clicar na drogaria rosário não quero que exiba a informação nutricionais dos remédios. Eu teria que fazer um *ngIF, mas não sei como trazer essa informação do componente do menu. Como saber qual componente está sendo clicado para restringir nesse *ngIf?

A: Uma ideia seria ter dentro do componente drogarias um @Input() pra cada atributo que você quer exibir, assim você consegue colocar um *ngIf para esconder quando não for usar, não sei como está seu componente drogaria, mas ficaria mais ou menos assim pelo que eu entendi da arquitetura que vc está usando, no drogaria.component.ts
@Input() exibeNome: boolean;
@Input() exibeData: boolean;
@Input() exibeDesc: boolean;
@Input() exibeInfo: boolean;

O @Input vem de '@angular/core';
Ai dentro do drogaria-demais.component.html e nos outros componentes que chama o drogaria.component.html vc coloca assim:
<aop-drogaria [exibeNome]="True" [exibeData]="False" [exibeDesc]="True" [exibeInfo]="False"></aop-drogaria>

e finalmente no seu código html do drogaria.component.html vc coloca assim:

        Nome do Remédio:{{remedio.nome}}

        Data de Fabricação:{{remedio.data}}

        Descrição do Remédio:{{remedio.descricao}}

        Informação nutricional:{{remedio.informacaoNutricional}}


text:
Q: How can I quickly disable standby lid off in Ubuntu Unity 16.04? What is the quickest way to quickly disable the standby feature when closing the lid? I very much like this behaviour but especially when playing music, I would like to close my lid without switching my machine into standby.
However, I do not want to permanently disable this feature but just temporarily turn it off until I finished listening to music, for example.
Maybe there is an indicator similar to Caffeine?

A: Another option would be changing from "Suspend" to "Do Nothing" in Ubuntu Settings - Power:

PS: This doesn't provide an indicator in the notifications area but is simpler than creating a script for new users.
PPS: In this screen snapshot the UPS is for Cable Modem + Sony Android TV, not the laptop which has battery... HAHA.

A: The script below will toggle the close-lid action between "nothing" and "suspend":
#!/usr/bin/env python3
import subprocess

key = ["org.gnome.settings-daemon.plugins.power",
       "lid-close-ac-action", "lid-close-battery-action"]

currstate = subprocess.check_output(["gsettings", "get",
    key[0], key[1]]).decode("utf-8").strip()

if currstate == "'suspend'":
    command = "'nothing'"
    subprocess.Popen(["notify-send", "Lid closes with no action"])
else:
    command = "'suspend'"
    subprocess.Popen(["notify-send", "Suspend will be activated when lid closes"])

for k in [key[1], key[2]]:
    subprocess.Popen(["gsettings", "set", key[0], k, command])

...And notify what is the currently set state:

How to use
Simply:

*

*Copy the script into an empty file, save it as toggle_lid.py

*Add it to a shortcut key: choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the command:
python3 /path/to/toggle_lid.py

Explanation
The current state of the close-lid action setting can be retrieved by the command(s)
gsettings get org.gnome.settings-daemon.plugins.power lid-close-ac-action

(on power), and
gsettings get org.gnome.settings-daemon.plugins.power lid-close-battery-action

(on battery)
The script reads the current state, and sets the opposite ('suspend'/'nothing') with the command:
gsettings get org.gnome.settings-daemon.plugins.power lid-close-ac-action '<action>'

Optionally (additionally)
Optionally/additionally, you can run an indicator as a detector to show what is the current state of the lid- setting. It will show:

...in the panel, if the suspend will be prevented on closing the lid, It will show a grey one if not.

The script
#!/usr/bin/env python3
import subprocess
import os
import time
import signal
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, AppIndicator3, GObject
from threading import Thread

key = ["org.gnome.settings-daemon.plugins.power",
       "lid-close-ac-action", "lid-close-battery-action"]

currpath = os.path.dirname(os.path.realpath(__file__))

def runs():
    # The test True/False
    return subprocess.check_output([
        "gsettings", "get", key[0], key[1]
        ]).decode("utf-8").strip() == "'suspend'"

class Indicator():
    def __init__(self):
        self.app = 'show_proc'
        iconpath = currpath+"/nocolor.png"
        self.indicator = AppIndicator3.Indicator.new(
            self.app, iconpath,
            AppIndicator3.IndicatorCategory.OTHER)
        self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
        self.indicator.set_menu(self.create_menu())
        self.update = Thread(target=self.check_runs)
        # daemonize the thread to make the indicator stopable
        self.update.setDaemon(True)
        self.update.start()

    def check_runs(self):
        # the function (thread), checking for the process to run
        runs1 = None
        while True:
            time.sleep(1)
            runs2 = runs()
            # if there is a change in state, update the icon
            if runs1 != runs2:
                if runs2:
                    # set the icon to show
                    GObject.idle_add(
                        self.indicator.set_icon,
                        currpath+"/nocolor.png",
                        priority=GObject.PRIORITY_DEFAULT
                        )
                else:
                    # set the icon to hide
                    GObject.idle_add(
                        self.indicator.set_icon,
                        currpath+"/green.png",
                        priority=GObject.PRIORITY_DEFAULT
                        )
            runs1 = runs2

    def create_menu(self):
        menu = Gtk.Menu()
        # quit
        item_quit = Gtk.MenuItem('Quit')
        item_quit.connect('activate', self.stop)
        menu.append(item_quit)
        menu.show_all()
        return menu

    def stop(self, source):
        Gtk.main_quit()

Indicator()
GObject.threads_init()
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()

How to use

*

*Copy the script above into an empty file, save it as show_state.py

*Copy both icons below (right click -> save as), and save them in one and the same directory as show_proc.py, and exactly named as indicated below
green.png

nocolor.png

*Now test- run show_state.py by the command:
python3 /path/to/show_state.py

and change the current state by pressing the shortcut you set the first section of this answer.

*If all works fine, add the following to startup applications:
/bin/bash -c "sleep 15 && python3 /path/to/show_state.py"

Note
The detector- indicator above is an edited version of this answer. Simply by changing the test in the function runs() (and optionally the according panel icons), you can use it to show the state of anything that is True or False.


text:
Q: How to animate view to slide down and push down everything below it? So I have looked into how to animate fade and drop down/slide up animations of Views using this thread, however it didn't quite work as expected. To begin with, here is the code I use for the animating:
public void toggleAdvancedVisibility(View text) { //text is a clickable textview thats acts as a toggle
    int dur = 1000;
    final View advView = findViewById(R.id.enc_advanced);
    if(advView.getVisibility() == View.GONE && animationDone) {
        advView.setVisibility(View.VISIBLE);
        advView.setAlpha(0.0f);

        //animate fade + drop down
        advView.animate()
                .setDuration(dur)
                .translationY(advView.getHeight())
                .alpha(1.0f)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        animationDone = true;
                    }
                });
        animationDone=false;
    }
    else if(advView.getVisibility() == View.VISIBLE && animationDone) {
        //animate fade + slide up
        advView.animate()
                .setDuration(dur)
                .translationY(0)
                .alpha(0.0f)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        advView.setVisibility(View.GONE);
                        animationDone = true;
                    }
                });
        animationDone = false;
    }
}

As I said, while there was animation, it didn't act anywhere near as expected.
Problem #1
The view is almost pushed out of visibility. I believe that this is due to the line .translationY(advView.getHeight()) as if I set the location of the view before the animation to advView.setTranslationY(-advView.getHeight()) and then animate .translationY(0) it goes to where it is supposed to.
The obvious problem with this is that while the view is animating, the view "collides" with the view above it before it is done. So how do I properly get this to slide down/up without running into the view above it?
Problem #2
The animation doesn't exactly "push" the view down, which is what I expected. What I mean by this is that the view being animated also has a view below it. I expected the view below it to be pushed down with the animated view. While I haven't tried it yet, I assume this can be simulated by setting the same animation to the view below it, but is there another way of doing it?
I am very new to this animation stuff and manipulating Views like this so any help is appreciated.

A: I made you a short example and I see it pushes down the rest of the view.
xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.teststuff.MainActivity"
android:orientation="vertical">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/b1"
    android:text="show"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tv1"
    android:text="Hello World!"
    android:visibility="gone"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!!!!"/>

and here is the .java:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv1 = (TextView) findViewById(R.id.tv1);
    tv2 = (TextView) findViewById(R.id.tv2);
    b1 = (Button) findViewById(R.id.b1);

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (tv1.isShown()){
                tv1.startAnimation(slideInAnimation(view));
                tv1.setVisibility(View.GONE);
            }
            else {
                tv1.startAnimation(slideOutAnimation(view));
                tv1.setVisibility(View.VISIBLE);
            }
        }
    });

}

private TranslateAnimation slideOutAnimation(View view){
    TranslateAnimation animate = new TranslateAnimation(0,0,-view.getHeight(),0);
    animate.setDuration(500);
    animate.setFillAfter(false);
    return animate;
}
private TranslateAnimation slideInAnimation(View view){
    TranslateAnimation animate = new TranslateAnimation(0,0,0,-view.getHeight());
    animate.setDuration(500);
    animate.setFillAfter(true);
    return animate;
}

It works fine for me.


text:
Q: I have trouble working with pyaudio . I can't record voice with this lib a few days ago i tried to install pyaudio in pycharm by pip install pyaudio and i have a problem with visual c++ tool because i used old version of this and somebody told my to instal pipwin (pip install pipwin) and install pyaudio with pipwin (pipwin install pyaudio) . that was ok. i can play .WAV file but i can't record the audio
import pyaudio
import wave

chunk = 1024  # Record in chunks of 1024 samples
sample_format = pyaudio.paInt16  # 16 bits per sample
channels = 2
fs = 44100  # Record at 44100 samples per second
seconds = 3
filename = "output.wav"

p = pyaudio.PyAudio()  # Create an interface to PortAudio

print('Recording')

stream = p.open(format=sample_format,
                channels=channels,
                rate=fs,
                frames_per_buffer=chunk,
                input=True )                #line 19 error

frames = []  # Initialize array to store frames

# Store data in chunks for 3 seconds
for i in range(0, int(fs / chunk * seconds)):
    data = stream.read(chunk)
    frames.append(data)

# Stop and close the stream
stream.stop_stream()
stream.close()
# Terminate the PortAudio interface
p.terminate()

print('Finished recording')

# Save the recorded data as a WAV file
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()

and my errors are
  File "F:/record_voice_pyaudio/RecordVoice.py", line 19, in <module>
    input=True)
  File "C:\Users\Ardin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "C:\Users\Ardin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
OSError: [Errno -9998] Invalid number of channels

A: problem solved . i used a microphone without any speaker, actually my mic have just one channel so i change it to
channels = 1

and problem solved.
if anybody have same problem first check the microphone that be enable for your compiler and second check the microphone ability


text:
Q: Load WMA file to iPod I have a lot of WMA files and I am trying to load them into my iPod. However it fails with the error:

Ecstasy of Gold.wma was not copied to
  this iPod because it cannot be played
  in this iPod

UPDATE: I tried converting wma files to mp3 with Audacity to see if that would work. However, the conversion itself failed. The wma file was about 17 Mb, whereas the mp3 file was only about 6 Kb.
UPDATE2: None of the wma files are protected. I checked this by enabling the field Protected in Windows Explorer.
UPDATE3: The codec as retrieved by GSpot is as follows

0x0163 (Windows Media Audio 9 Lossless)
  0x01:44100Hz  663 kb/s tot (2 chnls)

A: Convert them using iTunes into either .aac or, preferably, .mp3. This should solve your problem.

A: iTunes will convert some WMA files automatically.  You'll need to drag and drop them on to iTunes and not directly on to the iPod (although I'm guessing a little here).  If they're protected - i.e. DRM'd - then iTunes won't be able to convert then.
If you're running on Windows make sure you have a recent version of Windows Media Player installed for the WMA codecs.  If you're running on a Mac apparently having flip4mac will add WMV support to QuickTime allowing iTunes to do the conversion.

A: I downloaded MediaCoder and converted all of the WMA files to MP3 files. After coversion to MP3, I was able to drag-drop them into iTunes and it worked.
I was able to pull this from this Super User Question
However, I am still not able to understand why iTunes was not able to get the wma files as such. Why was the conversion to MP3 needed in the first place?

A: Part of the issue is that there is no such thing as a WMA file.  A WMA file is a container...  You may have OGG encoded files, or some other codec that itunes doesn't understand there...
Yes iTunes maybe able to play the file, but if the iPod doesn't natively recognize the audio format/codec, it won't be able to play it.  iTunes is programmed to detect what the ipod can and can't play...
What codec's are the files in question?

Try converting through iTunes, because WMA doesn't appear to be supported...  Evidently the WMA support I've read about is due to being converted through itunes...

Compatible codecs
iPod can play songs encoded with these codecs:

*

*MP3 (from 32 Kbps to 320 Kbps)

*MP3 Variable Bit Rate (VBR)

*AIFF *

*WAV (with no compression)

  The following require iPod software 1.3 or later:

*

*M4A AAC [*]

*M4P AAC (Protected) [*]

*M4B AAC (iTunes Store Spoken Word files) [*]

  The following require iPod software 2.2 or later or iPod mini 1.1 or later:

*

*Apple Lossless Encoder

  [*]Requires iTunes 4 or iTunes 4 for Windows. AAC files also require the most
   recent update to the iPod software.
Compatible sample rates
iPod can play songs with the these sample rates, and with all compatible codecs:

*

*8 kHz

*11.025 kHz

*16 kHz

*22.050 kHz

*32 kHz

*44.1 kHz

  Audible Spoken Word files
iPod Software 1.2 and later can play Audible spoken word files in formats 2,
  3, and 4.  These files have the filename extension, ".aa".
iTunes 4 and iTunes 4 for Windows work with Audible spoken word files.
Incompatible codecs
iPod cannot play songs that use these audio formats:

*

*snd

*QuickTime

*MP2

*MP1

*WAV with compression

*WMA and WMA Protected

*any other format not in the Compatible codecs list


text:
Q: BATCH SCRIPT TO PRINT NUMBERS IN WORD FILE Is there a way to print numbers from 1 to 100
i.e, first page print 1.... second page print 2 at the center in a word file
so basically there will be 100 pages with respective numbers on the center of the sheet
Any possible methods

A: Say you have a word file on your desktop called "Numbers.txt" with numbers 1 to 10, you would do:
@echo off
type "C:/Users/%username%/Desktop/Numbers.txt"
pause >nul

this would print out all the contents of that .txt file.


text:
Q: Setting up AWS-SDK (boto) on a Mac for PyCharm I'm new to Python and PyCharm, but have used a Mac and AWS for a number of years.  I have written a few simple Python scripts on my Mac using PyCharm CE and these also work when ported to my windows servers.
What I'm unsure is how to configure / import the boto-2.29.1 library so its available in PyCharm. I have downloaded and extracted to my home folder and also add to my PATH. I see references to PYTHONPATH but can see where to update this.


text:
Q: Laravel page refresh with out clicking refresh button in browser I'm doing a project in Laravel 5.1.I am  running the local development server through the command,
php artisan serve
After that i have done some changes in  sublime text editor, I get the desired results only after clicking the refresh button in my browser.But  i need to refresh the page when some  edits is in performed in my code instead of clicking the refresh button in the browser.
Is there any feature/plugin for that?

A: Simply just do the following:
Run on our terminal:
npm install

to have your node dependencies installed elixir,gulp...etc
then open your gulpfile.js file and add the following:
elixir(function (mix) {

    mix.browserSync({ proxy: 'foo.bar'});

});

then run in your terminal
gulp watch

Please note that you don't need the proxy leave it blank if you want so, only if you got your homestead or your development env with local domain and you wanted to use your domain instead of serve then replace the dummy domain with yours.
btw: the output of gulp watch won't help you with IPs generated therefore just use the port provided with it and not the IP, like so: foo.bar:3000 and foo.bar:3001.
Plus: if you needed to access you project from other PC on LAN just add a port forwarding from within Virtualbox and forward 3000 to 3000

And for sure you won't do it like this every time you destroy/delete your vagrant/homestead! you've to add this port forwarding into your homsetead configurations that reside within ~/.homestead/Homestead.yaml

A: Finally i found LiveReload.It is not currently updated in documentation to work with Sublime Text 3.But now they rewrote the plugin for ST3.
https://github.com/dz0ny/LiveReload-sublimetext2/tree/devel
Linux
cd ~/.config/sublime-text-3/Packages
rm -rf LiveReload
git clone -b devel https://github.com/dz0ny/LiveReload-sublimetext2.git LiveReload


text:
Q: "NameError: uninitialized constant" when trying to include a concern in a Rails model I am trying to include a Concern inside a Rails ApplicationRecord object.
Here is the model file: /app/models/item.rb
class Item < ApplicationRecord
  include Items::Validating
end

Here is the concern file: /app/models/concerns/items/validating.rb
module Items
  module Validating

    extend ActiveSupport::Concern
    included do
      before_create :set_defaults
      validates :status, presence: true
      validates :user_id, presence: true
      validates :day, presence: true
    end

    def set_defaults
      self.status ||= 'active'
      self.day ||= Date.today
    end

  end
end

When I try to run tests, I get the following error:
$ rails t

Error:
SessionsControllerTest#test_should_destroy_session:
NameError: uninitialized constant Item::Items
    app/models/item.rb:3:in `<class:Item>'
    app/models/item.rb:1:in `<main>'

It's weird, because I'm including concerns on the User model and it's working completely normally. I can't figure out what's different here.

Update: there are no errors when running the server or console, it is only when running tests. Here is the SessionsControllerTest file:
require 'test_helper'

class SessionsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @session = sessions(:one)
  end

  test "should fail to create session because of no email" do
    assert_difference('Session.count', 0) do
      post sessions_url, params: { email: 'no-email-found@no-email.com', password: 'password_hashed' }
    end

    assert_redirected_to login_url
  end

  test "should fail to create session because of no password" do
    assert_difference('Session.count', 0) do
      post sessions_url, params: { email: 'jerry@vandalay.com', password: 'password_hashed_wrong' }
    end

    assert_redirected_to login_url
  end

  test "should create session" do
    email = 'jerry@vandalay.com'
    assert_difference('Session.count') do
      post sessions_url, params: { email: email, password: 'password_hashed' }
    end

    user = User.first_with_email(email)
    assert_redirected_to dashboard_url
  end

  test "should destroy session" do
    get logout_url

    assert_redirected_to login_url
  end

end


text:
Q: Move existing item to the top of a listview I add items from an array into a ListView like below:
for (int i = 0; i < dataKeyList.Count; i++)
{
  CallTabLv.Items.Add(new { Label = " " + keyArray[i], Value = valueArray[i] });
}

If the keyArray[i] contains an item called CustomerName, how can I move it and its value to the top of the list ?
Edit:
Let say:
string[] arr1 = new string[] { "one", "two", "three" };
string[] arr2 = new string[] { "1", "2", "3" };

for (int i = 0; i < arr1.Length; i++)
{
  listView.Items.Add(new { C1 = arr1[i], C2 = arr2[i] });
}

Output:
Col    Col2
-----------
one     1
two     2
three   3

I want to move "three   3" to the top of the list, so it would be like:
Col    Col2
-----------
three   3
two     2
one     1

Any suggestions?

A: Instead of adding item, You can use [Items.Insert][1] to insert an item in particular position,It can be used To Change position of an existing item in nth index.
ListViewItem item= new ListViewItem("Test");//Define item here;
if(!CallTabLv.Items.Contains(theItem))
 {
    CallTabLv.Items.Insert(0,item);
 }
else
 {
   n = CallTabLv.Items.IndexOf(item);
   CallTabLv.Items.RemoveAt(n);
   CallTabLv.Items.Insert(0, item);
 }


text:
Q: Can I enable dhcp4 on all interfaces globally without knowing the interface names with netplan and networkd? Can I enable DHCP4on all interfaces globally without knowing the interface names with netplan?
I might add any USB connected ethernet NIC, and I just want any of them to get the network config via DHCP4.
I know it works with NetworkManager. But I would rather use the networkd renderer.

A: It is possible to enable wifi on an interface without knowing the exact interface name by using the match syntax:
network:
  version: 2
  renderer: networkd
  ethernets:
    alleths:
      match:
        name: en*
      dhcp4: true

Be sure to avoid any settings that would collide between multiple interfaces (and do not use set-name).


text:
Q: How to use Html color code in Java JPanel So, im trying to use a HTML color code #F5FAE3 in a Java Gui.
I find this Color aColor = Color.decode("#F5FAE3");
But in my JPanel who is:
    JPanel panel = new JPanel();
    Color aColor = Color.decode("#F5FAE3");
    panel.setBackground(new Color(aColor));
    tabbedPane.addTab("Ropa Items", null, panel, null);
    panel.setLayout(null);

When i trying to call aColor i get this error from eclipse IDE:
The constructor Color (Color) is undefine

A: Ok so after many atempts i see my problem, this method to use the HTML color is correct.
Color aColor = Color.decode("#F5FAE3");

You just have to call it in your Panel like: panel.setBackground(aColor);
Insted of: panel.setBackground(new Color(aColor)); by the way the "new color" is create by eclipse for default.


text:
Q: Инициализация значимых типов в C# Читаю книгу, написанную Дж. Рихтером, CLR via C#. К сожалению, в самом начале у меня возникают вопросы. Надеюсь, вы поможете мне разобраться.
Джеффри пишет, что различие между значимыми и ссылочными типами заключается в том, что значимые типы хранятся в стеке потока, в то время как ссылочные типы хранятся по принципу: объект типа лежит в управляемой куче, а ссылка на этот объект находится в стеке. Далее он говорит, что ссылка на объект ссылочного типа возвращается оператором 'new'. А для значимых типов возвращать ссылку не нужно, поэтому можно не писать оператор 'new'.
Дж. Рихтер приводит пример:
struct SomeVal { public Int32 x; } // здесь он объявляет структуру
SomeVal v1 = new SomeVal();

Потом он добавляет, что строку выше можно записать иначе:
SomeVal v1;

Дословно:

Здесь тоже создается IL-код, который помещает экземпляр SomeVal в стек
  потока и обнуляет все его поля.

Подскажите, правда ли это? Ведь мы же не можем обратиться к какому-нибудь полю структуры до тех пор, пока не выполним его инициализацию. А по словам Джеффри выходит, что ничего инициализировать не нужно, ведь все поля сами обнуляются.

A: Это правда. Вся выделенная память просто инициализируется нулями.

Ведь мы же не можем обратиться к какому-нибудь полю структуры до тех пор, пока не выполним его инициализацию.

Это проверка C# компилятора, CLR же не накладывает таких ограничений. Книга Рихтера -- она же в первую очередь о CLR, поэтому он не врет.


text:
Q: Button needs to redirect to the same page at different URL I have two domains:
domain.com and domain.it
Need to add a script/code to the language button so it redirects from all of the pages with English language to the same pages at Italian domain just replacing domain extension such as:
domain.com/text.html to domain.it/text.html
or
domain.com/text1.html to domain.it/text1.html
or
domain.com/text2.html to domain.it/text2.html
and etc.
How to go about it?

A: <button onclick="redirect()">Italian Version</button>

<script>
function redirect()
{
  var currentUrl = window.location.href;
  var newUrl = currentUrl.replace(".com", ".it");
  window.location.replace(newUrl);
}
</script>


text:
Q: Domain of a partial derivative in two variables I have a function $f$ from $R^2$ to $R$ such that $f(x,y) = |xy|$ and I need to find the domain of its partial derivative with respect to x.
So I know that $f_x = y$ when $xy > 0$ and that $f_x = -y$ when $xy>0$
I am struggling figuring out what the domain of $f_x$ is, how should  I reason in this case?

A: Well, given that you've been able to compute $f_x$ in the cases where $xy<0$ and where $xy > 0$, all points $(x,y)$ with $xy \ne 0$ should definitely be in the domain of $f_x$. All that remains to do is understand $f_x$ when $xy = 0$.
There are two cases here: if $xy=0$, then either $x = 0$ or $y = 0$. These cases should be considered separately. Ask yourself: does the derivative exist at these points?
One way to do it is to check whether the limits exist:
$$
   \lim_{h \to 0} \frac{|h \cdot y| - |0 \cdot y|}{h}
$$
(for the $x=0$ case)
$$
    \lim_{h\to 0} \frac{|(x+h) \cdot 0| - |x \cdot 0|}{h}
$$
(for the $y=0$ case).


text:
Q: Appropriate action to take once I've run 30 regressions with same IVs but tweaked DV I run 30 OLS and GLM regressions using the same 9 IV/variables/features, but each with a slightly tweaked DV/target/label. More or less the same same variables are significant each time, but DV-tweaks produces interesting variations regarding which IVs are significant and which are not. I have captured it all in a table, and feel the IVs that keep surfacing time after time (say 25 out of 30 regressions) are better predictors that those that come up only once or twice (as significant). However, I feel I might be accused of fooling myself by running so many regressions. Should I be using to sort of correction or penalty? How is this done?
Note 1: I'm teaching myself statistics, and have rather a few gaps in my knowledge.
Note 2: I use OLS for all the versions of the Target which are continuous. I use a "Negative Binomial" for the others, because it is count data, and overdispersed.
Note 3: I look at the number of protests in municipalities (i.e. count), but then also at protests/capita ; protests*size of protests / capita ; violent protests only / capita (all per municipality), and so on.
Note 4: When the IVs are significant, they are properly so - p values less than 0.001.
Is this unease of mine something to do with "false discovery rates"? Am I way off course?
Speak, oh wise ones.

A: State of play: There seems to be all sorts of corrections for multiple testing for some significance - especially in medical trails, where the efficacy of a drug is tested in slightly different doses, say. Such multiple tests naturally suffer, statistically, in that the more one tests, the more one is confronted by the likelihood of getting false positives. Crudely put - if you test a ineffectual drug enough times, you may find a case where the evidence seems to suggest efficacy.
https://www.ncbi.nlm.nih.gov/pubmed/20589856
To correct for these troubles, there is a whole family of adjustments and penalties - Bonferroni and Benjamini-Hochberg are two of several methods that has come up in my reading over the past week.
Still, until someone can tell me otherwise, I suspect I should maintain that, if one measures Y as a function of A, B, D and C, where one subjects Y to a series of tweaks, running the regression anew every time (and never changing A, B C and D), that, as long as one reports the findings from ALL the regressions, one is operating above board. Hence, if A and B presents p-values of less than 0.001 in 90% of the regressions (with coefficients in the same direction), I should be ok to say that A and B seems to matter, regardless of how one twiddles Y.
My intuition is that this is a precarious move, but I don't have the statistical wherewithal to express the problem more eloquently.


text:
Q: Can you please check "unsupported operand type(s) for -: 'str' and 'int'" Can You please check this code once, why 'unsupported operand type(s) for -: 'str' and 'int'' this error comes in python.
Code :
def missing_char(str, n):
  check = len(str -1)
  if check < n or n < 0:
      return False
  else:
      front = str[:n]
      back = str[n+1:]
      return front + back

A: You put the ) in the wrong place, - 1 should be outside of it:
def missing_char(str, n):
  check = len(str) - 1
  if check < n or n < 0:
      return False
  else:
      front = str[:n]
      back = str[n+1:]
      return front + back


text:
Q: MySQL -- SELECT Command denied to user This is a syntax error i am positive ...  However I am banging my head as to 'why'.  I have searched all "like" questions here on SO and they all (mostly) address a user with wrong permissions .. I assure you this isn't the case.
This  is my Query:
use database;    # I am using workbench .. I use this so I don't have to database.table

SELECT firstname
FROM user, user_role
LEFT JOIN user.uid ON user_role.uid

WHERE user.firstname LIKE '%zak%';

The exact error is
Error Code: 1142. SELECT command denied to user '###'@'##.##.##.##' for table 'uid' 0.197 sec

I am not looking for a TABLE called uid ..  I am looking for the FIELD iud.
I have truncated the statement down to this portion that's causing the error .. There are other fields and other tables .. But I simply can't JOIN.
Is is a logical error with the location of the . for field identification?

A: Try writing it this way:
SELECT firstname
FROM user
LEFT JOIN user_role ON user.uid = user_role.uid
WHERE firstname LIKE '%zak%';

A: You should be using:
SELECT firstname
FROM user, user_role
WHERE user.uid = user_role.uid

If you want all records in the user table regardless of what's in user_role, use
SELECT firstname
FROM user
    LEFT JOIN user_role
ON user.uid = user_role.uid

Using commas to separate tables and using the JOIN keyword is mutually exclusive.  It's either one or the other.  Using commas to separate tables is the same as an inner join.  If you want an outer join (with keywords LEFT or RIGHT), then you'll have to use the format with the JOIN keyword.


text:
Q: How to Manage Permission in Views in SharePoint Server 2016? I am trying to manage different custom created views in my SharePoint Server but couldn't find a way to do it.
Is there anyone to suggest me to do that?

A: Unfortunately, there is no way to manage permissions for Views as OOTB in SharePoint.
But there are some workarounds as the following:

*

*Using a 3rd party tool like info wise that will manage permission for views and column scope.

*Create a page with a list view,

*

*Specify your default view for the desired view that you need to show for a specific user/group,

*Set the permission for a page rather than the list itself. it's not the best solution but it should work.

by the way, you will face an issue where the Views bar will be shown in list view!

To hide the view bar, you could use the below CSS based on the current view bar ID, (use the F12 developer tools to get it)
<style type="text/css">
    #CSRListViewControlDivWPQ5 { display:none; }
</style>

A: You can use target audience feature to target a specific view to a particular group. However this does not hide the list view from appearing the list view drop down. This method can be used to target specific list view content to a target group. You can read more about target audience implementation from here :
TargetAudience
If you want to do it programmatically, you can add JSOM code to the view using CEWP and check if the user is present in the group. If user is not present, redirect him to a different landing page.
Check User's Presence in SPGroup