text:
Q: Key Words search in articles on website with python I just joined you, and it's been 1 month since I started learning python. I would like to search keyword from this site with Python (http://aeconf.com/may2013.htm).
Normally I manually click on the view abtsract and search for words after the "Key Words:". How can I do this with python automatically?

A: You should check out Selenium
pip install selenium

I provided a sample code of what it can do you should test this out.
Sample Code:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

caps = DesiredCapabilities().CHROME
caps["pageLoadStrategy"] = "normal"
driver = webdriver.Chrome(desired_capabilities=caps, executable_path=r'C:\Users\My-PC-Name\AppData\Local\Programs\Python\Python37-32\Scripts\chromedriver.exe')

url = "http://aeconf.com/may2000.htm" #Link
driver.get(url)
links = [x.get_attribute('href') for x in driver.find_elements_by_link_text('View Abstract')]
htmls = []

for link in links:
   driver.get(link)
   Keyword = [y.text for y in driver.find_elements_by_xpath("//font[2]/span[@style = 'mso-bidi-font-size: 1.0pt']")]
   if not Keyword: #If link is a dead link
     continue
   print(Keyword[0])
   htmls.append(driver.page_source)

In this example I changed the url to http://aeconf.com/may2000.htm The code I provided mostly get the "Key Words" you need but there are certain cases in which the index position of the "Key Words" changes depending on the links in the said Url.
Output of 'changed' link:
Fiscal decentralization; Corruption; Tax evasion.
Incentive mechanism design; Walrasian allocations; Implementation.
Debt and equity flows; Asymmetric information; Bankruptcy cost; Market failures;
Corrective taxation.
Transitory volatility; Price formation; Exogenous liquidity demand.
Investment horizon; Beta; Size; Book-to-market equity; CAPM.
G11, G13.                         #At This part you can see that the 'Key Words' printed are not correct
Portfolio constraints; Stochastic income; Relaxation-projection methods.
Foreign aid; Foreign borrowing; Capital accumulation.
Entrepreneurial ability; Asymmetric information; Liquidity constraints.
Contract; Human capital; Labor.
Endogenous structure of the division of labor; Dual economy; Endogenous trade policy regime.

If we changed the 'url' variable in my Sample Code to your original link there are more cases in which the index position is changed even the first link is a dead link. As a challenge I'll let you figure it out yourself :-)
There are more modules that can do the same thing like Selenium. Hope this gives you more interest on Browser Automation, Web Scraping and many more (Web Crawler etc.).
Just a tip (probably not a tip) You'll just have to change the index position of the 'Keyword' variable to get the desired "Key Word".


text:
Q: Custom Shipping Method Recalculate I am creating a woocommerce custom shipping method. Its working fine, but when I use the shipping calculator it doesn't refresh.
<?php
/**
 * Plugin Name:          Expresso Jundiaí for WooCommerce
 * Plugin URI:           https://valoremarketing.com.br
 * Description:          Adds Expresso Jundiaí shipping methods to your WooCommerce store.
 * Author:               Valore + NSC
 * Author URI:           https://valoremarketing.com.br
 * Version:              1.0.0
 * License:              GPLv2 or later
 *
 */

if (!defined('ABSPATH')) {
    exit;
}

/*
 * Check if WooCommerce is active
 */
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {

    function expresso_jundiai_shipping_method()
    {
        if (!class_exists('Expresso_Jundiai_Shipping_Method')) {

            class Expresso_Jundiai_Shipping_Method extends WC_Shipping_Method
            {
                 private $args = '';

                /**
                 * Constructor
                 *
                 * @access public
                 * @return void
                 */
                public function __construct($instance_id = 0)
                {
                    $this->id = 'expresso-jundiai';
                    $this->title = 'Expresso Jundiaí';
                    $this->instance_id = absint($instance_id);
                    $this->method_title = __('Expresso Jundiaí Entregas', 'expresso-jundiai');
                    $this->method_description = __('Entregas feitas por Expresso Jundiaí', 'expresso-jundiai');

                    /**
                     * Utilized to woocommerce to verify the supported features by the shipping method
                     */
                    $this->supports = array(
                        'shipping-zones',
                        'instance-settings',
                        'instance-settings-modal',
                        'settings'
                    );
                    $this->init();
                }

                /**
                 * Init your settings
                 *
                 * @access public
                 * @return void
                 */
                public function init()
                {
                    $this->init_form_fields();
                    $this->init_settings();

                    /// Actions.
                    add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
                }

                /**
                 * Define settings field for this shipping
                 *
                 * To access the fields:
                 * $shipping_methods = WC()->shipping->get_shipping_methods();
                 * foreach ( $shipping_methods as $key => $shipping_method ) {
                 *      $code = $shipping_method->settings->code;
                 * }
                 *
                 * @return void
                 */
                public function init_form_fields()
                {...}

                /**
                 * Get the args needed to make a post request to API target
                 *
                 * @param $package
                 * @return mixed
                 */
                private function get_request_args( $package )
                {...}

                /**
                 * This function is used to calculate the shipping cost.
                 * Within this function we can check for weights, dimensions and other parameters in package.
                 *
                 * @access public
                 * @param mixed $package
                 * @return void
                 */
                public function calculate_shipping( $package = array() )
                {
                    $args       = $this->get_request_args( $package );
                    $uri        = $this->get_option( 'apiUri' );
                    $response   = $this->request_to_api( $uri, $args );

                    if ($response !== NULL) {
                        $this->add_rate( array(
                            'id' => $this->id,
                            'label' => $this->title,
                            'package' => $package,
                            'cost' => $response->vlrFrete,
                        ) );
                    }
                }

                /**
                 * Calculates the cubage of all products.
                 *
                 * @param $package
                 * @return float|int
                 */
                private function get_total_cubage( $package ) {
                    $total = 0;

                    foreach ( $package['contents'] as $item_id => $values )
                    {
                        $_product = $values['data'];
                        $height = (float) $_product->get_height();
                        $width  = (float) $_product->get_width();
                        $length = (float) $_product->get_length();

                        $total += $height * $width * $length;
                    }

                    return ( ($total > 0) ? ( $total/1000000 ) : 0 );
                }

                /**
                 * @param $package
                 * @return int
                 */
                private function get_total_volumes( $package ) {
                    $total = 0;

                    foreach ( $package['contents'] as $item_id => $values ) {
                        $total += (int) $values['quantity'];
                    }

                    return $total;
                }

                /**
                 * Calculate the total wheight of all products of the order
                 * @param $package
                 * @return float|int
                 */
                private function get_order_total_weight( $package ) {

                    $total = 0;

                    foreach ( $package['contents'] as $item_id => $values )
                    {
                        $_product = $values['data'];
                        $_product_weight = (float) $_product->get_weight();
                        $total += $_product_weight * $values['quantity'];
                    }

                    $total = wc_get_weight( $total, 'kg' );

                    return $total;
                }

                /**
                 * @param $uri
                 * @param $args
                 * @return mixed|void
                 */
                private function request_to_api( $uri, $args )
                {
                    $response = wp_remote_post( $uri, $args );
                    var_dump($args, $response);
                    if ( is_wp_error( $response ) || '200' != wp_remote_retrieve_response_code( $response )) {
                        return;
                    }
                    $body = json_decode( wp_remote_retrieve_body( $response ) );
                    if ( empty( $body ) )
                        return;
                    return $body;
                }

            }
        }
    }
    add_action('woocommerce_shipping_init', 'expresso_jundiai_shipping_method');

    /**
     * Adds the name of class into shipping methods
     *
     * @param $methods
     * @return array
     */
    function add_expresso_jundiai_shipping_method($methods)
    {
        /**
         * The key of the array $method must match the shipping method id
         */
        $methods['expresso-jundiai'] = 'Expresso_Jundiai_Shipping_Method';
        return $methods;
    }

    add_filter('woocommerce_shipping_methods', 'add_expresso_jundiai_shipping_method');
}

I need it to recalculate with the same rules when i use the shipping calculator in cart... when wordpress calls /?wc-ajax=update_shipping_method
I' trying two days... Please... help

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I map a case class with non-default field types to a table in Slick? I can do this mapping a case class to a slick database table:-
case class SomeTimeStamp(id: Option[Long], timestamp: java.sql.Timestamp )

class TimeStampTable(tag: Tag) extends Table[SomeTimeStamp](tag, "TSTAMP_TABLE") {
  def id    = column[Long]("ID", O.AutoInc, O.PrimaryKey)
  def time  = column[java.sql.Timestamp]("TIME")

  def * = (id.?, time) <> (SomeTimeStamp.tupled, SomeTimeStamp.unapply)
}

The case class has fields that are converted to database types by default by slick, so all is well.
But this doesn't work, if a field in my case class is not a default database type. Slick allows me to provide an implicit conversion to and from a valid Database type using the MappedColumnType, so I tried this, notice that I now use the Java LocalDatetime thather than sql Timestamp.
case class SomeLocalDate(id: Option[Long], timestamp: java.time.LocalDateTime )

class LocalDateTable(tag: Tag) extends Table[SomeLocalDate](tag, "TLDATE_TABLE") {
import LocalDateTable._
  def id    = column[Long]("ID", O.AutoInc, O.PrimaryKey)
  def time  = column[java.time.LocalDateTime]("TIME")

  def * = (id.?, time) <> (SomeLocalDate.tupled, SomeLocalDate.unapply)
}

object LocalDateTable {
  implicit val localDateTimeToTimestamp = MappedColumnType.base[LocalDateTime, Timestamp](
    { Timestamp.valueOf(_) } ,
    { ts => ts.toLocalDateTime }
  )
}

I have added and implicit mapped column I still get a compile error in the projection and the implicit resolution
The compile error is:-
[info] Compiling 1 Scala source to ...target/scala-2.11/classes...
[error] db/Tables.scala:92: could not find implicit value for parameter tt: slick.ast.TypedType[java.time.LocalDateTime]
[error]   def time: Rep[LocalDateTime]  = column[java.time.LocalDateTime]("TIME")

If I modify the def time and add a type ascription I get a different error, see below.
case class SomeLocalDate(id: Option[Long], timestamp: java.time.LocalDateTime )

class LocalDateTable(tag: Tag) extends Table[SomeLocalDate](tag, "TLDATE_TABLE") {
import LocalDateTable._
  def id    = column[Long]("ID", O.AutoInc, O.PrimaryKey)
  def time: Rep[LocalDateTime]  = column[java.time.LocalDateTime]("TIME")

  def * = (id.?, time) <> (SomeLocalDate.tupled, SomeLocalDate.unapply)
}

object LocalDateTable {
  implicit val localDateTimeToTimestamp = MappedColumnType.base[LocalDateTime, Timestamp](
    { Timestamp.valueOf(_) } ,
    { ts => ts.toLocalDateTime }
  )
}

gives this error:-
[info] Compiling 1 Scala source to ...target/scala-2.11/classes...
[error] db/Tables.scala:92: could not find implicit value for parameter tt: slick.ast.TypedType[java.time.LocalDateTime]
[error]   def time: Rep[LocalDateTime]  = column[java.time.LocalDateTime]("TIME")
[error]                                                                  ^
[error]db/Tables.scala:94: No matching Shape found.
[error] Slick does not know how to map the given types.
[error] Possible causes: T in Table[T] does not match your * projection. Or you use an unsupported type in a Query (e.g. scala List).
[error]   Required level: slick.lifted.FlatShapeLevel
[error]      Source type: (slick.lifted.Rep[Option[Long]], slick.lifted.Rep[java.time.LocalDateTime])
[error]    Unpacked type: (Option[Long], java.time.LocalDateTime)
[error]      Packed type: Any
[error]   def * = (id.?, time) <> (SomeLocalDate.tupled, SomeLocalDate.unapply)
[error]                        ^
[error] two errors found

What do I have to do to map a case class to a table if the case class does not have the default supported database types (eg LocalDateTime) ?
cheers

A: After days of struggling I found the answer :-/
The problem was that the implicit MappedColumnType was declared after the Table class. for some reason this upset the implicit resolution even though I imported it above the table.
I found the answer when I removed the case class and simply used Tuples. When I did that the following error was presented
[info] Compiling 1 Scala source to target/scala-2.11/classes...
[error] /db/Tables.scala:100: could not find implicit value for parameter tt: slick.ast.TypedType[java.time.LocalDateTime]
[error]   def time: Rep[LocalDateTime]  = column[java.time.LocalDateTime]("TIME")
[error]                                                                  ^
[error] /db/Tables.scala:102: type mismatch;
[error]  found   : (slick.lifted.Rep[Option[Long]], slick.driver.H2Driver.api.Rep[java.time.LocalDateTime])
[error]     (which expands to)  (slick.lifted.Rep[Option[Long]], slick.lifted.Rep[java.time.LocalDateTime])
[error]  required: slick.lifted.ProvenShape[(Option[Long], java.time.LocalDateTime)]
[error]  Note: implicit value localDateTimeToTimestamp is not applicable here because it comes after the application point and it lacks an explicit result type
[error]   def * : ProvenShape[(Option[Long], LocalDateTime)] = (id.?, time)
[error]                                                        ^

So to be clear the solution was to put the implicit conversion above the table definition if in the same file or put it in another file and import it, see working solution below. Thanks.
case class SomeLocalDate(id: Option[Long], timestamp: java.time.LocalDateTime )

object LocalDateTableConversions {
  implicit val localDateTimeToTimestamp = MappedColumnType.base[LocalDateTime, Timestamp](
    { Timestamp.valueOf(_) } ,
    { ts => ts.toLocalDateTime }
  )
}
import LocalDateTableConversions._

class LocalDateTable(tag: Tag) extends Table[SomeLocalDate](tag, "TLDATE_TABLE") {
  def id    = column[Long]("ID", O.AutoInc, O.PrimaryKey)
  def time: Rep[LocalDateTime]  = column[java.time.LocalDateTime]("TIME")

  def * = (id.?, time) <> (SomeLocalDate.tupled, SomeLocalDate.unapply)
}


text:
Q: Fetching an jira issue using python i'm getting authentication error >>> # Get all projects viewable by anonymous users.

... projects = jira.projects()

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Python27\lib\site-packages\jira_python-0.16-py2.7.egg\jira\client.py", line 941, in projects
    r_json = self._get_json('project')
  File "C:\Python27\lib\site-packages\jira_python-0.16-py2.7.egg\jira\client.py", line 1526, in _get_json
    r = self._session.get(url, params=params, headers=self._options['headers'])
  File "C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg\requests\sessions.py", line 395, in get
    return self.request('GET', url, **kwargs)
  File "C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg\requests\sessions.py", line 383, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg\requests\sessions.py", line 486, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python27\lib\site-packages\requests-2.2.1-py2.7.egg\requests\adapters.py", line 381, in send
    raise ProxyError(e)
**requests.exceptions.ProxyError: Cannot connect to proxy. Socket error: Tunnel connection failed: 407 authenticationrequired.**

Can you please any one help me how to solve this issue.

A: Try This:
basic_auth = ('username', 'password')
options = {
    'server': <server url>,
    'proxies' : <proxy>,
    'verify' : False,
}
jira = JIRA(options,basic_auth=basic_auth,validate=True)

should work.
I tried and it is working for me.
Make sure you have access to the project to acess the issue.


text:
Q: Speech bubble background for arrow as well Hi I have done a speech bubble but I want to get the background image to come into the arrow as well. I did find some examples as well but editing them to fit my needs is confusing because I cant position the arrow to the place I want it to be in the end.
.bubble {
    position: relative;
    width: 227px;
    height: 310px;
    background-color:white !important;
    background: url(../images/thepartypeople/assets/main-bg.png) repeat 0 0;
}
.bubble:after {
    content: "";
    position: absolute;
    top: 128px;
    left: -15px;
    border-style: solid;
    border-width: 15px 15px 15px 0;
    border-color: transparent #000;
    display: block;
    width: 0;
    z-index: 1;

}

This is my code that I have for my speech bubble.
Any help would be appriciated
Thanks alot.

A: Here is the question answered elsewhere
Creating a transparent arrow above image in CSS3
But, I'll give you the HTML and CSS for your specific answer.  I changed your HTML a little bit by the way.

You can keep it with just the div .bubble and have background: url('http://placekitten.com/241/310'); but the image would have to be exactly the height and width of the div.
.bubble {
    position:relative;
    width:241px;
    height: 310px;
}
.bubble:before, .bubble:after {
    content:'';
    position:absolute;
    width:0;
    border-left:15px solid white;
    left:0;
}
.bubble:before {
    top:0;
    height:128px;
    border-bottom:15px solid transparent;
}
.bubble:after {
    top:143px;
    bottom:0;
    border-top:15px solid transparent;
}
.test {
    display:block;
    width:100%;
}

Here is a fiddle http://jsfiddle.net/WUXQd/2/ the fiddle has comments in it explaining a bit how it works.
EDIT: By the way this creates a mask around the image and two reverse triangles to make it look like there is a transparent triangle.

A: is this similar to what you wanted?
.bubble {
   position: relative;
   width: 250px;
   height: 120px;
   padding: 0px;
   background: #FFFFFF;
   -webkit-border-radius: 10px;
   -moz-border-radius: 10px;
   border-radius: 10px;
   background: url(border.jpg) repeat 0 0;
}

.bubble:after {
    content: "";
    position: absolute;
    top: 45px;
    left: -15px;
    border-style: solid;
    border-width: 15px 15px 15px 0;
    border-color: transparent #FFFFFF;
    display: block;
    width: 0;
    z-index: 1;
    border-image: url(border.jpg);
}

EDIT: This link can help you: http://www.sitepoint.com/pure-css3-speech-bubbles/


text:
Q: JavaScript: how to dynamically add a Flash file (SWF) to the DOM so IE will load it I have pages that need to dynamically load content based upon their data description in XML files.  Among the items that may be dynamically loaded are SWFs.  I have code that correctly loads and starts the movies in Firefox via the http and file protocols and Chrome via the http protocol.  I need it to successfully load in Internet Explorer in both http and file protocols as well, but all Flash Video Player reports is 'Movie not loaded...'.  Could someone please review the following information and give me a fix?
The description of Flash objects in the XML looks like this:
<multimedia
    type='flash'
    swf='swf/filename_here.swf'
    width='600'
    height='400'
    version='7.0.19.0'
/>

I have JavaScript that parses this and creates an object that looks like the following JSON:
{
    'tag': 'multimedia',
    'attributes': [
        'type': 'flash',
        'swf': 'swf/filename_here.swf',
        'width': '600',
        'height': '400',
        'version': '7.0.19.0'
    ]
}

Eventually, this object is passed to a function that creates the DOM element (yes, I know the function is ordered oddly; I was trying different things to make it work):
var path = var path = document.location.href;
path = path.substr(0, path.lastIndexOf('/') + 1);

var version = null;

function isIE() {
    return navigator.userAgent.lastIndexOf('Trident') > 0;
}

function buildFlash(element) {
    version = element.attributes.version;

    var name = document.createElement('param');
    name.setAttribute('name', 'movie');
    name.setAttribute('value', path + element.attributes.swf);

    (if (!isIE()) {
        var inner = document.createElement('object');
        inner.setAttribute('type', 'application/x-shockwave-flash');
        inner.setAttribute('data', path + element.attributes.swf);
        inner.setAttribute('width', element.attributes.width);
        inner.setAttribute('height', element.attributes.height);
    }

    var flash = document.createElement('object');
    flash.setAttribute('id', 'flashMovie');
    flash.setAttribute('classid', 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000');
    flash.setAttribute('width', element.attributes.width);
    flash.setAttribute('height', element.attributes.height);
    flash.appendChild(name);
    if (!isIE()) {
        flash.appendChild('inner');
    }

    var div = document.createElement('div');
    div.setAttribute('id', 'multimedia');
    div.appendChild('flash');
    return div;
 }

The resulting div is eventually added to the correct location in the page.
Any ideas?

A: IE does not support dynamically adjusting most of the attributes/parameters of the object element.
You can use this function to create a cross-browser object element with the given attributes and parameters.
var createSwfObject = function(src, attributes, parameters) {
  var i, html, div, obj, attr = attributes || {}, param = parameters || {};
  attr.type = 'application/x-shockwave-flash';
  if (window.ActiveXObject) {
    attr.classid = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000';
    param.movie = src;
  }
  else {
    attr.data = src;
  }
  html = '<object';
  for (i in attr) {
    html += ' ' + i + '="' + attr[i] + '"';
  }
  html += '>';
  for (i in param) {
    html += '<param name="' + i + '" value="' + param[i] + '" />';
  }
  html += '</object>';
  div = document.createElement('div');
  div.innerHTML = html;
  obj = div.firstChild;
  div.removeChild(obj);
  return obj;
};

Example
var swfEl = createSwfObject('http://example.com/example.swf', {id: 'myid', 'class': 'myclass', width: 100, height: 100}, {wmode: 'transparent'});
document.body.appendChild(swfEl);


text:
Q: C# 4.0 Task Library deadlock I am experimenting with this code:
        foreach (var r in _vm.Rules.Take(20)) {
            Task.Factory.StartNew(() => {
                new SQLRuleSerializer().SaveRule(_vm.SelectedKey, r);
            });
        }

Error:

Transaction (Process ID 600) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

I am not sure exactly how this is deadlocking considering i do not have any explicit locks.. i guess the problems is that serializer is a proxy and cannot be called in parallel even via separate instances?

A:
Transaction (Process ID 600) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

The deadlock is coming from the SQL Server, not the C# code.

A: You're trying to save 20 different rules in parallel, but it seems each save requires some locks on the SQL server. This means that there's most likely no gain in parallelizing, so you should use normal loop without using TPL.


text:
Q: Loop and Comma in HREF PHP I have to echo a list in a loop and remove last comma, what Ive done so far works with comma issue but when I try to echo a href it gives me all the results in one href tag.
This is my code
$select_actors=mysql_query("SELECT * FROM actors_in_movies WHERE  movie_ref='$movie_ref'");
if (mysql_num_rows($select_actors)>=1) {
    while ($row=mysql_fetch_array($select_actors)) {
        $actor_ref=$row['actor_ref'];
        $select_actor_name=mysql_query("SELECT * FROM actors WHERE actors_ref='$actor_ref' AND     active='1'");
        while ($row_actor=mysql_fetch_array($select_actor_name)) {
            $actor_name .= $row_actor['actors_name'] . ", ";
        }
    }
    $actor_name = substr(trim($actor_name), 0, -1);
    echo''.$actor_name.'';
}

All I need to do is list it list name1, name2, name3 but each need to have their own url (href).

A: I suggest using your loop to construct an array of links.
Then you can output the links using implode.
Something like this:
$actor_links=array();

// build array of links from db result
while ($row_actor=mysql_fetch_array($select_actor_name)) {
  $actor_links[]= '' .
                    $row_actor['actors_name'] .
                  '';
}

// output each link inside a
 tag
if (!empty($actor_links)) {
  echo "
".implode("

",$actor_links)."
";
}

// alternatively, output links separated by commas
if (!empty($actor_links)) {
  echo implode(",",$actor_links);
}

A: try to move the lines
$actor_name = substr(trim($actor_name), 0, -1);
echo''.$actor_name.'';

inside the while statement ...
I think it will works fine =)

A: Instead of appending the comma and then chopping it off, try, prepending it if the actor is not the first:
$select_actors=mysql_query("SELECT * FROM actors_in_movies WHERE  movie_ref='$movie_ref'");
if (mysql_num_rows($select_actors)>=1) {
    while ($row=mysql_fetch_array($select_actors)) {
        $actor_ref=$row['actor_ref'];
        $select_actor_name=mysql_query("SELECT * FROM actors WHERE actors_ref='$actor_ref' AND     active='1'");
        $first = true;
        while ($row_actor=mysql_fetch_array($select_actor_name)) {
            if ($first) {
                // no comma first time
                $first = false;
            } else {
                // comma all other times
                echo ", ";
            }
            echo''.$row_actor['actors_name'] .'';
        }
    }

}

Also, don't use mysql_*, functions; they're deprecated.  Use MySQLi or PDO instead.


text:
Q: How to split a string from an object in an array into new objects in the array We have the below input which has an address field with colon as value. This need to be considered as a new object.
Input:
{
 "Customer" : [
  {
   "name": "abc",
   "age": 23,
   "address": "test4"
  },
  {
   "name": "xyz",
   "age": 28,
   "address": "test:mule"
  },
  {
   "name": "pqr",
   "age": 25,
   "address": "test1"
  }
 ]
}

Expected Output considering colon in field:
{
 "Customer" : [
  {
   "name": "abc",
   "age": 23,
   "address": "test4"
  },
  {
   "name": "xyz",
   "age": 28,
   "address": "test"
  },
 {
   "name": "xyz",
   "age": 28,
   "address": "mule"
  },
  {
   "name": "pqr",
   "age": 25,
   "address": "test1"
  }
 ]
}

If we have colon in the field address then that needs to be updated as a different object.

A: you can try the below DataWeave Script
%dw 2.0
output application/json
---
 Customer: payload.Customer flatMap ((item, index) -> do {
      var codes = item.address splitBy ":"
      ---
      codes map {
        "name": item.name,
        "age": item.age,
        "address": $
      }
    })

below is the screenshot with input, script, and required output

A: %dw 2.0
output application/json
---
Customer: flatten(payload.Customer map (
     ($.address splitBy ":") map (item,index) -> ($ - "address" ++ {address: item })

))


text:
Q: Django: Template Doesn't Display Views Field I'm having a problem with a template not displaying model fields sent from a view.

*

*The url.py correctly directs to the right html template.

*The view debug correctly prints the field contents (title and body) to the terminal, but the template is blank.

*The base.html works, displaying the bootstrap header and container.
The page source is blank.

*If I replace the for...loop with
Hi
 the text prints.
Here are the files:
    from django.conf.urls import url

    from . import views

    urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^news/(?P<pk>[0-9]+)/$', views.detail, name='detail'),
    ]

def detail(request, pk):
story = Article.objects.get(pk=pk)
print(story)
print(story.body)
print(request)
context = {'story': story}
return render(request, 'articles/detail.html', context)

{% extends "base.html" %}

{% block content %}

     {% for story in stories %}

{{ story.title }}

     {% endfor %}

{% endblock %}

A: You haven't got anything called stories in the template, but you try and iterate over it. You only have one thing, called story; you should just display that directly.

A: You should write in second paramiter of render
Write previos folder.can i khow what is you folder to help exactly??


text:
Q: Discord.js - Is there a way to setup a click event handler? I have a bot that lists out a bunch of audio clips with the command !audio
exports.run = (client, message, args) => {
    const audioFolder = './audio/';
    const fs = require('fs');
    fs.readdir(audioFolder, (err, files) => {
        let filelist = '';
        files.length && files.forEach(file => {
            const audioFile = file.replace('.mp3', '');
            filelist += `${audioFile}\n`;
        });
        message.channel.send(`${filelist}`);
    });
}

The other command is !play filename
exports.run = (client, message, args) => {
    const   audioFolder = './audio/';
    const   fs = require('fs');
    const   fileName = args.join(' ');

    if( !fileName )  {
        message.channel.send(`Please request a filename. Example: !play filename`);
        return;
    }

    fs.readdir(audioFolder, (err, files) => {
        if( !files.includes(`${fileName}.mp3`) ) {
            message.channel.send(`File '${fileName}' does not exist, use !audio to see the full list of audio files.`);
            return;
        }

        const voiceChannel = message.member.voice.channel;

        if( !voiceChannel ) {
            message.channel.send(`You must be in a voice channel to use this command.`);
            return;
        }

        voiceChannel.join()
            .then(connection => {
                const dispatcher = connection.play(`./audio/${fileName}.mp3`);
                dispatcher.on('finish', () => {
                    voiceChannel.leave();
                });
            })
            .catch(console.error);
    });
}

What I want is to eliminate having to use the !play command. When the list of audio files comes out when using !audio I would like a way for users to click on the individual file and it runs a similar function to the play command based on the clicked file.
I cant find anything about click events within discordjs.
Any ideas here?


text:
Q: Help with Seemingly Hopeless Double Integral I hate to be that guy to just post an integration problem and ask how to solve it so I'll give a little relevant info
Okay, so I'm working on a physics project and my professor proposed that the following double integral could potentially solve a problem that I've used an alternative method to solve:
$$I=\int_0^\pi\int_0^\rho\frac{t^2\sin\phi\left(t\cos\phi-d\right)}{\left[t^2\sin^2\phi+\left(t\cos\phi-d\right)^2\right]^{3/2}}\;dt d\phi$$

*

*$\rho$ is an arbitrary, strictly positive real constant

*$d$ is a real constant that satisfies $d>\rho$
This integral's value could provide immense insight into fields of uniform, solid spherical objects, so it's actually pretty important for my work.
After some quick attempts to simplify, I decided to try some integral calculators with set values. Needless to say, the result after the first integral seemed so hopeless that I couldn't imagine simplifying and integrating again--not to mention then generalising constant inputs to their original variable form.
However, there is a strong likelihood that $I$ simplifies to one of the following two solutions:
$$\text{1.This solution comes from inverse square laws}$$
$$I=\frac{1}{d^2}$$
$$\text{2. This solution comes from a separate computation that I did (integrals below)}$$
$$I=\left(1-\frac{\rho^2}{5d^2}\right)\left[\frac{3}{2\rho^2}+\frac{3(\rho^2-d^2)}{4d\rho^3}\ln\left(\frac{d+\rho}{d-\rho}\right)\right]$$
Although it looks like these are vastly different answers, given $\rho=1$ and $d=10$, you get the following outputs from $(1)$ and $(2)$:
$$1.\; I=0.01$$
$$2.\; I\approx 0.01000046$$
Here's the ratio of solution (2) over (1) for $\rho\in(0,1),\;d\in(0,50)$

I tried to tackle this problem differently than my professor, and set up the following integrals to solve the problem that lead to solution $(2)$:
$$\frac{9}{4\rho^6}\left[\;\int\limits_{d-\rho}^{d+\rho}x\left[x-\frac{x^2+d^2-\rho^2}{2d}\right]\left[\frac{(x+d)^2-\rho^2}{4d\cdot x}\right]\;dx\right]\cdot\left[\;\int\limits_{d-\rho}^{d+\rho}\frac{\rho^2-(x-d)^2}{2d\cdot x}\;dx\right]$$

Where you come in
If the double integral is correctly composed (which my professor felt confident with), I need someone skilled in integration to solve said double integral. I've given two possible solutions and it's probable that the answer will be one of those. If it's solution $(1)$, I know that mine will have an error and you will essentially have proved the inverse square law for gravitational and electric fields. If it's solution $(2)$, then this will be far more exciting to me but less likely. If it's neither, then there are several possible implications
BOUNTY
I'm willing to award the following bounties for solving the double integral at the beginning. Since certain solutions have stronger implications (as explained above), I'm rewarding the following bounties:

*

*+200 rep if you verify solution $(1)$

*+500 rep if you verify solution $(2)$

*+75 rep for any other solutions (note they'll have to be verified by a second user first)

QUESTIONS
If you have any additional questions feel free to ask, and thanks for reading all this!

A: Hint:
With the change of variable $u=\cos\phi$, the integral on $\phi$ becomes
$$\int_{-1}^1\frac{t^2(tu-d)}{\sqrt{(u-dt)^2+d^2(1-t^2)}}du.$$
By decomposition of the numerator, you will get a term
$$c(t)\log((u-dt)^2+d^2(1-t^2))$$
and another
$$c'(t)\arctan\frac{u-dt}{d\sqrt{1-t^2}}.$$
These terms do not simplify at the bounds of the integration interval.
The integral on $t$ (cubic in $t$ at the denominator) is worse. I am not optimisitc about existence of a closed-form.

A: \begin{align*}
&\iint \frac{t^2 \sin(\phi) (t \cos(\phi) - d)}{(t^2 \sin^2(\phi) + (t \cos(\phi) - d)^2)^{3/2}} \,\mathrm{d}t\,\mathrm{d}\phi  \\
&= \frac{\sqrt{d^2 + t^2 - 2 d t \cos(\phi)}(d^2 - 2 t^2 - 2 d t \cos(\phi) - 3 d^2 \cos(2 \phi))}{6d^2} \\
&+ d \cos(\phi) \ln\left(t - d \cos(\phi) + \sqrt{d^2 + t^2 - 2 d t \cos(\phi)}\right) \sin^2(\phi)  \text{,} \end{align*}
as one can readily verify.  Then $I = \frac{-2 \rho^3}{3 d^2}$.
I think for your case $1$, you mean $I \propto \frac{1}{d^2}$.  The integral can't be positive because:

*

*$t^2 \geq 0$ and

*$\sin(\phi) \geq 0$ since $\phi \in [0,\pi]$, but

*$t \cos(\phi) - d < 0$ because $0 < t < \rho < d$, while

*the denominator is $\geq 0$, so

*the integrand is (zero or) negative everywhere.

A: As a mathematician, I would divide by force in the numerator and denominator by $d^3$, substitute $t/d$ by something, thus reducing to the case $d=1$. But here, let it be, we conserve the homogeneous setting as a control of the computations.

We split the numerator, compute first
$$
\begin{aligned}
J_1
&=
\int_0^\rho
dt
\int_0^\pi
\frac
{t^2\sin\phi\cdot t\cos\phi}
{\left[t^2\sin^2\phi+\left(t\cos\phi-D\right)^2\right]^{3/2}}\; d\phi
\\
&=
\int_0^\rho
dt
\int_0^\pi
\frac
{t^2(-\cos\phi)'\cdot t\cos\phi}
{\left[t^2-2Dt\cos\phi+D^2\right]^{3/2}}\; d\phi
\\
&\qquad\text{ Substitution: }u=\cos \phi\ ,
\\
&=
\int_0^\rho
dt
\int_{-1}^1
\frac
{t^3\; u}
{\left[t^2-2Dt\;u+D^2\right]^{3/2}}\; du
\\
&\qquad\text{ Substitution (for $u$, fixed $t$) of the radical }v=\sqrt{t^2-2Dt\;u+D^2}\ ,
\\
&\qquad u=\frac 1{2Dt}(t^2+D^2-v^2)\ ,\ du=-\frac v{Dt}\; dv\\ ,
\\
&=
-
\int_0^\rho
dt
\int_{\sqrt{t^2+2Dt+D^2}}^{\sqrt{t^2-2Dt+D^2}}
\frac
{t^3\; \frac 1{2Dt}(t^2+D^2-v^2)}
{v^3}\; \frac v{Dt}\; dv
\\
&=
\int_0^\rho
t\;dt
\int_{D-t}^{D+t}
\frac 1{2D^2}
\cdot
\frac {t^2+D^2-v^2}
{v^2}\; dv
\\
&=
\int_0^\rho
t\;dt
\;\frac 1{2D^2}
\left[
-(t^2+D^2)\frac 1v
-1
\right]_{v=D-t}^{v=D+t}
\\
&=
\int_0^\rho
dt
\;\frac t{2D^2}
\left[
(t^2+D^2)\left(\frac 1{D-t}-\frac 1{D+t}\right)
-
2t
\right]
\\
&=
\int_0^\rho
dt
\left[
\frac D{D+t}
+\frac D{D-t}
-2\frac{D^2+t^2}{D^2}
\right]
\\
&=
D\ln\frac {D+t}{D-t}
-
2\rho\left(1+\frac {\rho^2}{3D^2}\right)
\ .
\end{aligned}
$$
Computer check for $D=2$, $\rho=1$ (pari/gp code):
? D=2; r=1;
? intnum(t=0,r, intnum(s=0, Pi, t^2*sin(s)*t*cos(s) / (t^2-2*t*D*cos(s)+D^2)^(3/2) ) )
%19 = 0.030557910669552716123823807178384744388
? D*log( (D+r)/(D-r) ) - 2*r*(1+r^2/3/D^2)
%20 = 0.030557910669552716123823807178384742634
?
? D=223; r=101;
? intnum(t=0,r, intnum(s=0, Pi, t^2*sin(s)*t*cos(s) / (t^2-2*t*D*cos(s)+D^2)^(3/2) ) )
%22 = 1.9969022076015148346071622544965636670
? D*log( (D+r)/(D-r) ) - 2*r*(1+r^2/3/D^2)
%23 = 1.9969022076015148346071622544965636629

The other integral. I will integrate here first w.r.t. $t$.
$$
\begin{aligned}
J_2
&=
-D
\int_0^\pi
d\phi
\int_0^\rho
\frac
{t^2}
{\left[(t-D\cos\phi)^2+D\sin^2\phi\right]^{3/2}}
\; dt
\\
&\qquad\text{ and we consider separately (without the factor $-D$)}
\\
J_2(\phi)
&=
\int_0^\rho
\frac
{t^2}
{\left[(t-D\cos\phi)^2+D\sin^2\phi\right]^{3/2}}
\; dt
\\
&=
\int_{0-D\cos\phi}^{\rho-D\cos\phi}
\frac
{(u+D\cos\phi)^2}
{(u^2+a^2)^{3/2}}
\; du\ ,\qquad a:= D\sin\phi
\ .
\\
&\qquad
\text{ Now the integrals can be computed}
\\
\int \frac{u^2}
{(u^2+a^2)^{3/2}}
\; dt
&=
-\frac t{(u^2+a^2)^{1/2}}+\operatorname{arcsinh} \frac ta+C\ ,
\\
\int \frac{u}
{(u^2+a^2)^{3/2}}
\; dt
&=
-\frac 1{(u^2+a^2)^{1/2}}+C\ ,
\\
\int \frac{1}
{(u^2+a^2)^{3/2}}
\; dt
&=
-\frac {a^2\;u}{(u^2+a^2)^{1/2}}+C\ ,
\end{aligned}
$$
and the computation goes on.
If my calculus is ok, then
$$
\begin{aligned}
J_2(\phi)
&=
\int_0^\pi
d\phi\;
\Bigg[
\operatorname{arcsinh} \frac{t-D\cos \phi}{D\sin\phi}
\\&\qquad\qquad\qquad+
\frac{t-D\cos\phi}{(t^2-2Dt\cos\phi+D^2)^{1/2}\sin^2\phi}
\\&\qquad\qquad\qquad\qquad\qquad\qquad
+\frac2{(t^2-2Dt\cos\phi+D^2)^{1/2}}
\Bigg]_0^\rho\ .
\end{aligned}
$$
I have to submit, hope this is helpful to check with the own computations.
I'll be back, but typing kills a lot of time.

A: I have to say, that the solution of I looks similar to (1), it is:
$$I=-\frac{2 \rho ^3}{3 d^2}$$
I integrate the integral for several values of $\rho$ and $d$ numerical and checked this result, it is correct.
For the calculation you only need the substitution of @Yves it is not that difficult! - with the help of Mathematica:
First you have to do the integration over t, the antiderivative is just:\,
$\int \frac{t^{2}\text{Sin}[\phi ](t\text{Cos}[\phi ]-d)}{\left( t^{2}\ \text{
Sin}[\phi ]^{2}+(t\text{Cos}[\phi ]-d)^{2}\right) ^{3/2}}dt$
$=\frac{\left( 2\left( \rho ^{2}+3\varrho ^{2}\right) \text{Cos
}[\phi ]+\varrho \left( -4\rho +\sqrt{\rho ^{2}+\varrho ^{2}-2\rho \varrho
\text{Cos}[\phi ]}\,\text{Log}\left[ \rho -\varrho \text{Cos}[\phi ]+\sqrt{
\rho ^{2}+\varrho ^{2}-2\rho \varrho \text{Cos}[\phi ]}\right] +\text{Cos}
[2\phi ]\left( -6\rho +3\sqrt{\rho ^{2}+\varrho ^{2}-2\rho \varrho \, \text{Cos}
[\phi ]}\,\text{Log}\left[ \rho -\varrho \text{Cos}[\phi ]+\sqrt{\rho ^{2}
+\varrho ^{2}-2\rho \varrho \text{Cos}[\phi ]}\right] \right) \right)
\right) \,\text{Sin}[\phi ]}{2\sqrt{\rho ^{2}+\varrho ^{2}-2\rho \varrho \text{
Cos}[\phi ]}}$
Second you do the substitution:
$$y=\text{Cos}[\phi ]$$
and the simplification:
$$\text{Cos}[2 \phi ]=\text{Cos}^{2}[\phi ]-\text{Sin}^{2}[\phi ]$$
leading to:
$$I=\int_{1}^{-1}\left[ \frac{-t \varrho +6y^{2} t\varrho -y\left( t^{2}+3\ \varrho ^{2}\right) +\left( 1-3y^{2}\right) \varrho \,\sqrt{t^{2}-2 \,y \,t \varrho +\varrho ^{2}}\,\text{Log}\left[ t -y\,\varrho +\sqrt{
t^{2}-2\,y\, t\, \varrho \ +\varrho ^{2}}\right] }{\sqrt{t^{2}-2\,y\, t
\varrho +\varrho ^{2}}}\right] _{0}^{\rho }dy$$
Mathematica even finds the antiderivative of that function, I guess it should be found also in a table of integrals. Then the expression can be simplified in a way so the stated result is given.


text:
Q: How to create a table view with a section? My Table View right now is in "dynamic prototypes" so basically i cant add section by just increment the section like static cell. but i like to maintain in dynamic prototype. So how exactly can i create a section that contain their own cell?
Here is my code:
class ProfileViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource,FBSDKLoginButtonDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var profileTableView: UITableView!
    @IBOutlet weak var profileImg: UIImageView!
    @IBOutlet weak var bigIDLbl: UILabel!
    @IBOutlet weak var userNameLbl: UILabel!

    let titleArr = ["My Profile", "My BIG Point", "Options"]
    var detailArr = [String]()

    let userInfo = defaults.objectForKey("userInfo")
    let userTicketId = defaults.objectForKey("userticketId") as! String

    override func viewDidLoad() {
        super.viewDidLoad()
        //setupWhiteLeftButton()
        self.navigationItem.title = "My Profile"

        bigIDLbl.text = "BIG ID : \(userInfo!["CustomerNumber"] as! String)"
        userNameLbl.text = "\((userInfo!["FirstName"] as! String).capitalizedString) \((userInfo!["LastName"] as! String).capitalizedString)"
         detailArr = ["\((userInfo!["FirstName"] as! String).capitalizedString) \((userInfo!["LastName"] as! String).capitalizedString)", "8,950pts", ""]

        let username = userInfo!["UserName"] as! String
        let password = defaults.objectForKey("userPassword") as! String

        AirAsiaBigProvider.request(.GetUser(username, password, userTicketId), completion: { (result) in
            switch result {
            case .Success(let successResult):
                do {

                    let json = try JSON(NSJSONSerialization.JSONObjectWithData(successResult.data, options: .MutableContainers))

                    if json["Status"].string == "OK" {
                        defaults.setValue(json.object, forKey: "userData")
                    } else if json["Status"].string == "Error" {
                        showErrorMessage(json["Message"].string!)
                    }

                }
                catch {
                    showErrorMessage("Unable to connect the server")
                }
            case .Failure(let failureResult):
                showErrorMessage(failureResult.nsError.localizedDescription)
            }
        })

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func profileImgPressed(sender: AnyObject) {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)

        let choosePhoto = UIAlertAction(title: "Choose From Photos", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in
            NSLog("Action 1 Clicked")

            if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
                let imagePicker = UIImagePickerController()
                imagePicker.allowsEditing = true
                imagePicker.delegate = self
                imagePicker.sourceType = .PhotoLibrary
                self.presentViewController(imagePicker, animated: true, completion: nil)
            } else {
                showErrorMessage("Error Launch Photos")
            }
        })

        let takePhoto = UIAlertAction(title: "Take Photo", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in
            NSLog("Action 2 Clicked")

            if UIImagePickerController.isSourceTypeAvailable(.Camera) {
                let imagePicker = UIImagePickerController()
                imagePicker.allowsEditing = true
                imagePicker.delegate = self
                imagePicker.sourceType = .Camera
                self.presentViewController(imagePicker, animated: true, completion: nil)
            } else {
                showErrorMessage("Error Taking Photo")
            }
        })

        let deletePhoto = UIAlertAction(title: "Delete Photo", style: .Default, handler: {
            (alert: UIAlertAction!) -> Void in
            NSLog("Action 3 Clicked")
            self.profileImg.image = UIImage(named: "profileImg")
        })

        let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

        alert.addAction(choosePhoto)
        alert.addAction(takePhoto)
        alert.addAction(deletePhoto)
        alert.addAction(cancel)
        presentViewController(alert, animated: true, completion: nil)
    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        profileImg.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        profileImg.contentMode = UIViewContentMode.ScaleAspectFill
        profileImg.clipsToBounds = true
        dismissViewControllerAnimated(true, completion: nil)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleArr.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 40
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = profileTableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomProfileTableViewCell
        cell.title.text = titleArr[indexPath.row]
        cell.detail.text = detailArr[indexPath.row]
        cell.layoutMargins = UIEdgeInsetsZero
        return cell

    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if indexPath.row == 0 {

            let storyboard2 = UIStoryboard(name: "Profile", bundle: nil)
            let myProfileVC = storyboard2.instantiateViewControllerWithIdentifier("ViewProfileVC") as! myProfileTableViewController
            self.navigationController?.pushViewController(myProfileVC, animated: true)
        } else if indexPath.row == 2{

            let storyboard2 = UIStoryboard(name: "Profile", bundle: nil)
            let profileVC = storyboard2.instantiateViewControllerWithIdentifier("OptionsVC") as! OptionsViewController
            self.navigationController?.pushViewController(profileVC, animated: true)
        }

    }

    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        print("User Login")
    }
    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {

        print("User Logged Out")
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

A: By this way you can add sections in your tableView
 override func viewDidLoad() {

        super.viewDidLoad()
        profileTableView.delegate = self
        profileTableView.dataSource = self
  }

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2 // As per your requirement you can return no of sections.
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String
    {
        if section == 0
        {
            return "Section A"
        }
        else
        {
            return "Section B"
        }
    }


text:
Q: Link to libssl 0.9.8 instead of 0.9.7 in Qt for Mac I found my application compiled with Qt Creator under Mac (Qt 4.7.4 and Qt 4.8.0) is linked to /usr/lib/libssl0.9.7.
It is giving me a lot of SSL errors when I browse https websites from the application based on QtWebkit. The windows version of Qt is based on OpenSSL 0.9.8. I do see libssl 0.9.8 is also installed on my Mac OS Lion. How can I get Qt Creator to link against libssl 0.9.8?


text:
Q: Returning many objects on html page - Django 2.0 I am returning the "comentarios" objects of the database through a for, but since the display of these objects takes up a lot of space in the html page, I would like to know how to divide the objects into more lists or into a hidden space, since when they pass from seven comments they exceed the size of the body.
template.html
{% extends 'baseR.html' %}
{% load static %}
{% block title %} Comentários - SMILE 3D {% endblock %}
{% block tamanho %} 2000px {% endblock %}
{% load bootstrap %}

{% block main %}

Pregão:

{{msg}}

Dono: {{pregoe.usuario}}

Tipo do pregão: {{ pregoe.tipo }}

Dente: {{ pregoe.dente }}

Cor: {{ pregoe.cor }}

Escala: {{ pregoe.escala }}

Material: {{ pregoe.material }}

Observações: {{ pregoe.extra }}

Preço inicial: R${{ pregoe.preco }}

Data de registro: {{ pregoe.data }}

Prazo: {{ pregoe.prazo }}

             **
Comentários:

             {% for comentario in comentarios %}

{{comentario.user}}

{{comentario.comentario}}

             {% endfor %}**

             {{msg}}

               NOVO COMENTÁRIO

{% endblock %}

views.py
@login_required
def listaComentarios(request, id1, id2):
    user = get_object_or_404(CustomUser, pk=id2)
    pregao = get_object_or_404(Pregao, pk=id1)
    comentarios = Comentario.objects.all().filter(pregao=pregao)
    if user == pregao.usuario:
        return render(request, 'comentarios/lista-comentarios-dono.html', {'comentarios': comentarios, 'pregoe': pregao})
    return render(request, 'comentarios/lista-comentarios.html', {'comentarios': comentarios, 'pregoe': pregao})

A: You need to add pagination and you will receive your queryset by parts.
You can get information on about in official Django docs.
https://docs.djangoproject.com/en/2.1/topics/pagination/#using-paginator-in-a-view


text:
Q: Using \foreach with \SplitArgument Why does the \test command not split the argument when called from a foreach loop?
\NewDocumentCommand{\test}{ >{\SplitArgument{3}{|}} m }{\printtest#1}
\NewDocumentCommand{\printtest}{mmmm}{
    (#1,#2)\quad s_{\IfValueT{#3}{#3}}\IfValueT{#4}{#4}}

\newcommand{\looptest}[1]{
   \foreach \n in {#1}{
       $\test{\n}$\\
    };

$\test{1|1}$\\       % this works
$\test{2|2|1}$\\     % this works
$\test{3|3|2|'}$\\   % this works
$\test{4|4|3|''}$\\  % this works

\looptest{1|2|1, 3|7|2, 6|7|3, 6|5, 9|5|3|''} % this does not

A: This uses a listofitems approach to parse the input to \looptest.  The introductory \setsepchar{,} sets the parsing character as , . The macro \readlist*\looplist{#1} parses the list into a \looplist[<index>] array (while ignoring blank spaces around the , delimiters), which is then sequentially accessed with a \foreachitem loop.  However, the loop argument \n must be expanded once on its way to being digested by \test.
\documentclass{article}
\usepackage{pgffor,xparse,listofitems}

\NewDocumentCommand{\test}{ >{\SplitArgument{3}{|}} m }{\printtest#1}
\NewDocumentCommand{\printtest}{mmmm}{
    (#1,#2)\quad s_{\IfValueT{#3}{#3}}\IfValueT{#4}{#4}}

\newcommand{\looptest}[1]{%
   \setsepchar{,}%
   \readlist*\looplist{#1}%
   \foreachitem \n \in \looplist{%
       $\expandafter\test\expandafter{\n}$\\
    }
}

\begin{document}\noindent
$\test{1|1}$\\       % this works
$\test{2|2|1}$\\     % this works
$\test{3|3|2|'}$\\   % this works
$\test{4|4|3|''}$\\  % this works

\noindent\looptest{1|2|1, 3|7|2, 6|7|3, 6|5, 9|5|3|''} % this does not
\end{document}

And here is a way to totally eliminate pgffor and xparse, doing it completely within listofitems.  Note that stray blank spaces may be introduced not only around the list commas , but also around the | separators, with no ill effect.
\documentclass{article}
\usepackage{listofitems}
\makeatletter
\newcommand\test[1]{%
  \setsepchar{{|}}%
  \readlist*\testlist{#1}%
  \def\temp{\printtest}%
  \foreachitem\testitem\in\testlist{%
    \expandafter\g@addto@macro\expandafter\temp\expandafter{\expandafter{\testitem}}%
  }%
  \temp\relax\relax\relax%
}
\makeatother
\newcommand\printtest[4]{(#1,#2)\quad s_{#3}#4}
\newcommand{\looptest}[1]{%
   \setsepchar{,}%
   \readlist*\looplist{#1}%
   \foreachitem \n \in \looplist{%
       $\expandafter\test\expandafter{\n}$\\
    }%
}
\begin{document}\noindent
$\test{1|1}$\\       % this works
$\test{2|2|1}$\\     % this works
$\test{3|3|2|'}$\\   % this works
$\test{4|4|3|''}$\\  % this works

\noindent\looptest{1|2|1, 3|7|2, 6|7|3, 6|5, 9|5|3|''} % this does not
\end{document}

A: The arguments are not expanded timely. Every foreach spin argument is still inside a brace pair. Also don't use whitespace inside the foreach arguments. It might cause pattern mismatches.
\documentclass{article}
\usepackage{pgffor,xparse}

\NewDocumentCommand{\test}{ >{\SplitArgument{3}{|}} m }{\printtest#1}
\NewDocumentCommand{\printtest}{mmmm}{(#1,#2)\quad s_{\IfValueT{#3}{#3}}\IfValueT{#4}{#4}}
\newcommand{\looptest}[1]{\foreach\n in{#1}{$\expandafter\test\expandafter{\n}$\\}}

\begin{document}\noindent
$\test{1|1}$\\       % this works
$\test{2|2|1}$\\     % this works
$\test{3|3|2|'}$\\   % this works
$\test{4|4|3|''}$\\  % this works
\looptest{1|2|1,3|7|2,6|7|3,6|5,9|5|3|''} % this does not
\end{document}


text:
Q: How to access variables in blocks in Fuel CMS? I have been using Fuel CMS to develop a website, and I was thinking of using blocks to make my pages dynamic using CMS, but I can't access any passed variables inside block.
FUEL CMS Page
{fuel_block(array(
        'view' => 'nt_project_card',
        'vars' => array(
            'project_title' => 'Test Project',
            'project_desc' => 'Some details about project',
            'project_link' => 'projects/project1'
        )))}

FUEL CMS Block

{fuel_var('project_title', 'Title')}

{fuel_var('project_desc')}

    Read More...

Where am I going wrong? I have seen documentation (which is already very vague) and questions on forum but they didn't help either. I can only see my default value along with the rendered block.

A: So it seems I don't need to use any function I can just go with the usual $variable to use the passed variables in blocks.

A: can use
<?php echo $this->fuel->blocks->render('block_name'); ?>

same as application\views_blocks files


text:
Q: Accessing a class nested in a generic class Is this possible, or should I find another pattern and forget nesting?
Any help much appreciated!
Gregzo
public class OuterClass<T> where T : InnerClass, new()
{
    public T GetInnerInstance()
    {
        return new T();
    }

    public class InnerClass
    {
         public InnerClass
         {

         }
    }

}

public class Foo
{
    OuterClass<OuterClass.InnerClass> _instance; // nope
}

The goal is to let users extend InnerClass  and use OuterClass as a factory.
Edit: for clarity, here's the full pattern, completed thanks to Greg's help:
public class OuterClass< ProductType, ReturnInterfaceType > where ProductType : InnerClass, ReturnInterfaceType, new()
                                                            where ReturnInterfaceType : MinInterface
{
    private string _privateName;

    public OuterClass( string name )
    {
        _privateName = name;
    }

    public ReturnInterfaceType GetProduct()
    {
        ProductType product = new ProductType();

        product.SetParent( this );

        return new ProductType();
    }

    public class InnerClass
    {
        protected OuterClass< ProductType, ReturnInterfaceType > _parent;

        public InnerClass(){} //empty ctor for generic new()

        public void SetParent( OuterClass< ProductType, ReturnInterfaceType > parent )
        {
            _parent = parent;
        }

        //MinInterface implementation
        public string FactoryName
        {
            get{ return _parent._privateName; }//access parent private members
        }
    }
}

public interface MinInterface
{
    string FactoryName{ get; }
}

public interface MyProductInterface : MinInterface
{
    int productID{ get; }
}

public class MyProduct : OuterClass< MyProduct, MyProductInterface >.InnerClass, MyProductInterface
{
    public int productID{ get; private set; }
    static int __nbOfProducts = 0;

    public MyProduct()
    {
        productID = __nbOfProducts;
        __nbOfProducts++;
    }
}

Now it is easy to create a factory of whatever subproduct type and interface:
OuterClass<MyProduct, MyProductInterface> _factory;
_factory = new OuterClass<MyProduct, MyProductInterface>( "Factory");

MyProductInterface _protectedProduct = _factory.GetProduct();
string factoryName = _protectedProduct.FactoryName;
//interaction with the outer class's private members is limited to the product's base class and minimum interface
//New members and interfaces can be easily derived

A: Please specify the language you're referring to. I assume it's C#.
The pattern you're using makes no sense, when you think about it. OuterClass itself is not a class; OuterClass<T> is a class.  In fact, the identifiers used for OuterClass<T> and ΟuterClass by the compiler are different, so you could actually define these two classes in the same file.
Because ΟuterClass itself is not a class, it obviously has no members. However, if you really wanted to, you could do something like this:
public class X : OuterClass<X>.InnerClass
{

}

public class OuterClass<T> where T : OuterClass<T>.InnerClass, new()
{
    public T GetInnerInstance()
    {
        return new T();
    }

    public class InnerClass
    {
        public InnerClass()
        {

        }
    }

}

public class Foo
{
    OuterClass<X> _instance; // yup
}

In order to parameterize OuterClass, you first need to create a type that matches the zany constraint you want. You cannot actually use OuterClass<T>.InnerClass because you first need a type T that matches the constraint T : OuterClass<T>.InnerClass. It sort of becomes a catch 22 type situation. You avoid it by explicitly defining the type.


text:
Q: C# interface Doesn't allow member class to forfill requirements Sorry if the title is not very descriptive. I didn't know how to describe this.
First, I created an interface like this:
public interface IUser {}

Then implemented it in several classes like this:
public class Student : IUser {}

public class Teacher : IUser {}

Then I created an Interface that required the first interface
public class IUsers
{
    List<IUser> Users {get; set;}
}

Then I created a Class that used the second interface, but used one of the Members of the first interface to for fill the contract.
public class Students : IUsers
{
    List<Student> Users {get; set;}
}

The problem is the last one I wanted to constrain the list to just one implementation of the interface, but still need to maintain the interface for data compatibility. When I do this I get an error saying I'm not implementing the interface. I thought that since Student implemented the interface it would for fill the obligation, but it doesn't seem to. Is this correct or am I doing something else wrong

A: You need to say what kind of users your collection supports. Suppose your code were valid - then this would compile:
IUsers users = new Students();
// What would this do at execution time? It's not safe!
users.Users.Add(new Teacher());

After all, that's just adding a Teacher to a List<IUser>, right? But in Students, the Users property is a List<Student>, so that can't accept a teacher.
The best approach is probably to make your IUsers interface generic in the type of user it accepts:
public class IUsers<TUser> where TUser : IUser
{
    List<TUser> Users {get; set;}
}

Then your Students class would implement IUsers<Student>, and the property would be fine.
At that point, the problematic example at the top of the answer would fail to compile:
// This is fine
IUsers<Student> users = new Students();
// This won't compile, because users.Users is of type List<Student>, and you can't add
// a Teacher to that.
users.Users.Add(new Teacher());

A: Based on the code, to me the sample appears to indicate you would like to maintain separate implementations for your users, then return the desired implementation.
public interface IStudentFactory
{
     IUser Create();
}

public class StudentFactory
{
    public IUser Create() => new StudentContext();
}

Then based on your implementation inside your interface of IUser, you could connect to your data store to manage those types of user.
var context = new StudentFactory().Create())
var students = context.GetAllStudents();
context.Students.Add(new Student() { });

The approach I provided is under the notion that you want to be able to access this information about different types of users, persist, and manage.  Your example showed a primitive collection where you are adding, potentially handling other functionality, but I imagine you are working more towards something a bit more consistent.
I may be off the mark for your intent, but that is how I interpreted.


text:
Q: Find and replace string in parameter bash $ ./myscript my.site.com

How do I replace all dots in the first parameter? Here's my current try but it's returning a bad substition error.
#!/bin/bash
dbname=${$1//./_}

echo $dbname

A: dbname=${1//./_}

Remove $ before 1 since $1 and ${1} are the same.


text:
Q: My SSAS Dimension Hierarchy is not showing correctly I have a dimension called Dim_DueAnalysis in a multidimensional cube.
The underlying table looks like this (only a subset of the data is here):
DueAnalysis_Key  DueAnalysisID  DueAnalysisDays    DueAnalysisIntervalWeeks  DueAnalysisInterval   DueAnalysisDueOverdue
1052             26             Overdue by 26 days Overdue by 3 weeks        Overdue by 1-30 days  Overdue
1053             27             Overdue by 27 days Overdue by 3 weeks        Overdue by 1-30 days  Overdue
1054             28             Overdue by 28 days Overdue by 4 weeks        Overdue by 1-30 days  Overdue
1055             29             Overdue by 29 days Overdue by 4 weeks        Overdue by 1-30 days  Overdue
1056             30             Overdue by 30 days Overdue by 4 weeks        Overdue by 1-30 days  Overdue
1057             31             Overdue by 31 days Overdue by 4 weeks        Overdue by 31-60 days Overdue

This table looks fine and dandy.
My dimension in the cube has a hierarchy:
Due Analysis Key => Due Analysis Days => Due Analysis Interval Weeks => Due Analysis Interval => Due Analysis Due Overdue
                 => Due Analysis Day Number                          => Due Analysis ID sort

All my Relationship Types are Flexible. But still my dimension looks like this when I browse it in my Analysis Database:
Overdue
- Overdue by 1-30 days
  ...
  - Overdue by 3 weeks
    - Overdue by 21 days
      ...
    - Overdue by 27 days
- Overdue by 31-60 days
  - Overdue by 4 weeks
    - Overdue by 28 days
    - Overdue by 29 days
      ...

As you might have noticed, days 28-30 are in the 31-60 days interval.
What I want is that part of "Overdue by 4 weeks" (days 28-30) is in the Overdue in 1-30 Days hierarchy and not in the Overdue by 31-60 days. But "Overdue by 4 weeks" should also be present in the Overdue by 31-60 days as days 31-34 should be present there.
I thought that it was just a matter of setting my relationship type to "Flexible" instead of "Rigid" but that has not solved my problem.
I am not sure what further information is needed in order to solve this case so please ask about how certain properties etc are.

A: Ah of course - I had to create another column specifying which week AND day interval my data was in. By using that column I got my hierarchy correct.


text:
Q: Can "motivate" mean 'explain'; 'justify'? In my native language, the word corresponding to the English verb motivate can be used to mean something like 'explain' or 'justify'. We could for instance ask someone to 'motivate' a particular point of view, a particular choice, a particular answer etc. When I check the various dictionaries I have access to it seems that motivate cannot be used in this sense in English, but when I google BrE web pages for "motivate your answer", I nevertheless get a number of hits that seem to support this use also in English – for instance:

Use the specific data given above to motivate your answer

If you wish, please motivate your answer (max. 1000 characters)

Describe the objective data you would collect from patient T and motivate your answer.

So, is it, after all, possible to use motivate in this sense in English, or are the above examples just bad English? If it is possible, would it also be possible to use a modified participle of this verb as a premodifier in a NP, as in well-motivated choices and well-motivated answers? If not, what could I use instead?
Thank you!

A: It certainly is used in the UK by some people in that sense. I think it is a relatively recent arrival in our linguistic landscape though so perhaps it is a borrowing from other dialects or even a direct translation from another language like Spanish motivar for instance. That might explain it poor showing in dictionaries.

A: I am afraid to say that it would be bad English.
Motivate does not mean explain or justify. It is that simple.


text:
Q: How to fork a process I need help understanding how to demonize a process in Go.
package main

import (
   "fmt"
   "os"
)

func start() {
   var procAttr os.ProcAttr
   procAttr.Files = []*os.File{nil, nil, nil}
   _, err := os.StartProcess("/Path/prog", nil, &procAttr)
   if err != nil {
       fmt.Printf("%v", err)
   }
}

func main () {
   start()
}

If you start this code on the command line the program returns control, but is still connected with cmd. Closing the cmd closes the program.
How can I decouple it from the cmd?  Adding:
procAttr.Sys.HideWindow = true

Results in this error: "panic" to wrong memory pointer

A: Here is a fake daemon in go; it's simple to use: https://github.com/icattlecoder/godaemon
An example:
package main

import (
    _ "github.com/icattlecoder/godaemon"
    "log"
    "net/http"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/index", func(rw http.ResponseWriter, req *http.Request) {
        rw.Write([]byte("hello, golang!\n"))
    })
    log.Fatalln(http.ListenAndServe(":7070", mux))
}

A: I asked in 'golang-nuts', and found out that Go has a link option:
go tool 8l -o output.exe -Hwindowsgui input.8


text:
Q: Alt + right click does not work to edit GNOME panel in Unity The alt + right click combination does not work for editing gnome-panel in the unity interface, but I eventually found that holding alt and clicking both mouse buttons at the same time worked to bring up the panel's properties menu.
It occasionally works when I hold alt and press both mouse buttons on any panel applets. Most of the time I am stuck with the added applets.
I was able to delete the top gnome-panel. But when I changed the bottom panel's properties to be on the right side of the screen, it completely disappeared, and there was no way to get it back, even when I logged in with gnome-classic.
(So far, I have had to dump gnome-panel as an option for an extra Ubuntu 11.10 panel, as there appear to be too many conflicts between the gnome panel and the new unity interface.)
Are there any configurations that can be altered to make the editing of the gnome-panel easier?  Such as in Gconf-editor or Dconf-editor?

A: I had the same problem as you have, then I tried this combination: Alt + Super + Right Click and it worked!

A: Gnome Panel 3 uses GSettings, so yes, you can use dconf-editor. You'll find it under /org/gnome/gnome-panel.


text:
Q: Do orcs drink water? At least in the film version of Return of the King, Frodo and Sam run out of water while trekking across Mordor, apparently having been unable to refill their water pouches in the tower or at any other point past there.
We know that the orcs eat regular food, but are they ever shown drinking anything besides orc draught?

A: Yes.
Sam asks the same question, of whether orcs eat and drink or just live on foul air and poison, and Frodo gives him the following answer:

"No, they eat and drink, Sam. The Shadow that bred them can only mock, it cannot make: not real new things of its own. I don't think it gave life to the orcs, it only ruined them and twisted them; and if they are to live at all, they have to live like other living creatures. Foul waters and foul meats they'll take, if they can get no better, but not poison. They've fed me, and so I'm better off than you. There must be food and water somewhere in this place."
-- The Return of the King, Book VI, Chapter I: The Tower of Cirith Ungol

A: Yes.
In addition to the quote provided by @Randal'Thor, there is also this:

'Water, water!' muttered Sam. He had stinted himself, and in his parched mouth his tongue seemed thick and swollen; but for all his care they now had very little left, perhaps half his bottle, and maybe there were still days to go. All would long ago have been spent, if they had  not dared to follow the orc-road. For at long intervals on that highway cisterns had been built for the use of troops sent in haste through the waterless regions. In one Sam had found some water left, stale, muddied by the orcs, but still sufficient for their desperate case. Yet that was now a day ago. There was no hope of any more.
-The Return of the King, Book VI, chapter 3: Mount Doom
(emphasis mine)

A: They also drank blood
Your question asked if Orcs are "ever shown drinking anything besides orc draught". Other answers here have already showed that Orcs drink water, so I will show something else that they drunk.
From a circa 1968 typescript found among Tolkien's linguistic papers:

C[ommon]E[ladrin] *khōn-, khond- was only used of the physical heart, and that was not regarded as or supposed to be a centre of either emotion or thought. Thus when Treebeard uses the adjectives morimaitë, sincahonda ' black-handed, flint-hearted' of the Orks, these were both physical in reference - as indeed were all the other adjectives, whatever they may have implied with regard to Orkish minds and characters. Sincahonda referred to their immense
staying power in exertion, marching, running, or climbing, which gave rise to the jesting assertion that their hearts must have been made of some exceedingly hard substance; it did not mean pitiless. The last adjective 'blood-thirsty' (serkilixa) was also literal: the Orks actually drank the blood of their victims. A compound of similar kind meaning 'hard-hearted, pitiless', would have been in Quenya ondórëa.
The Nature of Middle-earth - "Gender and Sex", footnote


text:
Q: GNU parallel interactive mode. How to make chunk request instead of request for each job? Is it possible to make chunk request instead of request for each job?
function $1 $2 $3 | parallel --gnu --group --interactive -k -j 4 function_run {}
In that case, GNU Parallel is asking question to run each job, but i want question to run next chunk of 4 parallel jobs. And it would be great, if I could change -j in run process.

A: -j can read from a file: If the file changes, it will be re-read after each job stops. The content is the same as you would give to -j (e.g. 4, 100%, or -1).
If you want --interactive for chunks of 4 jobs, then you could write a wrapper:
run4() {
  parallel echo ::: "$@"
}
export -f run4
seq 10 | parallel -n4 --interactive run4
run4 1 2 3 4 ?...y
run4 5 6 7 8 ?...n
run4 9 10 ?...n

(--group is default).


text:
Q: SuperCSV, Dozer: Writing to a csv file. For Object with a list into multiple rows I have a class A which has few properties:
class A {

private String col1;
private String col2;
private List<B> bList;

// setters and getters
}

Class B {
private String b1;
private String b2;
//setters and getters
}

I am trying to write this into a csv file using supercsv and dozer.
The csv should have the same number of rows as elements in the list bList from class A.
And should have four columns col1, col2 (which would be common for all the rows) and b1, b2 from the list of class B in class A.
Currently in the mapping file I have:
<mapping type="one-way" wildcard="false" map-null="true">
                <class-a>package.a</class-a>
                <class-b>org.supercsv.io.dozer.CsvDozerBeanData</class-b>
.....
</mapping>

But it only maps the data into one row. What would be a better way to do it without mapping it into a flatter class.
In the mappings can be map it from class A to a list of CsvDozerBeanData? Will that work?
Thanks.

A: Can you add a relationship from B back to A? Then you could iterate over each List of children with the following bean mapping:
new String[] { "a.col1", "a.col2", "b1", "b2" }

Here's an example of how you'd use this. Note the nested loops to iterate over each B inside each A.
public class DozerTest {

    @Test
    public final void test() throws IOException {
        StringWriter out = new StringWriter();
        ICsvDozerBeanWriter writer = new CsvDozerBeanWriter(out,
                CsvPreference.STANDARD_PREFERENCE);
        writer.configureBeanMapping(B.class,
                new String[] { "a.col1", "a.col2", "b1", "b2" });

        for (A a : generateData()) {
            for (B b : a.getbList()) {
                writer.write(b);
            }
        }
        writer.flush();
        System.out.println(out.toString());
    }

    private List<A> generateData() {
        List<A> data = new ArrayList<A>();

        for (int i = 0; i < 3; i++) {
            A a = new A();
            a.setCol1("col1 for a" + i);
            a.setCol2("col2 for a" + i);

            B firstB = new B();
            firstB.setB1("first b1 for a" + i);
            firstB.setB2("first b2 for a" + i);
            firstB.setA(a);

            B secondB = new B();
            secondB.setB1("second b1 for a" + i);
            secondB.setB2("second b2 for a" + i);
            secondB.setA(a);

            a.setbList(Arrays.asList(firstB, secondB));
            data.add(a);
        }

        return data;
    }

}

This prints:
col1 for a0,col2 for a0,first b1 for a0,first b2 for a0
col1 for a0,col2 for a0,second b1 for a0,second b2 for a0
col1 for a1,col2 for a1,first b1 for a1,first b2 for a1
col1 for a1,col2 for a1,second b1 for a1,second b2 for a1
col1 for a2,col2 for a2,first b1 for a2,first b2 for a2
col1 for a2,col2 for a2,second b1 for a2,second b2 for a2

Update to address comments
If you can't add a relationship, then you can just use CellProcessors (and you don't even need to use Dozer). I've just created 3 simple cell processors:

*

*ElementAt - just grabs the element at the desired index

*GetB1 - gets the b1 field of a B

*GetB2 - gets the b2 field of a B
And here they are in action:
@Test
public final void test2() throws IOException {
    StringWriter out = new StringWriter();
    ICsvDozerBeanWriter writer = new CsvDozerBeanWriter(out,
        CsvPreference.STANDARD_PREFERENCE);
    writer.configureBeanMapping(A.class,
        new String[] { "col1", "col2", "bList", "bList" });

    for (A a : generateData()) {
        for (int i = 0; i < a.getbList().size(); i++) {
            CellProcessor[] processors = new CellProcessor[] { null, null,
                new ElementAt(i, new GetB1()),
                new ElementAt(i, new GetB2()) };
            writer.write(a, processors);
        }
    }
    writer.flush();
    System.out.println(out.toString());
}

class GetB1 extends CellProcessorAdaptor {
    public Object execute(Object value, CsvContext context) {
        validateInputNotNull(value, context);
        return ((B) value).getB1();
    }
}

class GetB2 extends CellProcessorAdaptor {
    public Object execute(Object value, CsvContext context) {
        validateInputNotNull(value, context);
        return ((B) value).getB2();
    }
}

class ElementAt extends CellProcessorAdaptor {

    private final int index;

    public ElementAt(int index) {
        this.index = index;
    }

    public ElementAt(int index, CellProcessor next) {
        super(next);
        this.index = index;
    }

    public Object execute(Object value, CsvContext context) {
        validateInputNotNull(value, context);
        Object element = ((List<?>) value).get(index);
        return next.execute(element, context);
    }

}

Output:
col1 for a0,col2 for a0,first b1 for a0,first b2 for a0
col1 for a0,col2 for a0,second b1 for a0,second b2 for a0
col1 for a1,col2 for a1,first b1 for a1,first b2 for a1
col1 for a1,col2 for a1,second b1 for a1,second b2 for a1
col1 for a2,col2 for a2,first b1 for a2,first b2 for a2
col1 for a2,col2 for a2,second b1 for a2,second b2 for a2

p.s. I wouldn't recommend supplying your own dozer mapping XML unless you really have to (and in this case it doesn't seem necessary).


text:
Q: Searching a Value in Binary tree haskell I have just started learning Haskell and I am trying to write a code for searching for a particular value in a binary tree and if present return true else false
This is how my tree structure looks like
data Tree = Leaf Int | Node Tree Int Tree

I am not sure how to proceed with the function to traverse through the tree and return the value. I did try BFS and DFS but I am not sure on how to return once I have got my value.
An example of how my function should look
Search 5 (Node (Node (Leaf 1) 3 (Leaf 4)) 5 (Node (Leaf 6) 7 (Leaf 9)))

A: A binary search could be written as follows. The type can be more generic, as we only need the items to be orderable to store / search in a binary tree.
We visit each node and either return true, or search in 1 of the child nodes.
example Node
   5
 /   \
3     7

lets search for 7.
We first visit the root. since 5 != 7, we test a child node. Since 7 > 5, we search in the right node, since 7 cannot appear in the left child (all values guaranteed to be lower than 5 on the left child)
If we reach a leaf, we just check if it contains the search term.
search :: Ord a => a -> BinaryTree a -> Bool
search a (Leaf b) = compare a b == EQ
search a (Node left b right)
  case compare a b of
    EQ -> True
    LT -> search a left
    GT -> search a right

A:
I am not sure how to proceed with the function to traverse through the tree and return the value.

From that sentence, I understand you would have no problem writing a traversal yourself, but that there is a mental leap you need to take to understand how Haskell works.
You see, you never return anything in Haskell. Returning is fundamentally an imperative statement. Haskell is a declarative language, which means that writing programs is done by stating facts. That nuance can be discomforting, especially if you've been introduced to programming through learning imperative languages like C, Java, JavaScript, etc. But once you truly understand it, you will see how much more expressive and easy declarative programming is.
Because of its strong mathematical roots, in Haskell facts are stated in the form of equations, i.e. expressions where the = sign literally means the left- and right-hand side are equal (whereas in an imperative language, it would probably mean that you assign a value to a variable -- that does not exist in Haskell).
The program @Haleemur Ali wrote is in 1:1 correspondence with how you would write search using math notation:
search(x, t) = { x == y       if t = Leaf y
               , true         if t = Node l y r and x == y
               , search(x, l) if t = Node l y r and x < y
               , search(x, r) if t = Node l y r and x > y
               }

Indeed many times, at least as a beginner, writing Haskell is just a matter of translation, from math notation to Haskell notation. Another interpretation of Haskell programs is as proofs of theorems. Your search is a theorem saying that "if you have a tree and an integer, you can always tell if the integer is somewhere inside the tree". That's what you are telling the compiler when you write a function signature:
search :: Int -> Tree -> Bool

The compiler will only be happy if you write a proof for that theorem ... you probably guessed that the algorithm above is the proof.
An interesting observation is that the algorithm is almost dictated by the shape of the data type. Imagine you wanted to sum all the values in a tree instead:
sum(t) = { x                   if t = Leaf x
         , x + sum(l) + sum(r) if t = Node l x r
         }

Every time you want to write an algorithm over a binary tree, you will write something like the above. That is fairly mechanical and repetitive. What if later on you expand your program to deal with rose trees? Tries? You don't want to write the same algorithms and take the risk of making a mistake. One would try to come up with a function that walks down a tree and combines its values (using Haskell notation from now on):
walk :: (Int -> b) -> (b -> b -> b) -> Tree -> b
walk f g (Leaf x) = f x
walk f g (Node l x r) =
  let a = walk f g l
      b = walk f g r
  in g (g (f x) a) b

With this function alone, you can write all manners of traversals on trees:
sum t      = walk id (+) t
search x t = walk (== x) (||) t

walk is such a recurring pattern that it has been abstracted. All the data structures that expose the same pattern of recursion are said to be foldable, and the implementation is often so obvious that you can ask the compiler to write it for you, like so:
{-# LANGUAGE DeriveFoldable #-}

data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving (Foldable)

There's even a definition of sum for any foldable data structure.


text:
Q: Как с помощью спецификаций реализовать исключения по 3 связанным таблицам? Есть три таблицы. Эмейлы, рассылки и типы рассылок. Эмейлы один ко многим к рассылкам. Типы рассылок многие ко одному к рассылкам. Нужно через спецификации исключить все эмейлы которые содержат в рассылках хоть один определённый тип рассылок за определенный период. В метод мне приходит просто id типа рассылки и Period. Этот вариант работает если у эмейла только одна рассылка.
private static Specification<Email> isModelExcludeEquals(List<Long> modelId, Period period) {
        return (root, query, criteriaBuilder) -> {
            query.distinct(true);
             return  criteriaBuilder.and(
              criteriaBuilder.lessThan(root.join("mailing",JoinType.LEFT).get("date"), LocalDateTime.now().minus(period)),
              root.join("mailing", JoinType.LEFT).get("model").get("id").in(modelId)));};
    }


text:
Q: Google maps Autocomplete returns Place with null I'm trying to get a Place from the Autocomplete of Google maps and then using its' longitude and latitude but every time I get a Place with the right name and all the other attributes got null in them. Does anyone know how to fix that?
Example of a Place I get:

I/System.out: Place{address=null, addressComponents=null, businessStatus=null, attributions=[], id=ChIJOwg_06VPwokRYv534QaPC8g, latLng=null, name=New York, openingHours=null, phoneNumber=null, photoMetadatas=null, plusCode=null, priceLevel=null, rating=null, types=null, userRatingsTotal=null, utcOffsetMinutes=null, viewport=null, websiteUri=null}

The code [the problem is at "setTargetPlace" (method is down the page)]:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place newTargetPlace = Autocomplete.getPlaceFromIntent(data);
            System.out.println(newTargetPlace);
            dataCenter.setTargetPlace(newTargetPlace);
            dataCenter.createParty();
            String response = dataCenter.getNextResponse();
            System.out.println(response);
            String[] commandAndPara = dataCenter.getCommandFromMsg(response);
            String command = commandAndPara[0];
            String para = commandAndPara[1];
            if(command.equals(DataCenter.MSG_OK)) {
                dataCenter.setPartyCode(para);
                moveToParty();
            }
            else {
                if(command.equals(DataCenter.MSG_FULL)) {
                    System.out.println("FULL");
                }
                else { //ERROR
                    System.out.println("ERROR");
                }
            }
        } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            // TODO: Handle the error.
            Status status = Autocomplete.getStatusFromIntent(data);
            Log.i(TAG, status.getStatusMessage());
        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
        return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The method:
    public void setTargetPlace(Place targetPlace) {
    this.targetPlace = targetPlace;
    this.target = this.targetPlace.getName();
    LatLng targetCords = this.targetPlace.getLatLng();
    this.targetX = targetCords.longitude;
    this.targetY = targetCords.latitude;
}

A: The reason why you are getting the latitude and longitude as null is because you didn't include LAT_LNG as part of the fields you want to retrieve. See the code snippet below to see how you can include it
  val fields = listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG)

So when you create the intent and pass the field variable, and then go ahead to launch it like this
  val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
                .build(requireContext())
            startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE)

it will return with the latitude and longitude in onActivityResult()


text:
Q: Assert function in C++ using cassert function - How can I declare the variables in the test function? #include <iostream>
#include <string>
#include <cassert>

using namespace std;

void test();

void test() { //my attempted test function in order to ensure the program works correctly

string answ1 = "noooooob";
string answ2 = "saaaaaadie";
string answ3 = "trish";

assert(answer(answ1) == "nob"); //this is where i get the compile error that "answer" not declared
assert(answer(answ2) == "sadie");
assert(answer(answ3) == "trish");

cout << "All test cases passed!" << endl;

}

int main() {

    int i = 0;
    string output;
    string input;
    char x;

    getline(cin, input); //input

    output += input[0];
    x = input[0];

    while (i < input.length()) {

        i++;
        if (input [i] != x) {
            output += input[i];
        }
        x = input[i];
    }

    cout << output << endl;

    test();

    return 0;
}

All I'm really asking is how to declare the "answer" variable in the assert function. Maybe I'm doing it completely wrong, and my apologies if so. I'm pretty new to the coding scene. Do I need to make a string that would loop through the current for loop in my main function? Any help is much appreciated.

A: *

*Either you forgot to include a header where you define a class or a function with name answer

*or you don't need it and just comapre strings:

assert(answ1 == "nob"); // operator== kicks in
assert(answ2 == "sadie");
assert(answ3 == "trish");

You should be aware that assert is a debug-only feature. It compiles to nothing in release mode.
You should probably reevaluate your approach for unit testing as the comments suggest (GTest would be fine).


text:
Q: Broken vertical lines in tables I've been trying to recreate a table. How do I achieve this table?
Especially how do you make the vertical border didn't meet like the way shown in picture?

A: If you compile this:
\documentclass[12pt]{article}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{c|cccc} \toprule
    Algorithms&\begin{tabular}{c}JPEG\\(QF=50)\end{tabular}&%
    \begin{tabular}{c}Med-Filter\\$7\times7$\end{tabular}&%
    \begin{tabular}{c}Gau-Filter\\$7\times7$\end{tabular}&%
    \begin{tabular}{c}Gau-Noise\\$\sigma=0.01$\end{tabular}\\ \midrule
    Nakamura \textit{et al.} [12]&$29.51\%$&$8.39\%$&$\mathbf{0.00\%}$&$\mathbf{0.00\%}$\\ \midrule
    Primila \textit{et al.} [13]&$38.35\%$&$26.31\%$&$1.19\%$&$22.75\%$\\ \midrule
    Gugelmann \textit{et al.} [15]&$15.76\%$&$8.86\%$&$3.93\%$&$16.14\%$\\ \midrule
    Proposed &$\mathbf{6.42\%}$&$\mathbf{1.18\%}$&$0.68\%$&$3.37\%$\\ \bottomrule
\end{tabular}
\end{document}

then you will get this:

Note that I don't think that those vertical bars look fine.

A: *

*used is  @José Carlos Santos answer (+1 for retyping table) as OP's  MWE

*for table is used tabularray packages

*omitted are all horizontal lines in table body (that table has more "professional" looks)

\documentclass[border=3.1314592]{standalone}
\usepackage{xcolor}
\usepackage{tabularray}
\UseTblrLibrary{siunitx, varwidth}
\usepackage{etoolbox}
\newrobustcmd\B{\DeclareFontSeriesDefault[rm]{bf}{b}%           %
                \bfseries\color{teal}}                          %

\begin{document}
    \begin{tblr}{hline{1,2,Z} = 1pt,
                 colspec={Q[r,m] | *{4}{Q[c,m,si={detect-weight, % <--
                                                  mode=text,     % <--
                                                  table-format=2.2{\,\%}}]}
                         },
                 measure=vbox
                 }
\SetCell{c} Algorithms
    & {{{JPEG\\(QF$=50)$}}}             & {{{Med-Filter\\$(7\times7)$}}}
    & {{{Gauss-Filter\\$(7\times7)$}}}   & {{{Gauss-Noise\\$(\sigma=0.01)$}}}  \\
%
Nakamura \textit{et al.} \cite{??}
    &   29.51\,\%   &    8.39\,\%   &\B  0.00\,\%   &\B  0.00\,\%    \\
Primila \textit{et al.} \cite{??}
    &   38.35\,\%   &   26.31\,\%   &    1.19\,\%   &   22.75\,\%    \\
Gugelmann \textit{et al.}  \cite{??}
    &   15.76\,\%   &    8.86\,\%   &    3.93\,\%   &   16.14\,\%    \\
Proposed
    &\B  6.41\,\%   &\B  1.18\,\%   &    0.68\,\%   &   3.37\,\%    \\
\end{tblr}
\end{document}

A: If you actually want to use vertical rules with the (horizontal) rules of booktabs (even though this is not at all in the spirit of booktabs, you can try {NiceTabular} of nicematrix.
\documentclass[12pt]{article}
\usepackage{booktabs}
\usepackage{nicematrix}
\begin{document}
\begin{NiceTabular}{c|cccc} \toprule
\Block{2-1}{Algorithms} & JPEG & Med-Filter & Gau-Filter & Gau-Noise \\
& (QF=50) & $7\times7$ & $7\times7$ & $\sigma=0.01$ \\ \midrule
Nakamura \textit{et al.} [12]&$29.51\%$&$8.39\%$&$\mathbf{0.00\%}$&$\mathbf{0.00\%}$\\ \midrule
Primila \textit{et al.} [13]&$38.35\%$&$26.31\%$&$1.19\%$&$22.75\%$\\ \midrule
Gugelmann \textit{et al.} [15]&$15.76\%$&$8.86\%$&$3.93\%$&$16.14\%$\\ \midrule
Proposed &$\mathbf{6.42\%}$&$\mathbf{1.18\%}$&$0.68\%$&$3.37\%$\\ \bottomrule
\end{NiceTabular}
\end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes under the hood).


text:
Q: How do I check if a post is private? What I am looking to do is check if a page is private, give the users the option to register and see the page. Here is what I have now:
<?php
if (have_posts()) :
    /* Print the most as normal */
else :
  if ($post->post_status = 'private')
    {
    /* Print login/register box */
    }
  else
    {
    /* Print page not found message */
    }
endif; ?>

My problem is that it is always falling through and displaying the login box even when the page does not exists. How do I fix this?

A: When a POST is set to private, non-logged in users will receive a 404 message. If you dump the global variable $wp_query,
var_dump($wp_query);

..you will notice that no post_status is present in the parameters returned therefore using the slug (or name parameter of query_vars array for example) we can get the post status of the POST that is trying to be accessed like so,
global $wp_query;
$slug = $wp_query->query_vars['name'];
$status = get_page_by_path($slug, OBJECT, 'post');

if ($status->post_status == "private") {

     //show form

} else {

    //etc...

}

Helpful Codex resources:
http://codex.wordpress.org/Function_Reference/get_page_by_path
Update:
On the basis that you are trying to perform this action for the "PAGE" post type (as per your comments) the above code should change 'post' to 'page' accordingly in get_page_by_path().
Now the reason why it still was not working while using $wp_query->query_vars['name']; is then related to the fact that your page is a CHILD page of another page, in otherwords it has a PARENT.
Because the function we are using is getting our page by its path, it needs to know its full path so the parent page matters. Therefore we must change,
$slug = $wp_query->query_vars['name'];

to
$slug = $wp_query->query['pagename']; //which will show the full path e.g. parent/child

Elaborating further what we are doing is accessing the full path from a different array within the $wp_query and here's an example (sample snippet) of what is $wp_query is actually comprised of when dumping the results
  ["query"]=>  //we are now accessing the ["query"] array instead of ["query_vars"]
  array(2) {
    ["page"]=>
    string(0) ""
    ["pagename"]=> //and this is what need, notice the full path
    string(20) "sample-page/sub-page"
  }
  ["query_vars"]=>
  array(57) {
    ["page"]=>
    int(0)
    ["pagename"]=> //this is what we don't need, no full path contained, will not work
    string(8) "sub-page"
    etc.......

Therefore the modified code in full will look like;
global $wp_query;
$slug = $wp_query->query['pagename']; //from ->query_vars to ->query
$status = get_page_by_path($slug, OBJECT, 'page'); //change to meet your desired post_type

if ($status->post_status == "private") {

     //show form

} else {

    //etc...

}

As Kaiser mentioned you can also use, get_post_status() function to retrieve the post status and that can be done like so,
if (get_post_status($status->ID) == "private") ... etc

A: Was just looking around for this answer myself in 2020 and it seems this is a great way to do it now.
<?php if ( $wp_query->have_posts() ) : ?>
  <?php while ( $wp_query->have_posts() ) : ?>
    <?php $wp_query->the_post(); ?>

    <?php if ( get_post_status ( get_the_ID() ) == 'private' ) { ?>

Private

    <?php } ?>
  <?php endwhile; ?>
<?php endif; ?>


text:
Q: How do I move a table from one sheet to another while rearranging it to a specific format? So I want to take a sheet in excel that looks something like this:

Name
Reason
Justification

Bob
he's cool
rides a bike

George
he's smart
yale

And have it fill out another sheet that looks like:

Person
Comments

Name
Bob

Reason
he's cool

Justification
rides a bike

Person
Comments

Name
George

Reason
he's smart

justification
Yale

(The blank rows included)
Now this isn't quite a pivot table or a transpose, so I am looking for any direction that would help me accomplish this. Unfortunately I don't know the right words to even google for a good answer.
Any help would be greatly appreciated

A: Press F11 and copy the following code into a new module (see how)
Read the code's comments and adjust it to fit your needs
Run in it by pressing F8 key (see how)
Public Sub rearrangeData()

    ' Set a reference to the source sheet
    Dim sourceSheet As Worksheet
    Set sourceSheet = ThisWorkbook.Worksheets("Sheet1")

    ' Set a reference to the target sheet
    Dim targetSheet As Worksheet
    Set targetSheet = ThisWorkbook.Worksheets("Sheet2")

    ' Set a reference to the source range (including headers)
    Dim sourceRange As Range
    Set sourceRange = sourceSheet.Range("A1:C4")

    ' Set a reference to the first cell in target sheet
    Dim targetFirstCell As Range
    Set targetFirstCell = targetSheet.Range("A1")

    ' Set a reference to the source range (excluding headers and just the first column)
    Dim sourceBodyRange As Range
    Set sourceBodyRange = sourceRange.Columns(1).Offset(1, 0).Resize(sourceRange.Rows.Count - 1)

    ' Store source headers in array
    Dim sourceHeaders As Variant
    sourceHeaders = Application.Transpose(sourceRange.Rows(1).Value)

    ' Count number of header cells
    Dim headerCellsCounter As Long
    headerCellsCounter = UBound(sourceHeaders)

    ' Start a counter for source cells
    Dim sourceCellCounter As Long
    sourceCellCounter = 1

    ' Write the data from source to target (loop through cells in first column and refer to other cells by using offset)
    Dim sourceCell As Range
    For Each sourceCell In sourceBodyRange.Cells

        ' Print data headers in target sheet
        targetFirstCell.Offset(sourceCellCounter - 1, 0).Value = "Person"
        targetFirstCell.Offset(sourceCellCounter - 1, 1).Value = "Comments"

        ' Print headers in target sheet
        targetFirstCell.Offset(sourceCellCounter, 0).Resize(headerCellsCounter, 1).Value = sourceHeaders

        ' Print row values
        targetFirstCell.Offset(sourceCellCounter, 1).Resize(headerCellsCounter, 1).Value = Application.Transpose(sourceCell.Resize(1, headerCellsCounter).Value)

        ' Increase rows
        sourceCellCounter = sourceCellCounter + headerCellsCounter + 2

    Next sourceCell

End Sub

Let me know if it works