text:
Q: Wordpress window manager button styling Created a custom window in wordpress looking like:

Now I need the buttons INSERT and CANCEL (see picture above) to be looking like everywhere else (see picture below) like CANCEL and Add Link

This code gave me the window but I couldn't find any options to change the buttons. There must be something, or it should be something!? Even tried to change the styles (some of the styles get added with javascript) inline styles with !important but no effect ...
( function($) {
    tinymce.create( 'tinymce.plugins.hd_fancybox_button', {
        init: function( editor, url )  {

            editor.addButton( 'hd_fancybox_button', {
                icon: 'icons dashicons-icon',
                tooltip: 'Fancybox',
                cmd: 'plugin_command',
                image : url + '/img/popup-icon.png'
            });

            editor.addCommand( 'plugin_command', function() {
                editor.windowManager.open({
                    title: 'Fancybox',
                    width: 500,
                    height: 300,
                    inline: 1,
                    id: 'hd-fancybox-button-insert-dialog',
                    body: [
                        {
                            type    : 'textbox',
                            name    : 'title',
                            label   : 'Title',
                            classes : 'selected_image_title',
                        }, {
                            type    : 'button',
                            name    : 'button',
                            label   : 'Image',
                            text    : 'Image',
                            classes : 'upload_image_button'
                        }
                    ],
                    buttons: [{
                        text: 'Insert',
                        id: 'hd-fancybox-button-insert',
                        onclick: function( e ) {
                            insertImg(editor);
                            closeBox();
                        },
                    },
                    {
                        text: 'Cancel',
                        id: 'hd-fancybox-button-cancel',
                        onclick: 'close'
                    }],
                });

                appendInsertDialog();

            });

        }

    });

Now a few hours later I found out that I can use a style property like
{
    text: 'Cancel',
    id: 'hd-fancybox-button-cancel',
    onclick: 'close',
    style: 'background-color:orange;border:lime 1px solid;position:absolute;left:0px;top:0px;'
}

Isn't it great that you have the opportunity to add stlyes like this? Off course you can just change the colors...

A: Ended up using the style property which I found here: http://www.tinymce.com/wiki.php/api4:class.tinymce.ui.Button like:
{
    text: 'Cancel',
    id: 'hd-fancybox-button-cancel',
    onclick: 'close',
    style: 'background-color:white;border:none;'
}

and at the end of the appendInsertDialog(); function i added
    $('#hd-fancybox-button-cancel').css({
        'position'  : 'absolute',
        'left'      : '20px'
    }).children('button').css({
        'color'     : '#a00'
    });

    $('#hd-fancybox-button-insert').css({
        'position'  : 'absolute',
        'left'      : 'auto',
        'right'     : '20px',
    });

So it's the worst code solution you can probably find but the result looks almost like desired:

A: Inspect the buttons you want and add the classes to your button definition:
Example:
{
  text: 'Insert',
  id: 'hd-fancybox-button-insert',
  classes: 'button button-primary',
  onclick: function( e ) {
    insertImg(editor);
    closeBox();
  },
}

I'd only add this to the insert button, as it is the primary button of the dialog.


text:
Q: Yii 302 redirects all requests to localhost to remote server I migrated my local development from a windows PC to Ubuntu and I didn't change any settings on Yii. But when I visit http://localhost, every requests are redirected to my server index page(http://www.xxx.com/). In windows, however, http://localhost will be redirect to http://www.xxx.com but localhost/controller/view will not. Now all requests to Yii are redirected to server(other documents in web root path that don't run through Yii's bootstrap index.php are not redirected). What probably caused this?
Here's my protected/config/main.php:
<?php
return array(
    'id'=>'xxx',
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'XXX',
    'language'=>'zh_CN',

    // preloading 'log' component
    'preload'=>array('log'),

    // autoloading model and component classes
    'import'=>array(
        'application.models.*',
        'application.components.*',
        'application.helpers.*',
    ),

    'modules'=>array(
        'gii'=>array(
            'class'=>'system.gii.GiiModule',
            'password'=>'xxx',
        ),
    ),

    // application components
    'components'=>array(
        'application'=>array(
            'defaultController'=>'www'
        ),
        'urlManager'=>array(
            'urlFormat'=>'path',
            'showScriptName'=>false,
             'rules'=>array(
                '<controller:\w+>/<id:\d+>'=>'<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            ),
        ),
        'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=xxx',
            'schemaCachingDuration'=>3600,
            'emulatePrepare' => true,
            'username' => 'xxx',
            'password' => 'xxx',
            'charset' => 'utf8',
        ),
      /*'cache'=>array(
            'class'=>'system.caching.CMemCache',
            'servers'=>array(
                array('host'=>'127.0.0.1', 'port'=>11211, 'weight'=>60),
               array('host'=>'127.0.0.1', 'port'=>11211, 'weight'=>40),
            ),
        ),*/
        /*'session' => array (
            'autoStart'=>'true',
            'class' => 'system.web.CDbHttpSession',
            'connectionID' => 'db',
            'autoCreateSessionTable' => FALSE,
            'timeout' => 7200,
            'cookieMode' => 'allow',
            'cookieParams' => array(
                'path' => '/',
                'domain' => '.xxx.com',
                'httpOnly' => TRUE,
             ),
        ),
        'httpCookie'=>array(
            'domain'=>'.xxx.com'
        ),*/
        'user'=>array(
            'loginUrl'=>array('accounts/login'),
            // enable cookie-based authentication
            'allowAutoLogin'=>true,
            'authTimeout'=>'7200'
        ),
        'errorHandler'=>array(
            // use 'site/error' action to display errors
            'errorAction'=>'site/error',
        ),
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                array(
                    'class'=>'CFileLogRoute',
                    'levels'=>'error, warning',
                ),
                //uncomment the following to show log messages on web pages
                 // array(
                      // 'class'=>'CWebLogRoute',
                  // ),
            ),
        ),
    ),

    // application-level parameters that can be accessed
    // using Yii::app()->params['paramName']
    'params'=>array(
        // this is used in contact page
        'adminEmail'=>'service@xxx.com',
    ),
);

A: There doesn't appear to be anything wrong with your main.php that could possibly do a redirect to your example.com domain. Could it be your .htaccess file?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to update value of pointer inside method I'm implementing an AVLTreeMap in Go but having some problems with values passed in as pointers. I'm attempting to update the value of a node pointer but its value won't persist after the function.
In the function func (tree *AVLTreeMap) put(key int, value string). I am able to modify the root node of the tree and can print it in the main. However, when I pass that same root to the function func (node *Node) insertByKey(key int, value string) right after, the value won't update and only the value from put() persists.
package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
    "io"
)

/* NODE */
type Node struct {
    key     int
    value   string
    left    *Node
    right   *Node
    height  int
}

/* TREE */
type AVLTreeMap struct {
    root *Node
}

func (tree *AVLTreeMap) get(key int) string {
    value := tree.root.lookupByKey(key)
    if value == "" {
        return "Not Found"
    }

    return value
}

func (node *Node) inOrder() {
    fmt.Println(node)
    if (node != nil) {
        fmt.Println(node.key)

        node.left.inOrder()
        node.inOrder()
        node.right.inOrder()
    }
}

func (node *Node) lookupByKey(key int) string {

    if (node == nil) {                  // check for nullptr
        return ""

    } else if (node.key == key) {       // key matching
        return node.value

    } else if (key < node.left.key) {   // recur left
        return node.left.lookupByKey(key)

    } else if (key > node.right.key) {  // recur right
        return node.right.lookupByKey(key)
    }

    return ""
}

func (node *Node) insertByKey(key int, value string)  {

    if (node == nil) {                  // check for nullptr
        node = &Node{ key: key, value: value,}

    } else if (key < node.key) {   // recur left
        node.left.insertByKey(key, value)

    } else if (key > node.key) {  // recur right
        node.right.insertByKey(key, value)
    }
}

func (tree *AVLTreeMap) put(key int, value string) {
    //fmt.Println(tree.root)
    tree.root = &Node{ key: 1, value: "2",}
    tree.root.insertByKey(key, value)
}

func (tree *AVLTreeMap) remove(key int) {
    return
}

func (tree *AVLTreeMap) levelOrder() {
    return
}

func (tree *AVLTreeMap) rotateLeft(curr *Node) *Node {
    return curr
}

func (tree *AVLTreeMap) rotateRight(curr *Node) *Node {
    return curr
}

func (tree *AVLTreeMap) getHeight(curr *Node) int {
    return 1
}

func (tree *AVLTreeMap) getBalance(curr *Node) int {
    return 1
}

/* UTILS */
func checkError(err error) {
    if err != nil {
        panic(err)
    }
}

func strToInt(val string) int {
    if val, err := strconv.Atoi(val); err == nil {
        return val
    }

    return 0
}

func readLine(reader *bufio.Reader) string {
    str, _, err := reader.ReadLine()
    if err == io.EOF {
        return ""
    }

    return strings.TrimRight(string(str), "\r\n")
}

func getCommand(command string, tree *AVLTreeMap) {

    vals := strings.Split(command, " ")
    var (
        key int
        val string
    )

    if len(vals) == 1 {         // level order
        tree.levelOrder()

    } else if len(vals) == 3 {  // put
        key, val = strToInt(vals[1]), vals[2]
        tree.put(key, val)

    } else if len(vals) == 2 {  // get
        //key = strToInt(vals[1])
        //fmt.Println(tree.get(key))
    }
}

func main() {
    reader := bufio.NewReaderSize(os.Stdin, 16 * 1024 * 1024)

    // get num commands
    numCommands := strToInt(readLine(reader))
    fmt.Println(numCommands)

    // initialize new TreeMap
    tree := AVLTreeMap{}
    //tree.root = &Node{ key: 1, value: "z", }

    for {
        val := readLine(reader)
        if val == "" {
            break;
        } else {

            // run commands on tree
            getCommand(val, &tree)
        }
    }
    fmt.Println(tree.root)
    //tree.root.inOrder()
}


text:
Q: c++: Writing to a file I have a couple of questions.
First, i am doing http byte range requests and then writing the received
data to a file.
Sometimes, i have to read a block of 1K, and then read that
from the file fetched through http. Now, the problem is that the next request
after the 1k request may be starting from 100 bytes and in that case i want to
write in the 1K file, overwriting from 100 bytes. How can i overwrite from a
specific offset in the file?
Secondly, how do i create a file with some data already in the file? For eg. i want
put the data in the file from lets say 500th byte, i do not care about the first
500 bytes, could be any garbage data, but its important to have the correct file
size for the code to work.
thanks

A: There's some reference material and sample code on ofstream's seekp at http://www.cplusplus.com/reference/iostream/ostream/seekp/


text:
Q: app pool identity - farm admin The userid that is the identity of the application pool is also in the Farm Administrators group.
Is that a bad thing?
We started seeing some weird permission errors after this change was made (that userid was added to the farm admin group).

A: We have done this several times in our dev environments where we wanted one single account with godlike permissions on everything.
It should not be causing permission problems as far as I know, but SharePoint can be a bit...fickle in this regard.

A: Microsoft recommends using seperate accounts:
http://technet.microsoft.com/en-us/library/cc263445.aspx#Subsection2


text:
Q: Manipulating user input (Mathematical) I'm using C#. I am trying to allow the user to input a numerical value (IE: how many do you want?) and then take that value and figure tax and total. I can not figure out how to do this and wondered if anyone could show me? My current script is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to Infinate Happiness Ranch.\nPlease enter your order information bellow. ");

            Console.WriteLine();

            Console.WriteLine("Please enter your first and last name:");
            string FirstName = Console.ReadLine();

            Console.WriteLine("Please enter your street address:");
            string Address = Console.ReadLine();

            Console.WriteLine("Please enter your city:");
            string City = Console.ReadLine();

            Console.WriteLine("Please enter your two letter state abbreviation:");
            string StateCode = Console.ReadLine();

            Console.WriteLine("Please enter your zip code:");
            string ZipCode = Console.ReadLine();

            Console.WriteLine("Please enter the number of Tribbles \nyou wish to purchase for $29.99 plus tax");
            string NumberOrdered = Console.ReadLine();

            Console.WriteLine("Invoice \nName {0}", FirstName);
            Console.WriteLine("Address {0}", Address);
            Console.WriteLine("City {0}", City);
            Console.WriteLine("StateCode {0}", StateCode);
            Console.WriteLine("ZipCode {0}", ZipCode);
            Console.WriteLine("NumberOrdered {0}", NumberOrdered);
            // PROGRAM WORKS UNTIL HERE.
            NumberOrdered = m;
            TotalBeforeTax = m * 29.99; //'n' is total b4 tax
            o = n * 0.9;// 'o' is total tax due
            p = o + n; // 'p' is total due

            Console.WriteLine("Your total is {0} {1}", n);
            Console.WriteLine("Your tax is {0}", o);
            Console.WriteLine("Your total charge is {0}", p);
            Console.WriteLine("Thank you for your order");
            Console.WriteLine();

            //Console.WriteLine("Name:" + FirstName);
            Console.Read();
        }
    }
}

A: You should parse the string with
int ordered = int.Parse(NumberOrdered);

And continue to calculate with this integer.

A: Because the user is entering information as strings, you should convert the number ordered to an integer. Also, to preserve your decimals, you need to store numbers as doubles for things such amounts.
int numOrdered = Convert.ToInt32(NumberOrdered);
double TotalBeforeTax = numOrdered * 29.99;

double beforeTax = TotalBeforeTax * 0.9;
double afterTax = beforeTax + TotalBeforeTax;

Console.WriteLine("Your total is {0}", TotalBeforeTax);
Console.WriteLine("Your tax is {0}", beforeTax);
Console.WriteLine("Your total charge is {0}", afterTax);
Console.WriteLine("Thank you for your order");

A: You forgot to declare some variables and assign some values.
Try this:
static float m;
static float n;
static float o;
static float p;
static float TotalBeforeTax;
static void Main(string[] args)
{
    Console.WriteLine("Welcome to  Infinate Happiness Ranch.\nPlease enter your order information bellow. ");
    Console.WriteLine();

    Console.WriteLine("Please enter your first and last name:");
    string FirstName = Console.ReadLine();

    Console.WriteLine("Please enter your street address:");
    string Address = Console.ReadLine();

    Console.WriteLine("Please enter your city:");
    string City = Console.ReadLine();

    Console.WriteLine("Please enter your two letter state abreviation:");
    string StateCode = Console.ReadLine();

    Console.WriteLine("Please enter your zip code:");
    string ZipCode = Console.ReadLine();

    Console.WriteLine("Please enter the number of Tribbles \nyou wish to purchase for $29.99 plus tax");
    string NumberOrdered = Console.ReadLine();

    Console.WriteLine("Invoice \nName {0}", FirstName);
    Console.WriteLine("Address {0}", Address);
    Console.WriteLine("City {0}", City);
    Console.WriteLine("StateCode {0}", StateCode);
    Console.WriteLine("ZipCode {0}", ZipCode);
    Console.WriteLine("NumberOrdered {0}", NumberOrdered);
    //PROGRAM WORKS UNTIL HERE ? HELP ? ? ? ? ?
    //NumberOrdered = m;
    m = float.Parse(NumberOrdered);
    TotalBeforeTax = m * 29.99f; //'n' is total b4 tax
    n = TotalBeforeTax;
    o = n * 0.9f;//'o' is total tax due
    p = o + n; //'p' is total due

    Console.WriteLine("Your total is {0}", n);
    Console.WriteLine("Your tax is {0}", o);
    Console.WriteLine("Your total charge is {0}", p);
    Console.WriteLine("Thank you for your order");
    Console.WriteLine();
    Console.Read();
}

Hope this helps !

A: Just a bit of advice, you can include non-string variables in Console.WriteLine() like:
Console.WriteLine("Your tax is " + o);

This is what most professional developers do. No need for complicated C/C++ style of parsing.
Also, you don't seem to be declaring the variables o and p. Try this:
double o = Convert.toDouble(n * 0.9);
or
double o = (double)(n * 0.9);


text:
Q: Alguém sabe como posso atribuir uma borda em um triangulo feito com css? O código é esse:

div {
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 0 40px 30px 40px;
    border-color: transparent transparent #007bff transparent;
}

Eu quero criar uma borda nele.

A: Você pode fazer um triângulo dentro de outro:

.triangle {
  position: relative;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 44px 34px 44px;
  border-color: transparent transparent #007bff transparent;
}
.inner-triangle {
  position: absolute;
  top: 6px;
  left: -38px;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 38px 28px 38px;
  border-color: transparent transparent #f09 transparent;
}


text:
Q: Translating data.table to dplyr: Is there something equivalent to setting the keys of a data table before merge on dplyr? I'm used to working on data table, but moving to use more dplyr. On data.table, if you set the keys of your your data before merging two data tables, the merge is much faster. Is there something equivalent to that in joining on dplyr?
library(tidyverse)

band_members_dt <- data.table::as.data.table(band_members)
band_instruments_dt <- data.table::as.data.table(band_instruments)

system.time({
  data.table::setkey(band_members_dt, name)
  data.table::setkey(band_instruments_dt, name)
  dt_merge <- merge(band_members_dt, band_instruments_dt,
                    by = data.table::key(band_members_dt), all.x = T)
})
# user  system elapsed
# 0.004   0.000   0.003

system.time({
  tbl_join <- band_members %>%
    left_join(band_instruments)
})
# user  system elapsed
# 0.05    0.00    0.05

Obviously for a small data set the difference is not much, but I'm working with data in the order of millions of rows, and the difference can get pretty big, especially if you are making multiple merges of smaller data tables into a big one. And I would work on data.table, except the rest of the team prefers dplyr, plus is planning on using Spark too.


text:
Q: VBA to trace precedents of index function Thanks in advance.
Has anyone created a VBA sub that traces the precedent of an INDEX?
For example, suppose A1 has:
INDEX(namedRange, namedCellVertical, namedCellHorizontal)
I would like to be able to select A1, run a macro, and then have the activated cell be the particular cell (not the entire range) that A1 refers to.
It seems that there is freeware (Arixcel) that does this (and a lot more), but we can't install it on our computers at work because of our policies.
Again, thanks in advance.

A: Try this:
Sub GetCell()
Dim c As Range

    On Error Resume Next
    Set c = Selection.Parent.Evaluate(Selection.Formula)
    On Error GoTo 0
    If Not c Is Nothing Then
        If c.Parent.Name <> ActiveSheet.Name Then c.Parent.Activate
        c.Select
    End If

End Sub


text:
Q: Focus to new element Okay so in my website I want to make it so when I click on a certain div it will display new information. For example if the div text said "What is your name?" I want to be able to click on it and it to say "My name is ...". Thank you in advance. Also just a note, I do not care what programming language I have to do this in.
Here are all my documents so far with my attempts.

body {
 margin 0;
 padding 0;
 font-family: sans-serif, arial;
}

header {
 background: #00795f;
 width: 100%;
 padding: 40px 0;
 color: white;
 text-align: center;
}

a {
 text-decoration: none;
 color: inherit;
}

nav ul {
 background-color: #43a286;
 overflow: hidden;
 color: white;
 padding: 0;
 text-align: center;
 margin: 0;
 -webkit-transition: max-height 0.4s;
 -ms-transition: max-height 0.4s;
 -moz-transition: max-height 0.4s;
 -o-transition: max-height 0.4s;
 transition: max-height 0.4s;

}

nav ul li {
 display: inline-block;
 padding: 20px;
}

nav ul li:hover {
 background-color: #399077;
}

section {
 line-height: 1.5em;
 font-size: 0.9em;
 padding: 40px;
 width: 75%;
 margin: 0 auto;
}

.handle {
 width: 100%;
 background: #005c48;
 text-align: left;
 box-sizing: border-box;
 padding: 15px 10px;
 cursor: pointer;
 color: white;
 display: none;
}

@media screen and (max-width: 1080px) {
 nav ul {
  max-height: 0px;
 }

 .showing {
  max-height: 20em;
 }

 nav ul li {
  width: 100%;
  box-sizing: border-box;
  padding: 15px;
  text-align: left;
  padding: 15px 10px;
  cursor: pointer;
 }

 .handle {
  display: block;
 }

}

.first-info {
 background-color: #43a286;
 height: 200px;
 width: 200px;
 border-radius: 20px;
}

.first-info-text {
 color: white;
 text-align: center;
 display: table-cell;
 vertical-align: middle;
 height: 200px;
 width: 200px;
 font-size: 20px;
 border-radius: 20px;
}

.first-info-text p {
 margin: 5px;
}

.first-info:hover {
 background-color: #399077;
 cursor: pointer;
}

.first-info-text:hover {
 background-color: #399077;
 cursor: pointer;
}

.switch {
 color: white;
 text-align: center;
 display: table-cell;
 vertical-align: middle;
 height: 200px;
 width: 200px;
 font-size: 20px;
 border-radius: 20px;
 display: none;
}

.first-info:focus {

 .first-info-text {
  display: none;
 }

 .switch {
  display: all;
 }
}
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Lorem Ipsum</title>
  <link rel="stylesheet" href="app.css" />

   Lorem Ipsum

Lorem

Lorem

Lorem

Lorem

Lorem

Lorem

Lorem

Lorem

Menu

What is my name?

bob!

A: Hope this will be useful
You wont need to add $(document).ready(function(){..... if it is bottom of body tag
JS
$(document).ready(function(){
 $('#first-info').on('click', function(){
   $('nav ul').toggleClass('showing');
   $('.first-info-text').toggleClass('switch');
   })

})

I have removed the p tags and have added span tag from mark up
HTML

            Lorem Ipsum

Lorem

Lorem

Lorem

Lorem

Lorem

Lorem

Lorem

Lorem

Menu

        What is your name
        My name is Bob

Modified CSS
body {
    margin 0;
    padding 0;
    font-family: sans-serif, arial;
}

header {
    background: #00795f;
    width: 100%;
    padding: 40px 0;
    color: white;
    text-align: center;
}

a {
    text-decoration: none;
    color: inherit;
}

nav ul {
    background-color: #43a286;
    overflow: hidden;
    color: white;
    padding: 0;
    text-align: center;
    margin: 0;
    -webkit-transition: max-height 0.4s;
    -ms-transition: max-height 0.4s;
    -moz-transition: max-height 0.4s;
    -o-transition: max-height 0.4s;
    transition: max-height 0.4s;

}

nav ul li {
    display: inline-block;
    padding: 20px;
}

nav ul li:hover {
    background-color: #399077;
}

section {
    line-height: 1.5em;
    font-size: 0.9em;
    padding: 40px;
    width: 75%;
    margin: 0 auto;
}

.handle {
    width: 100%;
    background: #005c48;
    text-align: left;
    box-sizing: border-box;
    padding: 15px 10px;
    cursor: pointer;
    color: white;
    display: none;
}

@media screen and (max-width: 1080px) {
    nav ul {
        max-height: 0px;
    }

    .showing {
        max-height: 20em;
    }

    nav ul li {
        width: 100%;
        box-sizing: border-box;
        padding: 15px;
        text-align: left;
        padding: 15px 10px;
        cursor: pointer;
    }

    .handle {
        display: block;
    }

}

.first-info {
    background-color: #43a286;
    height: 200px;
    width: 200px;
    border-radius: 20px;
}

.first-info-text {
    color: white;
    text-align: center;
    display: table-cell;
    vertical-align: middle;
    height: 200px;
    width: 200px;
    font-size: 20px;
    border-radius: 20px;
}

.first-info-text p {
    margin: 5px;
}

.first-info:hover {
    background-color: #399077;
    cursor: pointer;
}

.first-info-text:hover {
    background-color: #399077;
    cursor: pointer;
}

.switch {
    color: white;
    text-align: center;
    display: table-cell;
    vertical-align: middle;
    height: 200px;
    width: 200px;
    font-size: 20px;
    border-radius: 20px;
    display: none;
}

.first-info:focus { }

.switch {
        visibility: hidden;
    }
}

You didnt closed this css declaration .first-info:focus
Here is DEMO


text:
Q: Why won't my domain records display even after several hours? I updated my domain records to add CNAME records and a TXT record, but even after several days I cannot see them when I query the domain.
Screenshot of domain records:

Query results:
$ dig @dns1.name-services.com kizbit.com any

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.23.rc1.el6_5.1 <<>> @dns1.name-services.com kizbit.com any
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37571
;; flags: qr aa rd; QUERY: 1, ANSWER: 10, AUTHORITY: 0, ADDITIONAL: 5
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;kizbit.com.                    IN      ANY

;; ANSWER SECTION:
kizbit.com.             3600    IN      NS      dns5.name-services.com.
kizbit.com.             1800    IN      AAAA    2607:f878:5:9::b5d1:cb0f
kizbit.com.             1800    IN      SOA     dns1.name-services.com. info.name-services.com. 2002050701 10800 3600 604800 3600
kizbit.com.             1800    IN      TXT     "v=spf1 a ip4:184.82.92.84 ip4:192.185.179.138 include:_spf.spamarrest.com"
kizbit.com.             3600    IN      NS      dns4.name-services.com.
kizbit.com.             1800    IN      A       184.82.92.84
kizbit.com.             3600    IN      NS      dns1.name-services.com.
kizbit.com.             1800    IN      MX      10 kizbit.com.
kizbit.com.             3600    IN      NS      dns3.name-services.com.
kizbit.com.             3600    IN      NS      dns2.name-services.com.

;; ADDITIONAL SECTION:
dns2.name-services.com. 300     IN      A       98.124.197.1
dns5.name-services.com. 300     IN      A       98.124.196.1
dns4.name-services.com. 300     IN      A       98.124.194.1
dns3.name-services.com. 300     IN      A       98.124.193.1
dns1.name-services.com. 300     IN      A       98.124.192.1

;; Query time: 89 msec
;; SERVER: 98.124.192.1#53(98.124.192.1)
;; WHEN: Mon May 19 00:53:09 2014
;; MSG SIZE  rcvd: 404

I also tried without @dns1.name-services.com, and I also tried nslookup, but neither showed the extra CNAME records. I tried to contact ENom, but they directed me to my reseller. My reseller gave a vague "if you are using our servers, the changes happen without any delay whatsoever, as long as you click to save them" response.

A: It turns out I didn't know how dig works, and you have to query the actual sub-domain to get any information. I thought everything would appear as it did in the online form if you just look at the root domain!
$ dig @dns1.name-services.com _amazonses.kizbit.com any

;; ANSWER SECTION:
_amazonses.kizbit.com.  1799    IN      TXT     "C9DR1H5StZrI97xjWjkVcd/2jwW9R05MBr49T8IyooI="
_amazonses.kizbit.com.  1799    IN      SOA     dns1.name-services.com. info.name-services.com. 2002050701 10800 3600 604800 3600

A: It's there....
[Nevins-Mac-mini:~] nevin% host www.kizbit.com
www.kizbit.com is an alias for kizbit.com.
kizbit.com has address 184.82.92.84
kizbit.com has IPv6 address 2607:f878:5:9::b5d1:cb0f
kizbit.com mail is handled by 10 kizbit.com.

A CNAME has pointers to A-records, but A-records do not have pointers to CNAMEs.


text:
Q: ArrayFormula Google Sheets - remove high and low from average I'm trying to use an arrayformula to calculate the average across 7 columns while removing the max and min number from those columns. The tricky part is there is no preset limit on how may cell will be filled, each time its different.
I have the formula to calculate the average complete:
=ARRAYFORMULA(IF(ISBLANK($A$2:$A),"",IF($J$2:$J="Granted",($AO$2:$AO+$AP$2:$AP+$AQ$2:$AQ+$AR$2:$AR+$AS$2:$AS+AT2:AT)/6,0)))
I've tried using the Trimmean function but it isn't working with the array formula, =Trimmean(AO2:AU2,0.33) any suggestions on how to get it to work?

A: Assuming the values in the cells that you want to ignore are empty, you want :
Average of all cells that are filled and not maximum or minimum

Which is
Sum of all cells that are filled and not maximum or minimum / (number of filled cells - 2)

Thus
=(sum(YourRange)-max(YourRange)-min(YourRange))/(count(YourRange)-2)

should give you what you want


text:
Q: Help needed on homogeneous functions If $f$ is homogeneous of degree $1$, is differentiable at $0$ and $f(0)=0$, how can i prove that: $f(x) = \bigtriangledown f(0)\cdot x$

A: If $f$ is homogeneous of degree $1$, then $f(tx) = t f(x)$ for $t \ge 0$. Deriving this with respect to $t$ (and using the chain rule for derivatives) we get
$$\sum _i \frac {\partial f} {\partial x_i} \frac {\Bbb d (t x_i)} {\Bbb d t} = f(x)$$
and evaluating at $t=0$ gives
$$\nabla f (0) \cdot x = f(x) .$$
(This is a particular case of Euler's theorem on positive-homogeneous functions.)


text:
Q: Population Covariance Calculation with ddof parameter for DataFrame.cov() in Python I have a dataframe with stock prices.(actually its a excel with 2600 rows. My problem is when creating the covariance matrix, the ddof parameter in dataframe.cov has a value of 1 by default. This corresponds to the sample covariance method. However, I want to create a covar with the method of population, namely /N. I have tried =df1.cov(ddof=0) but it had no effect.
Can you help me to create a dataframe.cov with the bias true, that is, the population method? Or can you organize my code according to numpy.cov?
Thank you,
My dataframe; (dfr)

Date
Code
Price

28.02.2022
A
55

25.02.2022
A
55.1

24.02.2022
A
54

23.02.2022
A
54.2

22.02.2022
A
56.112

21.02.2022
A
56

28.02.2022
B
5

25.02.2022
B
4

24.02.2022
B
4

23.02.2022
B
4.2

22.02.2022
B
5.1

21.02.2022
B
5

28.02.2022
C
7

25.02.2022
C
7.2

24.02.2022
C
7

23.02.2022
C
8

22.02.2022
C
6.9

21.02.2022
C
7

My code;
dfr = dfr.set_index(['Date', 'Code']).Price.unstack(['Code'])
df1 = dfr.pct_change()
df1.to_excel(r'C:\sample\df1.xlsx', index = True)

#Covar
df2 = df1.cov()
df2.to_excel(r'C:\sample\df2.xlsx', index = True)

A: I am not sure what you mean you are not getting with ddof=0? I get the differences.

ddoftest=pd.read_csv("ddoftest.csv")
covar=ddoftest.cov()
print(covar)
covar1=ddoftest.cov(ddof=0)
print(covar1)

      A         B         C

A  0.060795 -0.007887 -0.018725
B -0.007887  0.092322  0.022308
C -0.018725  0.022308  0.075867
A         B         C
A  0.057418 -0.007448 -0.017685
B -0.007448  0.087193  0.021068
C -0.017685  0.021068  0.071652

I chose A, B and C as some random stock prices


text:
Q: Batch file read data from text file based on text category How do I read data from text file based on text category,
i.e inside this hello.txt have the following data:
Fruits
Apple
Orange

Food
Spaghetti
Hotdog
Burger

If category equal Food then result is Spahetti, Hotdog, and Burger
FOR /F %%i in (hello.txt) do (echo %%i)


text:
Q: React : why I have to click twice on the same option to set in select box import ProductCard from "./ProductCard";
import "../Styles/Products.css";
import "../Styles/Filter.css";
import { v4 as uuidv4 } from "uuid";

const Products = (props) => {
  const skins = props.skins;
  // const [filteredSkins, setFilteredSkins] = useState();
  const [gameFilter, setGameFilter] = useState("DEFAULT");

  const [qualityFilter, setqualityFilter] = useState("DEFAULT");
  let skinsObj = {};

  let qualityObj = {};

  for (let i = 0; i < skins.length; i++) {
    skinsObj[skins[i].gameName] = i;

    qualityObj[skins[i].quality] = i;
  }

  const setGame = (e) => {
    setGameFilter(e.target.value);
    console.log(gameFilter, qualityFilter);
  };

  const setquality = (e) => {
    setqualityFilter(e.target.value);
    console.log(gameFilter, qualityFilter);
  };
  console.log(gameFilter, qualityFilter);
  return (
    <React.Fragment>

          Game :
          <select name="games" id="games" onChange={(e) => setGame(e)}>
            <option value="DEFAULT">All</option>
            {Object.keys(skinsObj).map((game) => {
              return (
                <option value={game} key={uuidv4()}>
                  {game}
                </option>
                //
              );
            })}
          </select>

          Quality :
          <select name="quality" id="quality" onChange={(e) => setquality(e)}>
            <option value="all">All</option>
            {Object.keys(qualityObj).map((quality) => {
              return (
                <option value={quality} key={uuidv4()}>
                  {quality}
                </option>
                //
              );
            })}
          </select>

        {skins &&
          skins.map((skin) => {
            return (
              <ProductCard
                key={uuidv4()}
                className="product-list"
                name={skin.name}
                icon={skin.gameName}
                price={skin.price}
                quality={skin.quality}
                picture={skin.picture}
              />
            );
          })}

    </React.Fragment>
  );
};

export default Products;

I need to click on any option from the list twice in a row to be applied in the box but the state change when I log it, also the second select affected when I change the other one both get reset to default try some solution but nothing help don't know if it is problem with the way of importing data or what

A: You currently don't set the value prop on <select>.


text:
Q: How can I create a function prototype in C++ which accepts two integers as parameters and returns their difference? I know what a function is and how to create it, but what is a function prototype? And how can I create a function prototype in C++ which accepts two integers as parameters and returns their difference?

A: A function prototype in C++ is simply a function declaration. So in your case it could be
 int difference(int n1, int n2);

A: function prototype:
int difference(int,int);

function definition:
int difference(int a,int b)
{
 return abs(a-b);
}


text:
Q: Aurelia: How to handle a async request in a view? I have a dotnet core api that returns a FileContentResult..
return new FileContentResult(bytes, contentType)
{
    FileDownloadName = Path.GetFileName(request.Filename)
};

Via postman I can read out the image perfectly fine. Now I want to read the image, via the aurelia fetch client, and show it in my html view. This is my function to retrieve the image from the api.
public image(filename: string) {
    return this.http.fetch(AppConfiguration.base_url + 'assets/image',
        {
            method: 'post',
            body: json({
                filename: filename
            })
        });
}

I've tried to convert the blob in the response with this value converter. But I can't get that to work
Converter:
export class BlobToUrlValueConverter {
    public toView(blob) {
        return URL.createObjectURL(blob);
    }
}

Viewmodel:
export class Dashboard {

    public blob: any;

    constructor(
        public assets_service: AssetsService
    ) { }

    async attached() {
        let response = await this.assets_service.image('test.png');
        this.blob = response.blob();
    }
 }

View
<div if.bind="blob">
   ${ blob | blobToUrl }
</div>

I'm not sure this is the right approach. Also not sure how handle the async request part of it either. What is the best way to get that image response to show in the html view? Lets say via a img tag?

A: I was close. Here is how I got the image to show.
Viewmodel:
export class Dashboard {

    public url: string;

    constructor(
        public assets_service: AssetsService
    ) { }

    async attached() {
        let blob = await this.assets_service.image('test.png')
            .then(response => response.blob());
        this.url = URL.createObjectURL(blob);
    }
 }

View:
<div if.bind="url">
    <img src.bind="url">
</div>

EDIT:
Found a better solution using parts written above:
The exported function that does the call (for reusability on both ts and html sides):
export function image_request(filename: string): Promise<Response> {
    let http = new Http();
    return http.fetch(<your-url-that-fetches-the-image>,
        {
            method: 'post',
            body: json({
                filename: filename
            })
        });
}

Value converter that uses above function
import { image_request } from './AssetsRequests';

export class ImageRequestValueConverter {
    public toView(filename: string) {
        return image_request(filename);
    }
}

The important and most awesome part of the solution. Many thanks to http://www.sobell.net/aurelia-async-bindings/
for getting me on my way. You can override the binding behaviour. You can use this override to process async
Promise in a view in combination with a value converter.
export class AsyncImageBindingBehavior {

    public bind(binding, source): void {
        binding.originalupdateTarget = binding.updateTarget;
        binding.updateTarget = (target) => {
            // When we have a promise
            if (typeof target.then === 'function') {
            // Set temp value to loading so we know its loading
            binding.originalupdateTarget('Loading...');
            // Process the promise
            target
                .then(response => response.blob())
                .then(blob => binding.originalupdateTarget(
                    URL.createObjectURL(blob)
                ));
            }
            else {
                binding.originalupdateTarget(target);
            }
        };
    }

    unbind(binding) {
        binding.updateTarget = binding.originalupdateTarget;
        binding.originalupdateTarget = null;
    }
}

Finally the view is very simple
 <img src="${ 'test.png' | imageRequest & asyncImage }">


text:
Q: WCF Handling of Large Files All the posts and search results that I've reviewed regarding WCF and uploading of large files have pretty much have the same answers for increasing the maximums like maxReceivedMessageSize. That's great I guess if you're just trying to get it working, but what if you have an actual maximum that you want to enforce. How do you handle that better?
Currently the client gets a System.ServiceModel.EndpointNotFoundException
saying, "There was no endpoint listening", inner exception "The remote server returned an error: (404) Not Found." How could I catch this in my service and return a better error message? Like "File exceeds maximum allowable size"

A: You can pass your file as a Stream parameter to your service method. Doing so allows to dynamically check the file size without processing it entirely (one should set here some sane maxReceivedMessageSize which shouldn't be exceeded in the most of real-world cases).
Here is an example of RESTful WCF service:
[ServiceContract]
public interface IFileService
{
    [OperationContract, WebInvoke(Method = "POST", UriTemplate = "/ProcessFile")]
    string ProcessFile(Stream file);
}

public class FileService : IFileService
{
    public string ProcessFile(Stream file)
    {
        const int bufferLength = 32;
        const int maxSize = 256;
        var buffer = new byte[bufferLength];
        int bytesRead, totalBytesRead = 0;

        do
        {
            bytesRead = file.Read(buffer, 0, bufferLength);
            totalBytesRead += bytesRead;

            if (totalBytesRead > maxSize)
                return $"File is too large - maximum {maxSize} bytes allowed.";
        }
        while (bytesRead > 0);

        return $"Total {totalBytesRead} bytes read.";
    }
}

Here is a sample code for hosting this service:
var host = new ServiceHost(typeof(FileService));

host.AddServiceEndpoint(typeof(IFileService),
    new WebHttpBinding { TransferMode = TransferMode.StreamedRequest },
    "http://localhost:8080")
    .EndpointBehaviors.Add(new WebHttpBehavior());

host.Open();

Console.WriteLine("The host is opened. Press ENTER to exit...");
Console.ReadLine();

host.Close();

Note that one needs TransferMode = TransferMode.StreamedRequest to be able to process large files - see this question for details.


text:
Q: How to destroy/free an anonymousThread On windows, to stop and destroy an anonymous thread, i simply do FmyTask.free => that will call destroy => and that inside the destroy will set terminate = true and call waitfor to wait the task is finished => and finally clean the memory used
but on ARC, everything is different :(
i use this code :
TMyObject
private
  FMyTask: TThread;
public
  destructor Destroy; override;
  procedure DoSomething;
end;

destructor TMyObject.Destroy;
begin
  FMyTask.free;  // << will do nothing because FMyTask.refcount = 2 !! how it's possible ?
  FMyTask:= nil;
  inherited;
end;

procedure TMyObject.DoSomething;
begin

  FMyTask:= Thread.CreateAnonymousThread(
    procedure
    begin
      sleep(10000000);
    end);
  FMyTask.FreeOnTerminate := False;
  FMyTask.Start;

end;

and i do nothing else than just
MyObject := TmyObject.create;
MyObject.DoSomething;
MyObject.free;
MyObject := nil;

but as you see, in the onDestroy of TmyObject, FMyTask have a refcount of 2 !! so it's mean that the FMyTask will be not destroyed (refcount will be decreased to 1) with TmyObject (but later) and you imagine all the bug that can results :(
it's sean that a reference to fMyTask is keep inside this function :
function ThreadProc(const Thread: TThread): Integer;
var
  FreeThread: Boolean;
{$IFDEF MACOS}
  pool: Pointer;
{$ENDIF MACOS}
begin
{$IFDEF AUTOREFCOUNT}
  Thread.__ObjAddRef; // this ensures the instance remains for as long as the thread is running
{$ENDIF}
  TThread.FCurrentThread := Thread;
{$IF Defined(POSIX)}
  if Thread.FSuspended then
    pthread_mutex_lock(Thread.FCreateSuspendedMutex);
{$ENDIF POSIX}
{$IFDEF MACOS}
  // Register the auto release pool
  pool := objc_msgSend(objc_msgSend(objc_getClass('NSAutoreleasePool'),
                                    sel_getUid('alloc')), sel_getUid('init'));
{$ENDIF MACOS}
  try
    Thread.FStarted := True;
    if not Thread.Terminated then
    try
      Thread.Execute;
    except
      Thread.FFatalException := AcquireExceptionObject;
    end;
  finally
    Result := Thread.FReturnValue;
    FreeThread := Thread.FFreeOnTerminate;
    Thread.DoTerminate;
    Thread.FFinished := True;
    SignalSyncEvent;
    if FreeThread then
    begin
      Thread.DisposeOf;
{$IFDEF AUTOREFCOUNT}
      Thread.__ObjRelease; // This will clear the thread reference that was added by setting FreeOnTerminate.
{$ENDIF}
    end;
{$IFDEF AUTOREFCOUNT}
    Thread.__ObjRelease; // This will clear the thread reference we added above. This may initiate disposal.
{$ENDIF}
{$IFDEF USE_LIBICU}
    // Destroy Collator Cache
    ClearCollatorCache;
{$ENDIF}
{$IF Defined(MSWINDOWS)}
    EndThread(Result);
{$ELSEIF Defined(POSIX)}
{$IFDEF MACOS}
    // Last thing to do in thread is to drain the pool
    objc_msgSend(pool, sel_getUid('drain'));
{$ENDIF MACOS}
{$IFDEF ANDROID}
    // Detach the NativeActivity virtual machine to ensure the proper relase of JNI context attached to the current thread
    PJavaVM(System.JavaMachine)^.DetachCurrentThread(PJavaVM(System.JavaMachine));
{$ENDIF ANDROID}
    // Directly call pthread_exit since EndThread will detach the thread causing
    // the pthread_join in TThread.WaitFor to fail.  Also, make sure the EndThreadProc
    // is called just like EndThread would do. EndThreadProc should not return
    // and call pthread_exit itself.
    if Assigned(EndThreadProc) then
      EndThreadProc(Result);
    pthread_exit(Result);
{$ENDIF POSIX}
  end;
end;

is it a normal behavior ? if yes, i m the only one to think that arc is the worse think of delphi ?

A: ARC must keep an extra reference to the thread in order not free it too soon if the creator should go out of scope.
Under non-ARC, when you call FMyThread.Free, the Destroy destructor is called and subsequently Terminate; and WaitFor;
With ARC, calling Free decrements ref count and checks for zero. Since there is still one reference left, the destructor is not called.
This means that the pattern to free a thread (with FreeOnTerminate=false) should be:
fMyThread.Terminate;
fMyThread.WaitFor;  // Wait for the thread to finish
fMyThread.Free;

This means that the extra reference taken by ARC is removed and the thread object will be released any time after the creator goes out of scope.

Note that this pattern for freeing a thread (with FreeOnTerminate=false) works in all compilers, and also avoids rare race conditions when terminating threads in non-ARC land.

General rule for all threads that are set to FreeOnTerminate = true is they should not be accessed from outside by reference.


text:
Q: How to pinpoint extremely slow / CPU hogging Eclipse startup times? I need some Maven dependencies and stuff from my SBT project in my Eclipse RCP project so I used the p2-maven-plugin to create an update site and install them into my workbench from there. Now, after installing them, I get some serious slowdowns. When installing, the step "Committing the provisioning operation" (83%) takes about 5 minutes and upon starting Eclipse (or running a plugin in an RCP style run configuration) takes about as long to start. During this time, I get 100% CPU usage and all memory I gave the workbench by the -Xmx setting in eclipse.ini is taken. I tried using java instead of javaw and started with -verbose but I don't get any output or log file written during this process.
How should I track down this slowdown?


text:
Q: Facebook Connect API is not creating session in iPhone I want to post on Facebook via Facebook connect library in iPhone. I am using  http://www.mobisoftinfotech.com/blog/iphone/iphone-fbconnect-facebook-connect-tutorial/ library. After filling all keys [ API+Secret keys ]. Application runs successfully.
But when I fill Facebook credentials on Facebook login form and tap "Log In". It does not do nothing and it fires sessionDidNotLogin function.
I am filling right API+Secret keys. Please guide.
I am using iPhone 4.3 Simulator.
Any other Facebook API, Document, Code Sample would be appreciated.

A: https://github.com/reallylongaddress/iPhone-Facebook-Graph-API


text:
Q: Change css for certain user roles I am trying to do a #tribe_events_event_options{display:none;} for all the author users on my site. I don't want them to be able to set an event to featured, and I thought the simplest way was to not display the box.
Is there an easy way to target user groups for custom css?
I've made a author.css file in the child theme folder.
I found this post, but It did not do it for me.
Custom CSS In Admin Only For Certain Roles
function wpa66834_role_admin_body_class( $classes ) {
global $current_user;
foreach( $current_user->roles as $role )
    $classes .= ' role-' . $role;
return trim( $classes );
}
add_filter( 'admin_body_class', 'wpa66834_role_admin_body_class' );

Writing css like: example
.role-editor #main-header {display:none;}

But the css is not affected. Am I missing something?
Thanks in advance!

A: Your code seems to be correct maybe your selector is wrong? can you post the body html of your page that is outputed?


text:
Q: Reduce the load php cURL puts on the server I'm currently using php URL to browse over 500 web pages a day with cookies.
I have to check each page to ensure that the account is still logged in and the pages are being viewed as a member, not a guest.
The script takes an hour or two to complete as it sleeps in between views.
I just want to know if there's anything I can do to reduce the load this script puts on the local server, I've made sure to clear variables at the end of each loop but is there anything I'm missing that would help?
Any new cURL settings that would help?
$i = 0;
$useragents = array();

foreach($urls as $url){

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_COOKIEJAR, str_replace('\\','/',dirname(__FILE__)).'/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, str_replace('\\','/',dirname(__FILE__)).'/cookies.txt');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragents[array_rand($useragents)]);

    $html = curl_exec($ch);
    curl_close($ch);

    if(!$html)
        die("No HTML - Not logged in");

    if($i %10 != 0)
        sleep(rand(5,20));
    else
        sleep(rand(rand(60,180), rand(300,660)));

    $i++;

    $html = '';
}

A: You could reuse your curl handle instead of creating a new one for each connection.
Clearing $html at the end of each iteration won't reduce memory usage and just adds an extra operation because it already gets reset in the next iteration.
$i = 0;
$useragents = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, str_replace('\\','/',dirname(__FILE__)).'/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, str_replace('\\','/',dirname(__FILE__)).'/cookies.txt');

foreach($urls as $url){

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragents[array_rand($useragents)]);
    $html = curl_exec($ch);

    if(!$html)
        die("No HTML - Not logged in");

    if($i++ % 10 != 0)
        sleep(rand(5,20));
    else
        sleep(rand(rand(60,180), rand(300,660)));
}

curl_close($ch);


text:
Q: ttk tkinter multiple frames/windows The following application I have created is used to demonstrate multiple windows in tkinter. The main problem is that none of the Entry controls, neither in the bmi-calculator or the converter, accept the values in the entry boxes - they get a ValueError when I do a calculation.
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

class App1(ttk.Frame):
    def createWidgets(self):
        #text variables
        self.i_height = StringVar()
        self.i_weight = StringVar()
        self.o_bmi = StringVar()

        #labels
        self.label1 = ttk.Label(self, text="Enter your weight:").grid(row=0, column=0, sticky=W)
        self.label2 = ttk.Label(self, text="Enter your height:").grid(row=1, column=0, sticky=W)
        self.label3 = ttk.Label(self, text="Your BMI is:").grid(row=2, column=0, sticky=W)

        #text boxes
        self.textbox1 = ttk.Entry(self, textvariable=self.i_weight).grid(row=0, column=1, sticky=E)
        self.textbox2 = ttk.Entry(self, textvariable=self.i_height).grid(row=1, column=1, sticky=E)
        self.textbox3 = ttk.Entry(self, textvariable=self.o_bmi).grid(row=2, column=1, sticky=E)

        #buttons
        self.button1 = ttk.Button(self, text="Cancel/Quit", command=self.quit).grid(row=3, column=1, sticky=E)
        self.button1 = ttk.Button(self, text="Ok", command=self.calculateBmi).grid(row=3, column=2, sticky=E)

    def calculateBmi(self):
        try:
            self.weight = float(self.i_weight.get())
            self.height = float(self.i_height.get())
            self.bmi = self.weight / self.height ** 2.0
            self.o_bmi.set(self.bmi)
        except ValueError:
            messagebox.showinfo("Error", "You can only use numbers.")
        finally:
            self.i_weight.set("")
            self.i_height.set("")

    def __init__(self, master=None):
        ttk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

class App2(ttk.Frame):
    def create_widgets(self):
        """Create the widgets for the GUI"""
        #1 textbox (stringvar)
        self.entry= StringVar()
        self.textBox1= ttk.Entry(self, textvariable=self.entry).grid(row=0, column=1)

        #5 labels (3 static, 1 stringvar)
        self.displayLabel1 = ttk.Label(self, text="feet").grid(row=0, column=2, sticky=W)
        self.displayLabel2 = ttk.Label(self, text="is equivalent to:").grid(row=1, column=0)
        self.result= StringVar()
        self.displayLabel3 = ttk.Label(self, textvariable=self.result).grid(row=1, column=1)
        self.displayLabel4 = ttk.Label(self, text="meters").grid(row=1, column=2, sticky=W)

        #2 buttons
        self.quitButton = ttk.Button(self, text="Quit", command=self.quit).grid(row=2, column=1, sticky=(S,E))
        self.calculateButton = ttk.Button(self, text="Calculate", command=self.convert_feet_to_meters).grid(row=2, column=2, sticky=(S,E))

    def convert_feet_to_meters(self):
        """Converts feet to meters, uses string vars and converts them to floats"""
        self.measurement = float(self.entry.get())
        self.meters = self.measurement * 0.3048
        self.result.set(self.meters)

    def __init__(self, master=None):
        ttk.Frame.__init__(self, master)
        self.grid()
        self.create_widgets()

def button1_click():
    root = Tk()
    app = App1(master=root)
    app.mainloop()

def button2_click():
    root = Tk()
    app = App2(master=root)
    app.mainloop()

def main():
    window = Tk()
    button1 = ttk.Button(window, text="bmi calc", command=button1_click).grid(row=0, column=1)
    button2 = ttk.Button(window, text="feet conv", command=button2_click).grid(row=1, column=1)
    window.mainloop()

if __name__ == '__main__':
    main()

How can I fix this, but still maintaining the class structure and the use of python3? BTW - Anything similar to C#'s form1.Show()?

A: Thanks Joe, you helped quite a bit and I have stumbled onto the answer... using ttk you can use the notebook, and since both my classes are derived frames, I can just add them to the frames of the notebook...
def main():
#Setup Tk()
window = Tk()

#Setup the notebook (tabs)
notebook = ttk.Notebook(window)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="BMI Calc")
notebook.add(frame2, text="Feet to Meters")
notebook.grid()

#Create tab frames
app1 = App1(master=frame1)
app1.grid()
app2 = App2(master=frame2)
app2.grid()

#Main loop
window.mainloop()

That solves the issues :)

A: You have to convert the StringVar() to an integer/float or use IntVar() or DoubleVar()
There are other problems as well.  Statements like the following return "None" since it is a grid() object and not a Label() object:
self.label1 = ttk.Label(self, text="Enter your weight:").grid(row=0, column=0, sticky=W)

I think you will also have problems with two Tk() windows open at the same time.  Use Toplevel() or separate frames instead.


text:
Q: Path / Graph problem with X nodes looking for Y paths with the most similar length. I have the following graph / path problem:
There is exactly 1 start node and 1 end node.
There are also X (in this case 7) nodes, each connected to all other nodes and the start and end node with different lengths of the paths.
The visitor has to visit each and every node exactly once, starting at the start node and ending its path at the end node. Diagram
There may be Y (in this case 5) visitors (or path variations).
Assuming that all Y (or 5 visitors/path-variations) start at t0 at the start node (t1, t2, etc. representing the steps to the next node, independent from the path length). At t1, all of the Y visitors have moved to one of the X nodes, but each node is only capable of holding exactly one visitor for each step (t). There may not be more than one visitor at each step at the same node (except the start and end node obviously). Each path has tx steps.
I am now looking for a solution to get the most shortest but also most similar path lengths for all visitors/path variations Y through all X nodes in tx steps.
How can I solve this and is it possible to do that in Excel, Python or R?
Diagram


text:
Q: How do I show that $S^1$ is the suspension of $S^0$? How do I show that $S^1$ is the suspension of $S^0$?
I have all the definitions here, I'm just bad at applying them.
The suspension of a topological space $X$ is the quotient $CX / (X × ${$1$}$)$, where $CX$ is the cone on $X$, the quotient space $(X × [0, 1])/(X × ${$0$}$)$.

A: I think it would be helpful for you to draw a picture yourself, then write a proof. If you cannot do it after you draw the picture, I am sure others will be happy to help you with the proof writing process. By the way, your definition of suspension is not (but equivalent to) the usual one.

A: For convenience let $0$ and $1$ be the two points of $S^0$. Then the suspension of $S^0$ is the union of two line segments $x = 0$ and $x = 1$ ($0 \le y \le 1$) in the plane, where $\{(0,0)\}$ is identified with $\{(1,0)\}$ and $\{(0,1)\}$ is identified with $\{(1,1)\}$. This is homeomorphic to a circle.


text:
Q: Make Fn Key Control Numlock I have a VAIO laptop which, like most laptops, has an Fn key. In order for me to switch from the regular keyboard to the numeric keypad on the laptop, I am required to use NumLock; simply pressing the Fn key and then the number keys does not do anything.
Is there any way to make it so that I can just hold the Fn key to type numbers, instead of turning on NumLock?

A: You didn't tell us what OS, but if it's Windows, you can use KeyTweak.
If it's Linux, you'll probably want to use xmodmap in the X windows system.
I'm not sure how to do this in Mac OS X, but it is most probably similar to the Linux approach.

A: Enable Numlock using the Windows onscreen keyboard (osk.exe) instead of the physical keyboard and then use Fn to enter the numbers.


text:
Q: Sending multiline string into listViewAdapter I have the following method in my class:
private String getCallDetails()
{
    StringBuilder sb = new StringBuilder();
    Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI,
            null, null, null,null);
    int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
    while (managedCursor.moveToNext()) {
        String phNumber = managedCursor.getString(number);
        String callType = managedCursor.getString(type);
        String callDate = managedCursor.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = managedCursor.getString(duration);
        String callDirection = null;
        int callDirectionCode = Integer.parseInt(callType);
        switch (callDirectionCode)
        {
            case CallLog.Calls.OUTGOING_TYPE:
                callDirection = "OUTGOING";
                break;
            case CallLog.Calls.INCOMING_TYPE:
                callDirection = "INCOMING";
                break;
            case CallLog.Calls.MISSED_TYPE:
                callDirection = "MISSED";
                break;
        }
        sb.append(callDirection+"||"+phNumber+"||"+callDuration+"||"+callDayTime+";\n");
    }
    managedCursor.close();
    return sb.toString();
}

which returns the following output:
2018-09-12 17:43:55.253 6883-6883/test.package.android D/callDetails: OUTGOING||17||9||Tue Aug 28 11:09:21 GMT+02:00 2018;
OUTGOING||17||0||Fri Aug 31 15:03:34 GMT+02:00 2018;
INCOMING||17||13||Fri Aug 31 15:17:00 GMT+02:00 2018;

What I want to do is separate each line and in each line separate items divided with "||" and set them as strings that I can use. How can I do this


text:
Q: When should a shared_ptr be passed as a raw pointer? I was reading about how shared pointers should be passed around.
I came across this link which states

Guideline: Use a non-const shared_ptr& parameter only to modify the
shared_ptr. Use a const shared_ptr& as a parameter only if you're not
sure whether or not you'll take a copy and share ownership; otherwise
use widget* instead (or if not nullable, a widget&).

I had a two questions regarding the above mentioned statement
Question 1:
It states

.. otherwise use widget* instead (or if not nullable, a widget&).

Does this mean if we have something like this
std::shared_ptr<foo> f = std::make_shared<foo>();

And we need to pass it to a different method. That method should have the signature like
void doSomething(foo* ptr); //assuming its nullable

so to use it will be
doSomething(f.get());

Is this correct ? If so then would this not be dangerous ? if the reference count of f goes to 0 then ptr would basically be invalid ? In which situation would I want to create a method that takes in a raw pointer ? Why would I want to pass a smart pointer around like that ?
Question 2
What does modify mean here ? How do I modify a shared pointer ?

Use a non-const shared_ptr& parameter only to modify the shared_ptr

A: I'll give Question 2 a try: Modifying a shared pointer means assigning a different object instance (and dropping ownership of the previously owned pointer).
#include <memory>
#include <iostream>

int
main() {
    using intptr = std::shared_ptr<int>;
    intptr p = std::make_shared<int>(5);
    auto func = [](intptr &x) { x = std::make_shared<int>(6);};

    std::cout << *p << std::endl;
    func(p);
    std::cout << *p << std::endl;
    return 0;
}

A: All those are considerations of  streamlining code and readability, where function signature is used as a clue to what function is meant for.
If a function requires a shared state of pointer to object while accessing it, it have no practical sense to pass it as shared pointer unless function is meant to  grab ownership on it. I.e. function foo() with signature
void  foo( std::shared_ptr<Object> p);  // it shares ownership

would grab control of Object instance, because parameter p is a local variable for foo().
Functions with non-const reference signature rise questions what they actually mean to do:
void  foo( std::shared_ptr<Object>& p);  // new storage may be assigned

They can change object owned by shared pointer p OR can change - modify - pointer itself by calling its reset() method. The guideline offers to use this for the latter because using shared state to dereference pointer got its cost. The former task easily can be done by raw reference:
void  foo( Object& p);  // object may change but occupies same storage

Raw pointer would make sense if result of .get() can be nullptr, otherwise controlled objects are better to be passed by reference.
Finally, constant reference allows to make another shared or weak pointer or to change the object, but doesn't allow to modify original pointer. This signature suggest that foo() may do the former.
void  foo(const shared_ptr<Object>& p); // p cannot be changed but may be shared


text:
Q: flexbox and container widths so I have a strange issue,
I have this html:

1

2

3

4

5

6

7

8

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

and then I have this CSS
html,
body {
    padding: 0;
    margin: 0;
}

.container {
    height: 100vh;
    display: flex;
}

.row {
    display: flex;
    padding: 50px 20px 20px;
}

.flex-column {
    background-color: pink;

    width: auto;
    margin-right: 100px;
    width: 280px;

    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    justify-content: flex-start;
    padding: 20px 0 0 20px;
}

.box {
    background-color: blue;
    width: 120px;
    height: 120px;
    margin: 0 20px 20px 0;
}

If I use it like that, the content all tries to fit in the rows width, which is not what I want. I would like the row to expand (and present a scrollbar) depending on how much content is in it.
Now, by accident I noticed that if I add the flex-column class to the row, it fixes it (sort of). You can see with the background colours that it isn't doing everything correctly, but the side effect is that it actually works the way I want it to.
My question is how can I get it to wrap the row around the content but still have the scroll bar?
Here is the codepen to show what I currently have.
http://codepen.io/r3plica/pen/waPoQo
if you remove the flex-column class from the row, you will see the issue.

A: Do you have to use flexbox? You can do it without it. I have posted a flex and a non-flex example. If you want to use flex, you have to make sure you that you have a block container element around your flex element with overflow:scroll. Also your main flex element inside your container needs to be set to float so that it will properly expand horizontally to include your inline-block child elements.
Non-Flex Example:

html,
body {
  padding: 0;
  margin: 0;
}

.row {
    background-color: red !important;
    display: block;
    padding: 50px 20px 20px;
    overflow:scroll;
    white-space:nowrap;
}

.flex-column {
    background-color: pink;
    display: inline-block;
    margin-right: 100px;
    padding: 20px 0 0 20px;
    width: 280px;
    vertical-align:top;
}

.box {
    background-color: blue;
    display: block;
    float: left;
    height: 120px;
    margin: 0 20px 20px 0;
    width: 120px;
}

1

2

3

4

5

6

7

8

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

Flex Example:

html,
body {
  padding: 0;
  margin: 0;
}

.container{
  display:block;
  overflow:auto;
}

.row {
    background-color: red !important;
    display: flex;
    padding: 50px 20px 20px;
    overflow:scroll;
    white-space:nowrap;
    float:left;
}

.flex-column {
    background-color: pink;
    display: inline-block;
    margin-right: 100px;
    padding: 20px 0 0 20px;
    width: 280px;
    vertical-align:top;
}

.box {
    background-color: blue;
    display: block;
    float: left;
    height: 120px;
    margin: 0 20px 20px 0;
    width: 120px;
}

1

2

3

4

5

6

7

8

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6

1

2

3

4

5

6


text:
Q: Report viewer in php I have managed to successfully configure a SSRS reporting server and connect my PHP application to render a report from it. I followed this link. Now what I need is a Report Viewer plugin which handles pagination , exporting etc. (exactly like report viewer control in .Net). Is there something available for PHP?
Basically I want something like the image below auto generated with every report I display using SSRS

A: I had a project at work where we had to do something similar to what you are asking.  I can't post what I did for work but I would be willing to answer questions to help you get started or if you get stuck. I haven't found anything commercial to do this. I'm assuming that your report is tabular, I don't have an answer for how to do complex reports that utilize lists, graphs, or gauges.
If you are dealing with a single tabular result, then the way that I ended up solving this is to have the report render as xml, and use xpath to parse the response from reporting service to build a custom table object. I built a custom RenderAs function that would call the RenderAsXml function and build object that defined the columns and data that goes in the table. I then used a javascript table library that takes a an xml or json structure that was built from the xml result. The table library that we used was DataTables, a jquery plugin. It allows you to pass it a json object and transform it into a table.
DataTables


text:
Q: iOS: App icon appears on lock screen when beacon region detected, but not when circular region detected When monitoring for beacons, and a beacon is within range, the app icon is always displayed on the lock screen... But, if the app is within one of the monitored circular regions, it doesn't seem like the app icon is ever displayed.
I.e. CLCircularRegion monitoring doesn't seem to get the app icon on the lock screen for me
Code snippet:
CLLocationDistance monitorRadius = 2.0*1609.34; // 2 miles in meters;
CLCircularRegion *region = [[CLCircularRegion alloc]
                                  initWithCenter:_location.coordinate
                                  radius:monitorRadius
                                  identifier:_regionIdentifier];
[self.locationManager startMonitoringForRegion:region];

I've seen people SAY that registering for a circular region should work to get the app icon on the lock screen, given that an "entered" event is encountered, but I've seen a lot of people say it's not working...and I haven't seen the app icon on the lock screen yet myself for just a circular region.
Several responses on SO seem to be mixing up the two as well... (e.g. someone asks about region monitoring to get app on lock screen, and someone answers to use beacons).
Thanks

A: I spoke to an Apple engineer and he stated that yes it should show the apps icon when within an CLCircularRegion. Unfortunately it is not working that way. Has anyone seen an app icon on the lock screen when monitoring a CLCircularRegion (using requestAlwaysAuthorization)?


text:
Q: Solving simple wave equation This is a homework question for numerical analysis that I do not know how to find the solution to.
$\frac{du}{dt}-\frac{du}{dx}=0$
$u(x,0)=e^x$
$u(1,t)=e^{t+1}$
$0\leq x \leq1,0\leq t \leq1$
I know the solution should be of the form $u=f(x)g(t)$ but I can't find any literature that explains what to do with the boundary conditions. My teacher said I don't need to have worked with PDEs before to solve this but I am lost.

A: Assume a solution of the form $u(x,t) = X(x)T(t)$, you only need to deal with the BC's to get the solution. So the BC's become
 $$u(x,0) = X(x)T(0) = e^x $$
$$u(1,t) = X(1)T(t) = e^{t+1}$$
from these we have
$$X(x) = \frac{1}{T(0)} e^x$$
and
$$T(t) = \frac{1}{X(1)} e^{t+1}$$
we can write the solution as
$$u(x,t) = X(x) T(t) = \frac{1}{T(0)X(1)} e^{x+t+1}$$
To get rid of the constant in front use one of the BC's to get
$$X(1)T(0) = e$$
and the solution is
$$u(x,t) = \frac{1}{e}e^{x+t+1}=e^{x+t}$$


text:
Q: Retain rows up to first occurrence of a value in a column, by group. Groups without value allowed I have a data frame like this one:
> df
  id type
1  1    a
2  1    a
3  1    b
4  1    a
5  1    b
6  2    a
7  2    a
8  2    b
9  3    a
10 3    a

I want to keep all rows for each group (id) up to the first occurrence of value 'b' in the type column. For groups without type 'b', I want to keep all their rows.
The resulting data frame should look like this:
> dfnew
  id type
1  1    a
2  1    a
3  1    b
4  2    a
5  2    a
6  2    b
7  3    a
8  3    a

I tried the following code, but it retains additional rows that have the value 'a' beyond the first occurrence of 'b', and only excludes additional occurrences of 'b', which is not what I want. Look at row 4 in the following. I want to rid of it.
> df %>% group_by(id) %>% filter(cumsum(type == 'b') <= 1)
Source: local data frame [7 x 2]
Groups: id

  id type
1  1    a
2  1    a
3  1    b
4  1    a
5  2    a
6  2    a
7  2    b
8  3    a
9  3    a

A: You could combine match or which with slice or (as mentioned by @Richard) which.max
library(dplyr)
df %>%
  group_by(id) %>%
  slice(if(any(type == "b")) 1:which.max(type == "b") else row_number())
# Source: local data table [8 x 2]
# Groups: id
#
#   id type
# 1  1    a
# 2  1    a
# 3  1    b
# 4  2    a
# 5  2    a
# 6  2    b
# 7  3    a
# 8  3    a

Or you could try it with data.table
library(data.table)
setDT(df)[, if(any(type == "b")) .SD[1:which.max(type == "b")] else .SD, by = id]
#    id type
# 1:  1    a
# 2:  1    a
# 3:  1    b
# 4:  2    a
# 5:  2    a
# 6:  2    b
# 7:  3    a
# 8:  3    a


text:
Q: Arrays and Objects In Prototypes - Not Treated as References I have a prototype object in Javascript, when I initialise a new instance of the prototype and update properties in the prototype, it updates for all elements. I understand that arrays and objects are passed by reference and was wondering of a solution that would get you around this?
let Test = function () {}

Test.prototype = {
    array: [],
    add: function (value) {
        this.array.push(value)
    }
}

let test1 = new Test();
let test2 = new Test();

test1.add(1);
test1.add(2);

// Prints [1, 2]
console.log(test2.array);

One solution would be:
class Test {

    constructor() {
        this.array = []
    }

    add(value) {
        this.array.push(value)
    }
}

let test1 = new Test();
let test2 = new Test();

test1.add(1);
test1.add(2);

// Prints []
console.log(test2.array);

But I am not looking for an ES6 Approach, something more "native" javascript.
Thanks for the help!

A: That's the thing: they are treated as references.
When you do this:
Test.prototype = {
    array: [], // <- This creates a new array and it's being used in all instances
    add: function (value) {
        this.array.push(value)
    }
}

What you want is getting different array instances for different class instances. In that case, simply do this.array = [] in your constructor:
let Test = function () { this.array = []; }

let Test = function () { this.array = []; }

Test.prototype = {
    array: [],
    add: function (value) {
        this.array.push(value)
    }
}

let test1 = new Test();
let test2 = new Test();

test1.add(1);
test1.add(2);

console.log(test1.array);
// => [1, 2]

console.log(test2.array);
// => []

A: Initialize mutable members in the constructor, not in the prototype. If it's in the prototype, it will be shared between all instances:

let Test = function () {
    this.array = [];
}

Test.prototype = {
    add: function (value) {
        this.array.push(value)
    }
}

let test1 = new Test();
let test2 = new Test();

test1.add(1);
test1.add(2);

console.log(test1.array);
console.log(test2.array);

A: Define the array on the instance instead of on the prototype:
function Test() {
    this.array = [];
}

Test.prototype.add = function (value) {
    this.array.push(value)
}

A:
I understand that arrays and objects are passed by reference

No, they are not. But they're referenced by object references, which is an entirely different thing,1 and is indeed the issue you're running into.

and was wondering of a solution that would get you around this?

Do exactly what you did in the ES6 approach: Put it on the object itself, not the prototype:
let Test = function () {
    this.array = [];
};

1 (All that the concepts "pass by reference" and "object reference" have in common is that they both use the word "reference." In the former, it's a reference to a variable [and a concept JavaScript doesn't have]. In the latter, it's a reference to an object.)


text:
Q: Single I2S Source for Two Speaker Amplifier I have two same speaker amplifier which is TAS5720 series from TI.
I drawn two identical schematics for these ICs which driven by one I2S source.
In practise, one of them is playing sound bad. Both of two has correct duty cycle at output stage and one of them is modulating depending on digital sound data but the broken one could not modulate. If I only initialize the broken one by software. It plays sound well.

This is my schematic.


text:
Q: How to prevent closing parenthesis from being appended to my formula in openpyxl I am trying to provide a link that will download an autogenerated spreadsheet, and am attempting to use openpyxl to create the spreadsheet. It is almost working, except for one small detail: when I try to use a formula as the value of the cell, there is a closing parenthesis appended to the end in the saved spreadsheet. This results in a #NAME? error.
Namely, I use something like this as the value
"=VLOOKUP(A{}, $'lookup_table'.A1:B3, 2, 0) - B{}".format(i + 1, i + 1)
and the resulting value in the spreadsheet is something like (I open it with LibreOffice Calc)
=VLOOKUP(A1, $'lookup_table'.A1:B3, 2, 0) - B1)
Notice the extra parenthesis after the B1.
I have dug around the internet for a solution, but have kept coming up empty. Any guidance on how to make this format correctly?
minimal code example
from openpyxl import Workbook

wb = Workbook()
ws = wb.active

ws1 = wb.create_sheet(title="lookup_table")
lookup_table = {"one": 1, "two": 2, "three": 3}
for row, (key, value) in enumerate(lookup_table.items()):
    ws1.cell(column=1, row=row + 1, value=key)
    ws1.cell(column=2, row=row + 1, value=value)

for i, value in enumerate(["one", "two", "three"]):
    ws.cell(column=1, row=i + 1, value=value)
    ws.cell(column=2, row=i + 1, value=lookup_table[value])
    ws.cell(
        column=3,
        row=i + 1,
        value="=VLOOKUP(A{}, $'lookup_table'.A1:B3, 2, 0) - B{}".format(i + 1, i + 1),
    )

wb.save("test.xlsx")

A: So the issue actually had nothing to do with openpyxl. But was with LibreOffice.
I looked into the generated xml files, and found that value was exactly as expected. The issue is that LibreOffice Calc references another sheet as sheet2.A1 and Microsoft Excel references it as sheet2!A1. I suppose that since the sheet was being saved as a .xlsx it makes sense to use the Excel format.
The file now opens correctly in Microsoft Excel and LibreOffice Calc after updating the string from
"=VLOOKUP(A{}, $'lookup_table'.A1:B3, 2, 0) - B{}".format(i + 1, i + 1)
to
"=VLOOKUP(A{}, 'lookup_table'!A1:B3, 2, 0) - B{}".format(i + 1, i + 1)


text:
Q: How can I insert a comma in a selected string? How can I use SQL to insert a comma into a selected string, so that (2%10 NET30) becomes (2%10, NET30)?

A: Into this string? With REPLACE:
SQL> select replace('2%10 NET30', ' ', ', ') result
  2  from dual;

RESULT
-----------
2%10, NET30

SQL>

Other strings might require different approach.


text:
Q: PdfCopy breaks the string replacement of PDF using iTextSharp I have two pdfs, lets say content and header.
Now I want to add this header to the top of content.
So first, I have used Document, PdfWriter then took the PdfContentByte (canvas) to place the header.pdf inside content with desired location.
This addTemplate method breaks the format of PDF.
I already have string replacement method after this merging, which is not working now after this merge method.
After the suggestions from iText, I tried to use PdfCopy or PdfSmartCopy.
But how can we place this header in desired location using PdfCopy ?
If not, then how to merge without breaking the format of PDF using writer / pdfContentByte ?
Note:
I have tried to merge the Pdfs by using PdfCopy, but again its breaking.
PdfObject pdfObject = dict.GetDirectObject(PdfName.CONTENTS);
(pdfObject is PRStream)
Here the pdfObject is not a PRStream instead it becomes PdfArray.
Please help me to resolve this issue.


text:
Q: Install Sublime silently I have used both below commands but it asks a next wizard during installation:
start-process -FilePath 'C:\Users\suganthanraj.p\Downloads\Sublime Text Build 3126 x64 Setup.exe' -ArgumentList '/qn+

msiexec /quiet 'C:\Users\suganthanraj.p\Downloads\Sublime Text Build 3126 x64 Setup.exe'

A: There is a chocolatey Sublime 3 package which you can use to install Sublime:
choco install sublimetext3

A: ` Here i found answer for my question
start-process -FilePath 'C:\Users\suganthanraj.p\Downloads\Sublime Text Build 3126 x64 Setup.exe' -ArgumentList '/VERYSILENT'

A: Sublime Text silent install with context menu enabled:
start-process -FilePath 'C:\Downloads\Sublime_Text_Build_3143_x64_Setup.exe' -ArgumentList '/VERYSILENT /TASKS="contextentry"'

Just need to add to the end line: '/VERYSILENT /TASKS="contextentry"'
If you have Chocolatey use this for install silently:
choco install -y sublimetext3


text:
Q: tesseract giving a different result in a file than a stdout when recognizing chinese picture Environment
Operation System: win7
Tesseract Version: 5.0
Problem
I download chi_sim.traineddata file from https://github.com/tesseract-ocr/tessdata/raw/4.00/chi_sim.traineddata. I put the chi_sim.traineddata file in the tessdata directory.
After I finished it. I want to try to recognize the mandarin character's picture.

works with a file as the output
I tried to recognize this picture in a command line with a file as the output.
E:\data>tesseract target.png out_file -l chi_sim --psm 7

I open the out_file.txt file. The file's content is bellow:
你 好 , 中 国

It works well with output as a file.
doesn't work with stdout as the output
I run the command line with the stdout as output. and tried to recognize the same picture.
E:\data>tesseract target.png stdout -l chi_sim --psm 7
你 好 , 中 国

However, I got a mess.
Question
why it got a mess when I use a stdout as the output? Is there anything I need to specific?


text:
Q: Facebook Login for Web in Flask While using Facebook api in my website for logging in. There is an error "App Not Setup: This app is still in development mode, and you don't have access to it. Switch to a registered test user or ask an app admin for permissions."
kindly help error

A: First make sure you are logged in Facebook developers.
Select your app and make sure you have admin rights.
In Settings -> Basic -> Contact Email.
And in 'App Review' Tab : change
Do you want to make this app and all its live features available to the general public?
Yes
Then, your app will be live..


text:
Q: Prove that there'll always be three distinct integers $x$, $y$ and $z$ such that $x + y + z = 0$.
Prove that in $2m + 3$ distinct integers picked from $4m + 3$ integers between $-(2m + 1)$ and $2m + 1$, there'll always be three distinct integers $x$, $y$ and $z$ such that $x + y + z = 0$ ($m \in \mathbb Z^+$).

This problem is adapted from a recent competition. Because of obvious reasons, I decided to alter the problem a little bit. It is certainly not avoided that mistakes will happen. I apologise for that.
Assume that $x < y < z$ and $y = 0$, this case can easily be solved.
But I can't solve the case where $x < y < 0 < z$ or $x < 0 < y < z$. The problem then becomes

$a$ and $m$ are integers such that $0 \ne |a| \le |2m + 1|$. Prove that there'll always two distinct integers $p$ and $q$ such that $-1 < \dfrac{p}{a}, \dfrac{q}{a} \le 0$ and $p + q = -a$.

A: We try induction on $m$ (with the case $m=0$ being trivial: For the only choice of three out of three ingetgers, we have $-1+0+1=0$).
Let $S$ be the set of $2m+3$ integers picked.
Assume $0\in S$. Then the other $2m+2$ numbers can have $2m+1$ different absolute values, hence one absolute value occurs twice, say $x\in S$ and $-x\in S$ for some $x\ne 0$. Then $y=0$, $z=-x$ gives us a solution.
Hence we may assume $0\notin S$.
Assume there are $r$ negatives and $s$ positives in $S$,
$$a_1<a_2<\ldots<a_r<0<b_1<\ldots < b_s.$$
So $r+s=2m+3$ and in particular $r,s\ge 2$.
If $a_1>-2m$ then $S\setminus\{2m,2m+1\}$ has at least $2(m-1)+3$ integers in the range $-2(m-1)-1,\ldots,2(m-1)+1$ and the claim follows by indcution. Hence we may assume $a_1\le -2m$ and likewise $b_s\ge 2m$.
Now we find $r+s-1=2m+2$ distinct integers that are not "allowed" to be in $S$:
$$\tag1-(a_1+b_1)>-(a_1+b_2)>\ldots>-(a_1+b_s)>-(a_2+b_s)>\ldots>-(a_r+b_s).$$
Note that these all lie in the range $-2m,\ldots,2m$.
So among the $4m+3$ integers in $[-2m-1,2m+1]$, it looks as if we have $2m+3$ integers that are in $S$ and $2m+2$ that are not. As $(2m+3)+(2m+2)>4m+3$, this is impossible. The only way out is that numbers forbidden in $(1)$  are not always distinct from the other summands, i.e., we have at least two exceptional cases where $a_1+b_i+a_1=0$ or $a_1+b_i+b_i=0$ or $a_j+b_s+a_j=0$ or $a_j+b_s+b_s=0$.
As $a_1\le-2m$, the first option would mean $b_i=4m>2m+1$, hence this cannot happen. Likewise $a_i+b_s+b_s=0$ is imposible. So our two exceptions are that $a_1=-2b_i$ and $b_s=-2a_j$ for some $i,j$. It follows that $a_,b_s$ are even, hence $a_1=-2m$, $b_s=2m$. Then $S\setminus\{a_,b_s\}$ is a set of $2(m-1)+3$ integers in the range $-2(m-1)-1,\ldots,2(m-1)+1$ and again we can aply the induction hypothesis. $\square$


text:
Q: grub failure after installing new12.04 lenovo i7, 64 bit, win7, 11.10 on sda10 with home on sda8+swap on sda9. root 12.04 on sda12 with /usr on sda11 complete new. There was kubuntu before with grub, the grub on sda10 didn´t work, but all entries have been fine.
Install of 12.04 ok, but after reboot: file not found, grub rescue promt which even does not accept exit!
After set prefix, set root, insmod comes: invalid arch independent ELF magic. This seems to be the real reason.
Win7 repair finds nothing, parted magic cannot install lilo instead, the grub rescue-CD
updates grub on sda10-same error,,,but fails to update grub on sda12!
I tried to start via parted magic but don´t know the correct command.
I am happy to have not updated, because there seems to be many problems with 12.04!
If i could boot with grub on sda10 (old system) again is enough. But how to do?
Marek

A: " after reboot: file not found, grub rescue promt" This means that grub's core.img, embedded in the post-mbr gap, is looking for /boot/grub/ on the wrong partition.
"After set prefix, set root, insmod comes: invalid arch independent ELF magic." This means that the /boot/grub/ that you pointed grub to is for a different version of grub than the version of grub that the embedded core.img came from.
Those two things together strongly suggest that the core.img embedded in the post-mbr gap is from a previous Ubuntu install, not from your most recent Ubuntu 12.04 installation. To fix this you need to run grub-install, which when run from a LiveCD either requires a chroot or the --boot-directory= argument, and make sure that you tell grub-install to install to the MBR (not to a partitition) of the drive which your BIOS is booting from (don't assume that you know which one this is, it's commonly not the one people think is being booted from when they have multiple hard drives). If you have multiple drives, it's probably best to install grub's boot sector to all of them.
To install grub from a LiveCD, follow this guide: https://help.ubuntu.com/community/Grub2#ChRoot


text:
Q: Should I ignore automated code review errors for GUI class? Should I ignore automated code review errors for GUI class? This class was generated by Windowbuilder. Should I make it differently so it has A grade in automated code reviews, and how should I do it, or should I ignored them because this types of classes don't have real complexity? The only describe window components and nothing else. Code reviews show me:

*

*Assignment Branch Condition

*Too many instance variables

*Function too long

*Total complexity too high

This is the code
package gui.dialogs;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import data.elements.Property;
import data.elements.Model;
import gui.text.DeviceDefaultTextUtils;

import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import java.awt.Button;
import java.awt.Dialog;

import javax.swing.SwingConstants;

public class DeviceDialog extends JDialog
{
    private static final long serialVersionUID = -7176709114506808074L;
    public JPanel contentPane = new JPanel();
    public JLabel lblDeviceIDValue = new JLabel();
    public Button btnAddNewModel;
    public JTextField textFieldSerial = new JTextField();
    public Button btnAdd;
    public Button btnCancel;

    /**
     * Creates frame "Device Registration Form".
     */
    public DeviceDialog(Dialog parentWindow)
    {
        createJDialogView();
        createDeviceIDView();
        createDeviceTypeView();
        createDeviceManufacturerView();
        createDeviceModelView();
        createDeviceSerialView();
        createButtonsView();
    }

    private void createJDialogView()
    {
        setTitle(DeviceDefaultTextUtils.TITLE);
        setResizable(false);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 300, 420);

        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
    }

    private void createDeviceIDView()
    {
        JLabel lblDeviceID = new JLabel(DeviceDefaultTextUtils.DEVICE_ID_LABEL);
        lblDeviceID.setFont(new Font("Tahoma", Font.PLAIN, 15));
        lblDeviceID.setBounds(20, 10, 75, 25);
        contentPane.add(lblDeviceID);

        lblDeviceIDValue.setHorizontalAlignment(SwingConstants.CENTER);
        lblDeviceIDValue.setFont(new Font("Segoe UI Symbol", Font.BOLD, 15));
        lblDeviceIDValue.setBounds(200, 10, 75, 25);
        contentPane.add(lblDeviceIDValue);
    }

    private void createDeviceTypeView()
    {
        JLabel lblDeviceType = new JLabel(DeviceDefaultTextUtils.DEVICE_TYPE_LABEL);
        lblDeviceType.setBounds(20, 50, 255, 15);
        contentPane.add(lblDeviceType);

        JComboBox<Property> comboBoxDeviceType = new JComboBox<Property>();
        comboBoxDeviceType.setBounds(20, 75, 255, 25);
        contentPane.add(comboBoxDeviceType);
    }

    private void createDeviceManufacturerView()
    {
        JLabel lblManufacturer = new JLabel(DeviceDefaultTextUtils.MANUFACTURER_LABEL);
        lblManufacturer.setBounds(20, 115, 255, 15);
        contentPane.add(lblManufacturer);

        JComboBox<Property> comboBoxManufacturer = new JComboBox<Property>();
        comboBoxManufacturer.setBounds(20, 140, 255, 25);
        contentPane.add(comboBoxManufacturer);
    }

    private void createDeviceModelView()
    {
        JLabel lblModel = new JLabel("Model");
        lblModel.setBounds(20, 175, 255, 15);
        contentPane.add(lblModel);

        JComboBox<Model> comboBoxModel = new JComboBox<Model>();
        comboBoxModel.setBounds(20, 200, 255, 25);
        contentPane.add(comboBoxModel);

        btnAddNewModel = new Button(DeviceDefaultTextUtils.ADD_NEW_MODEL_BUTTON);
        btnAddNewModel.setBounds(95, 234, 110, 25);
        contentPane.add(btnAddNewModel);
    }

    private void createDeviceSerialView()
    {
        JLabel lblSerial = new JLabel(DeviceDefaultTextUtils.SERIAL_NUMBER_LABEL);
        lblSerial.setBounds(20, 265, 255, 14);
        contentPane.add(lblSerial);

        textFieldSerial.setBounds(20, 290, 255, 25);
        contentPane.add(textFieldSerial);
        textFieldSerial.setColumns(10);
    }

    private void createButtonsView()
    {
        btnAdd = new Button(DeviceDefaultTextUtils.ADD_DEVICE_BUTTON);
        btnAdd.setFont(new Font("Dialog", Font.PLAIN, 15));
        btnAdd.setBounds(20, 345, 110, 25);
        contentPane.add(btnAdd);

        btnCancel = new Button(DeviceDefaultTextUtils.CANCEL_BUTTON);
        btnCancel.setFont(new Font("Dialog", Font.PLAIN, 15));
        btnCancel.setBounds(165, 345, 110, 25);
        contentPane.add(btnCancel);
    }
}

A: Generally all generated code should be excluded from automated code reviews.
Of course this implies that any custom code you make does NOT exist within the same source file as the generated code. If you're modifying the generated code before offering it to your review process, you should count this file as not being generated in its entirety, unless you mark the generated sections explicitly and your tooling allows excluding only sections of files (e.g. in Sonar you can mark things as "won't fix" and give a reason of "generated code" as a comment in such cases).


text:
Q: Handling events for an Inherited Form I have a base Windows Form with a control. I have declared the control to be protected so his siblings will be able to handle properties, methods and events. This form is written in c#.
One of my clients is using VB.NET, and they have created a new inherited form in their project. Everything works fine ...
But, When they want to handle the control's clicked event in vb.net they're getting this error message:
"Handles clause requires a WithEvents variable defined in the containing type or one of its base types".
Can anybody tell me what should i do on the c# form to let the inherited form in vb.net use the control events?
Thanks for your help!

A: Two options:

*

*Write some VB which declares a protected WithEvents variable, then decompile it to see what the VB compiler does. (I believe that it makes it a property for one thing, and probably adds a bunch of other bits and pieces.)

*Tell them not to use a Handles clause - get them to subscribe explicitly in the same way that you would from C#, using AddHandler and AddressOf.


text:
Q: Question about continuity of stopping time probability in proof of Dirichlet problem in Stein and Shakarchi In Chapter 6 in the book Functional analysis by Stein and Shakarchi the following theorem (Dirichlet problem) is proved:

$\mathcal{R}$ denotes a bounded open set and a point $y$ is called regular if
$$\mathbb{P}(\tau_\ast^y=0) = 1$$
where $\tau^x = \inf\{t\geq 0: x+B_t\notin \mathcal{R}\}$ and $\tau_\ast^x = \inf\{t>0: x+B_t\notin \mathcal{R}\}$ and $B_t$ is a Brownian motion started at $0$ and $B_t^x = x+B_t$.
Now my question concerns a particular step in the proof of (b).
I find the fact that $x\mapsto 1_{\{\omega':x+B_t(\omega')\in \mathcal{R}, \, \forall \epsilon\leq t \leq \delta\}}(\omega)$ should be continuous, hard to believe. Assume that $\mathcal{R} = \mathbb{D}\setminus \{0\}$, the unit disk with the $0$ removed. Then if $B_{t_0}^y(\omega) = 0$ for precisely one $t_0\in [\epsilon,\delta]$ it is not necessarily so that $B_t^x(\omega) = 0$ for some $t\in [\epsilon,\delta]$ regardless of how close $x$ is to $y$. Could someone clarify this for me? Is this an error in the book?

A: DISCLAIMER: THIS ANSWER IS INCOMPLETE
I think the key point is that $\mathcal{R}$ is an open set. Fix an $\omega$ such that $B_t$ is continuous. First note that $g(y,t)= B_t^y =y+B_t$ is jointly continuous.
Let us first show that $A:=\{y:y+B_t \in \mathcal{R}, \text{  all }\varepsilon\leq t \leq \delta\}$ is open. Suppsoe that $A$ is not open. Then there is a point $y \in A$ such that for every $n\geq 1$, you will get a $y_n \in (y-\frac{1}{n}, y+\frac{1}{n})$ such that $y_n \not\in A$. This means $y_n+B_{t_n} \not\in \mathcal{R}$ for some $t_n \in[\varepsilon,\delta]$. Now take a subsequence $y_{a_n}$ of $y_n$ such that for $y_{a_n}+B_{t_{a_n}}\not\in \mathcal{R}$, $t_{a_n} \in [\varepsilon,\delta]$, and $t_{a_n}\to t'$ for some $t'\in [\varepsilon,\delta]$ (you can always choose such a subsequence since $[\varepsilon,\delta]$ is compact). Now note that by construction $(y_{a_n},t_{a_n})\to(y,t')$ and therefore $y_{a_n}+B_{t_{a_n}} \to y+B_{t'} \in \mathcal{R}$ (using joint continuity of $B_t^y$). On the other hand $y_{a_n}+B_{t_{a_n}} \in \mathcal{R}^c$ which is closed, therefore the limit must be in $\mathcal{R}^c$ which is a contradiction. Therefore $A$ is open.
Coming to your problem, let $$f(y)=1\{B_t^y \in \mathcal{R}, \text{  all }\varepsilon\leq t \leq \delta\}= 1\{y \in A\}$$,
and we showed $A$ is open. Now you can conclude $f(y)$ is continuous on $A$ from here.
It still does not show that $f$ is continuous everywhere.