text:
Q: HTML - Text is not inside the button I'm new here. I just wanted to ask about this problem.
The text is not inside the box The text seems to be outside of the box and it looks weird. How do I make the text appear inside the box?  What did I do wrong in the coding? I don't see any problem in my coding. By the way, I use Dreamweaver to code this interface.
HTML code:

<meta charset="utf-8">
<title>Deane.co</title>
<link href="style.css" rel="stylesheet" type="text/css" >
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Deane.co

<a href="index.html"Home

<a href="service.html"Products

<a href="contact.html"Contact

<a href="about.html"AboutAbout

 Welcome To Deane.co

 Welcome to Deane.co the place to shop beautiful clothes easier

Check our products

 Hipster Blouse

 RM40

 Hipster Blouse

 RM40

 Hipster Blouse

 RM40

© Allright Reserved

CSS code:
body {
font-family: 'Raleway', sans-serif;
}
*{
padding: 0px;
margin: 0px;
}

#nav1 {
width: 100%;
height: 70px;
line-height: 70px;
background: #a5aab1;
}
#nav1 h1 {
float: left;
font-size: 2.5em;
margin-left: 15px;

}
#nav1 h1 a {
text-decoration: none;
color: white;
}
#nav1 ul {
float: right;
margin-right: 15px;

}
#nav1 ul li {
display: inline-block;
list-style-type: none;
}

#nav1 ul li a {
text-decoration: none;
color: white;
padding: 25px;
}
#nav1 ul li:hover{
background: #bfc5ce;
transition: all ease-in-out 0.45s;

}
#active {
background: #bfc5ce;

}

#main-content {
width: 100&;
height: 600px;
background: url(Images/store-background3.jpg) no-repeat;
background-size: cover;
text-align: center;
color: black;
line-height: 40px;

}
#main-content a {
text-decoration: none;
color: black;
}
#products {
background: #a5aab1;
width: 170px;
height: 60px;
line-height: 60px;
margin-left: auto;
margin-right: auto;
border-radius: 5px;
color: white;
font-weight: 100;
}
#products:hover {
box-shadow: 1px 1px 10px 10px rgba(136, 131, 131, 0.83);
transition: all ease-in-out 0.45s;
}
#products a {
color: white;
text-decoration: none;
padding: 25px;

}

#shirtsaesthetic {
width: 100%;
height: 400px;
background: white;
}
#shirtsaesthetic1 {
width: 400px;
height: 300px;
padding: 5px;
display: inline;
float: left;
margin: 19px;
text-align: center;
}
#shirtsaesthetic1 img {
width: 300px;
height: 220px;
border-radius: 5px;
}

A: your first bits of code are messed up.
Close tags properly:

<title>Deane.co</title>
<link href="style.css" rel="stylesheet" type="text/css" >
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Deane.co

Home

Products

Contact

About

 Welcome To Deane.co

 Welcome to Deane.co the place to shop beautiful clothes easier

Check our products

 Hipster Blouse

 RM40

 Hipster Blouse

 RM40

 Hipster Blouse

 RM40

© Allright Reserved

A: In your style.css file, remove the line below:
 #products a {
  color: white;
  text-decoration: none;
  padding: 25px; //remove this line
 }

In your html file, you missed ">" of a tag in these line:

Home

Products

 Contact

About

A: The a tags in your navigation are wrong, and you need to remove the padding from #products a

body {
font-family: 'Raleway', sans-serif;
}
*{
padding: 0px;
margin: 0px;
}

#nav1 {
width: 100%;
height: 70px;
line-height: 70px;
background: #a5aab1;
}
#nav1 h1 {
float: left;
font-size: 2.5em;
margin-left: 15px;

}
#nav1 h1 a {
text-decoration: none;
color: white;
}
#nav1 ul {
float: right;
margin-right: 15px;

}
#nav1 ul li {
display: inline-block;
list-style-type: none;
}

#nav1 ul li a {
text-decoration: none;
color: white;
padding: 25px;
}
#nav1 ul li:hover{
background: #bfc5ce;
transition: all ease-in-out 0.45s;

}
#active {
background: #bfc5ce;

}

#main-content {
width: 100&;
height: 600px;
background: url(Images/store-background3.jpg) no-repeat;
background-size: cover;
text-align: center;
color: black;
line-height: 40px;

}
#main-content a {
text-decoration: none;
color: black;
}
#products {
background: #a5aab1;
width: 170px;
height: 60px;
line-height: 60px;
margin-left: auto;
margin-right: auto;
border-radius: 5px;
color: white;
font-weight: 100;
}
#products:hover {
box-shadow: 1px 1px 10px 10px rgba(136, 131, 131, 0.83);
transition: all ease-in-out 0.45s;
}
#products a {
color: white;
text-decoration: none;

}

#shirtsaesthetic {
width: 100%;
height: 400px;
background: white;
}
#shirtsaesthetic1 {
width: 400px;
height: 300px;
padding: 5px;
display: inline;
float: left;
margin: 19px;
text-align: center;
}
#shirtsaesthetic1 img {
width: 300px;
height: 220px;
border-radius: 5px;
}

  <meta charset="utf-8">
  <title>Deane.co</title>
  <link href="style.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Deane.co

Home

Products

Contact

About

 Welcome To Deane.co

 Welcome to Deane.co the place to shop beautiful clothes easier

Check our products

 Hipster Blouse

 RM40

 Hipster Blouse

 RM40

 Hipster Blouse

 RM40

© Allright Reserved

A: Your  tags in the first unordered list are not closed properly.


text:
Q: CakePHP AppController.php issues I am having an issue with a cakephp script. It was written with cakephp version 2.5.1.
I'm getting fatal error: Fatal error: Cannot call constructor in /lib/Cake/Controller/CakeErrorController.php on line 46.
The original AppController.php file looked like this:
<?php

if (session_id() == '') {
session_start();
}
class AppController
{
public $components = array('Auth');
public $helpers = array(
    0      => 'Form',
    'Html' => array('className' => 'MyHtml')
    );

public function beforeFilter()
{
    global $loguser;
    global $username;
    global $siteChanges;
    global $paypalAdaptive;
    global $user_level;
    global $setngs;
    global $price;
    global $colors;
    global $parent_categori;
    global $googlecode;
    parent::beforeFilter();
    $this->Auth->loginAction = array('controller' => '/', 'action' => '/login');
    $this->Auth->logoutRedirect = array('controller' => '/', 'action' => '/');
    $this->Auth->authenticate = array(
AuthComponent::ALL => array(
    'fields'    => array('username' => 'email', 'password' => 'password'),
    'userModel' => 'Users.User'
    ),
0                  => 'Form'
);

    if ($this->params['controller'] == 'api') {
        $this->Auth->allow();
    }

    if ($this->params['controller'] == 'fantasyhelps') {
        $this->Auth->allow();
    }

    if ($this->params['controller'] == 'paypals') {
        App::import('Vendor', 'PayPal');
    }

    $this->Auth->allow(, , 'login', 'signup', 'emailverification', 'verification', 'index', 'setpassword', 'userprofiles', 'viewshops', 'addto', 'press', 'about', 'toppeople', 'findpeople', 'storeprofiles', 'getstoreprofile', 'listings', 'show_color', 'show_price', 'showByCategory', 'getMorePosts', 'ipnprocess', 'getmorepricecolor', 'getItemByCategory', 'ajaxSearch', 'captcha', 'forgotpassword', 'showByRelation', 'getItemByRelation', 'faq', 'contact', 'item_comments', 'changePassword', 'copyrights', 'termsofsale', 'termsofservice', 'termsofmerchant', 'privacy', 'loginwith', 'loginwithtwitter', 'changecurrency', 'downimage', 'sitemaintenance', 'getviewmore', 'customviewmore', 'orderstatus', 'getsizeqty', 'searches', 'getmoregallery', 'viewitemdesc', 'followersList', 'getmoreprofile', 'getmorestorycomment', 'followingList', 'twittlogin_save', 'item_favorited', 'merupdate', 'custupdatend', 'testing', 'bookmarklet', 'getmorecomments', 'adaptiveipnprocess', 'additemusingurl', 'giftcardipnIpn', 'ggipn', 'ggcronjob', 'nearme', 'getMorenearme', 'gifts', 'story');
    $loguser = $this->Auth->user();
    $userid = $loguser[0]['User']['id'];
    $username = $loguser[0]['User']['username'];
    $first_name = $loguser[0]['User']['first_name'];
    $username_url = $loguser[0]['User']['username_url'];
    $user_level = $loguser[0]['User']['user_level'];
    $profile_image = $loguser[0]['User']['profile_image'];
    $this->set('loguser', $loguser);
    $this->set('username', $username);
    $this->set('username_url', $username_url);
    $this->set('user_level', $user_level);
    $this->set('first_name', $first_name);
    $this->set('profile_image', $profile_image);
    $this->set('currentaction', $this->params['action']);
    $this->loadModel('User');
    $user_datas = $this->User->findById($userid);

    if (!empty($loguser) && empty($user_datas)) {
        $this->Auth->logout();
    }

    $user_status_val = $this->User->find('first', array(
'conditions' => array('User.id' => $userid)
));
    $user_status = $user_status_val['User']['user_status'];

    if ($user_status == 'disable') {
        $this->Session->setFlash(__('Your account has been disabled please contact our support'), 'default', array(), 'bad');
        $this->redirect($this->Auth->logout());
        $this->redirect('/login');
    }

    $this->loadModel('Sitesetting');
    $this->loadModel('Cart');
    $this->loadModel('Orders');
    $this->loadModel('Item');
    $this->loadModel('Price');
    $this->loadModel('Color');
    $this->loadModel('Category');
    $this->loadModel('Forexrate');
    $this->loadModel('Managemodule');
    $this->loadModel('Googlecode');
    $this->loadModel('Contactseller');
    $this->loadModel('Story');
    $orderdetails = $this->Orders->find('all', array(
'conditions' => array('Orders.merchant_id' => $userid)
));
    $this->set('orderdetails', $orderdetails);
    $storyCount = $this->Story->find('count', array(
'conditions' => array('userid' => $userid)
));
    $this->set('storyCounts', $storyCount);
    $managemoduleModel = $this->Managemodule->find('first');
    $this->set('managemoduleModel', $managemoduleModel);
    $params = $this->params;
    $action = $params['action'];

    if ($this->params['controller'] != 'api') {
        $this->_setLanguage();
    }

    if (($action != 'sitemaintenance') && ($action != 'login') && ($this->params['controller'] != 'api')) {
        if (!$this->isauthenticated() || ($user_level != 'god')) {
            if ($managemoduleModel['Managemodule']['site_maintenance_mode'] == 'yes') {
                $this->redirect('/sitemaintenance');
            }
        }
    }

    $messageCount = $this->Contactseller->find('count', array(
'conditions' => array(
    'OR' => array(
        array('merchantid' => $userid, 'sellerread' => 1),
        array('buyerid' => $userid, 'buyerread' => 1)
        )
    )
));
    $_SESSION['userMessageCount'] = $messageCount;

    if (!isset($_SESSION['language_settings'])) {
        $languageJson = file_get_contents(SITE_URL . 'language_settings.json');
        $_SESSION['language_settings'] = json_decode($languageJson, true);
        $defaultLanguage = $_SESSION['language_settings']['settings']['default'];
        Configure::write('Config.language', $defaultLanguage);
    }

    if (!isset($_SESSION['currency_value'])) {
        $forexrateModel = $this->Forexrate->find('first', array(
'conditions' => array('status' => 'default')
));
        $_SESSION['currency_symbol'] = $forexrateModel['Forexrate']['currency_symbol'];
        $_SESSION['currency_value'] = $forexrateModel['Forexrate']['price'];
        $_SESSION['currency_code'] = $forexrateModel['Forexrate']['currency_code'];
        $_SESSION['default_currency_code'] = $forexrateModel['Forexrate']['currency_code'];
        $_SESSION['default_currency_symbol'] = $forexrateModel['Forexrate']['currency_symbol'];
    }

    $setngs = $this->Sitesetting->find('all');
    $price = ('all');
    $forexrateModel = $this->Forexrate->find('all', array(
'conditions' => array('status <>' => 'disable')
));
    $colors = $this->Color->find('all');
    $UserDetailss = $this->User->findById($userid);
    $this->set('UserDetailss', $UserDetailss);
    $this->loadModel('Shop');
    $sellerDetails = $this->Shop->find('all', array(
'conditions' => array('user_id' => $userid)
));
    $this->set('sellerDetails', $sellerDetails);
    $shopDetails = $this->Shop->find('first', array(
'conditions' => array('user_id' => $userid)
));
    $this->set('shop_name', $shopDetails['Shop']['shop_name']);
    $parent_categori = $this->Category->find('all', array(
'conditions' => array('category_parent' => 0)
));
    $googlecode = $this->Googlecode->find('all');

    if (!empty($userid)) {
        if (!empty($carts)) {
            foreach ($carts as $crt) {
                $itmids[] = $crt['Cart']['item_id'];
            }

            $itm_datas = $this->Item->find('all', array(
'conditions' => array('Item.id' => $itmids, 'Item.status' => 'publish')
));
            $total_itms = count($itm_datas);
            $this->set('total_itms', $total_itms);
        }
    }

    $this->set('price', $price);
    $this->set('colors', $colors);
    $this->set('forexrateModel', $forexrateModel);
    $this->set('parent_categori', $parent_categori);
    $this->set('googlecode', $googlecode);
    $this->set('media_url', $setngs[0]['Sitesetting']['media_url']);
    $this->set('setngs', $setngs);
    $siteChanges = $setngs[0]['Sitesetting']['site_changes'];
    $siteChanges = json_decode($siteChanges, true);
    $paypalAdaptive = $setngs[0]['Sitesetting']['paypaladaptive'];
    $paypalAdaptive = json_decode($paypalAdaptive, true);
    $this->set('siteChanges', $siteChanges);
    $_SESSION['site_url'] = SITE_URL;
    $_SESSION['media_url'] = SITE_URL;

    if (!empty($setngs[0]['Sitesetting']['media_url'])) {
        $_SESSION['media_host_name'] = $setngs[0]['Sitesetting']['media_server_hostname'];
        $_SESSION['media_url'] = $setngs[0]['Sitesetting']['media_url'];
        $_SESSION['media_server_username'] = $setngs[0]['Sitesetting']['media_server_username'];
        $_SESSION['media_server_password'] = $setngs[0]['Sitesetting']['media_server_password'];
    }

    $params = $this->params;
    $action = $params['action'];
    $this->set('action', $action);

    if ($this->params['controller'] != 'api') {
        $this->_setLanguage();
    }
}

public function isauthenticated()
{
    $user = $this->Auth->user();

    if (!empty($user)) {
        return true;
    }

    return false;
}

public function isauthorized()
{
    $user = $this->Auth->user();
    if (($user[0]['User']['user_level'] == 'god') || ($user[0]['User']['user_level'] == 'moderator')) {
        return true;
    }

    return false;
}

public function isauthorizedpersn()
{
    $user = ();
    if (($user[0]['User']['user_level'] == 'god') || ($user[0]['User']['user_level'] == 'shop')) {
        return true;
    }

    return false;
}

public function _setLanguage()
{
    if (isset($this->Cookie) && $this->Cookie->read('lang') && !$this->Session->check('Config.language')) {
        $this->Session->write('Config.language', $this->Cookie->read('lang'));
    }
    else if (isset($this->params['language']) && ($this->params['language'] != $this->Session->read('Config.language'))) {
        $this->Session->write('Config.language', $this->params['language']);
        $this->Cookie->write('lang', $this->params['language'], false, '20 days');
    }
}
}

$config['Settings'] = Configure::read('Settings');
define('SITE_URL', $config['Settings']['SITE_URL']);
define('SITE_NAME', $config['Settings']['SITE_TITLE']);
define('FB_ID', $config['Settings']['FB_ID']);
define('FB_SECRET', $config['Settings']['FB_SECRET']);
define('GOOGLE_ID', $config['Settings']['GOOGLE_ID']);
define('GOOGLE_SECRET', $config['Settings']['GOOGLE_SECRET']);
define('TWITTER_ID', $config['Settings']['TWITTER_ID']);
define('TWITTER_SECRET', $config['Settings']['TWITTER_SECRET']);
define('GMAIL_CLIENT_SECRET', $config['Settings']
['GMAIL_CLIENT_SECRET']);
define('GMAIL_CLIENT_ID', $config['Settings']['GMAIL_CLIENT_ID']);

?>

The first error pointed to this line:
    $this->Auth->allow(, , 'login', 'signup', 'emailverification',
so I removed the , , and hence it became:
    $this->Auth->allow('login', 'signup', 'emailverification',
The second error pointed to this line $user = ();
So I changed it to $user = $this->Auth->user();
But this change from $user = (); to $user = $this->Auth->user(); throws a fatal error:
Fatal error: Cannot call constructor in /lib/Cake/Controller/CakeErrorController.php on line 46
Below is the content of CakeErrorController.php. I'm told that CakeErrorController.php is a core file so I shouldn't really need to change it?
<?php
/**
 * Error Handling Controller
 *
 * Controller used by ErrorHandler to render error views.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc.
(http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the
LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright     Copyright (c) Cake Software Foundation, Inc.
(http://cakefoundation.org)
* @link          http://cakephp.org CakePHP(tm) Project
* @package       Cake.Controller
* @since         CakePHP(tm) v 2.0
* @license       http://www.opensource.org/licenses/mit-license.php MIT
License
*/

App::uses('AppController', 'Controller');

/**
* Error Handling Controller
*
* Controller used by ErrorHandler to render error views.
*
* @package       Cake.Controller
*/
class CakeErrorController extends AppController {

/**
* Uses Property
*
* @var array
*/
public $uses = array();

/**
* Constructor
*
* @param CakeRequest $request
* @param CakeResponse $response
*/
public function __construct($request = null, $response = null) {
    parent::__construct($request, $response);
    $this->constructClasses();
    if (count(Router::extensions()) &&
        !$this->Components->attached('RequestHandler')
    ) {
        $this->RequestHandler = $this->Components-
 >load('RequestHandler');
    }
    if ($this->Components->enabled('Auth')) {
        $this->Components->disable('Auth');
    }
    if ($this->Components->enabled('Security')) {
        $this->Components->disable('Security');
    }
    $this->_set(array('cacheAction' => false, 'viewPath' => 'Errors'));
}

}

I need help in fixing any issues you notice with the AppController.php file. I'm new at this. Any help will be much appreciated.
Thanks.

A: First of all, and I don't want to step on anyone's toes, but, that code looks horrible, there's so much wrong with it I don't even know where to start... global usage, accessing superglobals directly, manually starting a session via native calls, code outside of the class definition, public controller methods that aren't actual actions, massive amounts of unrelated code that should be in concrete controllers and/or components, etc... you really need to get that cleaned up.
That being said, your AppController class doesn't extend Controller (which it must do) and has no constructor itself, so there's no constructor to invoke via parent::__construct() in CakeErrorController::__construct(), hence the error.
See also Cookbook > Controllers

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to manage a changing List while performing enumeration? I have a list of objects (musical notes) that is enumerated on a separate thread as they are played.  I am doing this so that I can keep the UI thread responsive.
whilst a note is playing (as part of an enumeration) how can I allow for the fact that a new note may of been added to the List (without the obvious collection modified exception).
I know I could copy the list to a temporary list and enumerate that, but I actually want the list to grow as a user selects more (and this will happen whilst the first note is playing etc).
psuedo logic as is:
onClick()
{
 Queue.Add(theClickedNote)
 Queue.Play() <-- on another thread
}

Play()
{
 if(Playing==true){return ;}

 foreach(note theNote in Queue)
 {
  Note.Play();
  Queue.Remove(theNote);
 }
}

As you can see in the above, each Click event adds a note to the Queue and then invokes a play method on the queue.
the queue enumerates the notes and plays each one in turn before removing the note
I hope I have explained what I am trying to do clearly?

A: Something like this can be used with ConcurrentQueue<T> in .Net 4.
ConcurrentQueue<Note> Queue = new ConcurrentQueue<Note>();

void onClick()
{
  Queue.Enqueue(theClickedNote);

  // start Play on another thread if necessary
}

void Play()
{
  if (Playing) return;

  Note note;
  while(Queue.TryDequeue(out note))
  {
     note.Play();
  }
}

ConcurrentQueue is thread-safe, so no locking needs to be implemented.

A: Instead of using a List you should use a real Queue
Then your code will look like this:
    Queue<Note> queue = new Queue<Note>();
    void onClick()
    {
        queue.Enqueue(note);
    }

    void Play()
    {
        if (Playing == true) { return; }

        while (queue.Peek() != null)
        {
            var note = queue.Dequeue();
            note.play();
        }
    }

This code isn't thread safe so you should add locks on the queue but this is the general idea.

A: As suggested by mike z, use the ConcurrentQueue added in .NET 4.0

Along with the other concurrent collections, this queue allows you to add / remove items asynchronosly + work with a snapshot of the underlying collection, by using the GetEnumerator method and iterating with it.
Notice you still might need to deal with different situations, such as queue being empty, this can be solved via the BlockingCollection, which take method will block the thread as long as the collection is empty


text:
Q: How to create contour plot in R which with the color in each contour scaled separately by the density of all points within the contour I am trying to create a contour plot in R in which all points in a certain contour are scaled according to the density inside that contour, not with respect to the density of all points in total. For example, I am trying to replicate a plot like this: https://docs.flowjo.com/flowjo/graphs-and-gating/data-visualization-and-display/gw-zebra/.
I am not sure where to proceed in doing so. If anyone could provide any advice, that would be greatly appreciated.

A: Myabe this will hel you
Libraries
library(tidyverse)

Example Data
df <-
  tibble(
    x = rnorm(1000),
    y = rnorm(1000)
    )

Code
df %>%
  ggplot(aes(x, y))+
  geom_density_2d_filled()

Output


text:
Q: How to convert word in string array using System.Web.HttpUtility.UrlEncode How to convert word in string array using System.Web.HttpUtility.UrlEncode as
well also remove it-> "!!*!!"
var array= new string []
               {"windows!!1!!","dual+sim!!3!!","32+gb!!2!!","Intel+i5!!2!!","red%2fblue"};

Output array
var Output-array= new string []
                   {"windows","dual sim","32 gb","Intel i5","red/blue"}

How can do like this in single line of code in C#

A: It's HttpUtility.UrlDecode
string[] array = new string[] { "windows!!1!!", "dual+sim!!3!!", "32+gb!!2!!", "Intel+i5!!2!!", "red%2fblue" };
string[] result = array.Select(x => System.Web.HttpUtility.UrlDecode(System.Text.RegularExpressions.Regex.Replace(x, @"!!.*!!", "")).Replace("+", " ")).ToArray();


text: Q: Install wordpress without affecting clickfunnels I have a client that wants me to install wordpress to manage his main site. However he has clickfunnels redirecting his site to this page. How do I install wordpress without messing up his clickfunnels?


text:
Q: Function Pointers by Reference Good Day everybody, I am creating a List class in order to be able to manipulate data like in python, but in c++.
I came up with an idea. Basically a method that goes through every node, and deletes it if it meets a specific condition. But I wanted that condition to be determined by the user of the library, so I implemented a pointer to a bool function, that takes one template data (same type as the List) as its only parameter.
So far, I managed to run this...

.h file:
int delIf(bool (*)(T));

.cpp file:
template <typename T>
int List<T>::delIf(bool (*ptr)(T)){
    int tot=0;
    T aux;
    for (int i=0;i<tam;i++)
    {
        aux=(*this)[i]; //Ive overloaded the [], and it works fine
        if ((*ptr)(aux))
        {
            tot++;
            this->del(i);
        }
    }
    return tot;
}

main.cpp:
#include <iostream>
#include "lists.cpp"

using namespace std;

bool check(int);

int main()
{
    List<int> a;
    for (int i=0;i<10;i++)
        a.push(i);
    a.delIf(&check);

    return 0;
}

bool check(int a){
    if (a%2==0)
        return true;
    else
        return false;
}

This works fine, however, I was wondering if its possible to overload the delIf method so that it takes not a pointer to a function as parameter, but a reference to it, so the user of the library could call:
delIf(check); //No '&' required

Instead of the
delIf( & check);

That is currently mandatory. Ive tried changing the prototype to something like:
int delIf(  (bool (*)(T)) & );

but I keep getting errors.
Thanks in Advance Everybody.

A: Your premise is false.  You don't need an & in front of a function to pass it to delIf.  The name of a function decays into a pointer to the function almost everywhere it is used in an expression.  (Including when you call the function!)  In fact, the only place it doesn't is when it is used as an argument to & - so
func
&func

have exactly the same type and value.
Having said that, yes you can pass a reference.  First rule of pointers to functions - write a typedef
typedef bool pred_t(T);
void delIf( pred_t& pred );

But!  I strongly encourage you to write delIf as a function template, and allow anything which can be called with a T, and has a function result which can be implicitly converted to bool.
template <typename Pred>
void delIf(Pred pred) {
   ...
}

That will allow use with capturing lambdas, and functors in general.
Also, what is this CPP file of which you speak?  Templates have to be implemented in the header file.  See the answers to this question.
(Note: "Pred" is short for "predicate" which is what the standard calls this sort of function.)


text:
Q: ASP NET MVC download ZIP file I'm trying to download a ZIP file in ASP NET MVC. I have done in ASP NET Webforms, and it works correcly, but I do the same in MVC and I don't get the same result, I tried the following:
public ActionResult Download()
{
    using (ZipFile zip = new ZipFile())
    {
        zip.AddDirectory(Server.MapPath("~/Directories/hello"));
        zip.Save(Server.MapPath("~/Directories/hello/sample.zip"));
        return File(Server.MapPath("~/Directories/hello/sample.zip"),
                                   "application/zip", "sample.zip");
    }
}

But I get the binary data in screen, not the downloaded zip file why this is not working in MVC?

I have found that this does not work if I do it from a partial class, if I execute the download code from the Index and send the file if it works, why?

A: I use this to download files. In your view:
var ext = Path.GetExtension(path);
string contentType = GetMimeType(ext);

using (var stream = fileManager.GetStream(path))
{
    var filename = fileManager.GetFileName(path);
    var response = System.Web.HttpContext.Current.Response;
    TransmitStream(stream, response, path, filename, contentType);
    return new EmptyResult();
}

Where GetMimeType is a method that return known MIME types:
public static string GetMimeType(string extension, string defaultValue = "application/octet-stream")
{
    if (extension == null)
    {
        throw new ArgumentNullException(nameof(extension));
    }

    if (!extension.StartsWith("."))
    {
        extension = "." + extension;
    }

    string mime;
    return _mappings.TryGetValue(extension, out mime) ? mime : defaultValue;
}

With _mappings as:
private static readonly IDictionary<string, string> _mappings =
   new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) {
        {".323", "text/h323"},
        {".3g2", "video/3gpp2"},
        {".3gp", "video/3gpp"},
        {".3gp2", "video/3gpp2"},
        {".3gpp", "video/3gpp"},
        {".7z", "application/x-7z-compressed"},

        // Other types...

        {".xwd", "image/x-xwindowdump"},
        {".z", "application/x-compress"},
        {".zip", "application/x-zip-compressed"},
    };

And the TransmitStream:
    public static void TransmitStream(
        Stream stream, HttpResponse response, string fullPath, string outFileName = null, string contentType = null)
    {
        contentType = contentType ?? MimeMapping.GetMimeMapping(fullPath);

        byte[] buffer = new byte[10000];
        try
        {
            var dataToRead = stream.Length;

            response.Clear();
            response.ContentType = contentType;

            if (outFileName != null)
            {
                response.AddHeader("Content-Disposition", "attachment; filename=" + outFileName);
            }

            response.AddHeader("Content-Length", stream.Length.ToString());

            while (dataToRead > 0)
            {
                // Verify that the client is connected.
                if (response.IsClientConnected)
                {
                    // Read the data in buffer.
                    var length = stream.Read(buffer, 0, 10000);

                    // Write the data to the current output stream.
                    response.OutputStream.Write(buffer, 0, length);

                    // Flush the data to the output.
                    response.Flush();

                    buffer = new byte[10000];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    // Prevent infinite loop if user disconnects
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException(ex.Message);
        }
        finally
        {
            response.Close();
        }
    }

A: Usually, if you want to download something i suggest you to use ContentResult
,transforming the file you want to download into a Base64 String and transforming it on the frontend using javascript with a Blob
Action
public ContentResult Download()
{
   MemoryStream memoryStream = new MemoryStream();
   file.SaveAs(memoryStream);

   byte[] buffer = memoryStream.ToArray();
   string fileAsString = Convert.ToBase64String(buffer);

   return Content(file, "application/zip");
}

front end
var blob = new Blob([Base64ToBytes(response)], { type: "application/zip" });
var link = document.createElement("a");

document.body.appendChild(link);

link.setAttribute("type", "hidden");
link.href = url.createObjectURL(blob);
link.download = fileName;
link.click();


text:
Q: Find the values of $\sin 69^{\circ},\sin 18^{\circ} , \tan 23^{\circ}$
Calculate $\sin 69^{\circ},\sin 18^{\circ} , \tan 23^{\circ}$. accurate upto two decimal places or in surds .

$\begin{align}\sin 69^{\circ}&=\sin (60+9)^{\circ}\\~\\
&=\sin (60^{\circ})\cos (9^{\circ})+\cos (60^{\circ})\sin (9^{\circ})\\~\\
&=\dfrac{\sqrt{3}}{2}\cos (9^{\circ})+\dfrac{1}{2}\sin (9^{\circ})\\~\\
&=\dfrac{1.73}{2}\cos (9^{\circ})+\dfrac{1}{2}\sin (9^{\circ})\\~\\
\end{align}$
$\begin{align}\sin 18^{\circ}&=\sin (30-12)^{\circ}\\~\\
&=\sin (30^{\circ})\cos (12^{\circ})-\cos (30^{\circ})\sin (12^{\circ})\\~\\
&=\dfrac{1}{2}\cos (12^{\circ})-\dfrac{\sqrt3}{2}\sin (12^{\circ})\\~\\
&=\dfrac{1}{2}\cos (12^{\circ})-\dfrac{1.73}{2}\sin (12^{\circ})\\~\\
\end{align}$
$\begin{align}\tan 23^{\circ}&=\dfrac{\sin (30-7)^{\circ}}{\cos (30-7)^{\circ}}\\~\\
&=\dfrac{\sin (30)^{\circ}\cos 7^{\circ}-\cos (30)^{\circ}\sin 7^{\circ}}{\cos (30)^{\circ}\cos 7^{\circ}+\sin (30)^{\circ}\sin 7^{\circ}}\\~\\
\end{align}$
is their any simple way,do i have to rote all values of of $\sin,\cos $ from $1,2,3\cdots15$
I have studied maths upto $12$th grade.

A: This may make a nice challenge for you. Use a regular pentagon to find the $\sin 18^\circ$.

A: Please refer to : derivation of sin 18 on this page
Once you know sin 18, you can find sin 9, cos 9 etc. by using half angle formulas.
In brief:
sin 72° = 2 sin 36° cos 36°    by the double angle relationship.
 sin 72° = 4 sin 18° cos 18° (1 - 2sin^2 18°) by the double angle relationship, again.
  cos 18° = 4 sin 18° cos 18° (1 - 2sin^2 18°)
 sin 72° = cos 18°.
            1 = 4 sin 18° (1 - 2sin^2 18°)
    Let x = sin 18°, this is known as
            1 = 4*x(1-2x^2)                                             substitution
8*x^3-4*x+1 = 0                                                         A product is zero only when one of its factors is zero.
8x^3-4x+1 = (2*x-1)(4*x^2+2*x-1)=0                           (2*x-1)=0 implies x= ½=sin 30° > sin 18° ;
                                                                              Since we know sin is increasing on [0°,90°].
            x = (-2 ± \sqrt{(4 + 4•4•1))/8}                       So we must solve the other factor,
                = (-2 ± \sqrt{20})/8                                     using the quadratic formula.
                = (-2 ± \sqrt{4}\sqrt{5})/8
                = (-1 ± \sqrt{5})/4                                       But the sin 18° > 0, so it cannot be negative.
  sin 18°   = (\sqrt{5}-1)/4                                         Hence the middle root is the one we want.
Here at the bottom of the page referred above you will see a comment about how to find sin 1 also.
From sin 1 you can find sin (1/2) and note that 23 = (22 +(1/2)) + (1/2). But 22 + ( 1/2 ) is 1/2 of ( 45 ).

A: Hint:
in this table you have the values of:
$$
\sin 18°\qquad \sin 3°
$$
From these you can find:
$$
 \sin 21°=\sin(18°+3°) \qquad
\sin 69°=\sin(90°-21°)
$$
All these are constructible numbers, i.e. real numbers that we can express using square roots (and the other arithmetic operations).
For $\tan 23°$ you can note that $69°=3 \times 23°$and use the formula:
$$
\tan 3 \alpha=\dfrac{3\tan \alpha-\tan^3 \alpha}{1-3\tan^2 \alpha}
$$
But this gives a cubic equation and this means that the number $ \tan (23°)$ is an algebraic number but it is not constructible.
If you know how to solve a cubic you can find a finite expression for $ \tan (23°)$ , but if you does not know, you can only find an approximate value as shown in other answers.

A: I do not know if you know multiple angle trig formulas.
Let $ A = 18 ^\circ. $ In a right angled triangle if acute angles are  $ 2A= 36 ^\circ, \,3A= 54^\circ$,
$ \sin 2 A = \cos 3A $
$ 2 \sin  A \cos  A = 4 \cos^3 A -3 \cos A $
simplifying and solving for $ \sin A $ gives you
$$ \sin 18^\circ =\dfrac{\sqrt{5}-1} {4}. $$

A: You may exploit:
$$ \sin(60^\circ)=\frac{1}{2}\sqrt{3},\quad \sin(18^\circ)=\frac{1}{4}\left(\sqrt{5}-1\right),\quad \tan(22^\circ 30')=\sqrt{2}-1$$
then use some form of interpolation. For instance, in a neighbourhood of $x=\frac{\pi}{3}$:
$$ \sin(x)=\frac{1}{2}\sqrt{3}+\frac{1}{2}\left(x-\frac{\pi}{3}\right)-\frac{\sqrt{3}}{4}\left(x-\frac{\pi}{3}\right)^2-\frac{1}{12}\left(x-\frac{\pi}{3}\right)^3+\ldots $$
so by taking $x=\frac{\pi}{3}+\frac{9\pi}{180}$ we have:
$$ \sin(69^\circ) \approx \frac{\sqrt{3}}{2}+\frac{\pi}{40}-\frac{\pi^2\sqrt{3}}{1600}=0.933\ldots\tag{1}$$
and in a neighbourhood of $x=\frac{\pi}{8}$ we have:
$$ \tan(x)=(\sqrt{2}-1)+(4-2\sqrt{2})\left(x-\frac{\pi}{8}\right)+(6\sqrt{2}-8)\left(x-\frac{\pi}{8}\right)^2+\ldots $$
so by taking $x=\frac{\pi}{8}+\frac{\pi}{360}$ we have:
$$ \tan(23^\circ) \approx \sqrt{2}-1+(4-2\sqrt{2})\frac{\pi}{360}=0.424\ldots \tag{2}$$
At last, we have:
$$ \sin(18^\circ)=\frac{\sqrt{5}-1}{4}\approx 0.309\ldots\tag{3}$$

A: For Sin 69∘, Exact value may be determined as follows:
+45..............45.....................+2
+22.5............67.5...................+2
+11.25............78.75................+2
-5.625............73.125................-2
-2.8125............70.3125.............+2
-1.40625............68.90625.........+2
0.703125............69.609375........-2
-0.3515625..........69.2578125......-2
-0.17578125........69.08203125............+2
-0.087890625........68.9941406250........+2
0.043945313........69.0380859375........-2
-0.021972656........69.0161132813........-2
-0.010986328........69.0051269531........+2
-0.005493164........68.99963378906250.....+2
Hint for table: First column is half of earlier (called as Central) with sign towards 69∘; second is cumulative of the first column; and the third is division current Central with earlier Central.
If we follow above pattern infinitely, the sum will be 69. However, we can see the repeating pattern in third column (+2, +2, -2, -2); hence this is the exact value.
Now write the third column top-to-down approach as:$$+2+2+2-2\overline{+2+2-2-2} $$.
In the next step just replace 2 by  √(2; the result will be :
$$√(2+√(2+√(2-√(2\overline{+√(2+√(2-√(2-√(2} $$.
Sin 69∘ will be half of this (closing brackets are collapsed by "]").
Therefore, Sin 69∘ = $$√(2+√(2+√(2-√(2\overline{+√(2+√(2-√(2-√(2}]/2 $$
Above method is called as Precise-Rewritten method. You can find exact trigonometric value of all integer angles using this method.
I apologize above bad formatting and discourage to explain all angles here.


text:
Q: How to parse Java code stored in a string How can I parse Java code stored in a String?
Example:
String s = "int i = 2; System.out.println(\"the number is: \" + i);";

A: You would probably try to use the JavaCompiler interface...
Search for JavaCompiler and ToolProvider (which is what you typically use to get hold of an instance of the interface) for tutorials etc.

A: An alternative could be the Beanshell

A: Use Groovy!
String s = "int i = 2; System.out.println(\"the number is: \" + i);";
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate(s);


text:
Q: Get variables in scope at each PHP backtrace level? Is there a way to view the variables set in each stack frame in a backtrace? I can come pretty close with a combination of debug_backtrace(true) to get the objects, get_object_vars on each object to get $this vars, the args key in each backtrace frame, and get_defined_vars to get globals, but any temporary variables set within a function I can't find a way to retrieve.
Here's an example situation:
function method1($foo) {
    $temp = method2($foo + 1);
    foreach ($temp as $t) {
        method2($t);
    }
}

function method2($bar) {
    $temp2 = $bar->value + $_GET['val'];
    debug();
}

function debug() {
    // to be created
    $global_scope = get_defined_vars();
    $bt = debug_backtrace(true);
}

I can get $foo and $bar via the args key in the backtrace, the object variables of $bar through get_object_vars, and the globals through get_defined_vars. I want to get the value of $temp2 and $temp as well.

A: Install and Enable XDebug on your (local) server. Then use xdebug_get_declared_vars(). Make sure that you set xdebug.collect_vars to On in your xdebug .ini file.
Example:
<?php
    class strings {
        static function fix_strings($a, $b) {
            foreach ($b as $item) {
            }
            var_dump(xdebug_get_declared_vars());
        }
    }
    strings::fix_strings(array(1,2,3), array(4,5,6));
?>

Returns:
array
  0 => string 'a' (length=1)
  1 => string 'b' (length=1)
  2 => string 'item' (length=4)

Example from xdebug.org
Note, that the function only returns variables in the scope where the function xdebug_get_declared_vars() is called in.

A: Alter your debug to take 1 param. Then just pass in get_defined_vars. This will give you an array of all the vars in the local scope.


text:
Q: Need disk partition space advice in a dual-boot scenario I'm using a laptop with 1TB HDD running Windows 10. I'm about to install Ubuntu 16.04 on it and dual boot. I'm wondering how much disk space shall I give to both OSes because I want to keep them both on the same partition (C drive).
My aims:

*

*Windows boot shouldn't slow down.

*If there's a safety threshold (because I've seen at some place that Windows System Restore needs at least 50GB free space or something) of memory size for Windows C drive, I want to keep a healthy margin above that size.

*I don't want to compromise Ubuntu by giving all importance to Windows.

My framework:

*

*My personal files and data are all stored in drives other than C drive. Big software like Maya and Adobe MasterCollection and games are not installed in C drive.

*The C drive is 99.9GB and 49GB is free right now.

*Even with Ubuntu, I'll store my data on those other drives (like B for bulky software, A for personal files, D for movies, etc.).

My question: How much space shall I allocate to both OSes looking at all this information?
I have a related question -- if I'm running Ubuntu, does the disk usage required by Windows (reserved disk space for Windows) get invoked too? Suppose I give Windows x GB and Ubuntu y GB then if I boot with Ubuntu, will I:

*

*Only be able to use y (C drive - x GB)?

*Be able to use the whole C drive?

*(If x < y) experience no problems because Windows isn't invoked at all?

A: I just did the same setup on my computer. Apparently I am able to run Windows 10 with just 50 GB and some software installed, of course you need to make sure to always keep it kinda clean. The Ubuntu partition itself needs about 30 with software on mine. So it should work.
The question about the access depends on the kind of disk-formating you intend to use for ubuntu (ext4 recommended). In that case Ubuntu can access the Windows-partition (recognized as a second disk) but Windows cannot handle the Ubuntu partition that easily without software. Thats why in my case I made a data-partition which stores, well, all data and then the two partitions for the Window/Ubuntu.


text:
Q: Password validation regex: require and forbid certain characters I have an MVC form with jQuery validation and System.ComponentModel.DataAnnotations
Problem is if I enter & in the password textbox then jQuery and MVC Model.Isvalid allows it, even though it's not one of the allowed characters.
I have tried to search for this on Google but the results I get back have nothing to do with the issue. i.e. JavaScript: client-side vs. server-side validation - Stack Overflow
My regex is below in case I have made a mistake with that.
RegularExpression("^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,10})",
  ErrorMessage = "{0} must be between 6 and 10 characters and have at least 1 upper case letter, 1 lower case letter, 1 number and contain either @#$%")

A: The pattern in your example ^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,10}) uses positive lookaheads to ensure certain character classes are present in the input string but it will not in any way prevent other types of characters to appear. Each lookahead group starts with .* which allows literally anything hence & or any other character as a matter of fact will be accepted in the input string and whatever a lookahead signifies will be enforced in addition.
In other words, this approach using only positive lookaheads will make some types of characters required but it will not make any characters disallowed.
To overcome this, you can simply add another lookahead group but this time a negative one:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])(?!.*[&]).{6,10}$

Also, pay attention to end the pattern with string terminator $ (which was missing in your example). Without that the regex engine will produce a match for inputs that are more than 10 characters long.
See example here.


text:
Q: signInWithEmailAndPassword. Getting a NullPointerException I wanted to start my new and also first app, and it crashes every time i hit the button to login. It tells me that there is a NullPointerException, but i have no clue why. Could someone help me? Have been looking for solutions but can't find any helping ones so far.
package com.glowchat.app;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class LoginActivity extends AppCompatActivity {

    private Button loginbtn;
    private EditText email;
    private EditText password;

    private FirebaseAuth auth;
    private FirebaseUser user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        loginbtn = (Button) findViewById(R.id.loginbtn);

        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                email = (EditText) findViewById(R.id.inputEmailLogin);
                password = (EditText) findViewById(R.id.inputPasswordLogin);

                String loginemail = email.getText().toString();
                String loginpassword = password.getText().toString();

                if (loginemail.isEmpty() || loginpassword.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "Please fill out all fields.", Toast.LENGTH_SHORT).show();
                } else {
                    auth.signInWithEmailAndPassword(loginemail, loginpassword).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                Toast.makeText(LoginActivity.this, "Authentication successfull.", Toast.LENGTH_SHORT).show();
                                user = auth.getCurrentUser();
                            } else {
                                Toast.makeText(LoginActivity.this, "Authentication failed. Check your input and your internet connection.", Toast.LENGTH_SHORT).show();
                                user = null;
                            }
                        }
                    });
                }
            }
            });
    }

}

This is what i get in the Run tab:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.glowchat.app, PID: 29274
    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
        at com.glowchat.app.LoginActivity$1.onClick(LoginActivity.java:47)
        at android.view.View.performClick(View.java:6935)
        at android.widget.TextView.performClick(TextView.java:12742)
        at android.view.View$PerformClick.run(View.java:26211)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:7000)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)

A: You just declared FirebaseAuth auth but not init it so that you can't signInWithEmailAndPassword.
I think this Firebase docs will help you a little bit.


text:
Q: What's the worst injury ever inflicted to Wolverine? From all the canons that I have read or seen, I have seen Wolverine facing two worst injuries:

*

*Being split into two by The Hulk.

*Skin burning down by nuclear explosion (in The Wolverine movie)
Is there any other injury worse than this that has been inflicted on Wolverine?
Conditions:
a) Wolverine must be in his normal form. No power-suppressing materials must have been used on him (like they were later in The Wolverine).
b) Wolverine's death not included.
c) No mental or emotional injury included.

A: If you are excluding Wolverine's death, then the worst agony I can imagine him suffering was the extraction of his adamantium by Magneto in X-men #25 in 1993.

*

*Adamantium is supposedly unable to be altered by any force once it has been set. I imagine the magnetic field created by Magneto necessary to alter an immutable metal, not to mention the energy required should have been excruciating and easily one of the most terrible things to happen to Logan, that DIDN'T kill him.

From X-Men #25; Marvel, 1993: part of the Fatal Attractions epic.
Script by Fabian Nicieza, pencils by Andy Kubert, inks by Matthew Ryan.

A: In an alternate universe Wolverine was killed by The Punisher.
He was thrown against a high voltage fence, which vaporized every cell of his body. That seems to have done the trick


text:
Q: discord.py Spotify doesnt seem to do anything I'm developing my first bot just as a hobby and something to help me learn some Python and I've been trying to integrate Spotify with it but it just doesn't seem to work. I also read the other post on this website but it did not help.
I have tried reading through the documentation but I am a beginner and could not find much on google to help.
if I do print(discord.Spotify.title), I get this <property object at 0x0000020E42C5DE00>
This is the code I tried to use but did not work:
from discord import Spotify

@bot.command()
async def spotify(ctx, user: discord.Member = None):
    if user == None:
        user = ctx.author
        pass
    if user.activities:
        for activity in user.activities:
            if isinstance(activity, Spotify):
                embed = discord.Embed(title = f"{user.name}'s Spotify", description = "Listening to{}".format(activity.title), color = 0xC902FF)
                embed.set_thumbnail(url=activity.album_cover_url)
                embed.add_field(name="Artist", value=activity.artist)
                embed.add_field(name="Album", value=activity.album)
                embed.set_footer(text="Song started at {}".format(activity.created_at.strftime("%H:%M")))
                await ctx.send(embed=embed)

Apologies for any formatting issues. Not sure if I used the code block correctly
I am also using cogs if it makes a difference at all.
Just want it to at least send me back a message with the song the user is playing so I can have it respond differently to different artists or songs.
Thanks!

A: You can try to check if it is a problem with your Intents. Import all with the following function:
intents = discord.Intents.all()
client = discord.Client(intents=intents)

Connected with a code the following command works fine for me:
from discord import Spotify

@bot.command()
async def spotify(ctx, user: discord.Member = None):
    if user == None:
        user = ctx.author
        pass
    if user.activities:
        for activity in user.activities:
            if isinstance(activity, Spotify):
                embed = discord.Embed(title = f"{user.name}'s Spotify", description = "Listening to{}".format(activity.title), color = 0xC902FF)
                embed.set_thumbnail(url=activity.album_cover_url)
                embed.add_field(name="Artist", value=activity.artist)
                embed.add_field(name="Album", value=activity.album)
                embed.set_footer(text="Song started at {}".format(activity.created_at.strftime("%H:%M")))
                await ctx.send(embed=embed)

The output:

A: I was having the same issue.
After adding this line:
intents = discord.Intents().all()

you need to add intents to the bot parameter:
bot = commands.Bot(command_prefix = "?", intents=intents)


text:
Q: Get average outer pixel color of image So I want to get the average color of the outer pixels in an image, to give the background of the div the image is shown in, the same color. So I won't have to make all images the background color myself.
Example: if the image is 100px x 100px, you check the 5 outer pixels at the top of the image, 5 outer pixels of the right side of the image, same for left and bottom. You will get 5 x 100 x 4 pixels, get the colors, check the average and let JS give the div the same background.
So if the average color is #000000, the div BG will be #000000. If average is #FAFAFA, the div BG will be #FAFAFA

A: You have to use canvas for this. This will require CORS restrictions to be fulfilled though.
If it is it's just a matter of extracting the pixels from the region you want to analyse, add up and divide on number of pixels you counted.
Demo

var img = new Image();                            // load an image
img.crossOrigin = "";                             // we need CORS here...
img.onload = function() {                         // when image has loaded:
  var div = document.querySelector("div");
  div.appendChild(this);                          // add image to DOM (demo)
  div.style.background = analyse(img, 5);         // bg color = result from analyse
}
img.src = "http://i.imgur.com/rUeQDjE.png";       // some image (CORS enabled)

function analyse(img, border) {
  var canvas = document.createElement("canvas"),  // create a canvas element
      ctx = canvas.getContext("2d"),              // get context
      w = img.naturalWidth,                       // get actual width..
      h = img.naturalHeight;

  canvas.width = w;                               // set canvas size
  canvas.height = h;

  ctx.drawImage(img, 0, 0);                       // draw in image

  // do checks:, for example:
  //if (border*2 > canvas.width || border*2 > canvas.height) throw "Image too small!";

  // get borders, avoid overlaps (though it does not really matter in this case):
  var top = ctx.getImageData(0, 0, w, border).data;
  var left = ctx.getImageData(0, border, border, h - border*2).data;
  var right = ctx.getImageData(w - border, border, border, h - border*2).data;
  var bottom = ctx.getImageData(0, h - border, w, border).data;

  var r = 0, g = 0, b = 0, cnt = 0;

  // count pixels and add up color components: (see function below)
  countBuffer(top);
  countBuffer(left);
  countBuffer(right);
  countBuffer(bottom);

  // calc average
  r = (r / cnt + 0.5)|0;
  g = (g / cnt + 0.5)|0;
  b = (b / cnt + 0.5)|0;

  return "rgb(" + r + "," + g + "," + b + ")";

  function countBuffer(data) {
    var i = 0, len = data.length;
    while(i < len) {
        r += data[i++];   // add red component etc.
        g += data[i++];
        b += data[i++];
        i++;
        cnt++;            // count one pixel
    }
  }

}
div {padding:30px}


text:
Q: Can't detect WIFI I'm relatively new to Ubuntu and just dual booted 12.04 LTS with Windows 8.1
I can connect to WIFI with Windows; however, it doesn't allow me to with Ubuntu. It doesn't detect any wireless networks even when manually entered. It does connect via direct connection by ethernet cable. Any help would be awesome. Thanks!

A: First Check rfkill list commands. it shows wireless. Then Check your Additional Drivers in system settings whether it contains the Broadcomm STA wirless driver or not. If it is not and also if it have but you can't activate the driver in that time. you have to do this steps
First we have to remove the bcmwl kernel source
    sudo apt-get remove bcmwl-kernel-source
Then again install
    sudo apt-get install bcmwl-kernel-source


text:
Q: Cannot change global variables in a function through an exec() statement? Why can I not change global variables from inside a function, using exec()? It works fine when the assignment statement is outside of exec(). Here is an example of my problem:

>>> myvar = 'test'
>>> def myfunc():
...     global myvar
...     exec('myvar = "changed!"')
...     print(myvar)
...
>>> myfunc()
test
>>> print(myvar)
test

A: To add to Alex's answer: although when you omit the locals/globals arguments they default to the locals and globals of the caller, this only a convenience hack; it does not mean they are inheriting the full execution context of the caller. In particular:
a. nested scope cells are not available to the execed code. So this fails:
def f():
    foo= 1
    def g():
        exec('print foo')
    g()
f()

b. global declarations do not carry over into the execed code. So by default as in your example, written variables are put in the locals dictionary. However, you could make it work by saying
exec('global myvar\nmyvar = "changed!"')

You don't really want to be doing this if you can help it. global already isn't nice and exec is pretty much a code smell in itself! You wouldn't want to combine them unless there was really no alternative.

A: Per the docs, the exec statement takes two optional expressions, defaulting to globals() and locals(), and always performs changes (if any) in the locals() one.
So, just be more explicit/specific/precise...:
>>> def myfunc():
...   exec('myvar="boooh!"', globals())
...
>>> myfunc()
>>> myvar
'boooh!'

...and you'll be able to clobber global variables to your heart's contents.

A: How about this:
>>> myvar = 'test'
>>> def myfunc():
...     exec('globals()["myvar"] = "changed!"')
...     print(myvar)
...
>>> myfunc()
changed!
>>> print(myvar)
changed!

It worked for me in Python 2.6.
EDIT: Actually Alex Martelli's explanation is much better than mine :)


text:
Q: jest with react useState is not Override I have the following to
useState hooks:
const [file, setFile] = useState(null);
const [isLoading, setIsLoading] = useState(false);

this is my test:

  test('Happy path', async () => {
    jest
      .spyOn(React, 'useState')
      .mockImplementationOnce(() => [true, () => null])
      .mockImplementationOnce(() => [false, () => null]);
    render(<NarcUploadWindow {...mockPropsSuccess} />);
    const sendButton = await waitFor(() => screen.findByText(`Send`));
    fireEvent.click(sendButton);
    expect(mockPropsSuccess.showSuccessToasterMessage).toHaveBeenCalled();
  });

problem is the file field remains null and the isLoading also doesn't change if I try to set it to true, I have also tried:
import * as React from 'react';
...
const [file, setFile] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false);

basically all four of combinations the import and the useState
however the problem remains the same,
I saw this post:
enzyme react useState
but I don't want to use enzyme so the majority of the solutions are not valid without using it
any help on how can I change the initial state of the hooks using jest?


text:
Q: Set Cookie in React app works in localhost but not in production I am trying to set a cookie on the client side in my react web app.
I am using CRA deployed to Firebase.
Tried both js-cookie and react-cookie - in both cases I see that the set cookie code is running correctly.
When developing in localhost everything works perfectly - yet in production no cookie is ever being created.
Am I missing something?

A: According to react-cookie docs setCookie(name, value, [options]) and
removeCookie(name, [options]) accepts domain key in options object. Are you using your production url as a value of domain key ?


text:
Q: TCPServer: show exact request in ruby I'm trying to see the exact request incl. potential headers like IP, mac address etc.
Server side code:
require 'socket'

server = TCPServer.new 2000
loop do
  client = server.accept

  puts client.inspect # This should show IP and all transmitted information

client.close
end

Output is #<TCPSocket:fd 8>, but should show the exact request

A: You can read what client send to the server like this:
require 'socket'

server = TCPServer.new 2000
loop do
  client = server.accept

  # Print whatever client sends to server
  while line = client.gets
    puts line
  end

  client.close
end

The request header is not stored inside client, it works slightly differently: when your TCP server gets client request, you must accept it and then read whatever client is sending to server.


text:
Q: Wordpress Media Library - async-upload.php stuck at Crunching… Inside Wordpress(v3.6) when uploading images with Media Library process is stuck at Crunching… with Status Code: 403 Forbidden. The only change before this problem occurred, WP sites was migrated to SSL protocol. Before this problem many images was uploaded with no problem.
The problem remains if I remove SLL for domain or even upgrade Wordpress to latest version 4.7. The path for uploading images is temporary set to 777. Image is even created inside this folder, just process is stuck at Crunching... And image is not listed inside "Media list".
To make problem more strange, I installed clean copy of WP on same server, just used other sub domain. Here uploading works normal. So server PHP settings cannot be blamed.
Any clues how to fix this issue?

A: You might want to look for duplicates or ID=0 in your wp_posts table. I my case I did a server swap and during the DB transfer using find and replace it created duplicates. If you have any you would want to delete them. Just review the results first.
SELECT * FROM wp_posts WHERE ID = '0' AND post_type = 'attachment';

OR
SELECT ID, COUNT(*) c FROM wp_posts GROUP BY ID HAVING c > 1;

A: This was linked to an auto_increment issue on the database in my case.
Here's what fixed it for me:
DELETE FROM wp_termmeta  WHERE meta_id=0;
DELETE FROM wp_terms  WHERE term_id=0;
DELETE FROM wp_term_taxonomy  WHERE term_taxonomy_id=0;
DELETE FROM wp_commentmeta  WHERE meta_id=0;
DELETE FROM wp_comments  WHERE comment_ID=0;
DELETE FROM wp_links  WHERE link_id=0;
DELETE FROM wp_options  WHERE option_id=0;
DELETE FROM wp_postmeta  WHERE meta_id=0;
DELETE FROM wp_users  WHERE ID=0;
DELETE FROM wp_posts  WHERE ID=0;
DELETE FROM wp_usermeta  WHERE umeta_id=0;

ALTER TABLE  wp_termmeta ADD PRIMARY KEY(meta_id);
ALTER TABLE  wp_terms ADD PRIMARY KEY(term_id);
ALTER TABLE  wp_term_taxonomy ADD PRIMARY KEY(term_taxonomy_id);
ALTER TABLE  wp_commentmeta ADD PRIMARY KEY(meta_id);
ALTER TABLE  wp_comments ADD PRIMARY KEY(comment_ID);
ALTER TABLE  wp_links ADD PRIMARY KEY(link_id);
ALTER TABLE  wp_options ADD PRIMARY KEY(option_id);
ALTER TABLE  wp_postmeta ADD PRIMARY KEY(meta_id);
ALTER TABLE  wp_users ADD PRIMARY KEY(ID);
ALTER TABLE  wp_posts ADD PRIMARY KEY(ID);
ALTER TABLE  wp_usermeta ADD PRIMARY KEY(umeta_id);

ALTER TABLE wp_termmeta CHANGE meta_id meta_id  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_terms CHANGE term_id term_id  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_term_taxonomy CHANGE term_taxonomy_id term_taxonomy_id  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_commentmeta CHANGE meta_id meta_id  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_comments CHANGE comment_ID comment_ID  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_links CHANGE link_id link_id  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_options CHANGE option_id option_id  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_postmeta CHANGE meta_id meta_id  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_users CHANGE ID ID  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_posts CHANGE ID ID  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;
ALTER TABLE wp_usermeta CHANGE umeta_id umeta_id  BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT;

As taken from here


text:
Q: How to process razorpay refund in php the official doc says by using curl the refund process will takesplace. How to implement this in php?
curl https://api.razorpay.com/v1/payments/pay_6ydSup2U7aFMsA/refund \
   -u {KEY}:{SECRET} \
   -d 'amount=15000' \
   -d 'reverse_all=1'

output:
{
  "id": "rfnd_6ye1vPrRFo6TdA",
  "entity": "refund",
  "amount": 15000,
  "currency": "INR",
  "payment_id": "pay_6ydSup2U7aFMsA",
  "notes": {},
  "created_at": 1482998305
}

I tries something like this:-
<?php
$url="https://api.razorpay.com/v1/payments/pay_jhjhdfsjfhsdjf/refund";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'user: rzp_test_key',
  'pass: rzp_test_pass'
));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($output);
curl_close($ch);
?>

but nothing happens

A: I do not recommend interacting with a Saas API using curl, it is better to use a PHP library for that, razorpay has one.
Then refunding is this simple:
$refund = $api->refund->create(array('payment_id' => $id)); // Creates refund for a payment
$refund = $api->refund->create(array('payment_id' => $id, 'amount'=>$refundAmount)); // Creates partial refund for a payment
$refund = $api->refund->fetch($refundId); // Returns a particular refund

A: add this code and try i think it is because of ssl
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);


text:
Q: Purecss Roadmap and Project Status Does anybody know the project status of the Purecss framework? From their blog and github it appears to be a dead project.

A: It's alive, but in ownership transition. The most recent discussion is on Github https://github.com/yahoo/pure/issues/557. I'm helping to get the pieces in place to transition it properly.


text:
Q: How to declare a variable in `macro_rules!`? I'm creating a macro called throw_error. I expected this to compile yet, it fails:
// Util structs + types

...

// Util macros

#[macro_export]
macro_rules! throw_error {
    () => {
        RaptorexError {
            message: String::new(),
            line: line!(),
            file: file!().to_owned(),
        }
    };

    ($($msg:tt),*) => {
        let mut final_msg = String::new();

        $(
            final_msg.push_str(&format!("{} ", $msg));
        )*

        // remove trailing whitespace
        final_msg.pop();

        RaptorexError {
            message: final_msg,
            line: line!(),
            file: file!(),
        }
    }
}

// Util functions

...

I get several errors from using the macro in my other code.
Erros:
error: macro expansion ignores token `final_msg` and any following
  --> /Users/henryboisdequin/Desktop/raptorex/raptorex_util/src/lib.rs:30:13
   |
30 |             final_msg.push_str(&format!("{} ", $msg));
   |             ^^^^^^^^^
   |
  ::: compiler/src/parser/parser.rs:44:29
   |
44 |             _ => return Err(throw_error!("Unexpected token:", current_token)),
   |                             ------------------------------------------------- help: you might be missing a semicolon here: `;`
   |                             |
   |                             caused by the macro expansion here
   |
   = note: the usage of `throw_error!` is likely invalid in expression context

error[E0658]: `let` expressions in this position are experimental
  --> compiler/src/parser/parser.rs:44:29
   |
44 |             _ => return Err(throw_error!("Unexpected token:", current_token)),
   |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: see issue #53667 <https://github.com/rust-lang/rust/issues/53667> for more information
   = help: add `#![feature(let_chains)]` to the crate attributes to enable
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: `let` expressions are not supported here
  --> compiler/src/parser/parser.rs:44:29
   |
44 |             _ => return Err(throw_error!("Unexpected token:", current_token)),
   |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: only supported directly in conditions of `if`- and `while`-expressions
   = note: as well as when nested within `&&` and parenthesis in those conditions
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

warning: unused imports: `DATA_TYPES`, `KEYWORDS`
 --> compiler/src/parser/parser.rs:3:28
  |
3 |     lexer::tokens::{Token, DATA_TYPES, KEYWORDS},
  |                            ^^^^^^^^^^  ^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error[E0308]: mismatched types
  --> compiler/src/parser/parser.rs:44:29
   |
44 |             _ => return Err(throw_error!("Unexpected token:", current_token)),
   |                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `raptorex_util::RaptorexError`, found `bool`
   |
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to 4 previous errors; 1 warning emitted

What is the cause of these errors and how can I fix it?

A: You need another set of {}s so the macro creates a block containing the statements instead of the individual statements themselves:
#[macro_export]
macro_rules! throw_error {
    () => {
        RaptorexError {
            message: String::new(),
            line: line!(),
            file: file!().to_owned(),
        }
    };

    ($($msg:tt),*) => {
        { // <------------------
            let mut final_msg = String::new();

            $(
                final_msg.push_str(&format!("{} ", $msg));
            )*

            // remove trailing whitespace
            final_msg.pop();

            RaptorexError {
                message: final_msg,
                line: line!(),
                file: file!(),
            }
        } // <-------------------
    }
}

The {} in the (...) => {} is part of the macro syntax and isn't part of the generated code.


text:
Q: Migrating Android Studio Project to Desktop Application My question is very simple. Is there a straight forward way to migrate an Android Studio project, which uses Bluetooth, to a Desktop application project (Windows or Linux)?

A: No.  Totally different OSes, different APIs for everything.  YOu can keep some business logic, but anything referencing UIs or hardware will be a total rewrite.


text:
Q: Return data from anonymous class variables I'm looking for a way to achieve the results below. I'm constricted to using this class and it's methods to achieve it.
final class Trade {

    private $users_id;
    private $adj_id;

    public function display() {
        var_dump($this);
    }

    public function setData($form_results) {
        foreach ($form_results as $var => $value) {
            $this->{$var} = $value;
        }
    }

    public function getData() {
        return get_object_vars($this);
    }
}

The problem is calling get_object_vars() inside the class method. As expected it ignores the private variables I have set and returns an array of all the class variables both public and private due to its scope.
I'm trying to have the method return just the public anonymous variables. Is there a way I can do this?

A: Try to use
   foreach($this as $key => $value) {
       print "$key => $value\n";
   }

See details on http://www.php.net/manual/en/language.oop5.iterations.php

A: Why not just save all the data to some private variable and return that?
If your object must have the data as it's properties, you can use __get and __set to read and set items in that array, and on outside it will look as though they were properties.


text:
Q: O que pode causar a queda de desempenho do EF nesse cenário? Estive fazendo uma importação de dados para um projeto em ASP.NET MVC 5 com EF 6.1 e SQL Server 2008 onde a fonte de dados da importação era um arquivo txt.
As linhas de registro do arquivo não eram muito grandes mas contiam uma certa quantidade de informações para processar. Como por exemplo, na linha de registro havia os dados de um funcionário, um cargo na empresa, bairro, cidade etc. Tudo se tornando uma tabela em meu modelo.
Logo, linha por linha eu verificava a existência de cada bairro, cidade, cargo e todos os outros dados para obter a identificação dos que já estavam cadastrados ou então gravar os não existentes ainda.
Mais tarde optei por armazenar em cache. Simplesmente carreguei os dados em listas genéricas para a memória e antes de ir no banco de dados eu verificada essas informações na memória.
As outras informações não geravam um número grande de dados, porém o cadastro de funcionários sim. Eram mais de 27 mil registros.
Enfim, minha questão é sobre um problema de desempenho que tive ao fazer a importação utilizando o EF. Após os primeiros mil registros (um pouco mais) o desempenho da importação caia muito, cadastrando um funcionário a cada 1 ou 2 segundos.
Até que percebi que ao cancelar o processo de importação e começar novamente os primeiros mil registros eram importados em um tempo bom, mas depois dos mil registros a coisa voltava a ir lentamente.
Resolvi destruindo o meu contexto a cada mil registros e criando novamente. Dai então a importação teve uma boa performance desde o início até o fim.
Gostaria de saber de vocês que já passaram por algo semelhante, porque isso ocorre? Pode ser alguma configuração do Entity Framework? O meu está sem configurações.
Segue o trecho de código da importação para quem quiser analisar:
private List<Domain.int> Matriculas;
private List<Domain.CentroCusto> CacheCentrosCusto;
private List<Domain.Local> CacheLocais;
private List<Domain.Profissao> CacheProfissoes;
private List<Domain.Cidade> CacheCidades;
private List<Domain.Bairro> CacheBairros;

//Funcionarios
public ActionResult Funcionarios(string filePath)
{
    var fileInfo = new FileInfo(filePath);
    if (!file.Exists)
        throw new Exception("Arquivo não encontrado");

    Matriculas = contexto.Funcionarios
        .Select(x => x.Matricula)
        .ToList();

    CacheCentrosCusto = contexto.CentrosCusto.ToList();
    CacheLocais = contexto.Locais.ToList();
    CacheProfissoes = contexto.Profissoes.ToList();
    CacheCidades = contexto.Cidades.ToList();
    CacheBairros = contexto.Bairros.ToList();

    var file = new System.IO.StreamReader(filePath);
    try
    {
        var count = 0;
        string line = "";
        while ((line = file.ReadLine()) != null)
        {
            string[] campos = line.Split(';');

            int matricula;
            if (int.TryParse(campos[0].Trim(), out matricula))
            {
                if (Matriculas.Contains(matricula))
                    continue;
            }

            var funcionario = new Domain.Funcionario();

            funcionario.Matricula = matricula;
            // obtendo outros dados ...

            funcionario.CentroCustoId = GetCentroCustoId(campos[34].Trim());
            funcionario.LocalId = GetLocalId(campos[35].Trim());
            funcionario.ProfissaoId = GetProfissaoId(campos[36].Trim());

            //Cidade e Bairro
            funcionario.BairroId = null;

            var bai_desc = campos[11].Trim();
            if (!string.IsNullOrEmpty(bai_desc))
            {
                var cid_uf = "";
                var cid_desc = campos[12].Trim();

                // trabalho a string ...

                var cidade = new Domain.Cidade();
                cidade.Nome = cid_desc;
                cidade.Uf = cid_uf;

                var bairro = new Domain.Bairro();
                bairro.Nome = bai_desc;

                funcionario.BairroId = GetBairroId(bairro, cidade);
            }

            try
            {
                contexto.Funcionarios.Add(funcionario);
                contexto.SaveChanges();

                Matriculas.Add(matricula);

                count++;
                if (count == 1000)
                {
                    count = 0;
                    contexto.Dispose();
                    contexto = new DataAccess.Context();
                }
            }
            catch (DbEntityValidationException e) { ... }
            catch (Exception e) { ... }
        }
    }
    finally
    {
        file.Close();
    }

    return RedirectToAction("Index");
}

Meu contexto é criado no construtor da classe Controller e destruido no método Dispose.
Notem que há um contador e a cada mil registros eu destruo e crio novamente o meu contexto.
Um exemplo para os outros métodos presentes:
OBS: Todos os outros métodos contidos no código da importação possuem a mesma estrutura que este.

private int? GetProfissaoId(string descricao)
{
    int? profissao_id = null;
    if (!string.IsNullOrEmpty(descricao))
    {
        var profissaoTemp = CacheProfissoes
            .SingleOrDefault(x => x.Descricao.ToLower().Trim() == descricao.ToLower().Trim());

        if (profissaoTemp == null)
        {
            try
            {
                contexto.Profissoes.Add(profissao);
                contexto.SaveChanges();

                CacheProfissoes.Add(profissao);

                profissao_id = profissao.Id;
            }
            catch (DbEntityValidationException e) { ... }
            catch (Exception e) { ... }

            profissao_id = profissao.Id;
        }
        else
        {
            profissao_id = profissaoTemp.Id;
        }

    }
    return profissao_id;
}

A: Este problema de performance é bem conhecido. Ao adicionar os objetos um por um, você força o Entity Framework a verificar os estados de todos os objetos anexados ao contexto, o que é péssimo para a performance.
Há algumas maneiras de resolver. Vou apresentá-las e você escolhe qual a melhor para o seu caso:
1. Desligar o AutoDetectChangesEnabled
Simplesmente faça o seguinte:
context.Configuration.AutoDetectChangesEnabled = false;

Isto deve acabar com a verificação dos dados entre todas as entidades anexadas ao contexto.
2. Diminua o batch para 100 registros
Lembre-se de que você está inserindo não apenas funcionários, mas cidades e bairros, o que torna a unidade de trabalho tendo até 3000 registros. Deixe o número de registros por batch mais curto e realize o SaveChanges() antes de fazer o Dispose(), apenas para garantir que nada será perdido:
if (count == 100)
{
    count = 0;
    contexto.SaveChanges();
    contexto.Dispose();
    contexto = new DataAccess.Context();
}

3. Use as Caches em separado; AddRange() a cada batch
Crie listas em separado para suas caches, insira nelas normalmente, e ao término de cada batch insira todos os elementos de uma vez:
context.Funcionarios.AddRange(CacheFuncionarios);
context.Cidades.AddRange(CacheCidades);
...
context.SaveChanges();

Você pode, inclusive, usar todas as alternativas apresentadas ao mesmo tempo, mas recomendo ir implementando uma por uma e verificando a performance. Cada caso pode fazer o código se comportar bem diferente de um para o outro.
Veja mais em http://weblog.west-wind.com/posts/2013/Dec/22/Entity-Framework-and-slow-bulk-INSERTs

UPDATE
É necessária uma atualização desta resposta porque novas alternativas apareceram para resolver o problema de bulk insert usando Entity Framework.
Uma delas é o EntityFramework.BulkInsert (que tem um pacote separado para a versão 5 e outro para a versão 4). Há outras versões para outros bancos de dados, como o Microsoft SQL Server Compact Edition.
A primeira parte resposta ainda é útil para outros tipos de melhora de performance, mas já não tão útil para o caso de bulk insert.


text:
Q: About svproc documentclass I am supposed to submit my paper to conference, whose proceedings will be published by Springer in Lecture notes in Network and Systems(LNNS). But the said latex file is not running. It says svproc.cls not found. How to proceed further?

A: This is a stale question but for the benefit of others who visit this question in future, check if you have styles folder. If it does exist, the svproc.cls is most probably in that folder only. Link the class file using the command \documentclass{./styles/svproc}

A: Actually what happen, in your folder svproc.cls file is not exists thats why it say like this :
! LaTeX Error: File svproc.cls not found.

To resolve this issues just import the svproc.cls file on your working folder.
And code for the svproc.cls file will be found from https://github.com/rknaebel/report-template/blob/master/svproc.cls
Hope it wiil help you.

A: This is the simple error because sproc.cls file is not found.
First check it is in the same place in the working directory then use
\documentclass{svproc}

If sproc.cls file in the other directory then check path of directory. then use
\documentclass{../styles/svproc}


text:
Q: How to display UITableView Cells category wise? I want a UITableView to display the following data:

Instead of:

The code I've used is as follows:
// Data model class defining an Animal
class Animal {

    // data members
    var name: String
    var type: String

    // initializer
    init(name: String, type: String) {
        self.name = name
        self.type = type
    }

}

and
// View Controller
import UIKit

class AnimalsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    // an array of Animal(s)
    var animals: [Animal] = [Animal("Cat", "Domestic"), Animal("Dog", "Domestic"), Animal("Lion", "Wild"), Animal("Deer", "Wild"), Animal("Tiger", "Wild")];

    override func viewDidLoad() {
        super.viewDidLoad();

    }

    // returns the number of rows to be present in table
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return animals.count
    }

    // returns each cell to be present in the table
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentfier = "animalbasic"
        // uses a protype cell from storyboard
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentfier)
        cell.textLabel.text = animals[indexPath.row].name
        return cell
    }
}

What do I need to change, in my code, in order to get the required output?(Assume an array is always sorted Animal.type wise)

A: You need to break your data into sections by type.
class AnimalsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var animals: [Animal] = [Animal("Cat", "Domestic"), Animal("Dog", "Domestic"), Animal("Lion", "Wild"), Animal("Deer", "Wild"), Animal("Tiger", "Wild")]

    var sections: [[Animal]] = []

    override func viewDidLoad() {
        super.viewDidLoad();

        var sectionForType = [String: [Animal]]()
        for animal in animals {
            if sectionForType[animal.type] == nil { sectionForType[animal.type] = [] }
            sectionForType[animal.type]!.append(animal)
        }
        sections = sectionForType.keys.sorted().map({ sectionForType[$0]! })
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section][0].type
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "animalbasic")!
        cell.textLabel!.text = sections[indexPath.section][indexPath.row].name
        return cell
    }
}

A: Suggestions:
use a struct for this type of things, rather than a class
for expendability I would use an enum for the animal type, something like:
enum AnimalType: String {
 case domestic = "Domestic"
 case wild = "Wild"
}

Note: not actually needed to make it string, you can also have a function that based on the type would return a localised string, you can write something like
enum AnimalType: String {
 case domestic, wild
 var localizedString: String {
    switch self {
    case .domestic: return "Domestic"
    case .wild: return "Wild"
    }
}

Now your struct will look like this
struct Animal {
    let name: String
    let type: AnimalType
}

and now you are able to init it like this
let animal = Animal(name: "Cat", type: .domestic)
Now back your problem,
I would suggest to keep the type in a section header rather than a cell, it would make more sense don't you think?
Create a variable
let sections = [.domestic, .wild] now you have the count and it will also be easily extended
func numberOfSections(in tableView: UITableView) -> Int {
    return sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let sectionType = sections[section]

    switch sectionType {
    case .domestic:
        return animals.filter{ $0.type == .domestic }.count
    case .wild:
        return animals.filter{ $0.type == .wild }.count
    default:
        return 0
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let sectionType = sections[section]

    switch sectionType {
    case .domestic:
        /// Configure your cell
    case .wild:
        /// Configure your cell
    default:
        assertionFailure("Should not reach in this situation")
        return UITableViewCell()
    }
}

ofcourse you will have to also configure the header for your sections:
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let sectionType = sections[section]

    switch sectionType {
    default: sectionType.localizedString
}

Your approach is also doable, but this would mean that at numberOfRowsInSection you will have to add the number of sections:
// returns the number of rows to be present in table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return animals.count + sections.count
}

and then cellForRowAt would be a pain to mentain, you would need to do some calculations to see what row is it, is it still wild domestic, is it wild yet
TLTR you would have a bunch of if, if else, if else, else, and by only
adding one more type (dinosaur maybe) this pain will hit you back
Note: this code can be improved using a viewModel, but for the sake of being fast i skipped that part


text:
Q: what does ...var means on Array.prototype.map() I'm fairly new at creating anonymous functions and using map, what does ...i mean on the following lines of code. tia
const airlines = this.state.airlines.map(i => (
     { ...i, editing : this.state.editing && i===item }
   )
 )

A: It's known as spread syntax, and in the current context it involves copying an object. It's the same as doing this:
const airlines = this.state.airlines.map(object => {
    object.editing = this.state.editing && object === item;
    return object;
});

So what we do is we create a shallow copy of the object, and we add properties to it. This is the purpose of spread syntax - to make a shallow copy, or to collect items for a shallow copy (known as rest syntax - collects the rest of the items). Here's a simplified example of spread syntax:

const arr = [{
  name: "Jack"
}, {
  name: "Joe"
}];
const res = arr.map(e => ({ ...e,
  age: Infinity
}));
console.log(res);
.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}


text:
Q: Can't pass ID and call Controller from ajax or AngularJS I have a table of objects, and I want to pass their ID on click, and without refresh populate a div or table, I've tried with AJAX and angular but can not pass ID.
If I fix the ID on a specific number it works.
In the View:

    click for countries

A: On your view, you should have:
click for countries

where href will stop the link from reloading the page and the ng-click will call a method on your controller.
In your controller, you should define that function on the scope variable:
var myApp = angular.module('myApp',[]);

myApp.controller('ExamleController', ['$scope', function($scope) {
  $scope.CountryController = function(id) {
            $http.get("/api/SportApi/GetCountry/" + id).success(function (response) {
                $scope.controllerFunction = function (value) {
                    console.log(value);
                }
                obj = JSON.parse(response);
                $scope.country = angular.fromJson(obj);
            });
        }
}]);

Verify that you have bootstrapped angular js (by defining the root element of your html with ng-app).
Verify that you have attached the controller class to your view (by defining the controller html element with ng-controller).
You should also verify that you are getting the right id on the view when calling "x.id".
$scope.controllerFunction seems unnecessary in this case.

A: Could you try this:
function CountryController($scope, $http, id) {
console.log(id)
            $http.get("/api/SportApi/GetCountry/").success(function (response) {
                $scope.controllerFunction = function (value) {
                    console.log(value);
                }
                obj = JSON.parse(response);
                $scope.country = angular.fromJson(obj);
            });
        }


text:
Q: How to input in C# How to input in C#? and using loop on that input.
Here is my code so far i trying
static void Main(string[] args)
 {

            int[] ar = new int[10002];
            int n = Convert.ToInt32( Console.ReadLine() );

            for( int i = 0;i < n; i++ )
            {
                ar[i] = Convert.ToInt32( Console.ReadLine() );
            }

            for ( int i = 0; i < n; i++ )
            {
                Console.WriteLine(ar[i]);
            }
            Console.ReadKey();

   }

A: Here is a simple example of two ways of handling the invalid input in your case. One thing you can do, is just fail giving the user an information that the input was not correct. Second possibility is to treat invalid input as a null value.
This is just a simple example - usually you shouldn't fail silently (here: return a null and not complain), and you shouldn't use null values as an indicator for a special function return value. Also a good example would be not to finish the program but use a loop to ask the user repeatedly until they learn how a number looks like ;)
These all issues are left unsolved as a practice for the reader ;)
static int? ReadInteger()
{
    int result;

    if (!int.TryParse(Console.ReadLine(), out result))
    {
        return null;
    }

    return result;
}

static void Main(string[] args)
{
    int?[] ar = new int?[10002];
    int? n = ReadInteger();

    if (!n.HasValue)
    {
        Console.WriteLine("Please input a correct integer");
        return;
    }

    for( int i = 0;i < n.Value; i++ )
    {
        ar[i] = ReadInteger();
    }

    for ( int i = 0; i < n.Value; i++ )
    {
        Console.WriteLine(ar[i].HasValue
            ? ar[i].Value.ToString() : "Incorrect input");
    }

    Console.ReadKey();
}

A: I tried to build this as close as possible to your implementation. The other answer from BartoszKP should be used in a complete scenario.
    static void Main(string[] args)
    {
        int[] ar = new int[10002];
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            int nr;
            for (int i = 0; i < n; i++)
            {
                if (int.TryParse(Console.ReadLine(), out nr))
                {
                    ar[i] = nr;
                }
            }

            for (int i = 0; i < n; i++)
            {
                Console.WriteLine(ar[i]);
            }
        }
        Console.ReadKey();
    }


text:
Q: Design Choice: WCF or Service Stack? I have three core applications that have their own business functions (networks, active directory and helpdesk).  Each are running ASP.NET v2 or v3 and have their own respective databases.  However, the application functions have merged a bit so models were recreated in each application and app logic along with it.  So now I have some difficult to maintain code.  So here is my question:

*

*Is porting my models and repositories over to WCF a reasonable choice for this type of architecture?

*Is using a service stack such as serialized json calls a better choice?  I'd imagine this would be faster than setting up a central wcf app.
I'm not too familiar with communication between asp.net mvc web apps so please point me in the right direction.

A: I would recommend developing a service layer per the design pattern described by Fowler.  This service layer encapsulates the various domain models and repositories and handles interactions between different domains/models.  This will be an assembly and not a WCF or any other type of web service.  If you require a WCF web service then it will be a very thin layer which basically has a contract that mimics the service layer and only purpose is to provide a web service interface or API.
There are a couple of ways an MVC application can interact with your service layer.  If you are creating view models in your Controllers then it can access the service layer assembly directly.  There is added overhead to calling it through a web service that is most likely not necessary in this case.  Using this approach the service layer is pretty much your Model in the MVC trio.
The other way to access the service layer is from the Views/client using AJAX for rich clients.  In this case you would use MVC to put a REST API on top of your service layer so that you can make AJAX POST's, using something like JQuery, directly to the web service to update and retrieve data for the web page.
Note with this architecture you can use a combination of both approaches.  You may access the service layer directly from the Controller to render some initial pages and then use the web service REST interface for AJAX calls during user interaction.


text:
Q: Change trash icon command in Unity I have recently replaced my default file manger from Nautilus to Dolphin, so I would like when I click on the trash icon (in left narrow panel), Dolphin opens trash folder not Nautilus. For this I've set Dolphin as the default file manger.
Now, when I click on the trash icon, Dolphin opens and shows a message saying
Malformed URL trash://

Apparently clicking on the trash icon causes a command to run. But in Dolphin URL trash:/ works fine.
How can I change the command that runs when user clicks on the trash icon? I should replace trash:// to trash:/ there.

A: Looks like it's a bug related to Dolphin with a fix on the way.  https://bugs.kde.org/show_bug.cgi?id=353181


text:
Q: How do I change the synthetic voice for a section of my Action? Trying to change the voice from female to male for one section of my Action.
I'm using the Voiceflow tool, and have uploaded my Action to Actions on Google. However, I'm not clear on how to change one section of my action from a female voice to male.
I'm looking in Dialogflow, but not seeing any place where there are  tags. So maybe that's my question. Where are the speak tags in Dialogflow?
In "Fulfillment", I have the Webhook enabled, and it goes to a Voiceflow URL. However, that's just for the audio files I'm using, correct? Not the text in the  tags to be spoken?
I'm wanting to have a female voice for one part of the voice app, and a male voice for the other part.
Currently, the app plays all the way through with the female voice.

A: You would have to create the other voice snippet and save it as an audio file. You could use Amazon's Polly service to do it. Then in the speak block you would upload the audio file for the part that needs the other voice.


text:
Q: NSString stringWithUTF8String in swift for char[] In my .h file typedef looks like -> [I am using bridging header to import the .h file in Swift]
typedef struct {
  char xyzID[16];
} XYZ;

Now in ObjectiveC to convert xyzID[] into NSString it looks like ->
NSString *xid=[NSString stringWithUTF8String:XYZ.xyzID];

I have tried but somtimes the error is like "Cannot invoke initializer for type with an argument list of type '(Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)'"
So how can I can do the same thing in Swift (to convert xyzID[] into NSString)?


text:
Q: Python will Sometimes Not Read in Entire File I have python 2.7 program used on a unix server that reads in an ASCII file with two types of information and processes that information. I have put this process into a function that essentially does:
def read_info()
    f = open(file_name, 'rb')
    f_enumerator = enumerate(f, start=1)
    for i, line in f_enumerator:
        process_info
    process_last_info

When this function is called on the file from my main program, it stops at a seemingly arbitrary point halfway through a line towards the end of the input file, whereas when the function is called from a simple wrapper on the same input file it reads the entire file correctly.
I have tried one of the solutions here:  Python Does Not Read Entire Text File  , Where the file is read in as binary but that did not fix the problem.
The other solution there (reading in the file in chunks) would be problematic as I am trying to parse the file on a line-specific basis, and reading in a chunks of text would require a lot more parsing.
I would be willing to do that, except that the intermittent nature of the problem suggests to me that there might be some other solution?

A: On further reflection I realized it was because I had created the file earlier in the program and had not closed the file handle, and this was therefore perhaps a buffering issue. Closing the file earlier fixed the problem.
It was suggested that I use "with" syntax for writing to the file originally:
with open(file_name, 'w') as f:
    do foo

This would indeed have prevented me from forgetting to close the file, and prevented this problem.

A: def read_info():
    with open(file_name, 'rb') as f:
       for i, a_line in enumerate(f,1): #a_line must end with a newline
            process_info(a_line,i)
    # you have processed whole file here so no need for `process_last_info`

using with will ensure your filehandle is closed (you should especially do this when writing to a file but really its always good practice)...
on further information from OP I believe a generator would be an ideal solution to his problem
def data_gen(f):
   header = None
   lines = []
   for line in f:
       if line.startswith(">"): #header
          if header is not None: #if its not the first line basically
             yield header,lines
          header = line #set the header
          lines = [] #reinitialize lines
       else:
          lines.append(line)
    yield header,lines # the last section

def read_info(fname):
    with open(fname,"rb") as f:
        for header,lines in data_gen(f):
            process(header,lines)

A: As the O.P. found out, the problem was the file had been created previously on the same program, but had not been flushed or closed properly before the reading attempt.