text:
Q: Why does my Auth-guard stop without completing the observable code? I have an app that I need to use Auth-Guards in order to perform silent-renew calls to allow them through if they are already logged in to the IdentityServer project that is providing my authentication, through any of our other apps. Basically, we want to have a seamless login flow between applications.
Currently, the way I am handling that or trying to anyway is to have an auth guard on every page, and for certain pages that don't require authentication, but could use it to handle roles requests to the server, I would check it, perform a silent renew just in case, and then get the roles if they were authenticated, and still return true if not.
I have broken this into a test auth-guard, removed the roles bits, and tried to figure out the best approach to get this to work.  Currently, there seems to be an issue where the auth guard never completes the process inside the observable if I AM logged in to IdentityServer, but not the client application.
Here is the code:
AuthGuard:
canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): Observable<boolean> | Promise<boolean | UrlTree> | boolean {
    this.spinner.start();//this blocks the screen until it is done, it is what told me that nothing
    //else was getting hit
    return this.oidcAuthService.isUserLoggedIn.pipe(
      delay(1000),
      map(loggedIn => {
        if (!loggedIn) {
          this.oidcAuthService.renewToken().then(user => {
            if (user && !user.expired) {
              return true;
            } else {
              return this.accessDenied();
            }
          }).catch(error => {
            if (error instanceof HttpErrorResponse) {
              if (error.message === 'login_required') {
                return this.accessDenied();
              }
              return this.accessDenied();
            }
          })
        } else {
          return true;
        }
      }),
    );
}

private accessDenied() {
    window.alert("You don't have permission to view this page");

    this.router.navigate(['/']);

    return false;
  }

...
OidcAuthService:
  get isUserLoggedIn() {
    return this._isUserLoggedIn.asObservable();
  }

The issue is that I cannot seem to get the code inside the isUserLogged check to run if the client is not logged in and the Server is.

A: Don't use .pipe() but .subscribe()


text:
Q: How to compute the Surface Dice-Sørensen Coefficient in pytorch? I would like to compute the Surface Dice-Sørensen Coefficient from this  paper (page 19)in python3/pytorch.
I have to point out, that I do not try to implement the simple standard volumetric Dice-Sørensen Coefficient! This one would look as follows in my implementation:
import torch

def volumetric_DSC(M1, M2):
    M1 = M1.view(-1)
    M2 = M2.view(-1)
    dividend = 2 * (M1 * M2).sum()
    divisor = (M1 * M1).sum() + (M2 * M2).sum()
    return dividend / divisor

if __name__ == "__main__":
    m1 = torch.empty(5, 5, 5).uniform_(0, 1)
    m1 = torch.bernoulli(m1)
    m2 = torch.empty(5, 5, 5).uniform_(0, 1)
    m2 = torch.bernoulli(m2)
    loss = volumetric_DSC(m1, m2)
    print("loss = {0}".format(loss))

How can I extend this code to a Surface Dice-Sørensen Coefficient loss?

A: A surface dice implementation was provided here as part of this study. You can use it as an evaluation metric but not as a loss function as it contains non-differentiable ops. You will need to provide a "tolerance" distance i.e. a surface dice of 0.9 means that 90% of surfaces lie within the tolerance (which is better calculated from the data itself, such as the inter-observer variation of the task you are solving)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need Formula assistance Ok, first of all, I have WPS office as my suite, because I cannot afford excel. The formulas are the same. I have found that out for you.
Now here is my problem. I am trying to create a combined leaderboard for survey count and quality assurance contest for my job. I have figured out the formulas for the survey scores and points and they work. Now my question is, I need to make a yes/no function and score it Yes=2 and No=0.  Can you help?
Example(If A1 is the question. Did the Agent provide self-help links, Yes/No. B1 needs to have the score.)

A: It's a simple IF(logical_test, true, false).
In B1, make your test:
=IF(A1="Did the Agent provide self-help links", 2, 0)
That's all there is to it.


text:
Q: Elastic_Grid | "Uncaught TypeError: Cannot read property 'toLowerCase' of undefined" Putting together a personal & project portfolio, and trying to use Vu Khanh Truong's "elastic_grid" jQuery plugin for the actual portfolio. You can view it here.  The problem is that it seems to be causing the following errors on my page:
1) I have a header for the portfolio section, and when I load the page with the plugin running, it makes my header disappear.
2) There're supposed to be filtering buttons that appear based on different tags used to categorize your content, and those don't appear.
3) It loads the preview thumbnail images for the different categories I'm using, but when I click on them, it doesn't load the modal with the full-size images (and descriptions) as it's supposed to.
When I open the console in Chrome, I get this error:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
I tried creating a JSFiddle to post to replicate the problem I'm having, but I guess JSFiddle doesn't let you use certain scripts or something? 'Cuz whenever I try to include all of the scripts I'm using on the page, it gives me MIME type errors in the console.
I've installed & am using the plugin according to the documentation, and I'm not the best at de-constructing Javascript, so I can't figure out why I'm getting these errors. :P If anybody can help, I would appreciate it.
HTML

<!DOCTYPE HTML>

        <title>My Portfolio</title>

        <link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" />
        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
        <link href="elastic/css/elastic_grid.min.css" rel="stylesheet" type="text/css" />
        <link href="mycss.css" rel="stylesheet" type="text/css" />

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                </button>

About Me

Portfolio

Contact Me

About Me

This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text

This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text

Sample Work

Hire Me!

...or you know...just HMU to chat. :P

This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text
This is some text This is some text This is some text This is some text This is some text This is some text

                            Port-FAUX-lio | © Husayn Muhammad 2016

CSS
body {

    background-color: #e1e1e1;
    min-width: 430px !important;

}

/****** TOP NAVIGATION STYLES ******/

.navbar {

    background-color: #f2f2f2 !important; /*#190c03*/
    box-shadow: 0 1px 2px 2px rgba(0, 0, 0, 0.5);

}

.navbar-brand {

    float: left !important;
    height: auto !important;
    transform: translateX(0);
    opacity: 1;
    transition: transform 0.4s, opacity 0.4s;

}

.navbar-brand:hover {

    transform: translateX(25px);
    opacity: 0;
    transition: transform 0.4s, opacity 0.4s;

}

.navbar-right {

    margin-right: 15px !important;

}

.navbar-header {

    position: relative !important;
    float: left !important;
    width: 100% !important;

}

.navbar-toggle {

    /* margin-top: 0px !important; */

}

.navbar ul {

    float: right !important;

}

.nav-pills > li {

    border: 1px solid rgba(0, 0, 0, 0.4);
    background-color: #d8661A;
    border-radius: 5px;
    margin-top: 3.5%;
    margin-right: 5px;
    box-shadow: 0 4px 2px 0 rgba(0, 0, 0, 0.4);
    transform: scale(1, 1);
    transition: box-shadow 0.4s, transform 0.4s;

}

.nav-pills > li:hover {

    transform: translateY(-5px);
    border: 1px solid rgba(0, 0, 0, 0.7);
    transition: transform 0.4s, border 0.4s;

}

.navbar-inverse .navbar-nav > .active > a {

    background-color: transparent !important;

}

.nav-pills > li.active {

    transform: translateY(-5px);
    height: 50%;
    border: 1px solid rgba(0, 0, 0, 0.7);
    color: white !important;
    background-color: #337ab7 !important;
    transition: transform 0.4s, color 0.4s, background-color 0.4s;

}

.nav-pills > li a {

    color: white !important;
    border-bottom: 1px solid transparent !important;
    transition: color 0.4s, border-bottom 0.4s !important;

}

.nav-pills > li.active > a:hover {

    color: white !important;

}

/****** HEADER IMAGE STYLES ******/

.mast {

    width: auto;
    position: relative;
    height: 600px;
    margin-top: 7%;
    margin-bottom: 2%;
    /* box-shadow: 0 4px 2px 0px rgba(0, 0, 0, 0.7); */

}

/******
 STYLES ******/

.secA, .secB {

    width: auto;
    min-height: 400px;
    height: auto;
    padding: 4% 10% 8%;
    border-left: 1px solid rgba(255, 255, 255, 0.1);
    border-right: 1px solid rgba(255, 255, 255, 0.1);
}

.secA {

    background-color: rgba(0, 0, 0, 0.4);
    overflow: auto !important;
    border-top: 1px solid rgba(0, 0, 0, 0.2);
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);

}

.secB {

    background-color: rgba(0, 0, 0, 0.2);

}

/****** ABOUT ME SECTION STYLES ******/

.me-left {

    float: left;
    max-height: 200px;
    border: 5px solid black;
    border-radius: 50%;
    padding-left: 8px;
    margin: 10px 10px 10px 0px;
    background-color: white;
    transform: scaleX(-1);

}

.me-right {

    float: right;
    max-height: 200px;
    border: 5px solid black;
    border-radius: 50%;
    padding-left: 8px;
    margin: 10px 0px 10px 10px;
    background-color: white

}

/*********************************

**********sdFilterMe CSS**********

#sdfm-wrapper img,
.sdfm-overlay {

    //Define the WIDTH of sdFilterMe Images
    width: 200px !important;
    //Define the HEIGHT of sdFilterMe Images
    height: 200px !important;
    border-radius: 7px;
    overflow: hidden !important;

}

.sdfm-inner-wrapper {

    border-radius: 10px;
    margin: 5px !important;

}

.sdfm-overlay {

    background-color: rgba(0, 0, 0, 0.7) !important;
    color: white !important;
    font-size: 0.35em !important;
    text-overflow: clip !important;

}

.sdfm-overlay span {

    padding: 5% !important;
    margin: 8% auto !important;
    max-width: 85% !important;
    height: auto !important;
    word-wrap: break-word !important;
    border-radius: 2px !important;

}

*********************************/

/****** FOOTER STYLES ******/

.footer {

    width: auto;
    /* min-height: 150px; */
    /*margin-bottom: 5px !important;*/
    background-color: #1b1d1e;
    padding: 1.5% 5%;
    z-index: 3;
    border-top: 1px solid red;

}

.footer-content {

    /* border: 1px solid yellow; */
    margin: 0 auto;
    padding: 10px;
    display: flex;
    flex-flow: row wrap;
    justify-content: center;

}

.footer-text {

    font-size: 1.5em;
    font-weight: normal;
    color: rgba(255, 255, 255, 0.7);
    /* border: 1px solid white; */
    width: auto;
    padding: 5px;
    margin-left: 25px;
    margin-right: 25px;
    margin-top: 0.73%;
    display: flex;
    flex-flow: row wrap;
    align-self: flex-start;
    justify-content: center;

}

.footer-icons-box {

    /* border: 1px solid red; */
    width: auto;
    padding: auto;
    margin-left: 25px;
    margin-right: 25px;
    display: flex;
    flex-flow: row wrap;
    align-self: flex-end;

}

.sm-icon {

    display: inline-block;
    text-align: right;

}

.fa-circle {

    color: rgba(255, 255, 255, 0.9);
    transition: all 0.4s;

}

.footer-icons-box .fa-envelope,
.fa-twitter, .fa-free-code-camp, .fa-linkedin {

    color: #1b1d1e;
    transform: scale(1, 1);
    transition: all 0.4s;

}

.footer-icons-box .fa-envelope:hover,
.fa-twitter:hover, .fa-free-code-camp:hover,
.fa-linkedin:hover  {

    color: #337ab7 !important;
    transform: scale(0.8, 0.8);
    transition: all 0.4s;

}

JS (from the "my.js" file I referenced in the HTML section above)
/* Begin 'scrollTo' */

$(document).ready(function() {
    $('#topNav a').click(function() {
        $.scrollTo(this.hash, 1200, {offset: -70}, {easing:'swing'});
        return false;
    });
});

/* End 'scrollTo' */

A: In Elastic_grid.js search for 'if(numOfTag > 1){
         Creating the "Everything" option in the menu:
           createList("config.something");
            $.each(itemsByTags, function(I, i) {
                createList(I)
            })'
and change the line in bold with createList("All");

A: try:
find in elastic_grid.js the function createList(text)
And change the following lines:
[...]
    function createList(text) {
        var filter = text.toLowerCase().replace(' ', '-');
        // This is a helper function that takes the
        // text of a menu button and array of li items
        if (text != '') {
            var li = $('
');
            var a = $('', {
[...]

for:
[...]
        function createList(text) {
        // This is a helper function that takes the
        // text of a menu button and array of li items
        if (text != '' && text !== undefined) {
            var filter = text.toLowerCase().replace(' ', '-');
            var li = $('
');
            var a = $('', {
[...]

fixed for toLowerCase() undefined: https://github.com/vukhanhtruong/jquery-elastic-grid/pull/6/commits/5e6ceb02dccb57af536e1728dc5950d1622d0361


text:
Q: passing dynamic text box to jquery i have one php page where i generate textboxes from php and mysql table like
$sql="select * from product where pstatus=1";
    $result=mysql_query($sql);
    for($i=1;$i<=mysql_num_rows($result);$i++)
    {
    $row=mysql_fetch_array($result);
      ?>
 <input class="text_field1" id="<?php echo $i ?>" name="q_<?php echo $row['pid']; ?>" type="text" />
<?Php
}
?>

what i want is, to get values of textboex in JQuery to to process like this....
$.ajax({
 type: "POST",
 url: "add_pro.php",
 data: "cont_email="+ encodeURIComponent(cont_email)
+"&caccount="+ encodeURIComponent(caccount)
...............

where cont_email & caccount but in place of ........ i need to get values of these dynamic textboxs but total number of boxes depends upon database.
Thanks

A: I'm not sure how you want the data separated/formated but you could do something like:
var totalContent = '';

$('input .text_field1').each(function(){
    totalContent += $(this).val() + '\n';
});

....


text:
Q: Vue Testing Library won't rerender DOM when state changes I have a component with a strait forward Edit button. The Edit button calls a method that sets isEditing to true.
There are a few input elements with v-if="isEditing", so I'm testing that those input elements are visible after the Edit button is clicked.
When my test runs fireEvent.click(screen.getByRole('link', {name: 'Edit'})), it is updating isEditing to true (based on my console.log messages before/after the .click event), but it doesn't seem to re-render the components within the test (based on the DOM rendered in my terminal after getByRole fails).
It works as expected in the browser, but doesn't seem to update the DOM for the spec. I'm using Vue2, Vue Testing Library, and Jest.
Implementation:
<template>
  <a @click.prevent="startEdit" v-if="!isEditing">Edit</a>
  <input :v-if="isEditing" />
</template>
...
methods: {
  startEdit: () => {
    this.isEditing = true
  }
}

Spec:
describe('FormComponent', () => {
  beforeEach(() => {
    render(FormComponent)
  })

  it('displays input tags' () => {
    fireEvent.click(screen.getByRole('link', {name: 'Edit'}))
    expect(screen.getByRole('input')).toBeInTheDocument()
  })

})

A: The problem is your expect is running before the DOM has had a chance to update.  From the  testing library documentation:

Because Vue applies DOM updates asynchronously during re-renders, the fireEvent tools are re-exported as async functions. To ensure that the DOM is properly updated in response to an event in a test, it's recommended to always await fireEvent.

You should update your test to await the fireEvent promise like so:
it('displays input tags' async () => {
    await fireEvent.click(screen.getByRole('link', {name: 'Edit'}))
    expect(screen.getByRole('input')).toBeInTheDocument()
})

You also have a typo in your second v-if as Nicole pointed out in her answer.

A: It doesn't work because you wrote :v-if when it should be v-if. I guess this was simply a typo since you did it correctly the first time (v-if="!isEditing")


text:
Q: Unable to call addition method of calculator class in Main method of driver class although I am including cal.dll this is the driver class in driver.cs
using System;
public class driver{
public static void Main(){
    int meth;
    calculator obj = new calculator();
    do
    {
        System.Console.WriteLine("1. Addition\n2.Subtraction\n3.Multiplication\n4. Division\n5. Mod\n6. Square Root");
        meth=int.Parse(Console.ReadLine());

        if (meth==1)
        {
            Console.WriteLine("Enter 1st Number=");
            double num1=double.Parse(Console.ReadLine());
            Console.WriteLine("Enter 2st Number=");
            double num2=double.Parse(Console.ReadLine());

            double answer = obj.addition(num1,num2);
        }
    } while (meth!=0);
}}

this is the calculator class in cal.cs
using System;
public class calculator{

double addition(double x,double y){
return x+y;
}

double subtraction(double x,double y){
return x-y;
}

double multiplication(double x,double y){
return x*y;
}

double division(double x,double y){
return x/y;
}

double mod(double x,double y){
 return x%y;
}

double squareRoot(double x){
return Math.Sqrt(x);
}
}

I have created the cal.dll file using

CSC /target:library cal.cs

then compiling the driver class

CSC /reference:cal.dll driver.cs

everything is working fine except the
obj.addition(num1,num2);

in driver class
Need Help

A: You need to make your methods public to make them accessible from other classes. Apparently the error message is not very descriptive - CS1061 is also given when you attempt to call a non-public method from outside the class.
public double Addition(double x, double y) {
    return x + y;
}

I also recommend reading the naming conventions on capitalization.

A: Metohds of type are by default with internal protection level I just placed public before each method and it worked fine

A:
driver.cs(19.25):error 1061: 'calculator' does not contain a
  definition for 'addition' and no extension method 'addition' accepting
  a first argument of type 'calculator' could be found

As Matti Virkkunen has pointed already this is because method is private.
Normally if method is private and it is in the same project as console app, you'll get compile time error : "method is inaccesible due to its protection level".
Because it's in another project it's not inaccessible but completely invisible for console app.
P.S.
You can still access your private method using reflection :
    static void Main(string[] args)
    {
        calculator calc = new calculator();

        var addition = calc.GetType().GetMethod("addition", System.Reflection.BindingFlags.NonPublic
                                                          | System.Reflection.BindingFlags.Instance);

        var result = addition.Invoke(calc, new object[] { 5, 10 });

        Console.WriteLine(result);
    }

Output : 15


text:
Q: AFNetworking 2.0 not parse xml I want to read a response from a web service.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFXMLParserResponseSerializer new];
[manager GET:@"http://openapi.aibang.com/search?app_key=f41c8afccc586de03a99c86097e98ccb&city=%E5%8C%97%E4%BA%AC&q=%E9%A4%90%E9%A6%86" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

But I only got <NSXMLParser: 0x15d85490> from Xcode log. It's not the right xml response.

A: The output is correct, on iOS there is only the NSXMLParser which is a sax parser and you will need to implement the sax parsing.
The object returned in the block is an instance of  NSXMLParser and that is what you see in your log statement, with object you parse the data returned from the HTTP request. The passing it self is handled with the NSXMLParserDelegate.
If you want DOM parsing, you could use the ONO XML parser, it is made by on of the developers of AFNetworking and it a DOM Parser.
And Of course there is nice integration with AFNetworking:AFOnoResponseSerializer

A: EN: Because the responseObject is a NSXMLParser instance, you can't treat it like string!
You have to implement NSXMLParserDelegate to handler the xml parser progress!
CN: responseObject返回的是NSXMLParser实例,你必须实现NSXMLParserDelegate协议才能处理该xml字符串!骚年! :-)
solution 1: use NSXMLParser to parser
[manager GET:@"http://openapi.aibang.com/search?app_key=f41c8afccc586de03a99c86097e98ccb&city=%E5%8C%97%E4%BA%AC&q=%E9%A4%90%E9%A6%86" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSXMLParser *XMLParser = (NSXMLParser *)responseObject;
    [XMLParser setShouldProcessNamespaces:YES];
    XMLParser.delegate = self;
    [XMLParser parse];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

solution 2: use GDataXML to parser (much easier)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://openapi.aibang.com/search?app_key=f41c8afccc586de03a99c86097e98ccb&city=%E5%8C%97%E4%BA%AC&q=%E9%A4%90%E9%A6%86" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
   GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithData:responseObject encoding:0 error:nil];
   NSLog(@"%@",doc.rootElement);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];


text:
Q: How to generate random float in lua? I need to generate random float in Lua. It needs to be > 1, so math.random() is not a solution.
How can I do this?

A: Just posting for fun, but you can use math.random() with no arguments to do this :P
print(math.floor((math.random()*100)+0.5))

A: This should generate random floats between 1 (inclusive) and 100 (exclusive)
math.random() + math.random(1, 99)

A: You can also use something like this to get a number between lower and greater
function randomFloat(lower, greater)
    return lower + math.random()  * (greater - lower);
end


text:
Q: Using positional parameter ($1,..) in psql I often want to copy/paste sql out of my program code and test/debug in psql and it is tedious to have to replace positional arguments with literal values. Is there a good way to convert:
select * from users where name=$1 and email=$2;

to:
select * from users where name='troy' and email='t@me.com';

A: You could use psql variables. Those are interpolated in SQL code. Per documentation:

A key feature of psql variables is that you can substitute
("interpolate") them into regular SQL statements, as well as the
arguments of meta-commands. Furthermore, psql provides facilities for
ensuring that variable values used as SQL literals and identifiers are
properly quoted. The syntax for interpolating a value without any
quoting is to prepend the variable name with a colon (:).

Note that (per documentation):

The name must consist of letters (including non-Latin letters), digits, and underscores.

So you cannot work with positional parameters of the form $1. I am assuming you copy these pieces of code from function bodies, and that's the reason for the positional parameters?
Since PostgreSQL 9.2, even  SQL functions can reference parameters by name. Per documentation:

Arguments of a SQL function can be referenced in the function body using either names or numbers.

PL/pgSQL functions have been supporting named parameters in the function body since v8.0.
My preferred naming convention is to prepend function parameters with _ to avoid naming conflicts. But that's a matter of taste and style.
Only half a solution
So, your example could work like this:
db=> \set _name 'troy'
db=> \set _email 't@me.com'
db=> select * from users where name=:'_name' and email=:'_email';

You still have to prepare query strings ...
Note the quotes in :'_name'. That has the same effect as applying quote_literal() on the string. Details in the manual.

A: It's not a whole lot better than just running the original query, but assuming that your example is only a trivial one and the actual query is a bit more involved, you could create a function:
CREATE OR REPLACE FUNCTION get_users(user_name varchar, email_addr varchar)
  RETURNS SETOF users AS
$BODY$
  select *
  from users
  where
    name = user_name and
    name = email_addr
$BODY$
  LANGUAGE sql VOLATILE
  COST 100
  ROWS 1000;

To get the results you would:
select * from get_users('troy', 't@me.com')

Again with your example, this doesn't help a whole lot, but I've used this with big queries with lots of joins, and it works nicely.


text:
Q: SonarQube - Analyse JSON File Is it possible to analyse a json file with SonarQube? (I don't mean to analyse the format properties, I want to analyse a value in this file and trigger a rule if this value is greater than some threshold)
If this is possible I'm interested in how one could do this with a custom SonarQube plugin.

A: It seems like SonarQube does not support a built-in functionality to analyse the content of json files. However according to this thread it seems like there is a github plugin which should do the job.


text:
Q: Consolidate multiple calls to observer into one single metric I have setup a WKHTTPCookieStoreObserver in my class. I want to check if my cookie is missing and if so, I want to emit a single metric and set the cookie again. The problem is that the observer is asynchronous and creates multiple metrics for the single event. How can I consolidate all the calls to the observer into one single metric?
- (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore {

    dispatch_async(dispatch_get_main_queue(), ^{
        [cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> *cookies) {
            NSString *cookieValue = nil;
            for (NSHTTPCookie *cookie in cookies) {
                if ([cookie.name isEqualToString:cookieName]) {
                    cookieValue = cookie.value;
                }
            }
            if (![cookieValue isEqualToString:expectedCookieValue]) {
                [self createAndPublishCookieMismatchMetric]; // this line gets called ~300 times
                [self writeCookieToWKWebsiteDataStore]; // write the missing cookie to the cookie store
            }
        }];
    });
}

I want to merge all ~300 calls to function and emit only one metric for this event. Even though I write the cookie back to the store from the next line, it looks like there already are multiple calls in the queue waiting to be processed. What's the correct solution here?


text:
Q: #Value Error in User Defined Function VBA I am writing a function to find the first row that has a different interior color (with Conditional Formatting) above the current active cell. The function works when I print it out with debug.print or msgbox but not when I call it directly in the worksheet. The first row is header and that's why I exclude the top row.
Public Function blockStart() As Long
    Dim currColor As Long
    currColor = activecell.DisplayFormat.Interior.ColorIndex

    Dim currCol As String
    currCol = Number2Letter(activecell.Column)

    Dim startRow As Long
    startRow = activecell.Row

    'Find Ceiling
    Do While startRow >= 2
        If Range(currCol & startRow).DisplayFormat.Interior.ColorIndex <> currColor Then
            startRow = startRow + 1
            Exit Do
        End If
        startRow = startRow - 1
    Loop

    If startRow = 1 Then startRow = 2   ' at the very top

    blockStart = startRow

End Function

When I call the function directly in the worksheet, #value is prompted. Please let me know what I am doing wrong, thanks!

A: Just so you're not left feeling like this is impossible, one possible approach to doing what you want to do is to take the entire body of your BlockStart function and put it in the Worksheet's SelectionChange event. Then, instead of the line that says blockStart = startRow you can assign the value to startRow to the cell where you are trying to use the BlockStart function.
If multiples cells use the BlockStart function, assign the value to an unused cell somewhere and have the other cells reference it.


text:
Q: How to adjust this query of research? I need to adjust this query to do the search (like) in another column and another table.
See:
$query2 = "
select distinct(lances.codigo)
     , datacompra
     , horacompra
     , cupom
  from lances
     , ".$tabelaCad."
 where lances.idcliente = ".$tabelaCad.".id
   and lances.datapgto = '0000-00-00'
   and lances.horapgto = '00:00:00'
   and (".$tabelaCad.".nome like '%".$cliente."%' or ".$tabelaCad.".usuario like '%".$cliente."%')
 group
    by lances.codigo
 order
    by lances.datacompra desc
     , lances.horacompra desc
    ";

He currently searches only on: ".$tabelaCad.".nome and ".$tabelaCad.".usuario.
The variable $tabelaCad is the name of a table called cadastro, and the variable cliente is the one that receives the search POST.
I need her to look too in the column codigo from the table lances and in a new table called registro in the columns reg1 e reg2.
What would the query look like in this case? I have tried several ways and it does not work.
I am working with MySQL 5.7, still...

A: After a long discussion we found the last relation between the tables.
It is registro.reg1 to lances.codigo.
So the best way to solve the problem is to work with the inncer join.
You save unnecessary typing and can address the tables with aliases which is much more comfortable for writing procedures.
Here is my finished solution:
<?php
$query2 = "
select
    distinct lc.codigo as codigo,
    lc.datacompra as datacompra,
    lc.horacompra as horacompra,
    lc.cupom as cupom
from `lances` as lc
inner join `".$tabelaCad."` as ca on lc.idcliente = ca.id
inner join `registr` as ri on lc.codigo = ri.reg1
where lc.idcliente = ca.id
    and lc.datapgto = '0000-00-00'
    and lc.horapgto = '00:00:00'
    and (ca.nome like '%".$cliente."%' or ca.usuario like '%".$cliente."%')
group
    by lc.codigo
order
    by lc.datacompra desc, lc.horacompra desc
";
?>

I put them in the selection because I do not know exactly what you intend to xD


text:
Q: postfix check_policy_service not working I was hoping someone can help me out here. Cannot seem to get check_policy_service working. I am running policyd on port 10031 and postfix does not even makes a connection to it.
Already gone through the below thread, my problem is almost similar except the fact that firewall is already disabled on my system and thus port 10031 is not blocked by the firewall.
http://marc.info/?l=postfix-users&m=143886189409700&w=2
Here is the output form postconf -n :
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
config_directory = /etc/postfix
daemon_directory = /usr/libexec/postfix
inet_interfaces = localhost
lmtp_host_lookup = native
mail_owner = postfix
mail_spool_directory = /var/spool/mail
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
mydestination = $myhostname
mydomain = mydomain.com
myorigin = $mydomain
newaliases_path = /usr/bin/newaliases.postfix
notify_classes = resource, software, policy
queue_directory = /var/spool/postfix
relayhost = [mail-relay.mydomain.com]
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
smtp_fallback_relay = [mail-relay.mydomain.com]
smtp_host_lookup = native
smtpd_banner = $myhostname ESMTP $mail_name
smtpd_end_of_data_restrictions = check_policy_service inet:127.0.0.1:10031
smtpd_recipient_restrictions = check_policy_service inet:127.0.0.1:10031, reject_unauth_destination, reject_unlisted_recipient
transport_maps = hash:/etc/postfix/transport unknown_local_recipient_reject_code = 450

Postfix version 2.3.3
OS:    RHEL5.4

A: Ah! This should be marked resolved/closed.
I was making a mistake. I was generating mail locally on the server using sendmail/mailx etc which results in that mail getting picked up by the pickup daemon rather than by the smtpd i.e sendmail on the server locally is direct writing a queue file into the "maildrop" directory which is getting picked up by postfix 'pickup' rather than smtpd . So in order to check mail against check_policy_service, the mail must be submitted via SMTP (using any smtp client like mini_sendmail). Once i did that, connection to policy server was made and checked against throttling and got expected result.
Use below to send mail to smtp and thus validate against the set policies:
 cat /tmp/mail.txt | mini_sendmail -ffoo@bar.com -s127.0.0.1 -p25 foo2@ybar.com

Thanks.


text:
Q: Google Finance API address has changed Until yesterday the following URL (Google Finance API)

https://www.google.com/finance/getprices?q=TSLA&x=NASDAQ&i=3600&p=5d&f=d,o,h,l,c,v

would lead to a nice comma delimited data table with TSLA stock data. Since yesterday, the same call gets redirected to the standars google finance website for TSLA https://www.google.com/search?q=TSLA&tbm=fin. Does someone maybe know the new API address or has any information on the Google Finance API status? Changing the URL to

https://finance.google.com/finance/getprices?q=TSLA&x=NASDAQ&i=3600&p=5d&f=d,o,h,l,c,v

does not help, as it also redirects to the normal website.


text:
Q: Tidyverse -- integrating mutate select and case when to likert scales I'm a tidyverse user and I'm facing a difficulty to perform what I imagine is a simple command.
I have a dataset where some variables are Likert scales and, now, I want to assign some text labels to these specific set of variables. To do that, I imagine the best process involves to mutate, then select which variables I want to change and, then, tell R what will be the new values.
That seems logic to me. However, there is a bridge between what I want to do and the R code I'm creating.
I hope someone can help me to resolve this question.
The code below is a reproducible example:
library(tidyverse)
ds <- data.frame(sex=c(0,1), age=rnorm(n = 100, mean = 7, sd=2),
                 question1_1 = sample(1:5),
                 question1_2 = sample(1:5),
                 question1_3 = sample(1:5),
                 question1_4 = sample(1:5),
                 question1_5 = sample(1:5))
ds <- ds %>% mutate(
  select %>% starts_with("question1_") %>%
  case_when(. == 1 ~ "Strongly disagree",
            . == 2 ~ "Disagree",
            . == 3 ~ "Neutral",
            . == 4 ~ "Agree",
            . == 5 ~ "Strongly agree"))

I did not find any previous message asking the same question and because of that, I create this new thread. Please let me know if this message is duplicate to exclude it.
Thanks much.

A: We could use it in mutate_at
ds %>%
   mutate_at(vars(starts_with('question')),
         funs(case_when(.==1 ~ "Strongly disagree",
                        .==2 ~ "Disagree",
                        .==3 ~ "Neutral",
                        .==4 ~ "Agree",
                        .==5 ~ "Strongly agree")))

But, this can be made more simpler as the values are integers, so pass a vector of strings in the same order we want to change making use of the integer values as indexes
v1 <- c('Strongly disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly agree')
ds %>%
   mutate_at(vars(starts_with('question')),
         funs(v1[.]))

A: You could also use factors:
library(tidyverse)
ds %>%
  mutate_at(vars(starts_with('question')), factor,
                 labels= c("Strongly disagree","Disagree","Neutral","Agree", "Strongly agree")) %>%
  head

#   sex      age       question1_1       question1_2       question1_3       question1_4       question1_5
# 1   0 6.518414             Agree           Neutral          Disagree           Neutral             Agree
# 2   1 4.972210           Neutral          Disagree    Strongly agree Strongly disagree Strongly disagree
# 3   0 6.422792 Strongly disagree    Strongly agree             Agree          Disagree    Strongly agree
# 4   1 9.839967          Disagree             Agree           Neutral    Strongly agree           Neutral
# 5   0 7.518809    Strongly agree Strongly disagree Strongly disagree             Agree          Disagree
# 6   1 8.446730             Agree           Neutral          Disagree           Neutral             Agree

Translated in base R:
cols_lgl <- startsWith(names(ds),"question")
ds[cols_lgl] <- lapply(ds[cols_lgl],factor, labels= c("Strongly disagree","Disagree","Neutral","Agree", "Strongly agree"))


text:
Q: Compile Android app to iOS Is it possible to create a new iOS app with exsisting sources?
I am working with xamarin in Visual-Studio. I've got a project, an app that runs on Android devices. But can I make a new project for an iOS app with those existing sources? I have a Macbook that I can use to do this. I also have a PC with windows 10 on it. So the hardware/software requierments shouldn't be a problem.
Getting to the point..
Is it possible to transform the project from an Android app to an iOS app without writing any code extra? And how can I accomplish this, any tutorials that I can watch/read?
The code language is C#. The programs that I am using are Visual studio and the xamarin extention.
I've read something about Platform Abstraction and Divergent Implementation on the xamarin ducomentation page, but this couldn't fully answer my question.

A: Short answer: NO.
Long answer:
There are a quite a few cross platform developing tools out there. Xamarin, like the one you are using, or Cordova. They simplifies the development by "A LOT" but you can't just convert one app to another without writing 0 code. Some of the libraries in one platform do not exist in the other. So, the long answer is that cross platform shortens the development cycle as you do not need to start from scratch on other platform, that does not mean it can completely convert.
P.S. Youtube is your friend, but the difficulty of the transformation solely depends on the scope of your project, as they vary a lot.

A: I second the other answers.
Furthermore, I'd like to propose to have a look at Flutter.
Flutter is based on Dart  language . The framework and your application get compiled from Dart to the Android and the iOS target platform.
Flutter is a product of Google and likely to get the base development environment for Fuchsia, a new OS from Google.
My own experiments with Xaramin ended up kind of frustrating. The development was slow, several times problems with Xamarin itself or plugins made me stop the effort.
At the other side, I created an app with Flutter quite fast. While Dart and Futures might seem at first quite different compared to other concepts/languages, after some time things turn out to be very natural and well designed.
While Flutter originally was based on Material design, Google added an iOS theme using CupertinoWidget.
A simply great feature is the enormous quick development turnaround time: The app under development very ofter adopts within just a second your source-code changes. Flutter/Dart hot reloads changed classes often instantly.
Android Studio is a great and free IDE for Flutter development. Plugins enhance to IDE with Flutter development tasks.

A: If you have android application written in Java you can use Migeran Analyzer to understand how much % of the code could be reused between android and iOS: https://analyzer.migeran.com/
Once you have the % you can use Intel Multi-OS Engine (free product) to create cross-platform application in Java: https://software.intel.com/en-us/multi-os-engine. It will have module with cross-platform shared code, android specific code module and iOS specific code module


text:
Q: Vue, Mocha and webpack chunks configuration? I have a Vue2 application:
The vue.config file have a webpack bundle optimization to split the app into chunks to reduce file size:
module.exports = {
  ...,
  configureWebpack: {
    optimization: {
      runtimeChunk: "single",
      splitChunks: {
        chunks: "all"
      }
    }
  }
}

Now I'm trying to integrate mocha to enable testing, but I can see that it recognise the tests only when I remove the above optimization.
With optimization:

Without optimization:

How can I solve the issue?


text:
Q: What is the diffrents in below MOSFET circuit considering control circuit?
What is the different in below MOSFET circuit considering control circuit? What is the charge pump involving ? Is it required charge pump for the both the circuit?


text:
Q: Unable to Call Events using Zkemkeeper SDK I am facing trouble in calling events in Zkemkeeper.dll. I have succesfully established the connection however on putting the finger on sensor no event is fired. Infact no realtime event is being triggered.
Any help would be appreciated following is my code;
private void button2_Click(object sender, EventArgs e)
{
    string s = "";
    int Val = 0;
    bool bIsConnected = false;
    try {
        //zkemkeeper.CZKEMClass axczkem1 = new zkemkeeper.CZKEMClass();
       // bIsConnected = axczkem1.Connect_USB(1);
        bIsConnected = axczkem1.Connect_Com(6,1,115200);

        if(bIsConnected==true){
            Cursor = Cursors.Default;
           bool asa= axczkem1.EnableDevice(1, true);
            if (axczkem1.RegEvent(1, 65535))
            {

              axczkem1.OnFinger += new zkemkeeper._IZKEMEvents_OnFingerEventHandler(axczkem1_OnFinger);
             axczkem1.OnKeyPress += new zkemkeeper._IZKEMEvents_OnKeyPressEventHandler(axczkem1_OnKeyPress);
             axczkem1.OnConnected += new _IZKEMEvents_OnConnectedEventHandler(axCZKEM1_OnConnected);
             axczkem1.OnVerify += new zkemkeeper._IZKEMEvents_OnVerifyEventHandler(axCZKEM1_OnVerify);
            }
        MessageBox.Show("Connection established!!!");
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

And following are the event methods:
private void axCZKEM1_OnVerify(int UserID)
    {
        label2.Text = "Verify";
    }

    private void axCZKEM1_OnConnected()
    {
        label1.Text = "Connected";
    }

    private void axczkem1_OnKeyPress(int Key)
    {
        MessageBox.Show(Key.ToString());
    }

    private void axczkem1_OnFinger()
    {
        MessageBox.Show("Connection");
    }

A: *

*if this is a windows form application . If program have long running process event doesn't work . For example loop (while,for) . And also Thread.sleep() .
If you want to trigger work your program do nothing .

*If this is not a windows form see this link enter link description here


text:
Q: Couple, few and several During typical conversation, how would one define couple, few and several?  I have read the actual definitions; however, they appear to be a bit vague.  My thoughts are:

*

*A couple is two.

*A few is three to five.

*Several is six to 11.

*After 11 is obviously a dozen...

What is the consensus among us rational people?  Please do not get too literal.


text:
Q: iOS method called before scrollViewDidScroll on UITableView I need to process scroll event on UITableView before it is processed in scrollViewDidScroll method. Is there any way to do that?

A: Set table.scrollview.delegate to self and override the scrollviewDidScroll method. In the method do your processing before calling [super scrollViewDidScroll].

A: I used
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate

This is much more convenient.


text:
Q: VIM adds a character to a newline on hitting enter I looked around but haven't found an answer to this. I have a CentOS 6.2 server running with the same .vimrc as my CentOS 5.8 server, however when I hit enter in VIM on my 6.2 server, it adds the first character of the previous line if it's a certain character (% or # are the ones I've seen). This is what happens in VIM (The seconds lines are right after hitting enter, but without typing anything else):
# <enter>
#

% <enter>
%

Here's my .vimrc:
set autoindent
set smartindent
set tabstop=4
set shiftwidth=4
set showmatch
set number

imap jj <Esc> " Professor VIM says '87% of users prefer jj over esc', jj abrams disagrees

" Indenting *******************************************************************
set ai " Automatically set the indent of a new line (local to buffer)
set si " smartindent (local to buffer)

" Cursor highlights ***********************************************************
"set cursorline
"set cursorcolumn

" Set an orange cursor in insert mode, and a red cursor otherwise.
" Works at least for xterm and rxvt terminals.
" Does not work for gnome terminal, konsole, xfce4-terminal.
"if &term =~ "xterm\\|rxvt"
"   :silent !echo -ne "\033]12;red\007"
"   let &t_SI = "\033]12;orange\007"
"   let &t_EI = "\033]12;red\007"
"   autocmd VimLeave * :!echo -ne "\033]12;red\007"
"endif

" Searching *******************************************************************
set hlsearch  " highlight search
set incsearch  " Incremental search, search as you type
set ignorecase " Ignore case when searching
set smartcase " Ignore case when searching lowercase

" Colors **********************************************************************
"set t_Co=256 " 256 colors
set background=dark
syntax on " syntax highlighting
"colorscheme darkzen

Ran a diff against it and the one on my 5.8 server (where I don't have this problem) and there was no difference at all. Any idea why this may be happening?

A: It looks like automatic comment insertion.
Take a look at :help formatoptions and :set formatoptions. These are probably being set by file type.

A: Run verbose set formatoptions.  You should get back a string that contains 'r', which Automatically inserts the current comment leader after hitting <Enter> in Insert mode.  The verbose bit should point you at the file(likely a filetype plugin) who is the culprit.
I prevent vim from hijacking my formatoptions via the autocommand au FileType * set formatoptions=lq in my vimrc.  Most of the options drive me absolutely crazy, although r and o are by far the worst.


text:
Q: Dúvida acerca da hierarquia de Chomsky A respeito dos 4 tipos de linguagens, tenho dúvida em compreender sobre a linguagem dependente do contexto ou sensível ao contexto.
Acho muito confusa a explicação que encontro pelos sites, gostaria que alguem me ajudasse a entender o que é uma linguagem sensível ao contexto e uma linguagem irrestrita.

A: A hierarquia
A hierarquia de linguagens é essa:

As que Chomsky considerou à sua época, foram as linguagens regulares, livres de contexto, sensíveis ao contexto e irrestritas. No entanto, eu vou abordar todas elas, inclusive as outras três.
Linguagens finitas
Uma linguagem finita é aquela que corresponde a um conjunto finito de cadeias de caracteres. Logo, uma linguagem não é finita se existir um conjunto infinito de cadeias de caracteres nessa linguagem.
Linguagens regulares
Todas as linguagens finitas são regulares, mas nem todas as regulares são finitas.
Uma linguagem regular é aquela que pode ser expressa por uma expressão regular. Uma expressão regular consiste de sequências de caracteres que podem ter:

*

*(a) Repetições de determinadas subsequências em um indeterminado número de vezes e;

*(b) Escolhas entre duas ou mais subsequências.
A característica b existe nas linguagens finitas, e portanto é a a que aumenta o poder de reconhecimento das linguagens e permite que as linguagens regulares expressem um número infinito de cadeias de caracteres. Logo, uma expressão regular que não faça uso da característica a expressa uma linguagem finita.
Outras características frequentemente atribuídas às expressões regulares tal como repetição de subsequências uma ou mais vezes, repetição de subsequências um determinado número de vezes e subsequências que podem ou não aparecer, são todas características que advém de combinações das características a e b descritas acima.
Linguagens livres de contexto
Todas as linguagens regulares são livres de contexto, mas nem todas as livres de contexto são regulares.
Uma linguagem livre de contexto é aquela que pode ser expressa por meio de uma gramática livre de contexto.
Uma gramática livre de contexto é um conjunto de regras de derivação recursivas aninhadas além daquilo que as linguagens regulares já são capazes de reconhecer. Cada regra, denominada de produção, é definida como a forma como um símbolo não-terminal pode ser expandido em uma sequência de símbolos terminais e não-terminais. A cadeia de caracteres a ser reconhecida ou gerada por uma gramática livre de contexto consiste apenas de símbolos terminais, sendo os símbolos não terminais usados apenas nas etapas intermediárias de geração ou reconhecimento da cadeia de caracteres.
Mesmo sem o uso de recursão nas regras, a possibilidade de expandir símbolos não-terminais em sequências de símbolos terminais e não-terminais é o suficiente para expressar as características a e b das linguagens regulares. Portanto, é a possibilidade de utilizar-se tal recursão que torna as linguagens livres de contexto mais expressivas do que as regulares. Uma gramática livre de contexto que não utilize dessa característica é equivalente a uma expressão regular.
Explico mais sobre as linguagens livres de contexto aqui.
Linguagens sensíveis ao contexto
Todas as linguagens livres de contexto são sensíveis ao contexto, mas nem todas as sensíveis ao contexto são livres de contexto.
Uma linguagem sensível ao contexto é aquela que pode ser expressa por alguma gramática sensível ao contexto.
Uma gramática sensível ao contexto é um tanto similar a uma gramática livre de contexto, mas com uma grande diferença: As produções não necessariamente mapeiam apenas símbolos não-terminais para sequências de terminais e não-terminais. Elas podem mapear sequências de terminais e não-terminais para outras sequências de terminais e não-terminais, e essa característica as torna mais expressivas do que as gramáticas livres de contexto.
Um exemplo de gramática sensível ao contexto, que peguei da Wikipédia e que reconhece a linguagem { anbncn : n ≥ 1 } que não é livre de contexto é essa:
S → aBC
S → aSBC
CB → CZ
CZ → WZ
WZ → WC
WC → BC
aB → ab
bB → bb
bC → bc
cC → cc

Observe que diferente do que ocorre numa gramática livre de contexto, a parte da esquerda das produções não se restringe a um símbolo não-terminal singular.
Gramáticas sensíveis ao contexto são muitas vezes confusas, difíceis de se entender e difíceis de se analisar. O principal motivo para isso é que elas definem regras que podem ser usadas para substituir qualquer coisa da entrada por qualquer outra coisa de qualquer jeito em qualquer ordem e em qualquer lugar. Efetivamente, elas são computacionalmente equivalentes às máquinas de Turing com memória limitada ao tamanho da entrada.
Assim sendo, usar essas regras de produções não é a única forma de especificar-se como funciona uma linguagem livre de contexto. Uma forma mais natural é a de defini-la como uma máquina de Turing determinística cuja fita na qual ela opera é limitada apenas ao tamanho da entrada. Sendo uma máquina de Turing, ela pode realizar qualquer tipo de operações de leitura, escrita e manipulações de símbolos nessa fita de entrada. Entretanto, uma vez que a sua fita é limitada e finita, ela ainda tem um poder computacional menor do que uma máquina de Turing com memória ilimitada.
Ao utilizar-se uma máquina de Turing determinística com um alfabeto muito maior do que o alfabeto de entrada, é possível simular-se uma máquina de Turing determinística que opere sobre uma fita de memória cujo tamanho máximo é o tamanho da entrada multiplicado por alguma constante arbitrária. Assim sendo, uma definição equivalente para uma linguagem sensível ao contexto é aquela que pode ser reconhecida por uma máquina de Turing determinística operando sobre uma fita cujo tamanho mantém uma relação linear com o tamanho da fita de entrada.
Um exemplo prático de uma linguagem sensível ao contexto que não é livre de contexto é a dada anteriormente, { anbncn : n ≥ 1 }. Ou seja, a linguagem que corresponde a uma sequência de a's, seguida de uma sequência de b's e depois uma sequência de c's, onde o número de a's, b's e c's sejam iguais.
Outro exemplo de linguagem sensível ao contexto é o de verificar se pares de marcações de itálico ( - ), negrito ( - ) e sublinhado ( - ) abrem e fecham corretamente, mesmo que não estejam devidamente aninhados. Nessa linguagem, a sequência abcdefghijklmno é uma cadeia válida. Não há linguagem livre de contexto capaz de reconhecer isso.
Um outro exemplo simples de uma linguagem sensível ao contexto é aquela linguagem que consiste na sequência de dígitos entre 0 e 9 que expressam um número primo na base decimal. Novamente, não há linguagem livre de contexto capaz de reconhecer isso.
Mais um outro exemplo, e que abusa do poder computacional disponível, é o de determinar se uma sequência de símbolos representando variáveis, parênteses e os operadores lógicos E, OU e NÃO é ou não satisfatível. Esse é o problema da satisfazibilidade que é o problema NP-completo mais conhecido. A classe de linguagens sensíveis ao contexto é tão abrangente que engloba todos os problemas em NP.
Linguagens recursivas
Todas as linguagens sensíveis ao contexto são recursivas, mas nem todas as recursivas são sensíveis ao contexto.
A definição de uma linguagem recursiva é simples: Tudo aquilo para o qual existe alguma máquina de Turing que a reconhece ou a rejeita em tempo finito.
É difícil pensar-se em uma linguagem recursiva que não seja sensível ao contexto. A maioria dos problemas computacionais com que nos deparamos no dia-a-dia são computacionalmente equivalentes ao reconhecimento de alguma linguagem sensível ao contexto.
Uma linguagem recursiva que não seja sensível ao contexto deve ser necessariamente impossível de ser reconhecida com o uso de uma quantidade de memória limitada ao tamanho da entrada multiplicada por qualquer constante, por mais arbitrariamente alta que ela seja. Isso já implica em uma complexidade computacional fora de NP e em problemas absolutamente intratáveis, embora ainda solucionáveis.
Exemplos de problema que são recursivos, mas não são sensíveis ao contexto:

*

*Determinar se duas expressões regulares são equivalentes.

*Verificar ou refutar a validade de sentenças de primeira ordem (que incluem variáveis, E, OU, NÃO, para todos (∀) e existe (∃)) com números reais, adição e comparação (mas sem multiplicação).

*Determinar se existe alguma estratégia perfeita para vencer um jogo de xadrez sendo desconsiderada alguma regra que force o empate após algum número arbitrário de movimentos sem captura para um tabuleiro de tamanho arbitrário.
Uma vez que as linguagens recursivas são aquelas que podem ser decididas em tempo finito, então as que não são recursivas são aquelas que não podem ser decididas em tempo finito para todos os casos. Em outras palavras, as linguagens que não são recursivas são indecidíveis.
Linguagens recursivamente enumeráveis
Todas as linguagens recursivas são recursivamente enumeráveis, mas nem todas as recursivamente enumeráveis são recursivas.
Uma linguagem recursivamente enumerável (ou semi-decidível) é aquela que é aceita por alguma máquina de Turing em tempo finito, mas que pode demandar tempo infinito para ser rejeitada.
Para uma linguagem ser recursivamente enumerável sem que seja recursiva, é necessário que existam cadeias que não pertencem a linguagem, mas que seja impossível determinar-se isso em uma sequência finita de passos (afinal, ela deve ser necessariamente indecidível). Entretanto, cadeias que pertençam a linguagem em questão sempre podem ser decididas como tal em um número finito (mesmo que muito grande) de passos.
O exemplo clássico de uma linguagem recursivamente enumerável que não é recursiva é a do problema da parada. Dada uma descrição de uma máquina de Turing e uma cadeia de entrada, determinar se a máquina de Turing aceita ou não tal cadeia. Embora esse problema parece ser simples, na verdade é um problema muito cruel, pois simplesmente não existe algoritmo capaz de solucioná-lo em tempo finito para todas as possíveis entradas. Falo mais sobre esse problema aqui.
Linguagens irrestritas
Todas as linguagens recursivamente enumeráveis são irrestritas, mas nem todas as irrestritas são recursivamente enumeráveis.
A palavra irrestrita já diz o que a linguagem é: tudo e qualquer coisa. Esse é o conjunto que engloba todas as linguagens, inclusive as linguagens que não são recursivamente enumeráveis.
As linguagens que não são recursivamente enumeráveis são insolúveis. Elas contém cadeias de caracteres que são impossíveis de poderem ser determinadas como pertencentes a linguagem ou não.
De acordo com o teorema de Rice decidir sobre qualquer propriedade semântica não-trivial de algum programa é um problema indecidível. Por propriedade trivial entenda-se aquelas que são válidas para todos os programas ou para nenhum programa (e portanto, as não-trivias são aquelas que são verdadeiras para uns e falsas para outros). Por propriedade semântica, entenda-se por propriedades sobre o comportamento do programa. Sendo indecidíveis, logo, esses problemas não são recursivos e muitos deles também não são recursivamente enumeráveis. Podemos utilizar isso para conceber algumas linguagens que não são recursivamente enumeráveis. Por exemplo:

*

*O conjunto de cadeias de caracteres que descrevem máquinas de Turing que decidam se as suas entradas são números primos.

Outro exemplo conhecido, que não depende do teorema de Rice é esse:

*

*O conjunto de cadeias de caracteres que representam pares de gramáticas livres de contexto que reconheçam a mesma linguagem.


text:
Q: Boostrap flexbox same width children I have a flex box container in which the children are displayed in a flex-row. Im trying to use bootstrap and make all the children the same width and height.
HTML

            Procedures

            Quick Reference Guides

            Standardized
                Forms

            Member Forms

            Canvas Links

            Deposit and Loan
                Rates

 Policies

More

Here is an image of what it currently looks like. You can see that the deposit and loan rates box is wider then the more box:

A: Add for all children, this:
 flex: 1 1 0;


text:
Q: matplotlib.pyplot is not working! I'm using Jupyter Notebook, and matplotlib.pyplot is not working. I'm using Python 2.7 in Ubuntu 14.04.

A: Your code got the following error message:
ImportError: numpy.core.multiarray failed to import

Change your Python code like this and then test it first in the terminal:
:~$ python
>>> import numpy
>>> from numpy import core
>>> from numpy.core import multiarray as ma

If you also have python-matplotlib installed, the first line of code to enable plotting in the current Jupyter Notebook is %matplotlib inline
Your Jupyter Notebook also shows another error message:
RuntimeError: module compile against API version 0xa but this version of numpy is 0x9

numpy from Anaconda is not compatible with ipython or some other package that you have installed. This would not happen if you installed the python-numpy, ipython, and python-matplotlib packages from the default Ubuntu repositories. I have installed Jupyter Notebook in Ubuntu 14.04 with the command sudo apt-get -y install ipython ipython-notebook && pip install --user jupyter and used it with ipython, python-matplotlib and python-numpy also from the default Ubuntu repositories without any problems.
To install jupyter-notebook in Ubuntu 18.04-19.10 open the terminal and type:
sudo apt install python-all python3-pip python3-notebook jupyter jupyter-core python-ipykernel

To install jupyter-notebook in Ubuntu 20.04 and later open the terminal and type:
sudo apt install python-all python3-pip jupyter-notebook jupyter


text:
Q: What is Log Mechanism in AWS cloud watch? I have recently started learning about AWS cloud watch and I want to understand the concept of creating Logs so I went through a lot of links like
https://aws.amazon.com/answers/logging/centralized-logging/
I could understand that we can create log groups but and logs are basically to track activity. Is there anything more to it. When do the logs get created.
Any help would be highly appreciated!

A: You can get more details about Log Groups and CloudWatch Logs Concepts here
Following is the extract from that page

Log Events
A log event is a record of some activity recorded by the application or resource being monitored. The log event record that
  CloudWatch Logs understands contains two properties: the timestamp of
  when the event occurred, and the raw event message. Event messages
  must be UTF-8 encoded.
Log Streams
A log stream is a sequence of log events that share the same source. More specifically, a log stream is generally intended to
  represent the sequence of events coming from the application instance
  or resource being monitored. For example, a log stream may be
  associated with an Apache access log on a specific host. When you no
  longer need a log stream, you can delete it using the aws logs
  delete-log-stream command. In addition, AWS may delete empty log
  streams that are over 2 months old.
Log Groups
Log groups define groups of log streams that share the same retention, monitoring, and access control settings. Each log stream
  has to belong to one log group. For example, if you have a separate
  log stream for the Apache access logs from each host, you could group
  those log streams into a single log group called
  MyWebsite.com/Apache/access_log.

And to answer your question "When do the logs get created.", basically that is completely dependent on your application. However, whenever they are created they get streamed to cloudwatch streams (if you have installed the cloudwatch agent and are streaming that particular log)
The advantage of using cloudwatch is that you can retain logs even after your EC2 instance is terminated and you dont need to SSH into the resource to check the logs, you can simply get that from AWS Console


text:
Q: Updating product price from code not reflect in frontend category page until I save from admin We are updating the product prices every 10min using cron. The prices are pulled from a external API.
We are using the following way to update the price,
$this->updateProductAttribute('price', $productId, $price);

Then we are doing reindex for the updated items,
$categoryIndexer->reindexList(array_unique(array_keys($products)));

After the price update, Product detail page showing correct updated price. But the Category page still showing the old price. If I refresh the cache or save the product from admin then category page showing updated price.
Instead of using updateProductAttribute if I save the product from code then category page works.
Whether it advisable to save 100 of products every 10min programmatically?
Or, Do we have any other way to handle the category page cache issue?

A: Magento 1 and magento 2 are both not great at this.  They're just not designed for rapid data change.
My best advice is to handle your 100 product update as fast as you can and then refresh the cache programatically after the update just the once. You wont need to clear all of the caches but it will be trial and error which one
You will probably have to do a price update hourly though.
That's the closest you are going to get to realtime prices.
Or completely different solution. Refresh your prices via ajax on page load. Make sure your ajax controller is uncached.

A: This solves my problem,
When we have made the Update on Save index to Update by schedule, this issue has been resolved.


text:
Q: Is there a model of set theory in which $\mathfrak p< \mathfrak b < \mathfrak q$? Is there a model of set theory in which $\mathfrak p< \mathfrak b < \mathfrak q$?
Here $\mathfrak p$, $\mathfrak b$, $\mathfrak q$ are small uncountable cardinals:

*

*$\mathfrak p$ is the smallest cardinality of any family $\mathcal F \subseteq [\omega]^\omega$, which has the strong finite intersection property, but does not have a pseudo intersection;

*$\mathfrak b$ is the bounding number;

*$\mathfrak q = \min\{\kappa :\text{ no subset }X \subseteq \mathbb R\text{ of cardinality }|X| \ge κ\text{ is a Q-set}\}$.

*

*$\min\{\mathfrak b, \mathfrak q \}\in \{\mathfrak p,\mathfrak q \}$ ?


text:
Q: Tricky Linq Group by for time ranges I have a class that represents a shift that employee's can work:
public class Shift {
    public int Id { get; set;}
    public DateTime Start {get;set;}
    public DateTime End { get; set;}
    public DayOfWeek Day { get; set;}
}

And say I have a list of these shifts for a single employee:
List<Shift> myShifts;

I know I can get group the shifts by day with the following linq statement:
var shiftsByDay = from a in myShift
                  group a by a.Day;

My question: For each day, how can I get all the shifts that overlap, in separate groups, without double counting?
An overlapping shift is one where either the start or end times overlap with another shifts start or end times.
I'd love to be able to do this with linq if at all possible.

A: First, I think it would be easier if you gave each shift some unique identifier so that you can distinguish it.   Then I think you can use Where to choose each element that has any conflicts with another element in the collection.  Finally you can group them by day.  Note this won't tell you which shifts conflict, just the ones that have a conflict on any given day.
public class Shift {
    public int ID { get; set; }
    public DateTime Start {get;set;}
    public DateTime End { get; set;}
    public DayOfWeek Day { get; set;}
}

var query = shifts.Where( s1 => shifts.Any( s2 => s1.ID != s2.ID
                                        && s1.Day == s2.Day
                                        && (s2.Start <= s1.Start && s1.Start <= s2.End)
                                             || (s1.Start <= s2.Start && s2.Start <= s1.End))
                  .GroupBy( s => s.Day );

foreach (var group in query.OrderBy( g => g.Key ))
{
    Console.WriteLine( group.Key ); // Day of Week
    foreach (var shift in group)
    {
         Console.WriteLine( "\t" + shift.ID );
    }
}


text:
Q: can't access json_encode data from PHP in my JQuery script What I am trying to do is I ma sending a data which is a user input to PHP file called test.php and there I d like to do something with that data such as insert it into database for example and as I echo my data back as json_encoded to JQuery I d like to access a specific values and place them somewhere on the page however this is not working for me. Please help me to figure it out as I have tried many options.
My HTML code is:
<input type="text" class="form-control mr-2" placeholder="First name"
name="firstName">
<input type="text" class="form-control" placeholder="Surname"
name="surname">
<textarea  id="textarea"rows="4"  placeholder="Enter your profile summary
here and click save button" ></textarea>
<button id="saveprofile" type="submit" class="btn btn-success" title="save
your changes"></button>

My test.php
<?php
session_start();
include_once("db files/db_connect.php");

$bio =  $_POST['bio'];
$name = $_POST['name'];
$surname = $_POST['surname'];

echo json_encode(array($_POST));
?>

I can see the json_encode data as an output in the console however I can not access it and here is what I tried and my AJAX:
$("#saveprofile").click(function (e){
e.preventDefault();
// Get data to update
var bio = $('#textarea').val();
var name = $('input[name=firstName]').val();
var surname = $('input[name=surname]').val();

$.ajax(
       {
            url: 'test.php',
            type: 'post',
            datatype: 'json',
            cache: false,
            data: {bio: bio,
                   name: name,
                   surname: surname},
            success: function(result){
                console.log(result);
                console.log(result.bio);
                console.log(result[0].bio);

                    $('#profilesum').empty().html(result);
                }

            }
    )
});

console.log(results); prints out the following values from test.php
[{"bio":"My name is who... my name is haa...
","name":"Pit","surname":"Pistol"}]

I have tried using json_encode($_POST) and assiging the $_POST array to another array before encoding it but whatever I try the
console.log(result.name);
console.log(result.bio);
console.log(result[0].bio);

doesn't give me the value just says 'undefined' even that I can see the
console.log(result);

as shown above
Any clues anyone?
PS. my var_dump in PHP also shows correct values
array(3) {
["bio"]=>
string(61) "Please work..... but you don't ..... and I m confused.com :( "
["name"]=>
string(3) "Pit"
["surname"]=>
string(6) "Pistol"
}

Thank you guys in advance


text:
Q: Linux processes with no usage I made a complex C program that, during its execution, forks many other processes this way:
#include <unistd.h>

int main(int argc, char *argv[])
{
    pid_t childpid = fork();

    if(childpid == -1) {
        perror("Failed to fork");
    }

    if(childpid == 0) {
        setsid();
    int execReturn = execl("/bin/my_code", (char *) 0);
    } else {}

    return 0;
}

The point is that when I launch a TOP command from the shell, I can see lots of processes named "my_code", and they all look like this:
2377 root      20   0     0    0    0 Z   0,0  0,0   0:00.14 my_code
2379 root      20   0     0    0    0 Z   0,0  0,0   0:00.02 my_code
2380 root      20   0     0    0    0 Z   0,0  0,0   0:00.02 my_code

I fear this could be dangerous since my code is designed to run continuously without interruption.
Internet didn't help me much.
Note: My OS is Raspbian.
edit:
what I am asking, besides the code, is wether those processes that I see in the TOP output could be dangerous to the CPU or not.
As I said, my code is designed to run continuously, so I don't know if the problem will show up in a week or so.
edit:
I edited my code to make it independent from child processes using system(...) call.
Many thanks to @alk.


text:
Q: Can a for loop increment/decrement by more than one? Are there other ways to increment a for loop in Javascript besides i++ and ++i? For example, I want to increment by 3 instead of one.
for (var i = 0; i < myVar.length; i+3) {
   //every three
}

A: Andrew Whitaker's answer is true, but you can use any expression for any part.
Just remember the second (middle) expression should evaluate so it can be compared to a boolean true or false.
When I use a for loop, I think of it as
for (var i = 0; i < 10; ++i) {
    /* expression */
}

as being
var i = 0;
while( i < 10 ) {
    /* expression */
    ++i;
}

A: for (var i = 0; i < myVar.length; i+=3) {
   //every three
}

additional
Operator   Example    Same As
  ++       X ++        x = x + 1
  --       X --        x = x - 1
  +=       x += y      x = x + y
  -=       x -= y      x = x - y
  *=       x *= y      x = x * y
  /=       x /= y      x = x / y
  %=       x %= y      x = x % y

A: Use the += assignment operator:
for (var i = 0; i < myVar.length; i += 3) {

Technically, you can place any expression you'd like in the final expression of the for loop, but it is typically used to update the counter variable.
For more information about each step of the for loop, check out the MDN article.

A: You certainly can. Others have pointed out correctly that you need to do i += 3. You can't do what you have posted because all you are doing here is adding i + 3 but never assigning the result back to i. i++ is just a shorthand for i = i + 1, similarly i +=3 is a shorthand for i = i + 3.

A: For those who are looking to increment pair of numbers (like 1-2 to 3-4):
Solution one:

//initial values
var n_left = 1;
var n_right = 2;

for (i = 1; i <= 5; i++) {

    console.log(n_left + "-" + n_right);

    n_left =+ n_left+2;
    n_right =+ n_right+2;
}
//result: 1-2 3-4 5-6 7-8 9-10

Solution two:

for (x = 0; x <= 9; x+=2) {

    console.log((x+1) + "-" + (x+2));

}
//result: 1-2 3-4 5-6 7-8 9-10

A: A for loop:
for(INIT; TEST; ADVANCE) {
    BODY
}

Means the following:
INIT;
while (true) {
    if (!TEST)
        break;
    BODY;
    ADVANCE;
}

You can write almost any expression for INIT, TEST, ADVANCE, and BODY.
Do note that the ++ operators and variants are operators with side-effects (one should try to avoid them if you are not using them like i+=1 and the like):

*

*++i means i+=1; return i

*i++ means oldI=i; i+=1; return oldI
Example:
> i=0
> [i++, i, ++i, i, i--, i, --i, i]
[0, 1, 2, 2, 2, 1, 0, 0]

A: for (var i = 0; i < 10; i = i + 2) {
    // code here
}

A: The last part of the ternary operator allows you to specify the increment step size. For instance, i++ means increment by 1. i+=2 is same as i=i+2,... etc.
Example:
let val= [];

for (let i = 0; i < 9; i+=2) {
  val = val + i+",";
}

console.log(val);

Expected results: "2,4,6,8"
'i' can be any floating point or whole number depending on the desired step size.

A: There is an operator just for this. For example, if I wanted to change a variable i by 3 then:

var someValue = 9;
var Increment  = 3;
for(var i=0;i<someValue;i+=Increment){
//do whatever
}

to decrease, you use -=

var someValue = 3;
var Increment  = 3;
for(var i=9;i>someValue;i+=Increment){
//do whatever
}


text:
Q: CKEditor flickers/resizes on page load before settling on correct size hi there ive searched high and low to try find an answer to this one
would appreciate any help
see the screencast i took
http://screencast.com/t/B4y96D7rXgp
to explain the video
starts on the page with an editor in it
i then hit refresh
you can the editor loads like 100% height and then 100% width (from the editors left point) at first, then settles into its correct size
im hit refresh 3 times in the video to demo the bug
im using CKEditor 3.5.3 (revision 6655)
anyone got any ideas ive tried a few fixes like setting wifth and height etc but still does this stretch and contract thing
any ideas would be appreciated!

A: You can make use of

editor.on('instanceReady', function()
      {
       hide the container which has same height as ckeditor(you can probably
  show loading here);
       show the ckeditor container;
      });


text:
Q: Determine the category identifier of the category page template in wordpress This is something that has troubled me for the better part of the day. I created a new category.php template file for my girlfriend's cooking blog (you can see it here).
I wanted a specific layout for the category page - not the default one provided by the theme I use (Patchwork).
I googled around and eventually found that I could use the Wordpress PHP function <?php single_cat_title( $prefix, $display ); ?> as described in the Wordpress Codex. The point was then to use the Wordpress shortcode [catlist]. The shortcode can either take the category name or the category id.
I thought that would be it but unfortunately my girlfriend's blog is a bilingual one which means that single_cat_title doesn't always return the same value. It might return recipe in English and recette in French neither of which can be used to resolve the category in [catlist]. And if you think this is a corner case for bilingual blogs, it's not... It also applies to blogs that have categories with the same name (as to why you would have that, I don't know...)
All the other methods I could find were all specific to the_loop and not applicable in my case.
Anyway, I thought I would share the answer below for everyone's benefit. When I found it, it made my day!

A: The way to retrieve the current object identifier (be it a post, category, tag...) is to use the lower-level Wordpress objects and namely:
$wp_query->get_queried_object_id()

as described in Wordpress's class reference. The trick is to know the method name that gives you the property and Wordpress doesn't tell you that.
The closest described method is get_queried_object() (see function reference).
The final template for my page is as follows:
<?php
/**
 * The Template for displaying posts in the category view.
 *
 */
 get_header(); ?>

<?php single_cat_title("");?>

<?php echo do_shortcode('[catlist id='.$wp_query->get_queried_object_id().' orderby=date order=DESC excerpt=yes excerpt_size=25 thumbnail=yes numberposts=-1 template=del]'); ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
Q: Extremely slow GROUP BY on MySQL. Not index-related There are quite a few "why is my GROUP BY so slow" questions on SO, most of them seem to be resolved with indexes.
My situation is different. Indeed I GROUP BY on non-indexed data but this is on purpose and it's not something I can change.
However, when I compare the performance of GROUP BY with the performance of a similar query without a GROUP BY (that also doesn't use indexes) - the GROUP BY query is slower by an order of magnitude.
Slow query:
SELECT someFunc(col), COUNT(*) FROM tbl WHERE col2 = 42 GROUP BY someFunc(col)

The results are something like this:
someFunc(col)    COUNT(*)
=========================
a                100000
b                80000
c                20
d                10

Fast(er) query:
SELECT 'a', COUNT(*) FROM tbl WHERE col2 = 42 AND someFunc(col) = 'a'
UNION
SELECT 'b', COUNT(*) FROM tbl WHERE col2 = 42 AND someFunc(col) = 'b'
UNION
SELECT 'c', COUNT(*) FROM tbl WHERE col2 = 42 AND someFunc(col) = 'c'
UNION
SELECT 'd', COUNT(*) FROM tbl WHERE col2 = 42 AND someFunc(col) = 'd'

This query yields the same results and is about ten times faster despite actually running multiple separate queries.
I realize that they are not the same from MySQL point of view, because MySQL doesn't know in advance that someFunc(col) can only yield four different values, but still it seems like too big of a difference.
I'm thinking that this has to do with some work GROUP BY is doing behind the scenes (creating temporary tables and stuff like that).
Are there configuration parameters that I could tweak to make the GROUP BY faster?
Is there a way to hint MySQL to do things differently within the query itself? (e.g. refrain from creating a temporary table).
EDIT:
In fact what I referred to as someFunc(col) above is actually a JSON_EXTRACT(). I just tried to copy the specific data being extracted into its own (unindexed) column and it makes GROUP BY extremely fast, and indeed faster than the alternative UNIONed queries.
The question remains: why? JSON_EXTRACT() might be slow but it should be just as slow with the four queries (in fact slower because more rows are scanned). Also, I've read that MySQL JSON is designed for fast reads.
The difference I'm seeing is between more than 200 seconds (GROUP BY with JSON_EXTRACT()) and 1-2 seconds (GROUP BY on a CONCAT() on an actual unindexed column).

A: First, for this query:
SELECT someFunc(col), COUNT(*)
FROM tbl
WHERE col2 = 42
GROUP BY someFunc(col);

You should have an index on tbl(col2, col).  This is a covering index for the query so it should improve performance.
Small note:  The second version should use UNION ALL rather than UNION.  The performance difference for eliminating duplicates is small on 4 rows, but UNION is a bad habit in these cases.
I'm not sure what would cause 10x performance slow down.  I can readily think of two things that would make the second version faster.
First, this query is calling someFunc() twice for each row being processed.  If this is an expensive operation, then that would account for half the increase in query load.  This could be much larger if the first version is calling someFunc() on all rows, rather than just on matching rows.
To see if this is an issue, you can try:
SELECT someFunc(col) as someFunc_col, COUNT(*)
FROM tbl
WHERE col2 = 42
GROUP BY someFunc_col;

Second, doing 4 smaller GROUP BYs is going to be a bit faster than doing 1 bigger one.  This is because GROUP BY uses a sort, and sorting is O(n log(n)).  So, sorting 100,000 rows and 80,000 rows should be faster than sorting 180,000.  Your case has about half the data in two groups.  This might account for up to 50% difference (although I would be surprised if it were this large).


text:
Q: POST request in search query with Scrapy I am trying to use a Scrapy spider to crawl a website using a FormRequest to send a keyword to the search query on a city-specific page. Seems straightforward with what I read, but I'm having trouble. Fairly new to Python so sorry if there is something obvious I'm overlooking.
Here are the main 3 sites I was trying to use to help me:
Mouse vs Python [1]; Stack Overflow; Scrapy.org [3]
From the source code of the specific url I am crawling: www.lkqpickyourpart.com\locations/LKQ_Self_Service_-_Gainesville-224/recents
From the source of the particular page I found:
<input name="dnn$ctl01$txtSearch" type="text" maxlength="255" size="20" id="dnn_ctl01_txtSearch" class="NormalTextBox" autocomplete="off" placeholder="Search..." />
Which I think the name of the search is "dnn_ct101_txtSearch" which I would use in the example I found cited as 2, and I wanted to input "toyota" as my keyword within the vehicle search.
Here is the code I have of my spider right now, and I am aware I am importing excessive stuff in the beggining:
import scrapy
from scrapy.http import FormRequest
from scrapy.item import Item, Field
from scrapy.http import FormRequest
from scrapy.spider import BaseSpider

class LkqSpider(scrapy.Spider):
name = "lkq"
allowed_domains = ["lkqpickyourpart.com\locations/LKQ_Self_Service_-_Gainesville-224/recents"]
start_urls = ['http://www.lkqpickyourpart.com\locations/LKQ_Self_Service_-_Gainesville-224/recents/']

def start_requests(self):
    return [ FormRequest("www.lkqpickyourpart.com\locations/LKQ_Self_Service_-_Gainesville-224/recents",
                 formdata={'dnn$ctl01$txtSearch':'toyota'},
                 callback=self.parse) ]

def parsel(self):
    print self.status

Why is it not searching or printing any kind of results, is the example I'm copying from only intended for logging in on websites not entering to searchbars?
Thanks,
Dan the newbie Python writer

A: Here you go :)
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import scrapy
from scrapy.shell import inspect_response
from scrapy.utils.response import open_in_browser

class Cars(scrapy.Item):
    Make = scrapy.Field()
    Model = scrapy.Field()
    Year = scrapy.Field()
    Entered_Yard = scrapy.Field()
    Section = scrapy.Field()
    Color = scrapy.Field()

class LkqSpider(scrapy.Spider):
    name = "lkq"
    allowed_domains = ["lkqpickyourpart.com"]
    start_urls = (
        'http://www.lkqpickyourpart.com/DesktopModules/pyp_vehicleInventory/getVehicleInventory.aspx?store=224&page=0&filter=toyota&sp=&cl=&carbuyYardCode=1224&pageSize=1000&language=en-US',
    )

    def parse(self, response):
        section_color = response.xpath(
            '//div[@class="pypvi_notes"]/p/text()').extract()
        info = response.xpath('//td["pypvi_make"]/text()').extract()
        for element in range(0, len(info), 4):
            item = Cars()
            item["Make"] = info[element]
            item["Model"] = info[element + 1]
            item["Year"] = info[element + 2]
            item["Entered_Yard"] = info[element + 3]
            item["Section"] = section_color.pop(
                0).replace("Section:", "").strip()
            item["Color"] = section_color.pop(0).replace("Color:", "").strip()
            yield item

        # open_in_browser(response)
        # inspect_response(response, self)

The page that you're trying to scrape is generated by an AJAX call.
Scrapy by default doesn't load any dynamically loaded Javascript content including AJAX. Almost all sites that load data dynamically as you scroll down the page are done using AJAX.
^^Trapping^^ AJAX call's are pretty simple using either Chrome Dev Tools or Firebug for Firefox.
All you have to do is observe the XHR requests in Chrome Dev Tools or Firebug. XHR is an AJAX request.
Here's a screen shot of how it looks:

Once you find the link, you can go change its attributes.
This is the link that the XHR request in Chrome Dev Tools gave me:
http://www.lkqpickyourpart.com/DesktopModules/pyp_vehicleInventory/getVehicleInventory.aspx?store=224&page=0&filter=toyota&sp=&cl=&carbuyYardCode=1224&pageSize=1000&language=en-US

I've changed the page size to 1000 up there to give me a 1000 results per page. The default was 15.
There's also a page number over there which you would ideally increase till you capture all the data.

A: The web page requires javascript rendering framework to load the content in the scrapy code
Use Splash and refer the document for usage.


text:
Q: If I allow users to write HTML for their "profile", what elements should I disallow/remove to keep it safe for other users? For my users' profiles, I am going to let them insert HTML code, which will be displayed on their profile.
Is there any special tags I need to manually remove when they save their profile?
Besides the <script> tag, what else could be dangerous?
What else could be "dangerous"?

A: applet, embed, object, script and iframe should be avoided at all costs.
a and img can be problematic as they allow linking to off-site resources. They can also contain javascript: urls
Avoid letting users enter any head-tags into cotnent meant for the body.  style, link, meta, title etc
You also have to be careful of attributes.  Don't allow any attribute that begins with on, as they are javascript event bindings.  You also want to check any URL attributes for javascript: and data: urls.
EDITED TO ADD:
Forms and their children are also probably something to avoid as they can be used to dupe users into entering information that gets harvested by some other site.
I'd recommend using a whitelisting policy instead of blacklisting when it comes to tags and attributes, as it's far easier to miss something with a blacklist.  Also with HTML5 gaining traction there's a whole host of new tags and attributes to watch out for.

A: Pretty much everything. You don't know that people aren't doing:
<img onload="hax" />

In addition, you MUST validate it server-side, not just client-side

A: img seems another obvious one. But I agree with Lollero, don't think in terms of what to disallow, but in terms of what to allow. And keep in mind that it's not just tags, but attributes as well. You want to build a whitelist of tags and the attributes you want to allow on them.
FWIW, here's the whitelist that Wordpress uses for comments by default (er, at least the fairly out-of-date install of it I have handy):

*

*a

*

*href - be sure to only allow the protocols you want to allow, e.g., probably not the javascript: pseudo-protocol.

*title

*abbr

*

*title

*acronym

*

*title

*b

*blockquote

*

*cite

*cite

*code

*del

*

*datetime

*em

*i

*q

*

*cite

*strike

*strong
(You can find this list in the $allowedTags variable in wp-includes/kses.php.) I figured it was relevant as Wordpress is a hugely popular platform.

A: Basically remove every tag and attribute except harmless ones you want to allow like, p, strong, b, em, ul, ol, li, div, span, h2, h3, u, i
If you allow img tag, make sure not to remove alt, src and title attribute.
If you allow a tag, make sure not to remove href attribute.
Consider this, the list of possible tags and attributes will be almost endless in your check code.

A: Assuming that you're not using PHP or other server-side processing, the only other elements I'd worry about are iframe, object, and applet
If you are using a server-side language, just make sure to also sanitize any user input.
You might also want to read up on XSS attacks, just to be wary of any malicious crap: http://ha.ckers.org/xss.html

A: http://html5sec.org/ is a good list of what can be used to execute Javascript.
The best approach is to use whitelist: remove everything except what's definitely safe, like few basic styling elements; don't allow any attributes, if possible.


text:
Q: Loading serialized class from file, when class has changed (Java/Android) I have found many answers on how to write/read a serialized class to a file, and have successfully implemented it into my Android app, I have however hit an issue with expanding the functionality of my app.
For example if I have carClass:
String make;
String model;

I then save that to my save file and whenever I load it the stored values are ok :)
But when I then try to expand the class to include something else i.e. color:
String make;
String model;
String color;

When the app loads the file, it tries to cast the object into the new class, and as the loaded object does not have 'color' it fails to load the save file.
How do I overcome this?  At the moment every time I add new stuff to my app, user's save files are effectively invalid and they have to start again, which is not a good user experience!

A: Declare a static final long serialVersionUID in your class. This will make it forwards/backwards compatible e.g.
String make;
String model;
private static final long serialVersionUID = 0L;

is compatible with
String make;
String model;
String color;
private static final long serialVersionUID = 0L;

as long as you keep the value of serialVersionUID the same. Docs here for android, here for normal Java.


text:
Q: Text field in SVG viewbox does not rotate

        .pie{
            border-radius:50%;
            transform: rotate(-90deg);
        }
        .pie .background{
            fill:none;
            stroke:#eaeaea;
            stroke-width:3;
            stroke-dasharray:100.53 100.53;
        }
         .pie .chart{
            fill:none;
            stroke:#f73319;
            stroke-width:3;
            stroke-dasharray:0 100.53;
            animation: 2s linear slice ;
            animation-fill-mode:forwards;

        }
         .pie text{
            font-size:6px;
            transform: rotate(90deg);
            transform-origin: 50% 50%;
         }
        @keyframes slice{
            to{stroke-dasharray:75.39 100.53;}
        }
<body>
<svg viewBox="0 0 64 64" class="pie">
    <circle class="background" r="25%" cx="50%" cy="50%">

    </circle>
       <circle class="chart" r="25%" cx="50%" cy="50%">

    </circle>
        <text x="32" y="32">
        75%
    </text>
</svg>
</body>

JSFiddle
I have a <text> field in my svg viewbox. The viewbox has been rotated by -90deg, but for obvious reasons I want my text to be rotated back. However only Firefox seems to take into account the above code and rotate the text. Any reason why the other browsers don't? How do I write it correctly so that it does rotate?

A: UPDATE
OP does not prefer placing style in markup such as the previous example of using presentation attribute. I agree, SVG is ugly to begin with why make it uglier? If you are using a real SVG file rather than an embed in HTML...

*

*You could use on external CSS stylesheet by using this <?xml... format:
  <?xml-stylesheet type="text/css" href="style.css"?>

*Or you can use a <style ...<![CDATA[... block:
  <style type="text/css">
     <![CDATA[
       .pie .txt {
          fill: red;
          font-family: Consolas;
          font-size: 14px;
          transform: rotate(90deg);
        }
     ]]>
   </style>

*If it's an embed, a normal <style> block should work:
  <style>
    .pie .txt {
        fill: red;
        font-family: Consolas;
        font-size: 14px;
        transform: rotate(90deg);
     }
   </style>

Here's a Plunker that uses the most simplest option, number 3.

*

*I removed transform-origin: 50% 50%; because HTML starts in the middle, but SVG uses X, Y coords of (0,0) to start out usually. It might be anywhere but where I think it is, so I avoided it.

*Used the fill property.

*Added .txt class to <text> element.

OLD
You can use presentation attributes:
<text x="25" y="12.5" fill="red" transform="rotate(90 20,20)" style="font-family:Consolas;font-size:10">

SNIPPET

            .pie{
            border-radius:50%;
            transform: rotate(-90deg);
        }
        .pie .background{
            fill:none;
            stroke:#eaeaea;
            stroke-width:3;
            stroke-dasharray:100.53 100.53;
        }
         .pie .chart{
            fill:none;
            stroke:#f73319;
            stroke-width:3;
            stroke-dasharray:0 100.53;
            animation: 2s linear slice ;
            animation-fill-mode:forwards;

        }
       /*  .pie .txt {
            fill:red;
            font-family: Consolas;
            font-size:14px;
            transform: rotate(90deg);

         }*/
        @keyframes slice{
            to{stroke-dasharray:75.39 100.53;}
        }
<body>
<svg viewBox="0 0 64 64" class="pie">
    <circle class="background" r="25%" cx="50%" cy="50%">

    </circle>
       <circle class="chart" r="25%" cx="50%" cy="50%">

    </circle>
        <text x="25" y="12.5" fill="red" transform="rotate(90 20,20)" style="font-family:Consolas;font-size:10">

          75%
    </text>
</svg>
</body>

A: There is no need to rotate the whole SVG and then rotate the <text> back to compensate.  Simply rotate the "chart" circle.

.pie .background {
  fill:none;
  stroke:#eaeaea;
  stroke-width:3;
  stroke-dasharray:100.53 100.53;
}

.pie .chart {
  fill:none;
  stroke:#f73319;
  stroke-width:3;
  stroke-dasharray:0 100.53;
  animation: 2s linear slice ;
  animation-fill-mode:forwards;
}

.pie text {
  font-size:6px;
}

@keyframes slice {
  to{stroke-dasharray:75.39 100.53;}
}
<svg viewBox="0 0 64 64" class="pie">
    <circle class="background" r="25%" cx="50%" cy="50%"/>
    <circle class="chart" r="25%" cx="50%" cy="50%"
            transform="rotate(-90 32 32)"/>
    <text x="32" y="32">
        75%
    </text>
</svg>