text:
Q: Static page and posts page Actually, we use the "Last Posts" option for our home page blog.
And we have this kind of url :
http://www.example.com/page/52 (show the page 52)
http://www.example.com/page/10 (show the page 10)

etc.
We would like change home page for a static page. But when we make this setting, the previous URLs stop working and show home page only:
http://www.example.com/page/52 (home page, not the page 52)
http://www.example.com/page/10 (home page, not the page 10)

How can I use a static page and keep "/page/xx" still working?
Is it possible? It's really important for our SEO

A: Use this plugin, and just set all child pages of 'page/' redirect to the home page:
https://wordpress.org/plugins/redirection/


text:
Q: PayPal Subscriptions: validating success on a server I apologize in advance for this question, as its probably rather silly, but I really can not find any answers elsewhere.
My current goal is to integrate a subscription to my website, that allows for a user to have access to certain parts of the site.
I've watched a few videos on it, but it leaves me open ended with some questions.
PayPal allows you to manually create a subscription plan at https://www.paypal.com/billing/plans. When you create a plan here, it gives you the code you need to get the pay pal sub buttons to display on the page. Users can then use them to create the subscription. This is great. However, I have found now way to validate the results of the transaction. My goal would be that if the user was successful, I would be able to retrieve data via the API, that says it was successful, and I could then store than information in my database, and grant them access. Does anyone know how to get the data from the manually created facebook plans?
I did watch a video that had you do everything from your website (you create it all within your own code), the end result however sent everything through $_GET variables in the url. I feel like having this data exposed could result in the manipulation of the subscription, and grant it to users who were unsuccessful in creating a subscription.
I have no problem doing all of the coding to make this work, but I really want to make sure I do it the best possible way.

A: There is a few way to do it. By setting up a webhook and listen to paypal success notification and react to it. By using the Paypal Subscription API. Or a combination of both.
As you are using the paypal button you will have the onApprove function which will trigger upon user confirming the subscription. You can query the subscription data with:
onApprove={async (data: any, actions: any) => {
      const detailedSubscriptionData = await actions.subscription.get()

      // activate subscription on your side by sending it to your backend
      ...

      // etc.
    }}

Inside the data you have queried above, there will be a paypal transaction id (I-....) that is unique for each transaction, as well as your product id (plan_id). You can now do the following for verification on your backend:

*

*Check if there is already a subscription (from another customer) on your side with that paypal transaction id

*Check for the plan_id

*Queried the API Subscription Details with the paypal transaction id and check for status, etc. as well as matching of plan_id

Keep in mind that for using the API you will have to queried for an access-token which in turn required you to have Developer App Setup following these steps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Center multiline text vertically in a window, pure winapi and c++ I have a window that needs redrawing multiline text on demand, text could be of variable length.
So how to go about doing this ?
This is what I have for now and it doesn't work.
               RECT rc;

               GetWindowRect ( hwnd, &rc );

               int rectHeight = DrawText( hMemDc, text.c_str(), text.size(), &rc, DT_CALCRECT );                    // Get formating rectangle height

               int windowHight = rc.bottom - rc.top;
               int windowWidth = rc.right - rc.left;

               int yTop = rc.top + (  ( windowHight - rectHeight ) / 2  );
               int yBottom = yTop + rectHeight;

               int xLeft = rc.left + 20;
               int xRight = rc.right - 20;

               rc.top       = yTop;
               rc.bottom    = yBottom;
               rc.left      = xLeft;
               rc.right     = xRight;

               DrawText( hMemDc, text.c_str(), text.size(), &rc, DT_LEFT | DT_WORDBREAK );

A: There are two problems in your code. First, you need to specify DT_WORDBREAK in the DT_CALCRECT call otherwise it won't wrap the text to fit the available width.
int rectHeight = DrawText( hMemDc, text.c_str(), text.size(), &rc,
  DT_CALCRECT|DT_WORDBREAK );

Second, the DT_CALCRECT call will override the rc variable with calculated rect, so your window height will be wrong and your centering won't work. Either save the rc variable before the DT_CALCRECT call, or call GetWindowRect again afterwards.
GetWindowRect ( hwnd, &rc );

A: I solved the problem drawing some debug lines to help me with the code:
                {
                    CPen p;
                    p.CreatePen(PS_SOLID, 0, RGB(0,0,255));
                    pDrawDC->SelectObject(&p);

                    pDrawDC->MoveTo(rc.TopLeft());
                    pDrawDC->LineTo(rc.BottomRight());
                }

                CRect rdebug(rc);

                int height= pDrawDC->DrawText(sLabel, &rdebug, DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_CALCRECT);

                {
                    CPen p;
                    p.CreatePen(PS_SOLID, 0, RGB(0,255,0));
                    pDrawDC->SelectObject(&p);

                    pDrawDC->MoveTo(rdebug.TopLeft());
                    pDrawDC->LineTo(rdebug.BottomRight());
                }

                int center_y= rc.CenterPoint().y;
                rc.top= center_y - height / 2;
                rc.bottom= center_y + height /2;

                {
                    CPen p;
                    p.CreatePen(PS_SOLID, 0, RGB(255,0,0));
                    pDrawDC->SelectObject(&p);

                    pDrawDC->MoveTo(rc.TopLeft());
                    pDrawDC->LineTo(rc.BottomRight());
                }

                pDrawDC->DrawText(sLabel, rc, DT_CENTER | DT_VCENTER | DT_WORDBREAK);

Notice the rDebug, CPen, LineTo and MoveTo lines are only for debug purposes.
I've got the following image:

Now, without the debug part, I could reduce the source-code footprint to:
                int height= pDrawDC->DrawText(sLabel, CRect(rc), DT_CENTER | DT_VCENTER | DT_WORDBREAK | DT_CALCRECT);

                int center_y= rc.CenterPoint().y;
                rc.top= center_y - height / 2;
                rc.bottom= center_y + height /2;

                pDrawDC->DrawText(sLabel, rc, DT_CENTER | DT_VCENTER | DT_WORDBREAK);


text:
Q: See what actually happens in NetworkInterface.getNetworkInterfaces(); I want to know what code actually executing behind NetworkInterface.getNetworkInterfaces(); How can i find out it ? Where can i see native method ?
I need it, because suddenly this method start to take too long time (10 sec for only 3 network interfaces)


text:
Q: When will I need a javascript anonymous function immediately invoked? I see no situation where I need this
(function(param){
alert(param);
//do something
})("derp");

istead of this
alert("derp");
//do something

EDIT: ok, thanks everybody, i think i got it.
so if you have this:
var param = "x";
var heya = "y";

(function(param){
    alert(param);
    //do something
    })(heya);

the global variable "param" will be ignored in the scope of the anonymous function?

A: How about this scenario?
Example #1 - Uses an Immediately Invoked Function Expression that closes over a single variable and returns another function.  Resulting in a beautiful, encapulated function.
var tick = (function () {
   //Example of function expression + closure
   var tock = 0;

   return function() {
        return ++tock;
   }
}());

//It is impossible to alter `tock` other than using tick()
tick(); //1
tick(); //2
tick(); //3
tick(); //4

VERSUS
Example #2 - Uses a Function Declaration w/ a global variable
//Unnecssary global (unless wrapped in another function, such as jQuery's ready function)
var tock = 0;

function tick() {
    return ++tock;
}

tick(); //1
tock = 4; //tock is exposed... and can be manipulated
tick(); //5
tock = 6;
tick(); //7

It is a contrived example but still a real case scenario in situations where people may want to generate consecutive UNIQUE ID's with no possibility of collision.

A: Well, you don't - for this simple example.
In JavaScript, variables are scoped to functions; therefore, if you wrap it in a function, you avoid global namespace pollution.

A: Well, in the example you've given, no, there probably isn't any reason why you would do this.
However, such a pattern is used typically to ensure that variables or functions, you require at a global level

*

*Can be isolated from others potentially defined in other libraries

*

*thus is an effective way to hide private variables

*Can be protected against being tampered with by other libraries

Globals in Javascript are evil.
In particular, when working with jQuery I will frequently enclose the $(callback(){}) in a function like this, so that I can have global state for the jQuery code that I don't want inside the callback itself, usually because I have other code that isn't necessarily dependant on the jQuery ready initialisation:
function(){
  var something = 'something';
  $(function(){
    something = 'jQuery bound';
  });
}();

A: Aside from polluting the global namespace, memory usage is the other reason to do this - if you're pulling in a big data structure that only gets used once, wrapping that in a (function(){})() block means that you know it will be cleaned up once the function is finished executing.


text: Q: What library/framework can I use to make a file watch service that can detect when a file download is completed I have to build an automation project that will move all downloaded files into another file after the download is completed. What api/library should I use for this project?


text:
Q: What exactly can Taskmaster copy? What exactly can Taskmaster copy? For example, could he:

*

*copy a pregnant lady and get pregnant for only a short amount of time?

*copy non human things like animals?

*do accounting like a pro?

*make really hard sound effects after hearing them like a crane noise or something?

A: Taskmaster's powers are generally described as photographic reflexes in every comic with him that I've read. This generally means that he can mimic any action he sees, as soon as he sees it. It does not allow him to perform actions that he is not physically capable of performing.
For sound, wikipedia has an un-cited example of him being able to mimic voices, so it may be possible. Given the stated way that his powers work, he would likely need to see a human(oid) with a similar vocal tract making a sound to be able to mimic it.
Watching an accountant would probably given him the enter numbers in spreadsheets like a pro, but not necessarily know what numbers he should enter (he does generally get some ability to predict the next moves of his opponents by copying them, but I think it would be a stretch to apply that here).
As with any comic book power, the exact nature of it is guaranteed to change a bit between writers and over time.

A: This question was asked over on Reddit and user neoblackdragon answered with:

He can't perform a move that requires powers.
So he sees Quicksilver running then he can learn his running technique but he'd never have super speed. If Quicksilver without powers has great running technique though then Taskmaster may benefit from it.

It has some other answers you might like to look at as well.


text:
Q: Tracking the mouse relative to starting drag position HTML5, Ember Starting off of this fiddle I'd like to output the coordinates of the draggable object, as it's dragged, relative to its starting position, which is always {0,0}.  I know I can log the beginning and end drag events like:
DragNDrop.Draggable = Ember.Mixin.create({
    attributeBindings: 'draggable',
    draggable: 'true',
    dragStart: function(event) {
        var dataTransfer = event.originalEvent.dataTransfer;
        dataTransfer.setData('Text', this.get('elementId'));
        console.log('begin coordinates: (0, 0)');
    },
    dragEnd: function(event) {
        console.log('end coordinates');
    }
});

So I have two problems:
1.How do I get the mouse coordinates?
2.How do I continue to output the mouse coordinates until the dragEnd function is called?
Edit:
For 1. I can now get the mouse coordinates using:
DragNDrop.Draggable = Ember.Mixin.create({
    attributeBindings: 'draggable',
    draggable: 'true',
    dragStart: function(event) {
        var dataTransfer = event.originalEvent.dataTransfer;
        dataTransfer.setData('Text', this.get('elementId'));
        console.log('begin coordinates: ', event.originalEvent.pageX, event.originalEvent.pageY);
    },
    dragEnd: function(event) {
        console.log('end coordinates: ', event.originalEvent.pageX, event.originalEvent.pageY);
    }
});

But I still am not sure how to continually output the current mouse coordinates, rather than only one when the drag starts and once when the drag ends.

A: Try this
DragNDrop.Draggable = Ember.Mixin.create({
    attributeBindings: 'draggable',
    draggable: 'true',
    dragStart: function(event) {
        var dataTransfer = event.originalEvent.dataTransfer;
        dataTransfer.setData('Text', this.get('elementId'));
        console.log('begin coordinates: ', event.originalEvent.pageX, event.originalEvent.pageY);
        },
        // track the drag
        drag: function(event) {
            console.log('tracking coordinates: ', event.originalEvent.pageX,  event.originalEvent.pageY);
        },
        dragEnd: function(event) {
            console.log('end coordinates: ', event.originalEvent.pageX, event.originalEvent.pageY);
        }
});

A: This code shows the coordinates of the mouse on drag
HTML

<input type = 'text' value = 'test' id='myInput'/>

JQUERY
$(document).ready(function(e){
    $('#draggable').draggable();
    $('#draggable').on('drag' , function(event){
        $('#myInput').val(event.pageX + ',' + event.pageY);
    })
})

CSS
#draggable
{
    background-color:#EEE;
    width:200px;
    height:200px;
}

JSFIDDLE LINK


text:
Q: Generate dummy images local via CLI I need to generate some (thousands) dummy images local to test a CLI based content converter. The file names are set.
A name list as example:
fw4df.jpg
antotherName.jpg

and so on.
I would write a script using ImageMagick extension to create those images with some dummy content.
Any suggestion to solve this more clever?

A: ImageMagick ships with some built in images. The most common ones are wizard:, rose:, and logo:
convert wizard: wizard.jpg

convert rose: rose.jpg

convert logo: logo.jpg

Edit
If you just want a clever PHP function, I would continue to use PseudoImages to simplify everything.
function createPseudoImage($label_text, $width, $height, $label_format='No. %d') {
  $background = new Imagick;
  $background->newPseudoImage($width, $height, 'PATTERN:HORIZONTALSAW');

  $label = new Imagick();
  $label->setBackgroundColor('transparent');
  $label_width = $background->getImageWidth() * 0.8;
  $label_height = $background->getImageHeight() * 0.8;
  $label_text = sprintf('CAPTION:'.$label_format, $label_text);
  $label->newPseudoImage($label_width, $label_height, $label_text);
  $offset_x = $background->getImageWidth()/2 - $label->getImageWidth()/2;
  $offset_y = $background->getImageHeight()/2 - $label->getImageHeight()/2;
  $background->compositeImage($label, Imagick::COMPOSITE_ATOP, $offset_x, $offset_y);
  return $background;
}

$fpo = createPseudoImage(49, 500, 200);
$fpo->writeImage('/tmp/out.png');

But YMMV

A: I would do this for 1,000 images:
head -1000 /path/to/your/word/list |
   while read word; do                              \
      echo -n $word | convert label:@- "$word.jpg"  \
   done

You get

A: I wrote a script based on the PHP doc example. Perhaps it will help someone:
<?php

generateDummyImages(array("test.jpg", "test2.jpg"));

/**
 *
 * @param array $files
 * @param string $dataOutPath
 */
function generateDummyImages($files, $dataOutPath = "") {
    $width                      = 500;
    $height                     = 500;
    $imageCompressionQuality    = 90;

    foreach($files as $i => $filename) {
        /* Create a new imagick object */
        $im = new Imagick();

        /* Create new image. This will be used as fill pattern */
        $im->newPseudoImage($width, $height, "gradient:red-black");

        /* Create imagickdraw object */
        $draw = new ImagickDraw();

        /* Start a new pattern called "gradient" */
        $draw->pushPattern('typo', 0, 0, $width, $height);

        /* Composite the gradient on the pattern */
        $draw->composite(Imagick::COMPOSITE_OVER, 0, 0, $width, $height, $im);

        /* Close the pattern */
        $draw->popPattern();

        /* Use the pattern called "gradient" as the fill */
        $draw->setFillPatternURL('#typo');

        /* Set font size to 52 */
        $draw->setFontSize(100);

        /* Annotate some text */
        $draw->annotation($width / 2 - 100, $height / 2, "No. " . $i);

        /* Create a new canvas object and a white image */
        $canvas = new Imagick();
        $canvas->newImage($width, $height, "white");

        /* Draw the ImagickDraw on to the canvas */
        $canvas->drawImage($draw);

        /* 1px black border around the image */
        $canvas->borderImage('black', 1, 1);

        /* Set the format to PNG */
        $canvas->setImageFormat('jpg');
        $canvas->setImageCompression(Imagick::COMPRESSION_JPEG);
        $canvas->setCompressionQuality($imageCompressionQuality);

        /* Output the image */
        $canvas->writeimage($dataOutPath . $filename);
        echo "Image generated: " . $dataOutPath . $filename . PHP_EOL;
    }
}

?>


text:
Q: Acces to component instance inside mat-row Angular Material Table  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> <app-my-component [position]="element.position" ></app-my-component> </td>
  </ng-container>

image of my table
Hello,
I want to access to my component instance that is inside a matRow
https://stackblitz.com/edit/angular-mmuf6a
I have create an row directive with host on click listener and I try to get the component inside my row with the ng.probe function
Is there a better way to do this ?

A: Another possible solution is to use @ViewChildren() decorator to get List of all your custom components placed inside the table component.
table-basic-example.html
<tr mat-row
    [cdkRowDirective]="row"
    *matRowDef="let row; columns: displayedColumns;let i = index"
    (click)="doSomething(i)">
</tr>

table-basic-example.ts
export class TableBasicExample {
  @ViewChildren(MyComponent) private myComponents QueryList<MyComponent>;

  public doSomething(index: number): void {
    const item: MyComponent = this.myComponents.find((item: MyComponent, i: number) => {
      return index === i;
    });
    item.doWork();
  }
}

After that you could traverse through this list using QueryList api methods (map, find etc.).
Then add click event handler on row and pass row index to it, then access custom component by this index.


text:
Q: Can't get the 'page' parameter This question is related to THIS question.
What I have so far is:
onPaging: function(pgButton){
            var status = returnUserStatus();
            var pageNum = $('#userslist').getGridParam('page');
            if(pgButton=="next_pager"){
                //window.alert("next clicked! \n page: " + page);
                loadUsers(status, pageNum);
            }
            if(pgButton=="prev_pager"){
                //window.alert("prev clicked! \n page: " + page);
                loadUsers(status, pageNum);
            }
            if(pgButton=="last_pager"){
                //window.alert("last clicked! \n page: " + page);
                loadUsers(status, pageNum);
            }
            if(pgButton=="first_pager"){
                //window.alert("first clicked! \n page: " + page);
                loadUsers(status, pageNum);
            }else if((pgButton !="first_pager") && (pgButton !="last_pager") && (pgButton !="prev_pager") && (pgButton !="next_pager"))
                //window.alert("enter pressed \n page: "+ page );

                console.log(pageNum);
                loadUsers(status, pageNum);
        },

The problem is that the I can't get it when enter is clicked(in the testing above) for unknown reason the variable pageNum is undefined.
Please, help me! I'm trying to fix this issue since 2-3 days

A: Vipresh is right.
This code:
onPaging: function (pgButton) {
    var pageNumber = $(this).jqGrid("getGridParam", "page");
    alert(pageNumber);
    //...
}

Would have alerted the new page number in previous versions of the jqGrid, but is now alerting the old page number instead, which is quite useless at my own opinion.
Here is what I had to do in order to get the new page number with the latest version of jqGrid:
onPaging: function (pgButton) {
    var newUserValue = $('input.ui-pg-input', "#pg_pagerId").val();
    var newValue = 0;
    var currentValue = $("#gridId").getGridParam('page');
    if (pgButton.indexOf("next") >= 0)
        newValue = ++currentValue;
    else if (pgButton.indexOf("prev") >= 0)
        newValue = --currentValue;
    else if (pgButton.indexOf("last") >= 0)
        newValue = $("#gridId").getGridParam('lastpage');
    else if (pgButton.indexOf("first") >= 0)
        newValue = 1;
    else if (pgButton.indexOf("user") >= 0)
        newValue = newUserValue;
    alert(newValue);
},

A: The page number can be get by the following code
onPaging: function (pgButton) {
    var pageNumber = $(this).jqGrid("getGridParam", "page");
    alert(pageNumber);
    //...
}


text:
Q: Trying to determine the meaning of "event.target.contains===this.node" I'm working on some React stuff, and I found this relevant codepen to my work. Looking through their source code, they used some syntax I'm unfamiliar with.
Specifically, this line in the _handleClick function confused me:
const wasOutside = !(event.target.contains === this.root);

In the context of the code, it's checking to see whether or not the user has clicked outside of a context menu that was generated with a right click. I under stand what it's doing, but I'm unclear on how it's doing it. I've tried to track down documentation on event.target.contains, but I've had no luck.
Here's what I think is happening. Event.target gives me a node location. This.root is also a node location on the dom. I think that event.target.contains is the same as node.contains, but per my reading of the documentation, I think that node.contains could only return a boolean true or false, and it would take an argument of some sort? So far as I can tell, there's no way for wasOutside to have any value except for true, and this code is unnecessary. Is this accurate? Am I missing something, or interpreting something incorrectly?


text:
Q: jQuery dropdown menu opens all sub-menus I have a problem regarding jQuery. I want to make a responsive drop-down menu with sub-menus. If the window width is less than 700px the submenus will trigger onClick. If the window is wider than 700px the submenus will triger onHover.
The window.resize code is there to make the change when I resize the window, without refreshing the page. It works, but the problem is that if I click/hover any of the two links with nested sub-list it opens ALL the nested lists. Other than that works as it should.
This is the Html code (the .navLevel2 class has display: none):

link 1

link 2

link 2.1

link 2.2

link 3

link 3.1

link 3.2

link 4

And this is the jQuery:

The trigers, written in header:
function click_m(){
  $('.fakeLink > ul').slideToggle(300);
}

function toggle_m(){
  $('.fakeLink > ul').stop().slideToggle(300);
}

So, the problem is:
If I hover/click on Link 2, it opens ALL the nested lists. Same if click/hover the Link 3.
Where is the problem, because I can't find the bug.
Thank you!

A: The selector .fakeLink > ul in your trigger -
function click_m(){
   $('.fakeLink > ul').slideToggle(300);
}

function toggle_m(){
   $('.fakeLink > ul').stop().slideToggle(300);
}

will try to find all
 under the class .fakeLink, and thus all of them show.
You can use next() to just select the very next
 and I believe that should work.  So -
function click_m(){
   $('.fakeLink').next('ul').slideToggle(300);
}

function toggle_m(){
   $('.fakeLink').next('ul').stop().slideToggle(300);
}

Not tested.

A: I think you need to change your click_m function to target the specific element that's being clicked. I tried this:
function click_m($target){
  $($target).children().slideToggle(300);
}

and had the script call:
$('.fakeLink').attr('onclick','return click_m(this)');

which seems to work. You can see it here: Codepen Example
You'd then just duplicate the concept with the hover versions.


text:
Q: How to enable MultiAZ for an RDS Instance using Boto3? I wanted to enable the multi-az feature for an rds instance using Boto3.But it is not getting done by using the script.Also I updated my policy for rds instances but still it is not getting updated.I am using the following script.
    modified_rds_attributes = rds_conn_boto3.modify_db_instance(DBInstanceIdentifier=id, MultiAZ=True).

A: According to the RDS API docs, this change will not occur until the next maintenance window unless you specify the ApplyImmediately parameter.  So, this:
rds_conn_boto3.modify_db_instance(DBInstanceIdentifier=id, MultiAZ=True, ApplyImmediately=True)

Should cause the change to happen immediately.


text:
Q: Port go AES Encrypt function to node.js Im trying to port a go program (https://github.com/McKael/samtv) that can control samsung TVs via the "SmartView" API to node.js
In the program is a "AES Encrypt" function that i have trouble with porting to node.
func (s *SmartViewSession) aesEncrypt(plaindata []byte) ([]byte, error) {
    //logrus.Debugf("aesEncrypt(%#v) : '%s'", plaindata, string(plaindata))
    //logrus.Debugf("session ID:  %d", s.sessionID)
    //logrus.Debugf("session key: '%x'\n  %v", string(s.sessionKey), s.sessionKey)

    // Create cipher block
    block, err := aes.NewCipher(s.sessionKey)
    if err != nil {
        return nil, err
    }

    bs := block.BlockSize()
    //logrus.Debugf("block size: %d", bs)

    // Add padding
    padding := bs - len(plaindata)%bs
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    //logrus.Debugf("padding: %d byte(s)", padding)
    plaindata = append(plaindata, padtext...)

    // Encrypt
    ciphertext := make([]byte, len(plaindata))
    for cipherrange := ciphertext; len(plaindata) > 0; {
        block.Encrypt(cipherrange, plaindata[:bs])
        plaindata = plaindata[bs:]
        cipherrange = cipherrange[bs:]
    }

    //logrus.Debugf("ciphertext: %#v", ciphertext)
    return ciphertext, nil
}

The problem im facing right now is, i dont know what algorythim is used, or where the "initial vector" is coming from i need to specify in my node.js function:
const SESSION_KEY = "59e8ca4b09f2a19ab5421cf55d604c7c";

var aesEncrypt = ((val, algo = "aes-256-cbc") => {
    let cipher = crypto.createCipheriv(algo, SESSION_KEY, IV);
    let encrypted = cipher.update(val, 'utf8', 'base64');
    encrypted += cipher.final('base64');
    return encrypted;
});

Sould i use crypto.createCipher(...) instead? But its deprecated and have also the feeling that the padding stuff is important.
I have absolutely no clue about encryption.
Any hint is welcome.
NOTE: In the go function, s.sessionKey is the same value as in node.js the SESSION_KEY = "59e8ca4b09f2a19ab5421cf55d604c7c"

A: The Go code applies AES in ECB mode with PKCS#7 padding. The AES variant is implicitly derived from the keysize, e.g. AES-128 for a 16 bytes key. The ciphertext is returned as []byte.
In the NodeJS code, the AES variant is explicitly specified, along with the mode, e.g. aes-128-ecb. The ECB mode does not apply an IV, so it must be specified as null in createCipheriv(). As padding PKCS#7 (default) is used. The ciphertext can be returned as Buffer, which is closest to []byte.
The posted key 59e8ca4b09f2a19ab5421cf55d604c7c looks like a hex encoded key, which is hex decoded 16 bytes large and thus corresponds to AES-128. The hex decoding can be achieved in Go with the encoding/hex package, e.g. with hex.DecodeString("59e8ca4b09f2a19ab5421cf55d604c7c").
Example for a NodeJS code that uses AES-128 (16 bytes key) in ECB mode and PKCS#7 padding:
var crypto = require('crypto');

const SESSION_KEY = Buffer.from("59e8ca4b09f2a19ab5421cf55d604c7c", "hex");

var aesEncrypt = ((val, algo = "aes-128-ecb") => {
    let cipher = crypto.createCipheriv(algo, SESSION_KEY, null);
    return Buffer.concat([cipher.update(val, 'utf8'), cipher.final()]);
});

var ciphertext = aesEncrypt("The quick brown fox jumps over the lazy dog");
console.log(ciphertext.toString('base64')); // T/uQforseVFkY93mqwpwCGVVnEFDTT5Gle8a8XUxCfOXCfYUo3uCJ/nwzCIJ9xqf

The Go code gives the same result using the same key (hex decoded) and plaintext and with Base64 encoding of the ciphertext.
For completeness: The key could also be UTF-8 encoded and would then result in a 32 bytes key, e.g. with key := []byte("59e8ca4b09f2a19ab5421cf55d604c7c") in the Go code and const SESSION_KEY = Buffer.from("59e8ca4b09f2a19ab5421cf55d604c7c", "utf-8") in the NodeJS code. In the NodeJS code, additionally aes-256-ecb must be applied. Ultimately, the key specification must provide information about which encoding to use.

Note that the ECB mode is insecure. Nowadays, authenticated encryption is usually used, e.g. via GCM mode.


text:
Q: From which existing branch, the new branch should be created? I have completed the work in release20140116 branch and pushed it to remote.This branch is not yet merged with master branch. My master branch has updates till my last release  branch  release20140109 .
Now, I need to work on another module for which I would like to create another branch for next release release20140123.
From which existing branch should I create this new release20140123 branch ?
master or release20140116 ?
The sentence "From which existing branch",  I meant :
git checkout master
git branch release20140123

OR
git checkout release20140116
git branch release20140123

A: If you had a develop branch, my answer would be from develop. If you don't know git-flow yet, I strongly recommend you have a look at it: I find its branching model very effective. Have a look at this brief article for a short introduction.
Anyway, in your current situation, I would personally base it on master as it's supposed to hold the most recent and stable state of the project.


text:
Q: how to auto adjust design for all simulators I am developing an application with the 9630 BlackBerry simulator, but when I test with the 9550 simulator, my app draws off-screen.   How do I adjust for all simulators to avoid this?

A: Using HorisontalFieldManager and VerticalFieldManager (aspecially with USE_ALL_WIDTH, USE_ALL_HEIGHT style flags) makes life easier.
Also remember about using scroll inside field managers (ex. for vertical lists)
Talking about image resources, like backgrounds etc, there are several ways you can go:

*

*separated image resources for each screen size + ant file to copy/delete during device-specific build

*separated image resources for each screen size + runtime screen size check and resource selection by filename

*runtime image resources generation (like 9 patch in Android)

*try to avoid use of image resources, and use gradient or solid backgrounds

See also
Blackberry User Interface Design - Customizable UI?
developing application for diffrent screen size
Supporting multiple screens - Blackberry
UI compatibility across all BlackBerry devices


text:
Q: Running Invoke-AzureRmVMRunCommand through Azure automation I am trying to run a script thorugh Invoke-AzureRmVMRunCommand from azure automation but it is showing cmdlet does not exist. Please let me know how to implement this.
Below the script
Invoke-AzureRMVMRunCommand -ResourceGroup 'XXXXXX' -Name XXXXX-CommandID 'RunPowerShellScript' -ScriptPath 'Test.ps1'

Error details.
Invoke-AzureRMVMRunCommand : The term 'Invoke-AzureRMVMRunCommand' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is
correct and try again.
At line:1 char:1
+ Invoke-AzureRMVMRunCommand -ResourceGroup 'olf3em-rds-mgmt' -Name OLF   ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Invoke-AzureRMVMRunCommand:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

A: You need to install modules before using those:
https://learn.microsoft.com/en-us/azure/automation/automation-runbook-gallery#modules-in-powershell-gallery
in short:
go to modules
browse gallery
install

A: The Invoke-AzureRmVMRunCommand command is included in the AzureRM.Compute module. Which you will first need to install in your Automation Account.


text:
Q: Get RGB pixel data of a section of a screen as an array in pygame My code allows a user to draw on a section of a pygame screen. I want to be able to extract all the RGB pixel values for this section of the screen and convert them to a 3d array, like this:
top_left = [50, 50]
bottom_right = [100, 100]
pixel_data = SomeFunctionToGetPixelData(screen, top_left, bottom_right)

# get RGB value for pixel that was at position (53, 51) on the screen
print(pixel_data[3][1])
> [255, 255, 255]

What's the best way to do this?

A: Create a subsurface from the section of the screen. A subsurface shares its pixels with its new parent (see pygame.Surface.subsurface):
w = bottom_right[0] - top_left[0]
h = bottom_right[1] - top_left[1]
area = pygame.Rect(top_left[0], top_left[1], w, h)
sub_surface = screen.subsurface(area)

Use pygame.surfarray.array3d() to copy the pixels from a Surface into a 3D array:
pixel_data = pygame.surfarray.array3d(sub_surface)

Minimal function:
def get_pixel_data(surf, top_left, bottom_right):
    w = bottom_right[0] - top_left[0]
    h = bottom_right[1] - top_left[1]
    sub_surface = surf.subsurface(pygame.Rect(*top_left, w, h))
    return pygame.surfarray.array3d(sub_surface)


text:
Q: Encrypt on jenkins or S3 and decrypt on EC2 instance I want to automate the deployment of new code on my application using AWS CodeDeploy. I'm using AWS to run my application. What I want to do is the following:

*

*Build the application in jenkins (runs on AWS as well)

*Send the compiled application on S3, along with some environment variables that are to be set automatically by CodeDeploy hooks (AfterInstall)

*CodeDeploy will take care of the rest of the steps

What I want to know is, is there a AWS practice to encrypt those env vars (they are in a text file) while on S3 and decrypt them when inside the instance? If not, do you have any pointers on how I could achieve what I want (some security regarding these env vars while on S3)?
P.S. The reason for uploading these env vars in S3 and setting on every deployment is because they tend to change. I don't want to bake them in the image. Moreover moving away from env vars is not an option.

A: When putting data in Amazon S3, there are two ways to encrypt the data:

*

*Client-side encryption, or

*Server-side encryption.

Client-side Encryption
Amazon does not have any built-in client-side encryption mechanism. You'll have to roll this yourself: Encrypt the data in Jenkins using your favourite tool then upload it. When the objects are downloaded from S3, decrypt the objects after they are downloaded.
One way you could do this is using 7z to zip and encrypt the archive using AES256 encryption. Another is using OpenSSL.
Server-side Encryption
Amazon does have a built-in server-side encryption mechanism.
If you are using the AWS CLI to upload your files to S3, you can use the --server-side-encryption command-line argument to have your files encrypted on the server. When the objects are downloaded, they will automatically decrypted.
However, be aware, that this does not protect the object against being downloaded via the S3 API from anyone but you. If anyone uses valid AWS credentials and downloads the file, it will be open to them.
What it does protect against is someone accessing the object via non-API means, such as direct data-center access.
Final Notes
If you want the files to be unreadable to anyone but you, ever, then you want client-side encryption.


text:
Q: How to decompress faster in Java? Our system is having a problem with too much files, which is used in a webapp which should be using all the time. That mean the files cannot be deleted and there are too much of them, making the system(which is a windows) slow. We would like zip up the files, and when the file is request, we unzip the particular file out.
I've try the java ZipFile class, and the performance is not good enough, because there will be many people using the webapp and they will request the files. From my observation, the unzipping action require time between 0.5 secs to 2 secs, and when there are too much user, the system cannot catch up to them.
For example, I've use a Jmeter to simulate a situation where 30 user use the system, with a random delay between 0.3 secs to 0.6 secs. Although I doubt there may not be so much requests, I cannot know for advance that how many people will use the webapps.  I would like to ask you guys, is there any other method to solve this problem?
Thanks in advance!!
P.S. If any 3rd party library is need, it must be free!
P.S. Because the number of files is just too much, and it hang the machine. We would like do this : zip up 2000 file into a zip file, then the number of files will decrease and hope the system won't hang anymore, and when need, we unzip some file out.

A: Okay, here's some thoughts. It appears to me that your core problem is the slowness of your system and that you're trying to fix it by compressing the files and decompressing them on demand. Then you've found that the decompression is too slow and you need a faster way to do that.
Now I'm not entirely certain why you think this compression will speed things up instead of making things slower.
I would go back to the original problem and work more on solving that. Why is the number of files making your system slow? If you can figure that out, you can fix it in a way that doesn't involve things going even slower.
If it's an issue with too many files in a directory, think about splitting into multiple directories. But I have no idea whether NTFS even has that problem (FAT did). For example, if you have a directory with files for every minute of the last ten years (five million files), you can split them into day directories (three and a half thousand directories with fifteen hundred files in each).
Compression won't reduce the number of files, just the space taken by them.
If it's an issue with the number of files on the system (rather than in a directory), there are plenty of ways to split files between systems as well. Example, hive off 10% of the entire file set to ten different machines and forward incoming requests for a specific file to the relevant machine.
But, I have to say, I've seen Windows machines handle absolute bucket-loads of files so I'd be very surprised if the problem lay there. I think you're probably just going to have to track down what's actually causing your "hangs".

A: compressing/uncompressing the files will not make the windows faster.

A: If zip doesn't provides performance gain (despite has native implementation in Java), you can try to improve at the filesystem-level. Folders with too many (>10000) files doesn't work well under some Windows filesystems, so try to divide the files into several folders, tune the NTFS filesystem (cluster size, reserved space for filesystem), disable anti virus, disable indexing, buy an SSD SLC hard disk...


text:
Q: Exclude all lines with specific lower case characters in unix text file I have a text file which has combination of lower/upper characters. I want to remove lines where any of a few specific lowercase letters are seen.
Text file contents:
aASDF1234qwerty;lkJHG
fdsaAghiyirchgdadgqa2

Task - Remove all lines where any of the lowercase characters 'a','e','j','k' occurs.
I tried below option to get all lines where only upper case are found but its not working as expected. grep -wo '[[:alnum:]]*A*E*J*K*[[:alnum:]]*' test.txt

A: Using grep:
grep -v '[aejk]' /path/to/file

Using awk:
awk '! /[aejk]/ { print }' /path/to/file

Using sed:
sed '/[aejk]/d' /path/to/file

The regular expression used in all of these examples, /[aejk]/, can be transliterated to mean "any character of: a, e, j, or k".  The grep and awk invocations return any line which does not match that expression; the sed invocation has the same end result, but works by omitting from the parsed file any lines which do match.


text:
Q: Why is angularFire example deleting all of my Firebase entries? I'm trying to get a simple angularFire example working, and am seeing anything I add to my synced Firebase db being immediately deleted. I expected the input box to sync to a string in /items/foo. What am I missing?

A: angularFire is a little aggressive about removing items that don't match the expected data type. There's discussion about fixing this behavior on Github if you're interested, but you can work around it by explicitly specifying the data type using the 4th argument:
var url = 'https://andreystest.firebaseio.com/items';
angularFire(url, $scope, 'items', '');

The fourth argument is an empty string, which tells angularFire that whatever is stored at the URL is a string. The default model type is an array ([]).
Edit: There seems to be some issues with jsFiddle and Angular. You are missing the ng-app and ng-controller directives which means angular is never initialized. However, even after adding those tags I can't get it to work in jsFiddle, it does work on a regular web page though. Give http://misc.firebase.com/~anant/angular-test.html a try!


text:
Q: How to version string elements? I have below list of strings available as list
 List<string> available = new List<string> {"C1,C2,C3,C1_V1" };

I have input parameter C1. Now I have to match available strings in available list of strings. Whenever my input is C1 then matching elements are C1,C1_V1 in available so my string should increase by 1 to get C1_v2. I have mentioned clearly in below table

As per the above table,
case 1- Avail is C1,C2,C3 and input is C1 so my destination should be C1_V1
case 2 - avail is C1,C2,C3,C1_V1 and input is C1 but my destination cannot be C1_v1 because it is already available in avail so next version should be C1_v2 and so on.
I am trying to implement this logic in c#. I have started doing this but couldnt get it done
List<string> available = new List<string> {"C1,C2,C3,C1_V1" };

string input = "C1";

string destination = string.Empty;

foreach(var data in available)
{
    destination = $"{input}_V{initialVersion}";
}

Can someone help me to complete this. Any help would be appreciated.

A: You could count the number of items in available that match the given input, and use that count to determine the version.
A simple matching algorithm might be where a string in available is equal to input or where a string in available starts with "{input}_".
In order to handle cases where input is given with the version part, such as C1_V1 you need to split the input on the version separator, '_', and just look at the "key" part of the input.
public string NextVersion(string input, List<string> available)
{
    // Argument validation omitted.
    if (input.Contains('_'))
    {
        input = input.Split('_')[0];
    }
    int count = available.Count(a => string.Equals(a, input) || a.StartsWith($"{input}_"));
    if (count == 0)
    {
        // The given input doesn't exist in available, so we can just return it as
        // the "next version".
        return input;
    }

    // Otherwise, the next version is the count of items that we found.
    return $"{input}_V{count}";
}

This assumes that '_' is only valid as a version separator. If you can have strings in available such as "C1_AUX" then you'll run into issues trying to get the next version of "C1".
It also assumes that you want to increment to the next version, even if input is a version that doesn't exist. For example, if available is ["C1", "C1_V1"] and input is "C1_V123" than the return value should be "C1_V2".
Poul Bak raises another caveat. If you end up with a situation where available is missing a version. For example, if available is ["C1", "C1_V2"] and input is "C1" then the result of this function is "C1_V2", leading to a duplicate version. In this case, you'd probably have to find every item in available where the "key" part is input's key part, then parse each one to find the next version.
It isn't clear what the constraints are requirements are exactly, so these caveats may or may not be an issue. But they're certainly worth keeping in mind.


text:
Q: Bootstrap 4, is-pending form validation state I want to do a form pending state while checking server api for field validity. Using Bootstrap 4 scss code, I modified this piece of code in _form.scss file :

Normally, now setting is-warning, should put the form input in a warning state where the border are in warning color, but it not working, is-valid and is-invalid are of course working correctly
I have checked that the css related to is-warning is correctly add in Firefox debugger console, i just don't know why is-warning don't apply the correct effect event if it present in css.

A: @include form-validation-state("warning", ...) cannot work because of lines like this one: https://github.com/twbs/bootstrap/blob/v4.1.3/scss/mixins/_forms.scss#L55
.form-control,
  .custom-select {
    .was-validated &:#{$state},  // <====
    &.is-#{$state} {
      ...
    }
  }
}

See :#{$state}? it will generate :warning which does not exist in CSS.
The CSS pseudo classes :valid and :invalid do exist so they work.
When the browser encounters a CSS selector that he does not understand, he ignores the whole CSS statement so &.is-#{$state} (&.is-warning) won't be applied.
See https://github.com/twbs/bootstrap/issues/23371


text:
Q: Unable to get localhost certificate path using the %userprofile% in angular.json file I am trying to attach the cert and key when running npm start
But I couldn't able to get the current user folder path using %userprofile%
Getting error

Generating browser application bundles (phase: setup)...(node:8688) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'address' of undefined
at F:\Project\AngularApp\node_modules@angular-devkit\build-webpack\src\webpack-dev-server\index.js:79:46
(Use node --trace-warnings ... to show where the warning was created)
(node:8688) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:8688) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

In my Anguar.json file I have made changes like this.,
"serve": {
    ***,
    "options": {
    "browserTarget": "EmailAddIn:build:development",
    "ssl": true,
    "sslKey": "%userprofile%//.office-addin-dev-certs//localhost.key",
    "sslCert": "%userprofile%//.office-addin-dev-certs//localhost.crt"
}

If I move localhost.key & localhost.cert to project direct and run commands like ng serve --ssl --ssl-key .\\ssl\\localhost.key --ssl-cert .\\ssl\\localhost.crt then everything work fine but issues is everyone who working with me are need to do manually configured
Please help me to short out these issues.
Thanks.


text:
Q: Python len not working In the code below, I am trying to use len(list) to count the number of strings in an array in each of the tags variables from the while loop. When i did a sample list parameter on the bottom, list2, it printed 5 which works, but when i did it with my real data,it was counting the characters in the array, not the number of strings. I need help figuring out why that is and i am new to python so the simplest way possible please!
#!/usr/bin/python

import json
import csv
from pprint import pprint

with open('data.json') as data_file:
data = json.load(data_file)

#pprint(data)

# calc number of alert records in json file
x = len(data['alerts'])
count = 0
while (count < x):
    tags = str(data['alerts'][count]    ['tags']).replace("u\"","\"").replace("u\'","\'")
    list = "[" + tags.strip('[]') + "]"
    print list
    print len(list)
    count=count+1

list2 = ['redi', 'asd', 'rrr', 'www', 'qqq']
print len(list2)

A: Your list construction list = "[" + tags.strip('[]') + "]" creates a string, not a list. So yes, len works, it counts the characters in your string.
Your tags construction looks a bit off, you have a dictionary of data (data['alerts']) which you then convert to string, and strip of the '[]'. Why don't use just get the value itself?
Also list is a horrible name for your variable. This possible clashes with internal values.

A: list = "[" + tags.strip('[]') + "]"
print list
print len(list)

Ironically, list is a string, not a list. That's why calling len on it "was counting the characters in the array"

A: you need to make sure that your variable is a list rather than a str,
try:
print(type(yourList))

if it shows that it is a str, then try this:
len(list[yourList)

hope this answers your question
and when you want to establish a list variable, try this:
myList = []
for blah in blahblah:
    myList.append(blah)

I think these definitely solved your problem, so I hope you noticed this part.


text:
Q: Can't remove the gap between background image and header Trying to remove the gap that exists between the top of the page and my background image.
Tried adjusting with margin in CSS file but nothing is working.
Would greatly appreciate assistance.
Thank you!
screenshot of my issue
body {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}

#header {
-moz-transition: background-color 0.2s ease;
-webkit-transition: background-color 0.2s ease;
-ms-transition: background-color 0.2s ease;
transition: background-color 0.2s ease;
background: #2e3842;
height: 3em;
left: 0;
line-height: 3em;
position: fixed;
top: 0;
width: 100%;
z-index: 10000;
}

HTML:

DFKDJDFD

    Menu

Home

About Us

Contact

Where My background Image is added to CSS:
   body.landing #page-wrapper {
    background-image: -moz-linear-gradient(top, rgba(0,0,0,0.5),
    rgba(0,0,0,0.5)), url("../../images/banner.jpg");
    background-image: -webkit-linear-gradient(top, rgba(0,0,0,0.5),
    rgba(0,0,0,0.5)), url("../../images/banner.jpg");
    background-image: -ms-linear-gradient(top, rgba(0,0,0,0.5),
    rgba(0,0,0,0.5)), url("../../images/banner.jpg");
    background-image: linear-gradient(top, rgba(0,0,0,0.5),
    rgba(0,0,0,0.5)), url("../../images/banner.jpg");
    background-attachment: fixed;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    padding-top: 0;
    }

A: try this on your background image:
 position: absolute; top:0;

and let me know if this does work or not.

A: Try this CSS on your image
img {
position: absolute;
margin: 0px;
padding: 0px;

}

A: This CSS will remove the browser default padding and margin.
 body{
 padding:0px;
 margin:0px;
 box-sizing:border-box;
 }


text:
Q: Applying a data group filter to a gauge's scale and range expressions I am creating a series of gauges with which I'm trying to show how well groups are projecting the number of resource hours they consume each month. The scale of the gauge goes from 0 to a rounded up value of the projected hours, and the gauge needle points to the value of the actual hours used. The range is used to indicate actual is within 10% of the projected hours (green), between 10 to 30% (yellow), or more than 30% off (red). Some examples of gauges that were built individually:

The number of hours that each group projects and uses can vary greatly, as seen from the gauges. I have been able to apply a filter that makes it easy to set the gauge needle to point to the total actual hours for each group by simply changing the group name in the filter, but I can't get the sums of projected hours to filter for each group in the scale and range configurations. As a result, if I create a single gauge with a filter, copy that gauge, and then just change the group name in the filter for each new gauge, I can get the corresponding actual hours (i.e., where the needle points), but the scale defaults to the sum of projected hours for ALL of the groups:

Does anyone know of a way that I can apply the filter to the scale and range calculations other than actually specifying the group name in an already complex IIF expression? I have to create over 50 of these gauges, and it would be prohibitively time consuming to have to cut and paste every instance of the group name into every instance of these expressions.

A: Got it. I needed to add a filter to the Gauge Panel. The first filter I created was applied to the Gauge Data. Once I created that second filter, I was able to use simple expressions to set the scale and range values, and then just change the group name in both filters for each gauge I created. Still a little more manual than I'd like, but substantially more manageable and scalable.


text:
Q: how to find slope of a 3D plane I have a 3D terrain in my scene, I have the location of all the vertices of the terrain.
I want to place any geometry on this terrain procedurally. At the moment I can place the 3D models only on the vertices, as seen in the image below.
If I were to render grass for example in the plane which is highlighted, I need to calculate the slope of the plane, hence the question.
How do one go about calculating slope of a plane in 3D in order to get the coordinates inside the planes which is made by the 4 points? As stated earlier I have all the 4 points which make the plane.
Also Is there any other more efficient way to achieve what I am trying to do [collision detection with the plane may be?]

A: Turn the rectangles into triangles. That will make many things more simple since the rectangles in your example probably aren't planar.
Select two sides of the triangle and create two vectors which point along those sides (i.e. v1 = p2 - p1 and v2 = p3 - p1). To get a random point on the, use:
p = p1 + v1*x + v2*y

where p1 is the common starting point of the two vectors and x and y are random numbers between 0 and 1. If the sum of (x+y)/2 is > 0.5, then the point is outside of the triangle (you could also say that it's in the second triangle).
Related:

*

*Random points inside a 4-sided Polygon

A: There is no unique way to parametrize a 4-gon in 3D space if it is not planar. One simple variant, after the most simple of splitting it into 2 triangles, is to use the parametrization
p1+(p2-p1)*x+(p3-p1)*y+(p4-p3-p2+p1)*x*y,  0 <= x,y <= 1

This is linear at the edges, so neighboring 4-gons will fit together.
Keywords: bilinear (patch?), barycentric coordinates


text:
Q: Py/Tk Grid don't behave property Grid on Tkinter does not resize controls properly. Here is my code:
menubar = Menu(frm)
txt = Text(frm)
def TxtTupleLineCol():
    str = txt.index(INSERT)
    return tuple(str.split(sep='.'))
scrl = Scrollbar(frm, command=txt.yview)
scrl.grid(column=1, sticky=(E + N + S))
txt.config(yscrollcommand=scrl.set)
txt['wrap'] = WORD
scrlw = Scrollbar(frm, orient=HORIZONTAL, command=txt.xview)
scrlw.grid(row=1, sticky=(S + E + W))
st = StatusBar(frm)
tu  = TxtTupleLineCol()
st.variable.set(('Linha:' + tu[-2] + ' Coluna:' + tu[-1]))
txt.config(xscrollcommand=scrlw.set)
txt.grid(row=0, column=0, sticky=NSEW)
st.grid(row=2, sticky=S + E + W)
filen = Cfg("")
frm.columnconfigure(0, weight=1)
frm.columnconfigure(1, weight=1)
frm.rowconfigure(1,weight=1)
frm.rowconfigure(0, weight=1)
frm.grid_propagate(False)

If I resize the window, it spaces between scroll and text. #FIXME?(in another partof code I added that row/col config./ portuguese doesn't affect understanding.)

A: Your code won't run, but judging from what I see it appears you aren't giving your rows or columns any weight, which is usually what causes "doesn't resize properly" problems when using grid. Most likely, adding something like this will fix the problem:
frm.columnconfigure(0, weight=1)


text:
Q: Restrict tab access via search We have a group of users who are in a separate profile that we have hidden tabs from and setup basic security.  However, we have found that some of them are "inquisitive" enough to use search to get to the Account, Contact, Project records and then drill down to some of the financial records that they are not supposed to access.
I know how to set field level security and also page layouts but I was hoping that I could simply deny access to the tab so that even if they searched for it or figured out how to enter the url that it would not display.  I am also concerned that I have triggers, processes, flows, etc that might use these data fields. If I remove access to them for the profile, will the backend processes still work it they perform an action that triggers one of them?

A: It's not enough to remove access to the tab, or, strictly speaking, field level security. You need to remove access to the object itself (turn off "Read Object", e.g. "Read Accounts"). Triggers are not generally affected by the sharing model or profile permissions, so even if the user can't view/edit a given record or object, it won't stop the trigger from running. This is known as "system context." The exception to this are flows; flows run in "user context," so if they can't see the records, they may get flow errors. You might need to resort to using Workflow Rules or Visualforce pages instead of flows.

If you need to restrict access just to records the user should be able to see, you need to modify your Organization Wide Defaults and possibly your Sharing Rules. Only by correctly configuring your security settings can you limit access. Since you've tagged this as a Community question, this probably means you need to set the External Sharing Model to Private, and then configure additional access rules as necessary.


text:
Q: How to design a flexible multi-criteria prioritization? Let's assume that we have a set of valid results, ex. Fruits: "Apple, Banana, Kiwi, Pear, ...".
(In reality, it's not fruits but complex objects)
Now  we need to pick the best result according to some simple prioritization. For example, let's say this prioritization is simply an arbitrary order of preference determined on how well I like the Fruit:
Apple: 1
Banana: 3
Kiwi: 2
Pear: 4

It is easy to design and implement a simple prioritization list to achieve this.
However I know that in a foreseeable future, we'll need to use a much more complicated prioritization, which may rely on factors such as:

*

*What other fruits are in the result set?

*What other fruits aren't in the results?

*Does a fruit have a dirty specks or not?

*Was some fruit already picked in the past days?

*Any other prioritization criteria

What approaches and design can be used for achieving such a flexible multi-criteria prioritization in a maintainable way, ie without relying on a big messy code with tons of edge cases?

A: The priorities aren't complicated - they're still just numbers. The logic that assigns the priority number is more complicated.
Combining multiple factors by adding (or multiplying) them is normal - that way you can have an arbitrary number of classifiers and easily combine them without entangling the logic.

A: I'll assume that your set of results is finite and that you perform the prioritization when the set is fully known.
First naive approach
The prioritization corresponds simply to a mapping function s(o, r)->int which takes as argument an object o of the result set to be prioritized, and the whole result set r and returns a priority score.
You may then implement the prioritization list  by sorting the list according to the score of each element. This may be done for example by keeping in the list pairs of elements with their computed score, or by using an iterator on a map/dictionary.
More robust solution
You may need to take into account the list of possible values (for finding out the missing ones) or the history of previous elements, or anything else the future will bring you.
Therefore you should extend the scoring to take into account these information in addition. You'd best achieve this by making a scoring class, that you can specialize as needed, to take whatever contextual information is relevant to calculate whatever score you  need using the explicit parameters (o and r) as well as any contextual one.
This means that you'd best implement the scoring class as a strategy pattern of your prioritization container/list. This will also enable you to consider performance issues and not always redo the same iteration on the sale full set of results if it is not necessary.
Pseudocode would be something like:
abstract class Scoring {
   public initialize(); // determine loop invariants that are result-set independent
   public prepare(ResultSet R); // operations to be done only once per result set
   public score(ResultObject o); // calculate score using all available data, including prepared result set
};

Of course, depending on your implementation language you may prefer an interface or protocol instead of a pure abstract class.


text:
Q: Роли пользователей для созданий ограничений Есть сайт онлайн банк. Надо создать роли: клиент, менеджер (банкир), администратор.
Как создать роли для пользователей, чтобы можно как-то запрещать доступ к маршруту или наоборот разрешать?
Для клиента банка часть служебной информации надо закрыть и оставить эту информацию только для менеджера


text:
Q: A1278 13" MacBook Pro wake from sleep issue MacBook Pro 13.3"  - Early 2010
A1278
2.66 Ghz
16 GB RAM
2 TB Hard Drive (1.75 TB available)
10.9.5 (because I like Mavericks, we're happy together)
The issue is that the MacBook Pro won't wake up if I have closed the lid. This does not happen if I reopen the lid within a few quick minutes, but after an extended time, an hour, overnight. The sleep indicator light sometimes pulsates; sometimes is lit but not pulsating, but either way, it indicates that the laptop is not completely shutdown. I have to reset SMC every time (or hold down the power button until it shuts down) and restart it to get it up and going.  (I have also reset the NVRAM, only because I was trying everything.  No change.)  Resetting the SMC is ineffective, as the issue returns every time I close the lid.  Disk Utility only shows the typical Safari permissions that need changing, as they always do.  Rebooting in Safe Mode doesn't prevent the issue from happening.  I have reset the PRAM and I have reinstalled the OS.
I always leave my MBP plugged in, because I do all my work right by an outlet, so I have the energy power adapter settings to never sleep for both display and computer.  I have "put hard drive to sleep" unchecked.  I do have "wake for network access" checked.  My battery settings are set to 3 hours (although I never unplug it) and again, "put hard drive to sleep" is unchecked.
I recently disabled hibernation because I suspected it might be stuck in safe sleep mode, but it had no effect.  I also made sure that lidwake is set to 1.  In fact, here is a paste from Terminal:
Battery Power       -1
AC Power        -1*
Currently in use:
womp                 1
halfdim              1
sms                  1
hibernatefile        /var/vm/sleepimage
networkoversleep     0
disksleep            0
sleep                0
hibernatemode        0
ttyskeepawake        1
displaysleep         0
acwake               0
lidwake              1
The last thing I have done through Terminal is to set standby to 0, again with no change.  There are no magnets in my work space, so I don't suspect that sort of interference.  If I put the laptop to sleep by selecting that option from the apple menu, I can wake the computer up.  It really does seem to only fail to wake when I have closed the lid.
This is the only issue with my MacBook Pro when it is up and running; there are no display issues, etc.  I am wondering if there might be something "manual" going on, perhaps related to the lid itself?  I do know the display cable is housed in the hinge.  Other than that, I am at a loss and would appreciate any insight.  Thank you.


text:
Q: Connecting a DomainContext and loading data manually in Silverlight 4 RC application I am new to WCF & RIA services and have what seems like a basic problem. I have multiple times  in my silverlight 4 RC application dragged and dropped from my datasource window to my form and have returned information from the database. However I have a need to query the database for other information (Building a report) When I try to use the following code, I recieve no error, but I also do not get any information back from the service.
//Global
public UMSDomainContext _umsDomainContext = new UMSDomainContext();

//In the Initialization portion
_umsDomainContext.Load(_umsDomainContext.GetUMOptionsQuery());
//Queries
 var name = from n in _umsDomainContext.UMOptions
                              select n.DistrictName;

                var street1 = from c in _umsDomainContext.UMOptions
                              select c.Address1;

                var street2 = from c in _umsDomainContext.UMOptions
                              select c.Address2;

                var city = from c in _umsDomainContext.UMOptions
                              select c.City;

                var zip = from c in _umsDomainContext.UMOptions
                              select c.Zip;

Im calling the current additional references.
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.ComponentModel.DataAnnotations;
using MTT.Web;

A: The answer is very simple. The data when it was being loaded in was instantly being queried. While some applications will treat this procedurally, it seems Silverlight did not wait for the data to load before moving on. So I did the following:
public void LoadCustomerInformation()
{
     //Load the Query
     var loadOperation = _umsDomainContext.Load<UMOption>(_umsDomainContext.GetUMOptionsQuery());
     //Create a event handler to run after the data is fully loaded.
     loadOperation.Completed += new EventHandler(loadOperation_Completed);
}

void loadOperation_Completed(object sender, EventArgs e)
        {
            var name = (from n in _umsDomainContext.UMOptions
                       select n.DistrictName).First();

            var street1 = from c in _umsDomainContext.UMOptions
                          select c.Address1;

            var street2 = from c in _umsDomainContext.UMOptions
                          select c.Address2;

            var city = from c in _umsDomainContext.UMOptions
                       select c.City;

            var zip = from c in _umsDomainContext.UMOptions
                      select c.Zip;

            //Other code to work with the data, etc...
        }


text:
Q: Универсальный AsynkTask Имеется:
Приложение которое взаимодействует с удаленной БД. В каждой активити(фрагменте) может запускаться по несколько AsynkTask на получение(запись) данных.
Получаются код такого вида в каждой активити(фрагменте):
public class AuthorizationActivity extends Activity {
    ...
    class GetServerTimeTask extends AsyncTask<Void, Void, Void>{

        Connection conn;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ...
        }

        @Override
        protected Void doInBackground(Void... params) {

            try{
                conn = DriverManager.getConnection("jdbc:jtds:sqlserver://"+conServer+":"+conPort+"/"+conDB,
                        conUser,
                        conPass);

                ResultSet rs = null;
                CallableStatement cs = null;
                try{
                    cs = conn.prepareCall("{call skl_getdatetime()}");
                    rs = cs.executeQuery();
                    rs.next();
                    Date date = rs.getDate(1);
                    mCurrentDate = date.toString();
                }
                catch (SQLException e){
                    e.printStackTrace();

                }
                finally{
                    try{
                        if (rs != null) rs.close();
                        if (cs != null) cs.close();
                    }
                    catch(java.sql.SQLException e){
                        e.printStackTrace();
                    }
                }
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
            finally{
                if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mProgressDialog.dismiss();
            ..
        }
    }
    //
    class GetUserListTask extends AsyncTask<Void, Void, Void>{
        //Аналогичного плана, получение списка пользователей
    }

Мысли в слух:
До поры до времени такое решение устраивало, но со временем как известно наступает период отвращения к коду и хочется сделать какой то универсальный механизм Task'ов.
По поводу прямого подключения к БД знаю, это очень и очень плохо, но это уже совсем другая история.
Хотелось бы:
Сделать какое то универсальное средство обращения к БД.
Попытка:
Вот такого плана есть задумка, но все равно есть такое ощущение что меняю "шило на мыло":
public class SQLServerAsyncTask extends AsyncTask<Integer, Integer, ServerAsyncTaskResult> {
    private static final String TAG = "SQLServerAsyncTask";

    public static final int REQUEST_SERVET_TIME = 0;
    ...

    public static interface OnServerResponse {
        public abstract void onServerResponse(String response, int requestType);
        public abstract void onServerResponseMessage(String message, int requestType);
    }

    private static OnServerResponse getOnServerResponse(final Context context) {
        if (context == null) {
            return null;
        }

        if (context instanceof OnServerResponse) {
            return (OnServerResponse) context;
        }
        return null;
    }

    private Context context;

    public SQLServerAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected ServerAsyncTaskResult doInBackground(Integer... requests) {
        Response response = null;
        Exception exception = null;
        Connection conn =  DriverManager.getConnection("jdbc:jtds:sqlserver://"+conServer+":"+conPort+"/"+conDB,
                    conUser,
                    conPass);
        requestType = requests[0];
        try {
            switch (requests[0]) {

                case REQUEST_REGISTER: {
                    ...
                }
            }
        } catch (Exception e) {

        }
        ...
    }

    @Override
    protected void onPostExecute(ServerAsyncTaskResult result) {
        ...
    }
}

Так вот, хотелось бы услышать Ваше авторитетное мнение по поводу решения данной проблемы, может быть сталкивался кто нить с аналогичной задачей, и наработал хорошее решение.
Буду рад любому ответу и конструктивной критике. Спасибо за внимание!

A: Вы когда нибудь слышали про разделение логики, какой нибудь MVC? Разделить код на 3 основные компоненты (данные, логику и отображение) чтобы модификация одного из них оказывала минимальное воздействие на остальные.
У вас в первой версии например вот эти строки кода вообще не к месту:
                Date date = rs.getDate(1);
                mCurrentDate = date.toString();

По хорошему вам нужно создать класс - поставщик данных (например назовем его DatabaseHelper), а всякие Activity вообще не должны знать откуда берутся данные - по jdbc, из JSON или из локальной базы.
Т.е. весь ваш код свернется таким образом:
public class AuthorizationActivity extends Activity {
    ...
    class GetServerTimeTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ...
        }

        @Override
        protected Void doInBackground(Void... params) {
            Date date = DatabaseHelper.getDate();
            mCurrentDate = date.toString();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mProgressDialog.dismiss();
            ..
        }
    }

A: Попробую предложить свое виденье решения данного вопроса.
Использовать будем связку IntentService и BroadcastReceiver.
Создадим свой сервис, который будет взаимодействовать с БД:
public class DBConnectionService extends IntentService {

    private static final String TAG = "DBConnectionService";

    public static final String RESPONSE_CODE = "ResponseCode";
    public static final String RESPONSE_DATA = "ResponseData";

    public static final String REQUEST_TYPE = "RequestType";

    public static final int RESPONSE_OK = 1;
    public static final int RESPONSE_ERROR = -1;

    public static final int REQUEST_SERVET_TIME = 0;

    ...

    Connection conn;

    private boolean isDBConnect(){
        try {
            if(conn == null){
                conn =  DriverManager.getConnection("jdbc:jtds:sqlserver://"+conServer+":"+conPort+"/"+conDB,
                        conUser,
                        conPass);
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void sendResponseOk(String action, int requestType, Serializable data){
        Intent intent = new Intent();

        intent.setAction(action);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra(RESPONSE_CODE, RESPONSE_OK);
        intent.putExtra(REQUEST_TYPE, requestType);
        intent.putExtra(RESPONSE_DATA, data);

        sendBroadcast(intent);
    }
    private void sendResponseError(String action, int requestType, Serializable data){
        Intent intent = new Intent();

        intent.setAction(action);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra(RESPONSE_CODE, RESPONSE_ERROR);
        intent.putExtra(REQUEST_TYPE, requestType);
        intent.putExtra(RESPONSE_DATA, data);

        sendBroadcast(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String action = intent.getAction();
        int requestType = intent.getIntExtra(REQUEST_TYPE, -1);

        Serializable data;
        if(!isDBConnect()){
            sendResponseError(action, requestType, null);
            return;
        }

        try {
            switch (requestType) {

                case REQUEST_SERVET_TIME: {
                    ...
                    data = ...
                }
                ...
            }
        } catch (Exception e) {
            data = e.getCause();
            sendResponseError(action, requestType, data);
            return;
        }
        sendResponseOk(action, requestType, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if(conn != null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Вызываем сервис в активити так:
Intent intent = new Intent(this, DBConnectionService.class);
intent.setAction(getClass().getName());
intent.putExtra(DBConnectionService.REQUEST_TYPE, DBConnectionService.REQUEST_SERVET_TIME);
startService(intent);

Теперь остается дело за малым, поймать ответ, для этих целей в активити создадим внутренний класс - BroadcastReceiver:
public class ResponseBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        int responseCode = intent.getIntExtra(DBConnectionService.RESPONSE_CODE, 0);
        int requestType = intent.getIntExtra(DBConnectionService.REQUEST_TYPE,  0);

        if(code == DBConnectionService.RESPONSE_OK){
            switch(type){
                case DBConnectionService.REQUEST_SERVET_TIME: {
                    serverDateReceived();
                }
            }
        } else {
            //we have an error
        }
    }
}

Регистрируем слушатель при создании активити, а так же не забываем его убирать при уничтожении:
private ResponseBroadcastReceiver mBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    IntentFilter intentFilter = new IntentFilter(
            getClass().getName());
    intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
    mBroadcastReceiver = new ResponseBroadcastReceiver();
    registerReceiver(mBroadcastReceiver, intentFilter);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mBroadcastReceiver);
}

Так же как вариант можно создать какую нибудь базовую активити, в которой все это будет реализовано и наследоваться уже от нее.

Код написан на колене и не претендует на звание стопроцентно правильного и оптимального...пробуйте, экспериментируйте.


text:
Q: change property of a group of buttons WPF VB.NET
I have a customized control templated expander menu. Each menu item has some child buttons which will open its own page.
Example shown.
                -----------------------------------
                |   FILE   |   EDIT   |   TOOLS   |
                -----------------------------------
                FILE Menu has child items Button A1, A2, A3, A4
                EDIT Menu has child items Button B1, B2
                TOOLS Menu has child item Button C1

What i need is to change the foreground color of the child buttons based on Mouse selection.
When i select Button A1 (obviously Page of A1 opens), the foreground color of Button A1 should change. Say from white to Green.
Then menu bar collapses. when i go back & check the file menu again the color of Button A1 should be green. and should be disabled
Then when i Select button C1 (page of C1 opens), then the foreground color of C1 should change to green, button being disabled and the foreground color of A1 should change back to white and being enabled.
this is applicable for all child buttons in the menu bar.
How to make this possible in XAML.
Kindly suggest in xaml if it can be done in xaml itself. Else VB.Net


text:
Q: Negating a predicate with a biconditional Negate the following statement and make the negation appear immediately before the predicates
$$ \forall x \forall y(Q(x,y) \leftrightarrow Q(y,x)) $$
I did the following steps:
$$ \neg(\forall x \forall y(Q(x,y) \leftrightarrow Q(y,x))) $$
$$ \exists x  \neg \forall y(Q(x,y) \leftrightarrow Q(y,x)) $$
$$ \exists x   \exists y \neg(Q(x,y) \leftrightarrow Q(y,x)) $$
Now, I do not know what to do simply because of the notation. I assumed the following, knowing that:
$$ \neg(a \leftrightarrow b) \equiv \neg a \leftrightarrow b $$
Would it be enough/correct to leave the following as the answer?
$$ \exists x   \exists y (\neg Q(x,y) \leftrightarrow Q(y,x)) $$

A: First, let's note a couple of equivalences:
$$\begin{align}
p\leftrightarrow q &\equiv (p\land q)\lor (\neg p \land \neg q) \tag{1} \\
&\equiv (p\to q)\land (q \to p). \tag{2}
\end{align}
$$
The negation of $p\leftrightarrow q$ is therefore
$$\begin{align}
\neg(p\leftrightarrow q) &\equiv \neg((p\to q)\land (q\to p)) \tag{by (2)} \\
&\equiv \neg(p\to q)\lor \neg(q \to p) \tag{De Morgan} \\
&\equiv (p\land \neg q)\lor (q \land \neg p) \tag{$\neg(A\to B)\equiv (A\land \neg B)$} \\
&\equiv p\leftrightarrow \neg q \tag{by (1)} \\
&\equiv \neg p\leftrightarrow q. \tag{by (1)} \\
\end{align}$$
Now recall that $\neg\forall \equiv \exists\neg$. Thus the negation of $\forall x \forall y\,(Q(x,y)\leftrightarrow Q(y,x))$ is
$$\begin{align}
\neg \forall x \forall y\,(Q(x,y)\leftrightarrow Q(y,x)) &\equiv \exists x \exists y\,\neg\,(Q(x,y)\leftrightarrow Q(y,x)) \\
&\equiv \exists x \exists y\,(\neg\, Q(x,y)\leftrightarrow Q(y,x)) \\
&\equiv \exists x \exists y\,(Q(x,y)\leftrightarrow \neg\, Q(y,x)).
\end{align}$$


text:
Q: htaccess file-exist check doesnt seem to work when used with apache Alias's I've been using .htaccess files for 15 years so I feel reasonably confident with them. But today I discovered that the "file exists" check doesn't seem to work correctly with Apache's Alias command - and I can't figure out why not (I've read the docs multiple times and can't find anything that would explain this specifically).
e.g. this simple http conf:
Alias /site             /sites/site1.com

e.g. with this simple htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /site/

# this never matches: (despite being used in most examples all over the web)
RewriteCond %{DOCUMENT_ROOT}/$1.extension -f
# this doesn't match either: RewriteCond %{REQUEST_FILENAME} -f

RewriteRule (.*)$ FailOnPurpose [NC]
</IfModule>

...never triggers. The intent here was:

*

*When a request comes in...

*... check if there is a file with that name and the extension "extension"

*... if so: rewrite

e.g. if I request:
http://example.com/site/a.png

and there's a file:
/sites/site.com/a.png.extension

then I expected the RewriteCond to work.
If I remove all aliases from apache, and use plain direct subfolders, then it works.

A: You cannot use DOCUMENT_ROOT inside context of alias directory because DOCUMENT_ROOT will point to a path outside alias path and your condition will always fail.
You may use this rule:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME}.extension -f
RewriteRule (.*) FailOnPurpose [L,QSA]

I have tested it on my local Apache 2.4 within an alias .htaccess


text:
Q: Second Isomorphism Theorem for groups Notation Query The Second Isomorphism Theorem states :
If G is a group, N⊴G and H≤G, we know that:
N∩H⊴H and H/(N∩H)≅HN/N.
and it seems to me as if HN/N should equal H/N. Because, hnN is the same as hN. I just don't understand what's wrong with my train of thought, as surely if I were correct, the book wouldn't be using the notation HN/N.
I hope this doesn't sound like a silly question, it's really doing my head in. Thanks for the help guys!
I dont understand the answer given to the original post which I've copied above
which is
"In the usual framework H and N are subgroups of a larger group G. It is usual to assume only that H is a subgroup and N is a normal subgroup of G. In particular, N may not be a subgroup of H (let alone normal), so H/N doesn't make sense in all cases."
my problem with this answer is I cant understand why doesn't H/N make sense if N isn't a subgroup of H,
since N is a normal subgroup of G and H is a subgroup of G then for every g in G there exists gng^{-1} ∈ N , which entails hnh^{-1} ∈ N  which makes N "normal" to H, such that for each coset hN = Nh and thus the operator of multiplying cosets of hN is closed, and for each hN there exists h^{-1}N such that
hN * h^{-1}N = N
which makes it so that every elemnt of H/N has an inverse,
so why doesnt it make sense to look at H/N as a quotient group ?
So just to reiterate my two questions are:
1.
If G is a group, N⊴G and H≤G, the 2nd theroem of isomorphism says:
N∩H⊴H and H/(N∩H)≅HN/N.
why isnt HN/N rewritten as H/N

*If G is a group, N⊴G and H≤G and H doesnt contain N. Why is H/N not a quotient group ?

thanks
Cay (https://math.stackexchange.com/users/250263/cay), Second Isomorphism Theorem Notation Query, URL (version: 2015-07-08): Second Isomorphism Theorem Notation Query


text:
Q: Limit of a sequence of norms of functionals linear on a sequence of Hilbert spaces Let $H_n$ be a sequence of complex Hilbert spaces such that $H_{n+1}\subsetneq H_n$ and $\bigcap_{n=1}^\infty H_n=\operatorname{span}\{v_0\}$
Let $T_1:H_1\to \mathbb C$ be a continuous linear functional such that $T_1(v_0)=0$
Let, for each $n \in \mathbb N$, $T_n:H_n\to\mathbb C$ the continuous linear functionals obtained by restriction of $T_1$ to $H_n$
I would like to know if $\lim_{n\to\infty}\lVert T_n \rVert = 0$
Thanks for any suggestion.


text:
Q: Como instalar modulos de PHP con Dockerfile para instancias de ElasticBeanstalk AWS Necesito instalar las extensiones mysqli y zip en una imagen de Docker, utilice el archivo Dockerfile para ejecutar la instalación en mis instancias pero sin ningún resultado.
este es el mi archivo Docker file:
FROM php:5.6-fpm

RUN docker-php-ext-install mysqli mysqlnd pdo pdo_mysql zip

y este es el error que muestra mi sitio web:
Fatal error: Call to undefined function mysqli_connect() in /var/www/html/classes/ConnectionFactory.php on line 17

A: TL;DR
La imagen que posteaste no la pude construir, corrigiendo los errores que obtenía llegué a esta imagen que sí funciona:
FROM php:5.6-fpm

RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    zlib1g-dev && \
    docker-php-ext-configure pdo_mysql --with-mysql=mysqlnd && \
    docker-php-ext-configure mysqli --with-mysqli=mysqlnd && \
    docker-php-ext-install mysqli pdo pdo_mysql zip && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

NOTA: Las última dos líneas son para intentar reducir el espacio de la imagen.
Versión larga
Probé construir la imagen que posteaste y me da el siguiente error:
+ cd /usr/src/php/ext/mysqlnd
+ phpize
Cannot find config.m4.
Make sure that you run '/usr/local/bin/phpize' in the top level source directory of the module

Si miramos la documentación de MySQL Native Driver vemos que dice:

5.4.0 El Controlador Nativo de MySQL ahora es el predeterminado para todas las extensiones de MySQL (es decir, mysql, mysqli y PDO_MYSQL).
  Pasar mysqlnd a la configuración ahora es opcional.

Y más abajo en la misma página dice:

Las extensiones de bases de datos MySQL deben estar configuradas para
  utilizar la Biblioteca Cliente de MySQL. Con el fin de utilizar el
  Controlador Nativo de MySQL, PHP necesita ser compilado especificando
  que las extensiones de bases de datos MySQL están compiladas con el
  soporte para el Controlador Nativo de MySQL.

Y también indica cómo compilar las extensiones, es decir, podemos sacar el paquete mysqlnd y necesitamos indicar que las extensiones mysqliy pdo_mysql se compilen con el MySQL Native Drive.
Para esto último puede usar docker-php-ext-configure.
Si agrego las líneas necesarias para configurar los paquetes, luego me dá el error de que no encuentra zlib para compilar la extensión zip:
checking libzip... no
checking for the location of zlib... configure: error: zip support requires ZLIB. Use --with-zlib-dir=<DIR> to specify prefix where ZLIB include and library are located

Por lo que estaría faltando instalar el paquete zlib1g-dev para compilar zip. Agregándolo la instalación del paquete y luego haciendo limpieza de los paquetes, llego a la imagen de arriba.


text:
Q: Common identifier for flow or transactions between nodes Using a client to listen on vault updates proxy.vaultTrackBy on multiple nodes, I can't identify a parameter to reference the end of the same transaction across multiple nodes.
Tried: flowId, hashCode also looking into states but produced and consumed are empty.
Any other identifier or is this intended?

A: Currently, we purposefully avoid sending any kind of invocation ID outside of the node boundaries, since this is private node information and shouldn't be shared for privacy reasons. You have a few options:

*

*If the transaction records the same state in both nodes' vaults, you can check the Vault<Update> object produced on both sides to ensure that the same StateAndRef appears in both nodes' vaults

*

*If consumed and produced are empty, check that the nodes are recording the states in their vault. This is determined by:

*

*Whether they are the owner (for OwnableStates)

*Whether they are a participant (for other state types)

*Whether they are recording the transaction as a participant

*Do something like the following in your flows to notify yourself that the transaction has occurred (where myEventPublishingService is your own API):
@Suspendable
fun call() {
    val proposal = session.receive<TransactionBuilder>().unwrap { it }
    checkThatTheOtherPartyIsNotScammingMe(proposal)

    <here, before signing the transaction and sending it over>

    myEventPublishingService.publish(
        TransactionApprovedEvent.from(proposal, otherParty))

    proposal.sign(services)
    session.send(proposal)
}


text:
Q: MATLAB: How to delay a signal with noise I have an input signal s(n) = [1 -1 0 -1 1 -1 1].
The output signal is a delayed version of the input signal with noise:
x(n) = a*s(n-D) + w(n)

How do i delay the input signal by D?

A: You can pad the signal with zeros.
x = a * [zeros(1,D) s]


text: Q: Functions differentiable on a closed contour Suppose $f(z)$ is differentiable on a closed contour in $\mathbb{C}$, is it bounded on the contour? I guess if we take a closed path $\gamma(t),a\leqslant t\leqslant b$ wher $\gamma(a)=\gamma(b)$, then if I take $M=\sup\{f(\gamma(t))\mid a\leqslant t\leqslant b\}$, then $f(z)\leqslant M$ on this contour. Is it a proper proof?


text:
Q: how jvm handles creating object inside a loop List list = new ArrayList();

String[] test = {"ram", "mohan", "anil", "mukesh", "mittal"};

for(int i =0; i < test.length; i++)

{

  A a = new A();

  a.setName(test[i]);

  list.add(a);

}

How JVM handles creation of object a in each loop? How "list" differntiate between different instance? Is it good practice to create object on each iteration. If no, what is the best solution for adding object into a list.

A: In your example a new object is created on each iteration of the loop.  The list is able to differentiate between them because it does not care that you call them all "a" in your code, it keeps track of them by the reference that gets reassigned each time you call
a = new A();

Each time that line of code is called, a new object is created on the heap and it's address in memory is assigned to the reference a.  It's that reference that the list keeps a record of, not the variable name.
This is a perfectly fine and normal way to populate a list (aside from the syntax errors that others have mentioned, which I'm assuming you can fix when you try to compile your code).

A: List holds a reference to each instance of a that gets created.  It's fine to create each object inside the loop (I'm assuming you mean as opposed to declaring the 'a' variable outside the loop and then re-assigning it each iteration).

A:
Is it good practice to create a new object on each iteration?
  One of my friends told me that it is not a good practice to creating so much instances.

If you need different individual instances, you need to create them.
Since your list needs five objects with different names each (ram, mohan, anil and so on), you need a new object for every iteration of the loop. How else are you going to store the five names?
As for declaring the variable a outside of the loop, I do not think that makes a difference performance-wise and also reduces legibility.
A a;  // dont do this
for(int i =0; i < test.length; i++){
  a = new A();
  a.setName(test[i]);
  list.add(a);
}

You might be interested in the for-each loop
for(String name: test){
   A a = new A();
   a.setName(name);
   list.add(a);
}

A: If my understanding of the JVM is correct, the posted code will have no performance difference compared to
for (String name : test )
{
   list.add(new A(name));
}

(assuming, of course, that the constructor A(String s) is another way to create a new instance with a specific name)


text:
Q: Proper method to access Play! cache in Scala templates? I'm running a Play! app using Scala templates. However, I can't find an elegant method to access the Cache in an elegant (or valid) way inside of html templates.
I've tried everything like:
<some html>@play.cache.Cache.get(play.session.getId() + "-account")</some html>

But no luck. Thanks for the proper way to do this!

A: I found the methodology buried in the old 0.9 Scala documentation. For the time being it's not super-easy but it's 3min do-able. It requires adding a parameter to the controller and template like so:
In your controller, pass session as a parameter
object Application extends Controller {

    import views.Application._

    def index = {
        html.index(session)
    }
}

At the top of your template, define the implicit variable:
@(implicit session:play.mvc.Scope.Session)

Inside the template html, access it like so:
@(play.cache.Cache.get(session.getId() + "-account"))


text:
Q: Jenkins Trigger X minutes after last build We have recently switched from CruiseControl.Net to Jenkins for managing our builds.  With CCNET it would trigger a new build X minutes after the last one completed, but with Jenkins it is constantly dropping builds in the queue, not allowing any time in between the two.   We'd prefer the CCNET method.

*

*I don't see how this can be done with the Scheduler Trigger, it seems to be all date time based.

*I don't see any setting to prevent Queueing another build where the build is currently running.

*I don't see a trigger that would allow for timing based off last run.

How could I manage this?

A: Jenkins lets you set a quiet period between builds, which can be set at the system level and overridden at the job level.  Here's the help text from Jenkins:
If set, a newly scheduled build waits for this many seconds before actually being built. This is useful for:
Collapsing multiple CVS change notification e-mails into one (some CVS changelog e-mail generation scripts generate multiple e-mails in quick succession when a commit spans across directories).
If your coding style is such that you commit one logical change in a few cvs/svn operations, then setting a longer quiet period would prevent Jenkins from building it prematurely and reporting a failure.
Throttling builds. If your Jenkins installation is too busy with too many builds, setting a longer quiet period can reduce the number of builds.
If not explicitly set at project-level, the system-wide default value is used.
And here is a more detailed discussion.


text:
Q: combine 2 columns in sql table to search for full names JPA I have entity where I have fisrtName and lastname but in search I need to implement search for fullName. How can I combine this two fields in search in JPA
right now I have something like this:
Query query = em.createQuery("SELECT u from Client u where u.firstName like :firstName   or u.lastName like :lastName or u.documentID like :documentID");

I guess it is very commonly used feature but I don't know how to do that. Please help

A: You haven't defined what is "full name". If you mean a concatenation of the two "name" fields, then you can use a construct in JPQL such as
CONCAT(u.firstName, ' ', u.lastName)

to put them together with a space in between, and that ought to give enough idea how to get the precise query needed.


text:
Q: event.preventDefault() and return false; are failing me I think I am just too tired right now but why is this not working?
Got a simple form with id="contact"
   $("#contact").on('submit', function(event) {
       event.preventDefault();

       var name = $('#name').serialize();
       var email = $('#email').serialize();
       var message = $('#message').serialize();
       alert(name);

        });
    });

(I stripped out the AJAX that follows)
Why isnt' the window prevented from refreshing? return false; didnt do anything either..
I am probably missing something obvious here

A: You can try this :
$(document).on('submit', "#contact", function(event) {
   event.preventDefault();

   var name = $('#name').serialize();
   var email = $('#email').serialize();
   var message = $('#message').serialize();
   alert(name);
   return true;
});

A: The first point:

*

*You should use .val() instead of serialize() .

*.serialize() is a method applicable to the  element, this method returns a string like this : field1=value1&field2=value2&...&fieldn=valuen

An example:
$("#contact").submit(function(event) {
    event.preventDefault();
    var name = $('#name').val(),
        email = $('#email').val(),
        message = $('#message').val();

    alert(name);
    return false; // "Defensive" line (i think it's not necessary)
});

I hope it will help!


text:
Q: Xampp: Class 'RarArchive' not found I'm working with a php script which extract rar files. I need to make it works on xammp with php 5.6.
In order to install the rar class I have :

*

*put php_rar.dll (compatible with php 5.6) inside the C:\xampp\php\ext folder

*added extension=php_rar.dll inside php.ini

*restart apache service

Here is my code
<?php
    $archive = RarArchive::open('./lobo.rar');
    $entries = $archive->getEntries();
    foreach ($entries as $entry) {
        $entry->extract('./');
    }
    $archive->close();
?>

I still have this error

EDIT
The extension is not present in phpinfo()
In the error.log : PHP Fatal error: Class 'RarArchive' not found in C:\xampp\htdocs\myproject\index.php on line 2

A: The PHP_RAR has dependency to PEAR. See this for more information.
And you may install PEAR following this link.
If you install pear in windows, remember to user command-line tool with administrator privilege.
After installing PEAR, I think your problem will be solved.