text:
Q: php array arrangements Hi i convert an collections of string comma separated 0 1 5, 2 3 15, 4 18 20 into an array using this functions as follow:
$openHrs = explode(",", $openHrs['open_hours']);

The end result are as follow:
Array ( [0] => 0 1 5 [1] => 2 3 15 [2] => 4 18 20 )

In this array 0 1 5 means Mon 1 am 5 am and 4 18 20 means Thur 6 pm 8 pm, so first digit represent weekday rest 2 digits represent hours in 24hrs format, now how can i output the existing array into this format?
Array ( [0] => Mon 1 am 5 am [1] => Tue 3 am 3 pm [2] => Thur 6 pm 8 pm )

Thanks

A: I would use array_map to get a filtered version.  You can create dates using mktime() and format them using date().  I believe this should be the solution:
$filtered = array_map(function($incoming) {
    $parts = explode(' ', $incoming);
return
    date('D', mktime(0,0,0,1, $parts[0])) . ' ' .
    date('g a', mktime($parts[1])) . ' ' .
    date('g a', mktime($parts[2]));
}, $openHrs);

A: For the weekday, I suggest:
$weekday=array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');

foreach ($openHours As &$openHour) {
    $foo = explode(' ',$openHour);
    $openHour=$weekday[$foo].' '. // <-- write yourself a nice function to convert 24h to 12h, maybe there's something like this in PHP already?
}

A: Try this:
// This will be used for the week days
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

// Loop through each date
foreach($openHrs as &$temp) {
    // Separate the numbers
    $temp = explode(" ", $temp);

    // Change from a 24 hrs clock to a 12 hrs clock
    $temp[1] = $temp[1] > 12 ? $temp[1] - 12 . 'pm' : $temp[1] . 'am';
    $temp[2] = $temp[2] > 12 ? $temp[2] - 12 . 'pm' : $temp[2] . 'am';

    // Update the element
    $temp = $weekdays[$temp[0]] . ' ' . $temp[1] . ' ' . $temp[2];
}

A: I would explode each Arrayelement again with a whitespace as Delimiter so you have a better array structure:
Array ( [0] => Array(0, 1, 5), [1] => Array(1, 3, 3) [2] => Array(4, 18, 18) )

If you have this structure there are probably several approaches. There might be a solution with date() and timestamps but Iam honestly not to sure about that. An other solution would be. Define another array with the Weekdays.
$weekdays = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

Then you can use the numbers that you have as index for that array to output the correct weekday.
The hours can you output with a little selfmade function ala:
function twentyFourHourToAmPM($number) {
    if ($number > 12) {
         return ($number - 12)." pm";
    } else {
         return $number." am";
    }
 }

Output everything should then work like this:
foreach ($openHrs as $key => $value) {
    echo $weekdays[$value[0]]." ".twentyFourHourToAmPM($value[1])." - ".twentyFourHourToAmPM($value[2]);
}


text:
Q: scala: problems with return statement I'm a little puzzled wth this
The following code compiles ok:
def save: Action[AnyContent] = Action {
  if (1 == 2) {
    BadRequest(toJson("something went wrong"))
  } else {
    Ok(toJson(Feature.find))
  }
}

but if I just add the return statement, I get the following:
def save: Action[AnyContent] = Action {
  if (1 == 2) {
    return BadRequest(toJson("something went wrong"))
  } else {
    return Ok(toJson(Feature.find))
  }
}

[error]  found   : play.api.mvc.SimpleResult[play.api.libs.json.JsValue]
[error]  required: play.api.mvc.Action[play.api.mvc.AnyContent]
[error]       return BadRequest(toJson("something went wrong"))

I thought this two codes would be equivalent...
BTW, Action is a companion object, with an apply method that receives a function of the form: Request[AnyContent] => Result, and that returns an Action[AnyContent]
It seems like with the return statement, the block is returning the result of directly executing BadRequest... and Ok... instead of returning the result of passing the block to the Action object companion...
Am I right?
Note: I'm trying to find a way of getting rid of so many nested map and getOrElse
ps: sorry if the question is a little confuse, I'm confused myself...

A: The method you use is indeed defined in the Action companion object, but it is not the one you describe in your question, but rather:
def apply (block: ⇒ Result): Action[AnyContent]

The argument (block) is an expression of type result, that would be evaluated later on demand (by-name evaluation). It is not a function or a closure, just an expression. So you cannot return from an expression.
BTW: Using return in Scala is a code smell, and should be avoided.

A: These two expressions do very different things indeed!
def save: Action[AnyContent] = Action {
  if (1 == 2) {
    BadRequest(toJson("something went wrong"))
  } else {
    Ok(toJson(Feature.find))
  }
}

Here, save will return the result of Action(Ok(toJson(Feature.find))). Now,
def save: Action[AnyContent] = Action {
  if (1 == 2) {
    return BadRequest(toJson("something went wrong"))
  } else {
    return Ok(toJson(Feature.find))
  }
}

The situation here is more complicated. When return Ok(toJson(Feature.find)) is evaluated, it will return from save! That is, Ok(toJson(Feature.find)) will not be passed to Action. Instead, the execution of the method save will stop and Ok(toJson(Feature.find)) will be returned as its result -- except that this is not the type save is supposed to return, so it gives a type error.
Remember: return returns from the enclosing def.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can solve 'error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054' when pushing files to a github repository? I initialized git and I did git push -u origin master but when I'm trying to push files to my github repository I get these logs in my terminal
Enumerating objects: 118, done.
Counting objects: 100% (118/118), done.
Delta compression using up to 4 threads
Compressing objects: 100% (118/118), done.
Writing objects: 100% (118/118), 2.78 MiB | 2.55 MiB/s, done.
Total 118 (delta 0), reused 0 (delta 0), pack-reused 0
error: RPC failed; curl 56 OpenSSL SSL_read: Connection was reset, errno 10054
fatal: the remote end hung up unexpectedly
fatal: the remote end hung up unexpectedly
Everything up-to-date

And turns out it hasn't push anyhting to repository and my repo is still empty .
How can I solve this error and push to my repo ?

A: Some reasons you know(I am a developer from China), and I also encountered this problem, but I have not solved it after seeing many solutions.
Finally, I replaced a vpn and it took effect. I hope it will help you. This problem may be a network problem.
# this is error
$ git push origin master
Enumerating objects: 494, done.
Counting objects: 100% (494/494), done.
Delta compression using up to 6 threads
Compressing objects: 100% (467/467), done.
Writing objects: 100% (491/491), 23.12 MiB | 112.20 MiB/s, done.
Total 491 (delta 36), reused 1 (delta 0), pack-reused 0
error: RPC failed; curl 56 OpenSSL SSL_read: error:1408F10B:SSL routines:ssl3_get_record:wrong version number, errno 0
fatal: the remote end hung up unexpectedly
fatal: the remote end hung up unexpectedly
Everything up-to-date

# this is ok
$ git push origin master
Enumerating objects: 494, done.
Counting objects: 100% (494/494), done.
Delta compression using up to 6 threads
Compressing objects: 100% (467/467), done.
Writing objects: 100% (491/491), 23.11 MiB | 110.05 MiB/s, done.
Total 491 (delta 37), reused 1 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (37/37), done.

A: I solved the error by building my project again and git init and other steps again and finally it worked

A: Hello I am Chetan(I am student from Pune) from India. According to me this error is coming because of internet connection issue or might your network slow/unstable. You can fix this error by reconnecting your network or upgrading your internet speed. Than push your code again.


text:
Q: lsof reports no files open on external volume but it still cannot be safely unmounted I've searched around here on SX and other places but have not found an approach that gives me any traction on my issue.  I've a volume (used by Time Machine as it happens) on an external Firewire drive.  When the drive is connected, it has 3 volumes. Two out of three eject with no problems but the last one (LaCie) can never be unmounted unless by force (e.g. $ umount -f LaCie).  I can see the drive being accessed almost continuously but I have no idea which process is doing this; and lsof is of limited help.  Mostly it returns no results as below but occasionally it reports that Finder has a directory open on the volume.  But I don't see why that would be a problem as Finder should close any open files or directories when a volume is unmounted.  This problem only arose after I upgraded to Mountain Lion.  I use a cloning tool (SuperDuper!) but have made sure that is not running; and lsof appears to confirm this. How else can I find out what is locking up the volume?  I'm not keen on forcibly ejecting the volume every time I want to disconnect the drive as I surely risk data loss on my main backup disk.
~ $ sudo diskutil unmount /Volumes/LaCie/
Volume LaCie on disk1s1 failed to unmount
~ $ lsof | grep LaCie
~ $ lsof | grep /Volumes/LaCie
~ $

A: If you run lsof without sudo, it can only see what files your processes have open, not those open by system or other users. Use sudo lsof | grep /Volumes/LaCie to get a better idea what's going on.


text:
Q: How to add a button to a chart by a user control in C#? I want to customise a chart in C# and add two buttons to it for zoom in and zoom out. I started adding 2 buttons in Visual Studio toolbox and encountered a problem that once I have added new controls to my project I lost the main feature of the chart in properties like ChartAreas, Legends, Series...
My code is below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace DemoCustomGraph
{
    public partial class customGraph : UserControl
    {
        public customGraph()
        {
            InitializeComponent();
        }

        private void btnScrollOnOff_Click(object sender, EventArgs e)
        {
            if(chart1.ChartAreas["ChartArea1"].CursorX.AutoScroll == false)
            {
                chart1.ChartAreas["ChartArea1"].CursorX.AutoScroll = true;
                btnScrollOnOff.Text = "Scroll On";
            }
            else
            {
                chart1.ChartAreas["ChartArea1"].CursorX.AutoScroll = false;
                btnScrollOnOff.Text = "Scroll Off";
            }
        }
    }
}

What am I doing wrong?


text:
Q: Angular 4 Karma testing error I want to make Karma tests on my Angular 4 application. When I leave the tests simple without importing anything they succeed. For example:
describe('Sample test', () => {
    it('should pass', () => {
        expect(1 + 1).toBe(2);
    });
});

However, when I try to import a class which is in the same folder like so:
import { ApiResponseTimeRepository } from './ApiResponseTimeRepository';

I get an error saying:
Chrome 58.0.3029 (Windows 10 0.0.0) ERROR
  Uncaught SyntaxError: Unexpected token import
  at services/TestRepositories.spec.ts:1

For reference, my class looks like this:
...
imports
...

@Injectable()
export class ApiResponseTimeRepository {
    ...
    code
    ...
}

And here is karma.conf.js :
// Karma configuration
// Generated on Mon Jun 12 2017 14:21:41 GMT+0200 (Central European Daylight Time)

module.exports = function (config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: 'src/app',

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        // list of files / patterns to load in the browser
        files: [
            { pattern: '**/*.spec.ts' }
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['progress'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Chrome'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false,

        // Concurrency level
        // how many browser should be started simultaneous
        concurrency: Infinity,

        mime: {
            'text/x-typescript': ['ts', 'tsx']
        }
    });
};


text:
Q: How to construct GLMM with differing random effect variance structure by group? I have a longitudinal dataset with a normally distributed outcome variable, a normally distributed predictor variable, and a binary grouping variable. I am trying to construct a GLMM with differing random effect variance structures for group 1 and group 0. The code that I am using is
library(lme4)
dat$group1 = ifelse(dat$group==0, 1, 0)
dat$group0 = ifelse(dat$group==1, 1, 0)
mod<-lmer(response~predictor + (0+group1|id) + (0+group0|id), data= dat)
summary(mod)

The output that I get is:
 Groups             Name     Variance Std.Dev.
 visit_individual   group0    466.81   21.606
 visit_individual.1 group1    676.92   26.018
 Residual                     352.60   18.778

Does this look right? What mathematical model does this correspond to? My interpretation of the output is that variance for group0 describes, on average, how much the outcome bounces around from group 0 participant to group 0 participant and the variance for group1 describes, on average, how much the outcome bounces around from group 1 participant to group 1 participant. What does the residual variance describe here?


text:
Q: Can't display input value Trying to take user input and print calculated values
//html

 Input Empty Total

    <ion-item>
        <ion-input placeholder="Enter Empties.." type="number" name="emptySeats" [(ngModel)]="emptySeats"> </ion-input>
    </ion-item>

 {{arenaCurrent}}

//js
arenaTotal: number = 1000;
emptySeats: number;
arenaCurrent: number;

constructor() {
    this.arenaCurrent = this.arenaTotal - this.emptySeats;
 }

arenaCurrent will print 1000 - emptySeats (user input)

A: You're doing the math only once in the constructor, you probably want to make it a property. This way the template can remain unchanged but the value will update whenever either arenaTotal or emptySeats changes.
arenaTotal: number = 1000;
emptySeats: number;

get arenaCurrent() {
    return this.arenaTotal - this.emptySeats;
}

constructor() {}

A: Use (ionChange) to display the result.

 Input Empty Total

      <ion-item>
      <ion-input (ionChange)="change()" placeholder="Enter Empties.." type="number" name="emptySeats"[(ngModel)]="emptySeats"> </ion-input>
        </ion-item>

 {{arenaCurrent}}

In javascript call the function change.
arenaTotal: number = 1000;
emptySeats: number;
arenaCurrent: number;
constructor() {}
change(){
    this.arenaCurrent = this.arenaTotal - this.emptySeats;
}

The above will update the result instantly when user inputs value in ion-input.

A: You can try something like this
#emptySeats="ngModel"  in you ion-input tag

 Input Empty Total

    <ion-item>
        <ion-input placeholder="Enter Empties.." type="number" name="emptySeats" [(ngModel)]="emptySeats" #emptySeats="ngModel"> </ion-input>
    </ion-item>

 {{arenaCurrent}}


text:
Q: WP7 + Live SDK - file overwrite doesn't work I'm trying to upload a file to SkyDrive using Live SDK. It works well except overwriting existing files. Whenever I try to overwrite an existing file I get the error message "The resource file_name already exists.", although I use the Overwrite option:
_liveClient.UploadAsync(
                   FolderId,
                   Filename,
                   MemoryStream,
                   OverwriteOption.Overwrite);

Is there anything else I need to set?
I could try handling the error by deleting the file and uploading again but that's obviously not the cleanest way to do that.

A: Microsoft admitted here that it's a bug that they are aware of . It will be fixed in the next release.
Also, as per answer in that link, the overloaded method works fine:
_liveClient.UploadAsync(
               FolderId,
               Filename,
               MemoryStream,
               OverwriteOption.Overwrite,
               null);

A: When your upload a file, and a file with the same name already exists in the same location in SkyDrive, the default behavior is for SkyDrive to overwrite the existing file. You are not required to specify OverwriteOption.
From my point of view, there is a problem else where. Try to use another folder and show a little more code.


text:
Q: Talk to/with me I just want to know what I've done since you suddenly don't want to talk to me anymore.
Is "...talk to me..." natural if my intention with the sentence is this: "...since you suddenly don't want to have a conversation with me anymore." and not "...since you suddenly don't want to say a word to me anymore." Or should I use "with" instead?

A: Broadly, both are interchangeable. However, if you still want to dig it deeper, I'd give my choice/preference.

talk to someone

is more kind of monologue where you speak more and whom you are talking to listens more.
On the other hand,

talk with someone

is a kind of dialogue between two where both almost equally participate.
To elaborate, let me think of an example -
I'm a team leader and if A from my team comes and 'complains' about B, I may say,

Okay, I'll talk to B.

What I mean is I'll raise the issue and probably instruct B not to do such things in future. Mostly, I'll speak and B will listen.
However, if my boss calls me and asks to implement some new strategies across the teams, I'd probably say,

Okay, I'll speak with my team members.

It'll have a fruitful discussion probably each one of my team will participate and give their inputs.
But, as I said earlier, largely, both are interchangeable with no big difference in most of the cases.


text:
Q: Calculations within Matrix Tikz How can I tell tikz to make a calculation within a matrix. The same syntax outside does not work within as is shown in this MWE:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,calc}
\usetikzlibrary{intersections}

\begin{document}
\begin{center}
\begin{tikzpicture}[scale=.8, declare function={f(\x)=1/ln(2)*ln(\x);}]
\draw[step=1.0,gray,thin,dotted] (-.5,-3) grid (8.5,4);
\draw [-latex] (-.5,0) -- (8.5,0) node (xaxis) [below] {$x$};
\draw [-latex] (0,-3.5) -- (0,4) node [left] {$y$};
   \foreach \x/\xtext in {1/1,2/2,3/3,4/4,5/5,6/6}
   \draw[xshift=\x cm] (0pt,3pt) -- (0pt,0pt)
     node[below=2pt,fill=white,font=\normalsize]
  {$\xtext$};
   \foreach \y/\ytext in {-2/-2,-1/-1, 1/1,2/2,3/3}
     \draw[yshift=\y cm] (2pt,0pt) -- (-2pt,0pt)
    node[left,fill=white,font=\normalsize]
    {$\ytext$};
\draw[name path=curve,domain=.17:8.5,samples=200,variable=\x,red,<->,thick]
   plot ({\x},{f(\x)});
 \draw[fill=red,red] (1,{f(1)}) circle (3pt) node[] {};
 \draw[fill=red,red] (2,{f(2)}) circle (3pt) node[] {};
 \draw[fill=red,red] (4,{f(4)}) circle (3pt) node[] {};
 \draw[fill=red,red] (8,{f(8)}) circle (3pt) node[] {};
 \draw[fill=red,red] (.5,{f(.5)}) circle (3pt) ;
 \draw[fill=red,red] (.25,{f(.25)}) circle (3pt) node[] {$$};
 \node at (3.5,3.5) [text=red,fill=white] {$f(x)=\log_{2} x,\ \text{or}\ 2^{y}=x$};
 \matrix[matrix of math nodes,nodes={align=center,inner sep=3pt,
  text height=1.5ex,text depth=.25ex,draw=gray!40,ultra thin},draw,inner
   sep=0pt,ampersand replacement=\&] (mat1)
    at (-5,0){
   |[fill=green!40!gray,text width=15mm]| x,\ \text{or}\ 2^{y}  \& |
  [fill=green!40!gray,text width=11mm]| f(x) \\
                 |[text width=15mm]|   1                      \& |[text
     width=11mm]|  0\\
                                     |[text width=15mm]|   2
  \& |[text width=11mm]|  1\\
                                     |[text width=15mm]|   4
  \& |[text width=11mm]|  2\\
                                     |[text width=15mm]|   8
    \& |[text width=11mm]|  {f(3)}3\\
                                     |[text width=15mm]|   \frac{1}{2}
  \& |[text width=11mm]|  -1\\
                                     |[text width=15mm]|   \frac{1}{4}
  \& |[text width=11mm]|  -2\\
                                    };
\end{tikzpicture}
\end{center}
\end{document}

This outputs

A: I'll be happy to remove this if you want to remove your question, or feel it is not appropriate.
\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix,calc}
\usetikzlibrary{intersections}

\begin{document}
\begin{center}
\begin{tikzpicture}[scale=.8, declare function={f(\x)=1/ln(2)*ln(\x);}]
\draw[step=1.0,gray,thin,dotted] (-.5,-3) grid (8.5,4);
\draw [-latex] (-.5,0) -- (8.5,0) node (xaxis) [below] {$x$};
\draw [-latex] (0,-3.5) -- (0,4) node [left] {$y$};
   \foreach \x/\xtext in {1/1,2/2,3/3,4/4,5/5,6/6}
   \draw[xshift=\x cm] (0pt,3pt) -- (0pt,0pt)
     node[below=2pt,fill=white,font=\normalsize]
  {$\xtext$};
   \foreach \y/\ytext in {-2/-2,-1/-1, 1/1,2/2,3/3}
     \draw[yshift=\y cm] (2pt,0pt) -- (-2pt,0pt)
    node[left,fill=white,font=\normalsize]
    {$\ytext$};
\draw[name path=curve,domain=.17:8.5,samples=200,variable=\x,red,<->,thick]
   plot ({\x},{f(\x)});
 \draw[fill=red,red] (1,{f(1)}) circle (3pt) node[] {};
 \draw[fill=red,red] (2,{f(2)}) circle (3pt) node[] {};
 \draw[fill=red,red] (4,{f(4)}) circle (3pt) node[] {};
 \draw[fill=red,red] (8,{f(8)}) circle (3pt) node[] {};
 \draw[fill=red,red] (.5,{f(.5)}) circle (3pt) ;
 \draw[fill=red,red] (.25,{f(.25)}) circle (3pt) node[] {$$};
 \node at (3.5,3.5) [text=red,fill=white] {$f(x)=\log_{2} x,\ \text{or}\ 2^{y}=x$};
 \matrix[matrix of math nodes,nodes={align=center,inner sep=3pt,
  text height=1.5ex,text depth=.25ex,draw=gray!40,ultra thin},draw,inner
   sep=0pt,ampersand replacement=\&] (mat1)
    at (-5,0){
   |[fill=green!40!gray,text width=15mm]| x,\ \text{or}\ 2^{y}  \& |
  [fill=green!40!gray,text width=11mm]| f(x) \\
                 |[text width=15mm]|   1                      \& |[text
     width=11mm]|  0\\
                                     |[text width=15mm]|   2
  \& |[text width=11mm]|  1\\
                                     |[text width=15mm]|   4
  \& |[text width=11mm]|  2\\
                                     |[text width=15mm]|   8
    \& |[text width=11mm]|
    {\pgfmathparse{f(8)}\pgfmathprintnumber{\pgfmathresult}}\\
                                     |[text width=15mm]|   \frac{1}{2}
  \& |[text width=11mm]|  -1\\
                                     |[text width=15mm]|   \frac{1}{4}
  \& |[text width=11mm]|  -2\\
                                    };
\end{tikzpicture}
\end{center}
\end{document}


text:
Q: How to embed Electron in a Windows window with a HWND Having the HWND of window in Microsoft Windows, how can I start a BrowserWindow embedded in it effectively embedding my app?
I'm writing a screen saver for Windows and for configuration and preview I get passed the HWND of the parent window to embed my program in it.


text:
Q: Adding single quotes in batch to a SQL script embedded in Pandas I am using the Pandas library in Python with the Spyder application to import data from a SQL server. The import requires the following construct:
conn=pyodbc.connect('Driver=SQL Server;'
'Server=WB-SB-SQL-3,1542;'
'Database=WQI;'
'Trusted_Connection=yes;')

Finding2021=pd.read_sql_query(' SELECT'
' ID, '
' SYSTEM_NO, '
' SOURCE_NO, '
' SAMP_DATETIME, '
' STORE_NUM '
' FROM WQI.DBO.Finding '
' WHERE SAMP_DATE >= \'20110101\''
,conn)

I am adding the single quote and space to both sides of each line of the embedded SQL script, manually (see below).
'

Is there a way to add the single quote and space in bulk--let's say I have a 100-line SQL script--I don't want to have to type the single quotes 200 times. I know I could use Excel to concatenate the strings, but I was wondering if there's a built-in command using the Spyder application. Some programs like SSMS allow you to comment or uncomment blocks of code with a single click for example.


text:
Q: Using table of integrals to solve $\int y \sqrt{6+12y-36y^2}dy$ I'm supposed to use a table of integrals to solve the below equation:
$$\int y \sqrt{6+12y-36y^2}dy$$
I'm having trouble identifying the form to use because I guess my weakness in algebra shows in my inability to compete the square of the square root function.
Here is how I tried to complete the square (first rewriting the equation and factoring out a -12):
$$6-12(-y+3y^2)$$
And I assume the next step is dividing my $b$ by $2$ and then squaring the number which would give:
$$6-12(\frac{1}{4}-\frac{1}{2}y+3y^2)$$
But I don't think this is right and I don't know how to get it in the form of $\sqrt{a^2-u^2}$

A: As $6+12y-36y^2=7-(6y-1)^2,$
Put $6y-1=\sqrt7\sin\theta$
$$\int y\sqrt{6+12y-36y^2}dy=\frac{\sqrt7\sin\theta+1}6\sqrt7\cos\theta\frac{\sqrt7\cos\theta}6 d\theta$$
$$=\frac7{36}\int(\sqrt7\sin\theta+1)\cos^2\theta  d\theta$$
$$=\frac7{36}\sqrt7\int \sin\theta \cos^2\theta  d\theta+\frac7{36}\int \cos^2\theta  d\theta$$
For the first part, put $\cos\theta=u$
For the second, $$\int \cos^2\theta  d\theta=\frac{(1+\cos2\theta)}2 d\theta=\frac{\theta}2+\frac{\sin2\theta}4$$


text:
Q: Scala: How to always make certain utils available to sub packages? All my code is under package com.company.project. In almost all of my files, I end up importing some common things like import scala.util.{Failure, Try, Success} and import scala.util.control.NonFatal etc. Is it possible to somehow setup a package object in such a way that all these utils are always available to all sub packages in com.company.project.sub (kind of my own project level Predef)?

A: Simply create a package object with type aliases:
package com.company.project

import scala.util

package object sub {
  type Failure = util.Failure
  type Try = util.Try
  type Success = util.Success
  type NonFatal = util.control.NonFatal
}


text:
Q: How to find global extremum when constraint isn't compact set Sometimes, the constraint is not a compact set. As a result, the local minimum may not be global.
For example, $ f=x^2+y^3$ subject to constraint $ x+y=4/3$.
Using Lagrange multiplier method, I calculated local minimum at $(x,y)=(\frac23,\frac23)$. But I don't know what to do next.
I cheated a bit and looked at Wolfram Alpha's plot that shows that there is no global minimum subject to the constraint.
http://www.wolframalpha.com/input/?i=min+x^2+y^3+such+that+{x+y=4/3}
Is there any way to get this result (no global minima) without graphing?

A: Sure. Find points where the values of $f$ are smaller than the values of $f$ at all the critical points. (For some functions, it's not so clear from a computer graph, unless you know what you're looking for.)

A: Simply substituting $x=\frac43-y$ gives you a cubic function $\mathbb R\to\mathbb R$, $y\mapsto y^3+(\frac43-y)^2$. This is  has no global extrema as it is onto.


text:
Q: JS - How can I prevent that if the translate isn't finished yet, I can't press the button? When I click the Slider Button, the transform of the Slider changes. This animation lasts 1 second. How can I prevent, that if the translate isn't finished yet, I can't press the button?
// Slider Button Navigation
sliderBtnLeft.addEventListener("click", () => {

    // Container Width
    x = slider.clientWidth;

    // Get the Slider TranslateX value
    tempTranslateX = getTranslateX(slider);

    // Check for first Slider Element
    if(tempTranslateX >= 0)
    {
        // Set translate, to show last item
        slider.style.transform = "translateX(-" + (amountElems - 1) * x + "px)";
    }
    else
    {
        // Set tranlate, to show next (left) item
        tempTranslateX += x;
        slider.style.transform = "translateX(" + tempTranslateX + "px)";
    }
});

// Function to get Translate Value
function getTranslateX(elem) {
    let style = window.getComputedStyle(elem);
    let matrix = new WebKitCSSMatrix(style.transform);
    return matrix.m41;
}

A: You can disable the button by default and You can make use of transitionend event to enable it once the transition is completed. requestAnimationFrame would work too.


text:
Q: Question about the logic of a simple C++ function (is_palindrome) The function below is supposed to check if the input parameter is a palindrome and return true/false.
I know that there is a mistake in the code, it's supposed to be: int i = text.size() - 1;
Question: if I don't add "-1" and print out text and textR, both of them would be "madam" and in my understanding when I check (text == textR) it's supposed to be true. It does return false, however.
Could someone please explain what am I missing?
I understand that it has something to do with string.size() and string contents not being the same thing and that a string index starts with a 0... I still don't fully get why text != textR.
#include <iostream>
#include <bits/stdc++.h>

// Define is_palindrome() here:

bool is_palindrome(std::string text) {

  // create an empty string to store a reversed version of text
  std::string textR;

// iterating backward over text and adding each character to textR
  for (int i = text.size(); i >= 0; i--) {
    textR.push_back(text[i]);
  }

std::cout << text << std::endl;
std::cout << textR << std::endl;

  // check if the reversed text is the same as text; return true or false

  if (text == textR) {
    return true;
  } else {
    return false;
  }
}

int main() {

  std::cout << is_palindrome("madam") << "\n";

}

A: text[text.size()] is '\0' (nul character) which is not printable.
so TextR is "\0madam" instead of expected "madam".

A: Answer is given and accepted. Good.
Additionally, I would like to give the answer for a more or less standard solution for this function.
This is a typical one liner:
#include <iostream>
#include <string>

bool is_palindrome(const std::string& s) { return s == std::string(s.crbegin(), s.crend()); };

int main()
{
    std::cout << "Is HannaH a palindrome?: " << is_palindrome("HannaH") << "\n";

    return 0;
}


text:
Q: Function to append strings returning pointer/cast error I'm trying to create a function that takes two input strings, dest and src, and appends the src string to the dest string.
Below is the current function I have. However, when I try to use it, I
get an error stating "returning 'char' from a function without a cast." I understand that my error involves the return statement and how I'm using it as a pointer, but I'm unsure how to fix it.
char* strcat(char dest[], char src[]) {
    int destL = lenstr(dest);
    int srcL = lenstr(src);
    char result[destL + srcL];

    int i;
    for(i = 0; i < destL; i++){
        result[i] = dest[i];
    }

    for(i = destL; i < destL+srcL; i++){
        result[i] = src[i-destL];
    }

    return *result;
}

The lenstr function is:
int lenstr(char* s) {
    int len = 0;
    while(s[len++] != '\0');
    return len-1;
}

A: You cannot return a locally declared array. Well you can, but the data may be overwritten at any time since it is no longer valid.
What you need to do is something like this:
char* strcat(char dest[], char src[]) {
    char * result = malloc((lenstr(dest)+lenstr(src)+1) * sizeof *result);

    // Code to copy data

    return result;
}

Note that +1 is important to make room for the \0 terminator.

A:
However, when I try to use it, I get an error stating "returning 'char' from a function without a cast."

This error simply indicates that your return value doesn't match the function declaration. In your function declaration, you have mentioned that it returns a char *. However, in your actual return statement, you are returning *result which is a dereferenced char pointer i.e. a char.
The second problem in your code is that you are returning an array from the function. Memory allocated using an array in a method becomes unavailable to the caller method. You need to create memory on heap and return a pointer to it and then let the caller free up the memory after usage.
Checkout the following working code:
char* strcat1(char dest[], char src[]) {
    int destL = lenstr(dest);
    int srcL = lenstr(src);

    char * result = malloc(sizeof(char) * (destL + srcL));

    int i;
    for(i = 0; i < destL; i++){
        result[i] = dest[i];
    }

    for(i = destL; i < destL+srcL; i++){
        result[i] = src[i-destL];
    }

    return result;
}

Please make sure the caller frees up the result as shown below:
char * result = strcat1("hi", "ho");
printf(result);
free(result);


text:
Q: How to implement dynamic theme in django app? My app is multitenant, with many groups with unique site like group1.myapp.com, group2.myapp.com etc. Requirement is that user should be able to select different theme for a particular group.
I don't seem to come up with good approach to do it. Anyone has done before? Would be really grateful to get some inputs.

A: If you haven't started yet, you can consider using bootstrap for having switchable css for themes.
For example, here's the demo site for Mezzanine which uses switchable themes by saving the theme name in a cookie.
Here's the relevant part in the demo code which handles this:
https://github.com/stephenmcd/mezzanine.jupo.org/blob/master/templates/base.html#L28

A: I solved it. Basically, I am allowing users to select color and background which are basic theme component and save them in db. Then I make theme from the variables, using LESS CSS which works great. I use NodeJS for LESS to CSS server-side compilation.
Python/Django part of the solution is open sourced on github as Django dynamic-theme. Go through the code if you want to implement something similar.


text:
Q: Decorator works for Function but not Class Need a bit of help correcting a decorator for unittest. I'm not sure how to meet the requirements of unit test.  The idea of this decorator is to mark the test as an expectedFailure IF True is passed in.  Otherwise allow the test to simply run.  This decorator works for test functions but doesn't work for class definitions
import unittest

def expectedFailureIf(expFailure):
    if expFailure:
        return unittest.expectedFailure
    return lambda func: func

@expectedFailureIf(GetCurrentOS() == kPlatMac)  # Fails on Class
class someClass(unittest.TestCase):
    #@expectedFailureIf(GetCurrentOS() == kPlatMac) # Works on Function
    def test_sometestA(self):
        assert True

    def test_sometestB(self):
        assert False

The error that I'm getting is test_sometest() takes exactly 1 argument.  Removing the decorator allows the test to run.  Moving the decorator to top of function allows the test to run.
History... One of my platforms works fine and the other platform does not.  I want to allow one platform to run all the tests while the other platform will be marked as expected failures.  Of course I do not want to use skip or skip if.  Since that won't allow the valid platform to run.  Marking them as expected failure will also not work since one platform will return unexpected success.  With the expectedFailureIf() in place each platform will correctly report and once things are fixed these tests will report as unexpected success.  Which will notify ME when things are fixed.  For me... this seems a better outcome.

A: On Python 3 your code is working fine.  The implementation of unittest.expectedFailure is better there, and it works correctly when decorating on either classes or functions.
On Python 2, the unittest.expectedFailure is only designed to work on functions.
Here's a replacement which works on Python 2.
import inspect
import types
import unittest

def expectedFailureIf(condition):
    if callable(condition):
        condition = condition()
    if not condition:
        # return identity function for no-op
        return lambda x: x
    def patch(func_or_class):
        if isinstance(func_or_class, types.FunctionType):
            return unittest.expectedFailure(func_or_class)
        for name, member in inspect.getmembers(func_or_class):
            if name.startswith('test') and isinstance(member, types.MethodType):
                setattr(func_or_class, name, unittest.expectedFailure(member))
        return func_or_class
    return patch

@expectedFailureIf(True)
class MyTest(unittest.TestCase):

    def test_that_passes(self):
        assert 2 + 2 == 4

    def test_that_fails(self):
        assert 2 + 2 == 5

if __name__ == "__main__":
    unittest.main(verbosity=2)

Result:
test_that_fails (__main__.MyTest) ... expected failure
test_that_passes (__main__.MyTest) ... unexpected success

----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK (expected failures=1, unexpected successes=1)

Warning!
The fact that an unexpected success doesn't fail the test run is a bug in Python! It was addressed back in Jan 2014 (Python 3.4), but this bugfix was not merged into 2.7's branch due to backwards compatibility concerns (see the comments on issue20165).  So, that's now a Python 2 "feature", unfortunately.
If this is a deal-breaker to you, consider upgrading to a more recent Python version and/or using a better test runner.


text:
Q: React.js and Jasmine Spies Using basic test-utils and jasmine for unit testing.
How do you spy on a function inside a react component?
test.js:
class Test extends React.Component {
  handleClick() {
    // Do something
  }

  render() {
    return (

Test

    );
  }
}

const React = require('react-with-addons');
const RequireJsTest = require('requirejs-test');
const Utils = React.addons.TestUtils;
const Test = require('./test');

describe('test', () => {
  it('should test', function() {
    const test = Utils.renderIntoDocument(<Test/>);
    const el = Utils.findRenderedDOMComponentWithClass(test, 'test-class');
    spyOn(test, 'handleClick');
    Utils.Simulate.click(el);

    expect(test.handleClick).toHaveBeenCalled();
  });
});

I'm getting the following error:
Expected spy handleClick to have been called. (1)

Any ideas? Thanks!

A: To be honest, I haven't tested react apps yet, but try the method (the last test in describe block), which I've just found in enzyme readme doc.
I think you should spy on component class prototype method before rendering component:
spyOn(Test.prototype, 'handleClick');
// and then
expect(Test.prototype.handleClick).toHaveBeenCalled();


text:
Q: How to get method URL programmatically in SpringBoot test? I would like to test my controller with
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MyTest {

    @LocalServerPort
    int port;

    @Autowired
    TestRestTemplate rest;

    String myUrl = ...;

    @Test
    public void testSequence() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String requesString = ...
        HttpEntity<String> request = new HttpEntity<>( requesString, headers );
        String response = rest.postForObject(myUrl, request, String.class);

here I need to hardcode myUlr with something like
 String.format("http://localhost:%d/my/endpint/path", port);

where my/endpint/path depends on annotations I applied to my controller class and it's methods.
But can I derive it programmatically having class name and method name?

A: Of course you could extract the @RequestMapping path from your REST controller using reflection and combine it with the path from a handler method in it, but it's really not worth the hassle and it is much easier to put them into public constants and use those to construct the resulting url in your test.
Also, constructing an url before testing it is actually a part of the test - you check that your api url looks like you expect it to.


text:
Q: How do I dynamically reference variables in jMeter HTTP Requests? I'm setting up a test that needs to first read some json data and then build other http requests.
So I have some json that I retrieve first that is something like this:
Store Array
  -- Teams Array (Each store has some teams)
    -- Members (Each team has some members)

I created some BSF code to parse this out:
vars.put("team_id_" + teamIndx,teamArray.get(teamIndx).get("id").asString());
vars.put("associate_ids_" + teamIndx, memberIdList);

This works and I see the data in the debug sampler:
team_id_0=ABC
team_id_1=XYZ
associate_ids_0=92988,
associate_ids_1=105093,82959,95913,92256,31032,77896,

Now, I need to setup a loop controller (loop count = ${countOfTeams}) where I will need to pass in team_id_indx and associate_id_indx in the url:
&teamId=${team_id_<index>}&associateIds=${associate_ids_<index>}

However, I have tried several things (doing a counter, an __Eval etc..) but I cannot use a dynamic variable name to reference something that was setup by BSF.

A: Please try something like below;-
for(int i=1;i<=count;i++){
vars.get("paramname_" + i)
}

Also, it is recommended to use groovy over beanshell for performance.
Kindly check if this helps.


text:
Q: Android gridView with Constant first item Initially i start my screen with gridview with one item. click on the item will take me to another screen where i enter image and title and press ok will come to the first screen where the grid view is update , but i wan the first item to stay even after entering many items.
Tried with below adapter but it is not working
public class CustomBaseAdapter extends BaseAdapter {
    Context context;
    List<RowItem> rowItems;

    public CustomBaseAdapter(Context context, List<RowItem> items) {
        this.context = context;
        this.rowItems = items;
    }

    /*private view holder class*/
    private class ViewHolder {
        ImageView imageView;
        TextView txtTitle;

    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;

        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

            if (convertView == null) {

                convertView = mInflater.inflate(R.layout.addcompany_layout,null);
                holder = new ViewHolder();

                holder.txtTitle = (TextView) convertView.findViewById(R.id.location);
                holder.imageView = (ImageView) convertView.findViewById(R.id.addbutton);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

        if(position!=0){
            RowItem rowItem = rowItems.get(position);
            Toast.makeText(context, rowItem.getCompany_name(), Toast.LENGTH_SHORT).show();
            holder.txtTitle.setText(rowItem.getCompany_name());
            holder.imageView.setImageBitmap(BitmapFactory
                    .decodeFile(rowItem.getImagepath()));
        }

                return convertView;
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public int getCount() {
        return rowItems.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}

A: From what you've posted I don't see any method to update your adapter. So it boils down to what you pass into constructor.
If you don't want to manage this outside of your adapter class, you can create your first RowItem in constructor, put it on the first position, then populate the rest.
public CustomBaseAdapter(Context context, List<RowItem> items) {
    this.context = context;
    // Construct your first item
    // Alternatively you can pass it as a param
    this.firstItem = new RowItem();

    this.rowItems = items;
    this.rowItems.add(0, firstItem);
}


text:
Q: JavaScripts not working in mac OS, iphone I wrote js code for wordpress website, and unfortunetly it is not working in safari and every browser in mac system. I don't know why. My scripts should react for 'click' event and charge input value. In windows evrything is ok, but in safari, mac, iphone not.
I'm not sure where is a error, in safari console i can't see any mistake. My code is a little long, so if you want help me, i can send you link for my website.
<button id="checkBank" class="checkNumberButton" type="submit">Sprawdź</button>

document.querySelector("#checkBank").addEventListener("click", function () {my code here}

Where i can find information about difference between apple system and windows?

A: You forgot to close addEventListener. This should work (works on my Mac)
document.querySelector("#checkBank").addEventListener("click", function () {alert("test")});

https://jsfiddle.net/hpeyr870/


text:
Q: postgreSQL mysql oracle differences I'm having to start building the architecture for a database project but i really don't know the differences between the engines.
Anyone can explain whats the pros and bads of each of these three engines? We'll have to choose one of them and the only thing I actually know about them is this:

*

*Mysql & Postgres:

*

*Are free but not so good as oracle

*Mysql as security problems (is this true?)

*Oracle:

*

*Best data base engine in the world

*Expensive

Can someone clear out other differences between them? This is a medium/large (we're thinking of around some 100 to 200 tables) project with low budget, what would you choose? And with a higher budget?

A: The differences between different SQL Implementations are big, at least under the hood. This boards wont suffice to count them all.
If you have to ask, you also have to ask yourself whether you are in the position to reach a valid and founded decision on the matter.
A comparison von MYSQL and Postgres can be found here
Note that Oracle offers also an Express (XE) edition, reduced in features, but free to use.
Also, if you have little knowledge to start with, you will have to learn yourself, I would just choose any one, and start learning by using it.

A: See the comparison tables on wikipedia: http://en.wikipedia.org/wiki/Comparison_of_object-relational_database_management_systems && http://en.wikipedia.org/wiki/Comparison_of_relational_database_management_systems
Oracle may or may not be the best. It's expensive, but that doesn't mean best.
Have you looked at DB2? Sybase? Teradata? MS SQL?

A: I think that for low budget scenarios Oracle is out of the question.
100-200 tables is not big and generally the amount of tables in a schema is not a scale measure. Dataset and throughput is.
You can have a look at http://www.mysqlperformanceblog.com/ (and their superb book) to see how MySQL can handle huge deployments.
Generally nowadays most RDBMSes can do almost anything that you'd need in a very serious application.

A: A few years ago I had to write a translation engine; you feed it one set of sql and it translates to the dialect of the currently connected engine. My engine works on Postgres (AKA PostgreSql), Ingres, DB2, Informix, Sybase, and Oracle - oh, and ANTS. Frankly, Oracle is my least favorite (more on that below)... Unfortunately for you, mySql and SQL Server are not on the list (at the time neither was considered a serious RDBMS - but times do change).
Without regard to the quality or performance of the engine - and ease of making and restoring backups - here are the primary areas of difference:

*

*datatypes

*limits

*invalids

*reserved words

*null semantics (see below)

*quotation semantics (single quote ', double quote ", or either)

*statement completion semantics

*function semantics

*date handling (including constant keywords like 'now' and input / output function formats)

*whether inline comments are permitted

*maximum attribute lengths

*maximum number of attributes

*connection semantics / security paradigm.

Without boring you on all the conversion data, here's a sample for one datatype, lvarchar:
oracle=varchar(%x) sybase=text db2="long varchar" informix=lvarchar postgres=varchar(%x) ants=varchar(%x) ingres=varchar(%x,%y)
The biggest deal of all, in my view, is null handling; Oracle SILENTLY converts blank input strings to null values. ...Somewhere, a LONG time ago, I read a writeup someone had done about "The Seventeen Meanings of Null" or some such and the real point is that nulls are very valuable and the distinction between a null string and an empty string is useful and non-trivial! I think Oracle made a huge mistake on this one; none of the others have this behavior (that I've ever seen).
My second least favorite was ANTS because unlike all the others, they ENFORCED the silly rules for perfect syntax that absolutely no one else does and while they may be the only DB company to provide perfect adherence to the standard, they are also a royal pain in the butt to write code for.
Far and away my favorite is Postgres; it's very fast in _real_world_ situations, has great support, and is open source / free.


text:
Q: Split list for punctuation I have a given title
I want to  start splitting on whitespace and punctuation of a list, so that no word in the resulting list contains any whitespace or punctuation character.
Ex: the word "Joe's" gets split into "Joe" and "s"
'ad sf' gets split into 'ad' and 'sf'
Starting:
['Toms', 'ad  sf', "Joe's"]

Ending:
    ['Toms', 'ad', 'sf' , 'Joe', 's']

I have tried regex, split, but there's not an easy and concise way. Can anyone think of a better way?

A: You can use re.split:
import re
s = ['Toms', 'ad  sf', "Joe's"]
final_result = [j for i in s for j in re.split(r'\W+', i)]

Output:
['Toms', 'ad', 'sf', 'Joe', 's']

A: Split each item and join the pieces:
from itertools import chain
mylist = ['Toms', 'ad  sf', "Joe's"]
list(chain(*[re.split("\W+", item) for item in mylist]))
#['Toms', 'ad', 'sf', 'Joe', 's']

Here's a "clean" functional solution:
list(chain(*map(lambda item: re.split("\W+", item), mylist)))
#['Toms', 'ad', 'sf', 'Joe', 's']

A: There is no builtin way to achieve what you want, but here is the most concise way I could think of using map.
import re

words = ['Toms', 'ad  sf', "Joe's"]

sum(map(re.compile(r'\W+').split, words), [])

# Output: ['Toms', 'ad', 'sf', 'Joe', 's']


text:
Q: Cannot compile MEX LAPACK example Summary
I am trying to write some MEX files that use LAPACK, and I thought I'd start by looking through the examples provided by MathWorks.
However, I am having some trouble compiling them. After copying the matrixDivide.c example from [MATLAB root]/extern/examples/refbook into a working directory, I tried to build a mex file, but it failed with error undefined reference to `dgesv_' (where dgesv is the name of the LAPACK routine being called).
I was able to build a different mex example (timestwo.c) that doesn't use LAPACK.
So what's going on? What's the deal with the trailing underscore? What about this memcpy warning?
More info
I think this is fairly similar to the issues encountered by this user:
  How can I use CLAPACK,BLAS or LAPACK in a mex file?
I've tried this with MATLAB R2013b and R2014b. I am running on 64-bit Linux (RHEL 6) and my compiler is gcc 4.4.7 (which is not the MathWorks recommended version, but is the newest version I can get).
Here are the relevant portions of the code I'm trying to compile:
  1 /*=========================================================
  2  * matrixDivide.c - Example for illustrating how to use
  3  * LAPACK within a C MEX-file.
  4  *
  5  * X = matrixDivide(A,B) computes the solution to a
  6  * system of linear equations A * X = B
  7  * using LAPACK routine DGESV, where
  8  * A is an N-by-N matrix
  9  * X and B are N-by-1 matrices.
 10  *
 11  * This is a MEX-file for MATLAB.
 12  * Copyright 2009-2010 The MathWorks, Inc.
 13  *=======================================================*/
 14 /* $Revision: 1.1.6.3 $ $Date: 2011/01/28 18:11:56 $ */
 15
 16 #if !defined(_WIN32)
 17 #define dgesv dgesv_
 18 #endif
 19
 20 #include "mex.h"
 21 #include "lapack.h"
 22
 23 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
 24 {

      [ snip ]

 73     /* Call LAPACK */
 74     dgesv(&m,&n,A2,&m,iPivot,B2,&p,&info);
 75     /* plhs[0] now holds X */
 76
 77     mxDestroyArray(Awork);
 78     mxDestroyArray(mxPivot);
 79 }

Here is the output of the failed mex build:
>> mex -v -largeArrayDims matrixDivide.c
-> mexopts.sh sourced from directory (DIR = $MATLAB/bin)
   FILE = /sw/matlab/R2013b/bin/mexopts.sh
----------------------------------------------------------------
->    MATLAB                = /sw/matlab/R2013b
->    CC                    = gcc
->    CC flags:
         CFLAGS             = -ansi -D_GNU_SOURCE  -fexceptions -fPIC -fno-omit-frame-pointer -pthread
         CDEBUGFLAGS        = -g
         COPTIMFLAGS        = -O -DNDEBUG
         CLIBS              = -Wl,-rpath-link,/sw/matlab/R2013b/bin/glnxa64 -L/sw/matlab/R2013b/bin/glnxa64 -lmx -lmex -lmat -lm -lstdc++
         arguments          =
->    CXX                   = g++
->    CXX flags:
         CXXFLAGS           = -ansi -D_GNU_SOURCE -fPIC -fno-omit-frame-pointer -pthread
         CXXDEBUGFLAGS      = -g
         CXXOPTIMFLAGS      = -O -DNDEBUG
         CXXLIBS            = -Wl,-rpath-link,/sw/matlab/R2013b/bin/glnxa64 -L/sw/matlab/R2013b/bin/glnxa64 -lmx -lmex -lmat -lm
         arguments          =
->    FC                    = gfortran
->    FC flags:
         FFLAGS             = -fexceptions -fbackslash -fPIC -fno-omit-frame-pointer
         FDEBUGFLAGS        = -g
         FOPTIMFLAGS        = -O
         FLIBS              = -Wl,-rpath-link,/sw/matlab/R2013b/bin/glnxa64 -L/sw/matlab/R2013b/bin/glnxa64 -lmx -lmex -lmat -lm
         arguments          =
->    LD                    = gcc
->    Link flags:
         LDFLAGS            = -pthread -shared -Wl,--version-script,/sw/matlab/R2013b/extern/lib/glnxa64/mexFunction.map -Wl,--no-undefined
         LDDEBUGFLAGS       = -g
         LDOPTIMFLAGS       = -O
         LDEXTENSION        = .mexa64
         arguments          =
->    LDCXX                 =
->    Link flags:
         LDCXXFLAGS         =
         LDCXXDEBUGFLAGS    =
         LDCXXOPTIMFLAGS    =
         LDCXXEXTENSION     =
         arguments          =
----------------------------------------------------------------

-> gcc -c  -I/sw/matlab/R2013b/extern/include -I/sw/matlab/R2013b/simulink/include -DMATLAB_MEX_FILE -ansi -D_GNU_SOURCE  -fexceptions -fPIC -fno-omit-frame-pointer -pthread  -O -DNDEBUG  "matrixDivide.c"

In file included from matrixDivide.c:21:
/sw/matlab/R2013b/extern/include/lapack.h:6907:1: warning: "dgesv" redefined
matrixDivide.c:17:1: warning: this is the location of the previous definition
matrixDivide.c: In function `mexFunction':
matrixDivide.c:64: warning: incompatible implicit declaration of built-in function ?memcpy?
-> gcc -O -pthread -shared -Wl,--version-script,/sw/matlab/R2013b/extern/lib/glnxa64/mexFunction.map -Wl,--no-undefined -o  "matrixDivide.mexa64"  matrixDivide.o  -Wl,-rpath-link,/sw/matlab/R2013b/bin/glnxa64 -L/sw/matlab/R2013b/bin/glnxa64 -lmx -lmex -lmat -lm -lstdc++

matrixDivide.o: In function `mexFunction':
matrixDivide.c:(.text+0x1c6): undefined reference to `dgesv_'
collect2: ld returned 1 exit status

    mex: link of ' "matrixDivide.mexa64"' failed.

A: After some more messing around, I figured out my (rather elementary) mistake.
You need to specify the -lmwlapack option (and/or -lmwblas, as appropriate) to the linker:
mex -largeArrayDims -lmwlapack matrixDivide.c

It even says so on the MathWorks page I was trying to follow along on. RTFM!


text:
Q: Find number of occurences of string elements in an Array using lodash or underscore js I have an array in the following format:
var array = [
  { id: '555weibo' },
  { id: '578weibo' },
  { id: '111facebook' },
  { id: '123facebook' },
  { id: '145facebookpage' },
  { id: '145facebookpage' },
  { id: '766facebook' },
  { id: '242facebook' },
  { id: '432twitter' },
  { id: '432exing' }
 ];

I need to find the number of occurrences of facebook, twitter, xing, and weibo inside that array.
eg:
{
  weibo: 2,
  facebook: 6,
  twitter: 1,
  xing: 1
}

I've searched for a solution, but nothing seems to work.
The following code doesn't give the expected result. Your help is much appreciated. Thank you.
var filtered = _.map(diff, function(value, key) {
   return { id: key, count:value };
});

A: You must specify the possible keys as there's no way to guess them in the initial array.
Here's a solution, you don't need any library:
var filtered = array.reduce(function(m,v){
    for (var k in m) if (~v.id.indexOf(k)) m[k]++;
    return m;
},{facebook:0, weibo:0, twitter:0, xing:0});

Demonstration

A: With using underscore:
var services = ['weibo', 'facebook', 'twitter', 'xing'];
var result = _.map(services, function(service){
     var length = _.reject(array, function(el){
           return (el.id.indexOf(service) < 0);
     }).length;
     return {id: service, count: length};
});

A: Here's how you could do it using lodash:
_.countBy(array, _.flow(
    _.method('id.replace', /^\d+/, ''),
    _.method('replace', /page$/, '')
));

*

*countBy() returns an object with counts as values. The keys are generated by the passed in callback, so this is where you can parse and manipulate the keys you want to count by.

*flow() generates a function, usually for callbacks to map() and so on. It takes an arbitrary number of functions as arguments. The input is filtered through each of these functions and the result is returned. This is a powerful way to compose callbacks because it's easy to rearrange/add/remove it's parts.

*method() returns a function that's invoked on the given object. You want to replace the beginning numbers with an empty string here.

*method() is doing the same thing here, except it's removing page from the end of the string. Notice how there's no id prefix since it's just being passed the result of the function in front of it.


text:
Q: how to use intent and bundles for custom list view I am new to android application development.. I am trying to create new activity for button click inside a custom list view..(i.e) I want to add on Click event for buttons used in item of List view. How can I give on Click event for buttons in List Item. I am trying to use intent and bundles to pass data for two different activities. but If I use intent then it is not working properly for me.. anyone please help me to solve this..

A: Since you did not post any code, I will try my best to give an answer based on your question. You want button click events inside ListView items. Simply get the id using findViewById() for the button inside the getView() method of the ListView and add an onClickListener on that button. Start the new activity inside this onClick event.
Edit:
based on your comments change the line :
intent.putExtra("data",tvmername.getText().toString());
                startActivity(intent);

to this:
intent.putExtra("data",holder.tvmername.getText().toString());
                startActivity(intent);

Code for ArrayAdapter:
public class MovieAdapter extends ArrayAdapter {
    private List<CarrotModel> carrotModelList;
    private int resource;

    private LayoutInflater inflater;

    public MovieAdapter(Context context, int resource, List<CarrotModel> objects) {
        super(context, resource, objects);
        carrotModelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder=null;
        if (convertView == null) {
            holder=new ViewHolder();
            convertView = inflater.inflate(resource, null);

            holder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);

            holder.tvDiscount = (TextView) convertView.findViewById(R.id.tvDiscount);
           holder.tvmername = (TextView) convertView.findViewById(R.id.tvMerName);
            holder.tvDealDesc = (TextView) convertView.findViewById(R.id.tvDealDesc);
            holder.tvOfftoDis = (TextView) convertView.findViewById(R.id.tvOftoDis);
            holder.tvmeradd = (TextView) convertView.findViewById(R.id.tvmeradd);
            convertView.setTag(holder);
        }
        else {

            holder = (ViewHolder) convertView.getTag();
        }

        final ProgressBar progressBar;

        progressBar=(ProgressBar) convertView.findViewById(R.id.progressBar);

        ImageLoader.getInstance().displayImage(carrotModelList.get(position).getImageURL(), holder.ivIcon, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                progressBar.setVisibility(View.GONE);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                progressBar.setVisibility(View.GONE);
            }
        });
        holder.tvDiscount.setText(carrotModelList.get(position).getDiscount() + "% OFF");
        holder.tvmername.setText(carrotModelList.get(position).getMerchantName());
        holder.tvDealDesc.setText(carrotModelList.get(position).getDealDescription());
        holder.tvOfftoDis.setText(carrotModelList.get(position).getOffersToDisplay());
        holder.tvmeradd.setText(carrotModelList.get(position).getMerchantAddress());

        Button Button1= (Button)  convertView.findViewById(R.id.button);

        Button1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent=new Intent(getApplicationContext(), SecondActivity.class);
                intent.putExtra("data",holder.tvmername.getText().toString());
                startActivity(intent);
            }

        });

        return convertView;
    }

    class ViewHolder{
       private ImageView ivIcon;
        private TextView tvDiscount;
        private   TextView tvmername;
        private TextView tvDealDesc;
        private TextView tvOfftoDis;
        private  TextView tvmeradd;

    }

}

A: Just do below changes.
  Button1.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Intent intent=new Intent(getApplicationContext(), SecondActivity.class);
                    intent.putExtra("data",holder.tvmername.getText().toString());
                    startActivity(intent);
                }

            });

If still you got NullPointerException then send resource file.


text:
Q: Unit testing model relationships in Laravel In my app I have a many-to-many relationship between users and organisations,
User
public function organisations()
{
    return $this->belongsToMany('App\Organisation')->withPivot(['owner']);
}

Organisation
public function users()
{
    return $this->belongsToMany('App\User')->withPivot(['owner']);
}

There is a pivot column on this relationship to state whether the user is an owner of the organisation or not.
I am struggling to test the relationship though, my test returns,

Failed asserting that null matches expected 1.
  Expected :1
  Actual   :null

Here is my test function,
public function testUserHasOwnershipOfOrganisations()
{
    $userRow = factory(User::class)->create();
    $organisation = factory(Organisation::class)->create();
    $userRow->organisations()->attach($organisation->id, ['owner' => true]);
    $user = User::first();
    $ownOrganisations = $user->organisations()->wherePivot('owner', true);
    $this->assertEquals($organisation->id, $ownOrganisations->first()->organisation_id);
}

The thought process of the above is make a user, make an organisation, create the relationship. Query the first user in the table, get their organisations and make sure the organisation in the organisation relationship as the same ID as the one I just created.
Can anyone tell me why this is not working as I would expect it too?
Thanks

A: UPDATE:
Also check this:
$ownOrganisations->first()->organisation_id

Probably it should be this:
$ownOrganisations->first()->id

/END UPDATE
The only problem I can see is with this line of code:
$user = User::first();

It depends on how your test environment is configured, but there is no assurance that your newly created user is the first in the table. I would suggest to do something more explicit then:
$user = User::find($userRow->id);

Also double check your factories, to assure that they don't add models to this relationship on their own. If they do, you need to take it into account when retrieving your models.


text:
Q: Calculating distance between *multiple* sets of geo coordinates in python I am struggling to calculate the distance between multiple sets of latitude and longitude coordinates.  In, short, I have found numerous tutorials that either use math or geopy.  These tutorials work great when I just want to find the distance between ONE set of coordindates (or two unique locations).  However, my objective is to scan a data set that has 400k combinations of origin and destination coordinates.  One example of the code I have used is listed below, but it seems I am getting errors when my arrays are > 1 record.  Any helpful tips would be much appreciated.  Thank you.
# starting dataframe is df

lat1 = df.lat1.as_matrix()
long1 = df.long1.as_matrix()
lat2 = df.lat2.as_matrix()
long2 = df.df_long2.as_matrix()

from geopy.distance import vincenty
point1 = (lat1, long1)
point2 = (lat2, long2)
print(vincenty(point1, point2).miles)

A: Edit: here's a simple notebook example
A general approach, assuming that you have a DataFrame column containing points, and you want to calculate distances between all of them (If you have separate columns, first combine them into (lon, lat) tuples, for instance). Name the new column coords.
import pandas as pd
import numpy as np
from geopy.distance import vincenty

# assumes your DataFrame is named df, and its lon and lat columns are named lon and lat. Adjust as needed.
df['coords'] = zip(df.lat, df.lon)
# first, let's create a square DataFrame (think of it as a matrix if you like)
square = pd.DataFrame(
    np.zeros(len(df) ** 2).reshape(len(df), len(df)),
    index=df.index, columns=df.index)

This function looks up our 'end' coordinates from the df DataFrame using the input column name, then applies the geopy vincenty() function to each row in the input column, using the square.coords column as the first argument. This works because the function is applied column-wise from right to left.
def get_distance(col):
    end = df.ix[col.name]['coords']
    return df['coords'].apply(vincenty, args=(end,), ellipsoid='WGS-84')

Now we're ready to calculate all the distances.
We're transposing the DataFrame (.T), because the loc[] method we'll be using to retrieve distances refers to index label, row label. However, our inner apply function (see above) populates a column with retrieved values
distances = square.apply(get_distance, axis=1).T

Your geopy values are (IIRC) returned in kilometres, so you may need to convert these to whatever unit you want to use using .meters, .miles etc.
Something like the following should work:
def units(input_instance):
    return input_instance.meters

distances_meters = distances.applymap(units)

You can now index into your distance matrix using e.g. loc[row_index, column_index].
You should be able to adapt the above fairly easily. You might have to adjust the apply call in the get_distance function to ensure you're passing the correct values to great_circle. The pandas apply docs might be useful, in particular with regard to passing positional arguments using args (you'll need a recent pandas version for this to work).
This code hasn't been profiled, and there are probably much faster ways to do it, but it should be fairly quick for 400k distance calculations.
Oh and also
I can't remember whether geopy expects coordinates as (lon, lat) or (lat, lon). I bet it's the latter (sigh).
Update
Here's a working script as of May 2021.
import geopy.distance
# geopy DOES use latlon configuration
df['latlon'] = list(zip(df['lat'], df['lon']))
square = pd.DataFrame(
    np.zeros((df.shape[0], df.shape[0])),
    index=df.index, columns=df.index
)

# replacing distance.vicenty with distance.distance
def get_distance(col):
    end = df.loc[col.name, 'latlon']
    return df['latlon'].apply(geopy.distance.distance,
                              args=(end,),
                              ellipsoid='WGS-84'
                             )

distances = square.apply(get_distance, axis=1).T

A: I recently had to do a similar job, I ended writing a solution I consider very easy to understand and tweak to your needs, but possibly not the best/fastest:
Solution
It is very similar to what urschrei posted: assuming you want the distance between every two consecutive coordinates from a Pandas DataFrame, we can write a function to process each pair of points as the start and finish of a path, compute the distance and then construct a new DataFrame to be the return:
import pandas as pd
from geopy import Point, distance

def get_distances(coords: pd.DataFrame,
                  col_lat='lat',
                  col_lon='lon',
                  point_obj=Point) -> pd.DataFrame:
    traces = len(coords) -1
    distances = [None] * (traces)
    for i in range(traces):
        start = point_obj((coords.iloc[i][col_lat], coords.iloc[i][col_lon]))
        finish = point_obj((coords.iloc[i+1][col_lat], coords.iloc[i+1][col_lon]))
        distances[i] = {
            'start': start,
            'finish': finish,
            'path distance': distance.geodesic(start, finish),
        }

    return pd.DataFrame(distances)

Usage example
coords = pd.DataFrame({
    'lat': [-26.244333, -26.238000, -26.233880, -26.260000, -26.263730],
    'lon': [-48.640946, -48.644670, -48.648480, -48.669770, -48.660700],
})

print('-> coords DataFrame:\n', coords)
print('-'*79, end='\n\n')

distances = get_distances(coords)
distances['total distance'] = distances['path distance'].cumsum()
print('-> distances DataFrame:\n', distances)
print('-'*79, end='\n\n')

# Or if you want to use tuple for start/finish coordinates:
print('-> distances DataFrame using tuples:\n', get_distances(coords, point_obj=tuple))
print('-'*79, end='\n\n')

Output example
-> coords DataFrame:
          lat        lon
0 -26.244333 -48.640946
1 -26.238000 -48.644670
2 -26.233880 -48.648480
3 -26.260000 -48.669770
4 -26.263730 -48.660700
-------------------------------------------------------------------------------

-> distances DataFrame:
                                   start                             finish  \
0  26 14m 39.5988s S, 48 38m 27.4056s W   26 14m 16.8s S, 48 38m 40.812s W
1      26 14m 16.8s S, 48 38m 40.812s W  26 14m 1.968s S, 48 38m 54.528s W
2     26 14m 1.968s S, 48 38m 54.528s W     26 15m 36s S, 48 40m 11.172s W
3        26 15m 36s S, 48 40m 11.172s W  26 15m 49.428s S, 48 39m 38.52s W

           path distance         total distance
0  0.7941932910049856 km  0.7941932910049856 km
1  0.5943709651000332 km  1.3885642561050187 km
2  3.5914909016938505 km   4.980055157798869 km
3  0.9958396130609087 km   5.975894770859778 km
-------------------------------------------------------------------------------

-> distances DataFrame using tuples:
                       start                  finish         path distance
0  (-26.244333, -48.640946)    (-26.238, -48.64467)  0.7941932910049856 km
1      (-26.238, -48.64467)  (-26.23388, -48.64848)  0.5943709651000332 km
2    (-26.23388, -48.64848)     (-26.26, -48.66977)  3.5914909016938505 km
3       (-26.26, -48.66977)   (-26.26373, -48.6607)  0.9958396130609087 km
-------------------------------------------------------------------------------

A: As of 19th May
For anyone working with multiple geolocation data, you can adapt the above code but modify a bit to read the CSV file in your data drive. the code will write the output distances in the marked folder.
import pandas as pd
from geopy import Point, distance
def get_distances(coords: pd.DataFrame,
   col_lat='lat',
              col_lon='lon',
              point_obj=Point) -> pd.DataFrame:
traces = len(coords) -1
distances = [None] * (traces)
for i in range(traces):
    start = point_obj((coords.iloc[i][col_lat], coords.iloc[i][col_lon]))
    finish = point_obj((coords.iloc[i+1][col_lat], coords.iloc[i+1][col_lon]))
    distances[i] = {
        'start': start,
        'finish': finish,
        'path distance': distance.geodesic(start, finish),
    }
output = pd.DataFrame(distances)
output.to_csv('geopy_output.csv')
return output

I used the same code and generated distance data for over 50,000 coordinates.


text:
Q: How to get a blur in effect after a blur out effect on an underlying Div I have put together a blur out/in effect for a landing page. However it is not quite working how it is supposed too and i am not sure why.
It blurs out fine, The problem lies on when i want the underlying Div to appear, i would like that to "fade in", as it stands it just appears after the fade out has finished.
Here is a snippet:

splash = document.getElementById('intro');
content = document.getElementById('content');

 function enterSite (element) {
  opac = 1;
  fps = 1000/30;
  function decrease() {
   opac -= 0.02;
   if (opac <= 0.1){
    splash.style.display = 'none';
    return true;
   }
  splash.style.opacity = opac;
  setTimeout(decrease,fps);
  }
  function increase() {
   opac += 0.02;
   if (opac >= 0.1){
    content.style.display = 'block';
    return false;
   }
  content.style.opacity = opac;
  setTimeout(increase,fps);
  }
  decrease(), increase();
 }
html, body {
    overflow: hidden;
}
main {
    width: 100%;
    height: 100vh;
    position: relative;
}
#intro {
    background-image: url(Images/splash.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    display: flex;
    text-align: center;
    height: 100vh;
}
#splash {
    margin: auto;
    width: 40%;
    background-color: rgba(56,56,56,0.4);
    border-radius: 50px 50px;
}
#splash-p {
    width: 70%;
    font-size: 1.2em;
    line-height: 1.5em;
    margin: auto;
    text-align: center;
    padding-top: 10px;
    color: #fff;
}
.btn {
    width: 35%;
    margin: auto;
    margin-top: 10px;
    margin-bottom: 10px;
}

/* Main Content Page */

article {
    position: absolute;
    height: 100vh;
    background-color: red;
}

Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing.

   <input type="image" src="Images/Button.png" class="btn" onclick="enterSite()">

   Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,Just a random piece of online text that means nothing,

A: I think you could benefit from breaking things out a little bit more and not nesting so many functions and calls. Also, it may be helpful to use a setInterval() instead of repeating setTimeout().
splash = document.getElementById('intro');
content = document.getElementById('content');
var fadeOut = null;
var fadeIn = null;
opac = 1;
fps = 1000/30;

function increase() {
    content.style.opacity = opac;
    opac += 0.02;

    if (opac >= 1){ //Opacity is 100%
      window.clearInterval(fadeIn); //Stop fade-in
    }

}

function decrease() {
    splash.style.opacity = opac;
    opac -= 0.02;

    if (opac < 0.1){ //If object is almost gone
        splash.style.display = 'none'; //Hide it completely
        window.clearInterval(fadeOut); //Stop fade-out

        content.style.display = 'block'; //Set up new content
        content.style.opacity = 0;
        fadeIn = setInterval(increase, fps); //Begin fade-in

    }
}

function enterSite () {
    fadeOut = setInterval(decrease, fps); //Start the fadeout
}

JSFiddle


text:
Q: Chrome developer tools won't inspect elements within body tag (mac OSX) Has anyone else experienced problems with chrome developer tools for OSX not showing any elements / html inside the body tag?
I inspect an element as normal, but instead of seeing the html, I just get the body tag, which cannot be expanded or opened in any way (see attached pic). This makes dev tools useless for css debugging.
I have tried

*

*deleting and reinstalling Chrome (latest version)

*Resetting Chrome to its defaults

*Restarting my computer

*refreshing and hard refreshing the page

This is all the information I can get, for any element within the body tag :

A: It's not a solution but you can do alt+r to refresh devtools and it fixes the problem temporarily.


text:
Q: Como guardar valores num vetor usando herança/polimorfismo? Estou iniciando na linguagem Java e me deparei um problema. É o seguinte: Tenho 1 classe que chama Veiculo, nela tem o atributo marca(string) e tem 3 classes que a herdam, no caso são: Carro(qtdPortas int), Moto(qtdCilindradas int), Barco(potMotor int) e terei um vetor[] para armazenar os veiculos inseridos, o meu problema é o seguinte, como faço pra inserir no vetor[] um objeto do tipo Carro, ou Moto, ou Barco, especificamente? Eu tinha pensado no seguinte código, mas ele serve apenas pra inserir valores normais, quando não existe herança, como ficaria o código pra inserir num vetor quando existe herança?
public void insereVeiculo(Veiculo veiculo)
    {
        int contador = 0;
        for (int i = 0; i < this.vetVeiculo.length; i++)
        {
            if(this.vetVeiculo[i] == null)
                break;
            else
                contador++;
        }
        this.vetVeiculo[contador] = veiculo;
    }

A: Se a intenção é limitar pelo subtipo através de um objeto do supertipo, acredito que um simples verificação com instanceof já resolveria:
public void insereVeiculo(Veiculo veiculo)
{
        int contador = 0;
        for (int i = 0; i < this.vetVeiculo.length; i++)
        {
            if(this.vetVeiculo[i] == null)
                break;
            else
                contador++;
        }

        if(veiculo instanceof Carro) {
            this.vetVeiculo[contador] = veiculo;
        }
}

A: Se o que desejava era mesmo a resposta que foi aceita então o mais correto seria:
public void insere(Carro carro) {
    int contador = 0;
    for (carro : vetVeiculo) {
        if(caro == null) break;
        contador++;
    }
    vetVeiculo[contador] = carro;
}

Coloquei no GitHub para referência futura.
Na verdade esse loop é horrível, mesmo eu tendo melhorado, e ineficiência é enorme. Como não sei o contexto nem posso ajudar mais.
Se ainda quiser fazer do jeito conceitualmente errado, pelo menos torne um pouco mais eficiente porque só varre quando é do tipo que deseja:
public void insereVeiculo(Veiculo veiculo) {
    if (veiculo instanceof Carro) {
        int contador = 0;
        for (carro : vetVeiculo) {
            if(caro == null) break;
            contador++;
        }
        this.vetVeiculo[contador] = veiculo;
    }
}

A: Você vai criar um vetor de Objetos.
Objects[] vetors = new Objects [] {Carro,Moto, Barco};

Dai no método de cada sub classe você implementa o addVeiculo() colocando o objeto no vetor.


text:
Q: two selects queries instead of one before insert I'm using grails 2.2.2 and I have created a domain class with one unique String attribute:
class Myclass {
    String dscr // my String attibute

    static constraints = {
        dscr unique: true // the code to set it unique
    }
}

and then I run the grails console command to test this simple class with the following code with loggingSql = true to see the resulting queries:
def a = new Myclass([dscr:'dscr1'])
a.save()

The resulting queries are sone below:
Hibernate: select this_.id as id0_0_, this_.version as version0_0_, this_.dscr as dscr0_0_ from myclass this_ where this_.dscr=?
Hibernate: select this_.id as id0_0_, this_.version as version0_0_, this_.dscr as dscr0_0_ from myclass this_ where this_.dscr=?
Hibernate: insert into myclass (version, dscr) values (?, ?)

The mystery here is the two select queries instead of one. The reason for the one query, as I found here, is that the select query is made to to check uniqueness. Why does the second select happen?

A: After all, I couldn't find a logical explanation for the two select queries. The best I found is to get rid of these two selects without a manual change of the database, as said here.
So to get rid of these selects, someone should first set the domain class in a different way (without constraints, but with mapping).
class Myclass {
    String dscr

    static mapping = {
        dscr unique: true
    }
}

And then to protect your code from exceptions, because now hibernate doesn't check for uniqueness, you should insert new elements like this:
try {
    def a = new Myclass([dscr:'dscr1'])
    a.save()
} catch(e) {
    Myclass.withSession { session ->
        session.clear()
    }

    // do whatever you want to handle a possible exception
}

And now the resulting query is only one import query, which may run successfully or not.
Hibernate: insert into myclass (version, dscr) values (?, ?)


text:
Q: AVPlayer Duration is NAN with Twilio The duration property of AVPlayer.currentItem is returning NAN always with the Twilio audio urls. However, the audio is playing fine.
I'm able to get the duration property of all other audio urls than Twilio.
Sample url to test this issue:
http://api.twilio.com/2010-04-01/Accounts/AC1db6911efe574fc890ee332f140f7e8c/Recordings/RE06adfbfd2ad2cfd5d95585ff91cb3b88.mp3

Here are the different ways that I have tried out:
if (avPlayer.currentItem.status.rawValue == AVPlayerStatus.ReadyToPlay.rawValue) {

     var asset = AVURLAsset(URL: sourceURL, options: nil)
     var duration: Float64 = CMTimeGetSeconds(asset.duration)
     println(duration)
}

if (avPlayer.currentItem.status.rawValue == AVPlayerStatus.ReadyToPlay.rawValue) {
     var duration: Float64 = CMTimeGetSeconds(self.avPlayer.currentItem.duration)
     println(duration)
}

var thePlayerItem = self.avPlayer.currentItem
if thePlayerItem.status.rawValue == AVPlayerStatus.ReadyToPlay.rawValue{

     println(CMTimeGetSeconds(thePlayerItem.duration))
     println(CMTimeGetSeconds(thePlayerItem.asset.duration))
}

Any help on this is appreciated.
I have requested GET through the browser and it returned all the details including the audio duration <Duration>37</Duration>
GET /2010-04-01/Accounts/ACda6f1.../Recordings/RE557ce644e5ab84fa21cc21112e22c485.xml

Response:
HEADERS

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Accept, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since
Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: ETag
Connection: keep-alive
Content-Length: 550
Content-Type: application/xml
Date: Tue, 08 Sep 2015 06:50:43 GMT
Etag: b1512f..
Last-Modified: Fri, 04 Sep 2015 04:19:20 +0000
Strict-Transport-Security: max-age=15768000
X-Powered-By: AT-5000
X-Shenanigans: none
BODY
view raw
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
  <Recording>
    <Sid>RE…</Sid>
    <AccountSid>ACda6f1... </AccountSid>
    <CallSid>CA3..</CallSid>
    <Duration>37</Duration>
    <DateCreated>Fri, 04 Sep 2015 04:19:20 +0000</DateCreated>
    <ApiVersion>2010-04-01</ApiVersion>
    <DateUpdated>Fri, 04 Sep 2015 04:19:20 +0000</DateUpdated>
    <Price/>
    <Uri>/2010-04-01/Accounts/ACda6f1.../Recordings/RE557ce644e5ab84fa21cc21112e22c485.xml</Uri>
  </Recording>
</TwilioResponse>

A: I had the same problem but I was able to get the duration by doing the following:
let timeRange = self.avPlayer.currentItem.loadedTimeRanges[0].CMTimeRangeValue
let duration = CMTimeGetSeconds(timeRange.duration)

Hope this helps!

A: Hey I am just doing it and in fact recording from twilio with mp3 extension didn't wokred for me when I have used .duration, and when using suggested @inga loadedTimeRanges[0].rangeValue.duration it returns wrong time. But I changed to twilio path without .mp3 extension and it start working
if let playerItem = player.currentItem, playerItem.status == AVPlayerItemStatus.readyToPlay {
    let durationTime = playerItem.duration
   //playerItem.loadedTimeRanges[0].timeRangeValue.duration
}

A: I finally found out the reason for this. Actually the song i was trying to get the duration from was not having the metadata set with it that's why it was giving Nan duration. AVPlayerItem asynchronously loads the data with load-asynchronous with keys method, when data is there you will get it in the current Item property of avplayer.
By the way using loadedTimeRanges[0].rangeValue.duration is not the correct way to calculate the total duration becuase it this value gets updated every second until the whole data is not loaded. For Shorter data it sometimes works fine as it loads whole data at one shot and when you use loadedtimeinranges.rangeValue.duration property it gives you correct Results but for larger data this is not the right solution.
If you want to see if your problem is related to the metadata, just stream any online mp3 file and check if the problem is still there, it should work fine for streaming any downloaded file or any remote file if it is having the meta data set with it and should give you correct duration. Hope This helps!!


text:
Q: How to change GTK Notebook header background color? I am designing a GUI in Glade and Python GTK 3. I want to change the background color of a GTK Notebook's header (the darker grey in the image below).

I've tried this CSS:
.header.top {
    border-width: 0;
    background-color: red;
}

and this code (and many other combinations):
self.provider = Gtk.CssProvider()
self.provider.load_from_file(Gio.File.new_for_path('styles.css'))
Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), self.provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
self.measurements_notebook.get_style_context().add_class('header.top')

but it does not work.
How can I do this?


text:
Q: How to detect slow internet speed in mobile apps? I am developing a mobile app. And I want to treat very slow internet connections as if we were offline.
Getting this information from Network Signal Strength is not enough as we can have a strong Wifi and very slow Internet.
I am looking for a simple way to detect these slow connections. Any ideas ?


text:
Q: Force the chrome web driver to load a Japanese language website translated into English The website link is:
https://used.sofmap.com/r/item?categories1%5B%5D=audio&stock_shop_code%5B%5D=298&stock_type%5B%5D=2&categories2%5B%5D=midi
I need this website to load translated into English.
This is what i have attempted:
options = Options()
options.add_argument('--lang=es')
driver = webdriver.Chrome(options=options, executable_path=r'E:\chromedriver\chromedriver.exe')

I have also tried:
options.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})

But nothing seems to work. Any help would be appreciated. Thanks!

A: You can use add_experimental_option and prefs
prefs = {
    "translate_whitelists": {'ja': 'en'}, # translate from Japanese to English
    "translate": {'enabled': 'true'}
}

options = Options()
options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=options, executable_path=r'E:\chromedriver\chromedriver.exe')

Notice it will translate the site after the url is loaded, it will not load it already translated. Loading the site already translated using options.add_argument('--lang=en') requires the site to support localization. The prefs option uses Google translate to to the translation after the site is loaded.,


text:
Q: how to get value generated in mock method I have a service method in FooService
public void doSomething(){
    ArrayList<Foo> fooList = ...;
    barService.batchAddFoos(fooList);

    List<String> codeList = new ArrayList<>();
    for (Foo foo : fooList) {
        codeList.add(foo.getCode());
    }
    String key = "foo_codes";
    redisService.sadd(key,codeList.toArray(new String[]{}));
    // other code also need use code
}

BarService.batchAddFoos
    for (Foo foo : foos) {
        foo.setCode(UUID.randomUUID().toString()); // dynamically generate the code value
    }

Then I have a unit test to test FooService logic
@Test
public void doSomething() throws Exception {
    fooService.doSomething();
    ArgumentCaptor<List<Foo>> fooListCaptor = ArgumentCaptor.forClass(List.class);
    verify(barService).batchAddFoos(fooListCaptor.capture());
    List<Foo> fooList = fooListCaptor.getValue();
    Assert.assertNotNull(fooList.get(0).getCode()); // check code value is generated successfully
    List<String> codeList = new ArrayList<>();
    for (Foo foo : fooList) {
        codeList.add(foo.getCode());
    }
    verify(redisService).sadd("foo_codes",codeList.toArray(new String[]{}));
}

but it is failed, because the code value is null, actually it does not execute any code in BarService.batchAddFoos.I even tried to explicitly populate code value,
    fooList.get(0).setCode("aaa");
    fooList.get(1).setCode("bbb");

but it is still failed.
Argument(s) are different! Wanted:
redisService.sadd("foo_codes", "aaa", "bbb");
Actual invocation has different arguments:
redisService.sadd("foo_codes", null, null);

Any idea to solve this problem?

A: Since the fooList is a local variable of the FooService.doSomething, you cannot populate it from the test. Your test will not fail, if assertion will be as following:
Mockito.verify(barService).batchAddFoos(fooListCaptor.capture());
List<Foo> fooList = fooListCaptor.getValue();
//Assert.assertNotNull(fooList.get(0).getCode());
Assert.assertFalse(fooList.isEmpty());
...

If you will initialize the code in the Foo constructor with Strings.EMPTY or any other not null value, your original assertion will work.

A: As such scenario, could populate some properties of some object parameters as you like, e.g.
    doAnswer(new Answer() {
        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            List<Foo> fooList = invocationOnMock.getArgumentAt(0, List.class);
            fooList.get(0).setCode("aaa"); // explicitly specify the first foo object have code of "aaa"
            fooList.get(1).setCode("bbb"); // explicitly specify the second foo object have code of "bbb"
            return null;
        }
    }).when(barService).batchAddFoos(anyList());


text:
Q: How to display date in angular with filter How to display date in angular with filter.
Below output shows the input and the output (with/without angular date filter)
In: {{v.Dt}}
Angular: {{v.Dt | date:'yyyy-MM-dd HH:mm:ss Z'}}
prints:

In: 2015-03-19T05:52:10.634062Z
Angular: 2015-03-19T05:52:10.634062Z

The desired display format is 19 Mar 2015

Any help is appreciated.

A: I also had similar problem and then I came across this solution:
Add this into your app.js file
angular.module('AngularAuthApp').filter('Convertdate', function ($filter) {
    return function (input) {
        if (input == null) { return ""; }
        var _date = $filter('date')(new Date(input), 'dd MMM yyyy');
        return _date.toUpperCase();
    };
});

And then call like this
   <small class="styleColor">{{Event.EventStartDate | Convertdate}}</small>

EventStartDate is your datefield
You also can change the format of date in this
var _date = $filter('date')(new Date(input), 'dd MMM yyyy');
                                                 ^^ here

To mention that angularauthapp is your app name

A: You can do it in the markup
{{v.Dt | date : 'dd MMM yyyy'}}


text:
Q: find all nested array in single array in python WITHOUT FLATTEN or any inbuilt function Hi I need a single list of nested lists in python without any inbuilt function. I did a lot of research but not able to find without flatten or ravel function().
for ex:
input = [1,2,[2,3,[4,5]],[6,7],[8,[9]],10]
output = [1,2,2,3,4,5,6,7,8,9,10]

A: You can use recursion to implement your own flatten function. Here's a nice tutorial explaining the concepts of recursion.
The idea here is that you loop through each element in your list and if you encounter a sublist you recursively call the same method with the current list. If it's a valid element you add it to to your output list.
Example:

def flatten(input_list, output_list=[]):

  for i in input_list:
    if isinstance(i, list):
      flatten(i, output_list)
    else:
      output_list.append(i)

  return output_list

input_list = [1,2,[2,3,[4,5]],[6,7],[8,[9]],10]

print(flatten(input_list))

Outputs:
[1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10]

A: I found a solution on my own. Below is the solution:
c = []
def test(a):
    for val in a:
        if type(val) == list:
            test(val)
        else:
            c.append(val)
return c

a=[1,2,[2,3,[4,5]],[6,7],[8,[9]],10]
   print test(a)


text:
Q: Uncaught ReferenceError: $ is not defined error in jQuery I have this code in jQuery: (the file name is javascript.js ...I was using JavaScript before...)
$(document).ready(function() {
 $("#readFile").click(function() {
    $.get('test.txt', function(data) {
      $("#bottom_pane_options").html(data); // #bottom_pane_options is the div I want the data to go
    }, 'text');
 });
});

...and this in HTML:
<!DOCTYPE html>

    <title>Culminating</title>
    <link href="style.css" rel="stylesheet" type="text/css">

hi

            <button id="readFile">Read File</button>

When I check the console, I get the Uncaught ReferenceError saying that $ is not defined on the first line.  I'm assuming that it is referring to the first character on the first line.  I got this code from a website and I'm new to jQuery so I'm not sure what is going wrong here.
Any suggestions?

A: Include the jQuery file first:

A: Scripts are loaded in the order you have defined them in the HTML.
Therefore if you first load:

without loading jQuery first, then $ is not defined.
You need to first load jQuery so that you can use it.
I would also recommend placing your scripts at the bottom of your HTML for performance reasons.

A: Change the order you're including your scripts (jQuery first):

A: The MVC 5 stock install puts javascript references in the _Layout.cshtml file that is shared in all pages. So the javascript files were below the main content and document.ready function where all my $'s were.
BOTTOM PART OF _Layout.cshtml:

        @RenderBody()

© @DateTime.Now.Year - My ASP.NET Application

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

I moved them above the
            @RenderBody() and all was fine.
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

        @RenderBody()

© @DateTime.Now.Year - My ASP.NET Application


text:
Q: translate3d on firefox (moz) and safari (webkit) how can I add some code so that my translate3d effect also works on firefox. The jquery code is:

if (st > lastScrollTop){

$('div#search-apartments #content-inner #search-box').attr('style', '-webkit-transform:translate3d(0, '+movepx+'px, 0)');

} else {

$('div#search-apartments #content-inner #search-box').attr('style', '-webkit-transform:translate3d(0, '+movepx+'px, 0)');

So how and where do I need to add the code for "-**moz**-transform:translate3d(0, '+movepx+'px, 0)"??
Thanks!

A: use this code this will help you to solve for firefox also
$('div#search-apartments #content-inner #search-box').attr('style', '-webkit-transform:translate3d(0, '+movepx+'px, 0);-moz-transform:translate3d(0, '+movepx+'px, 0)');

A: USE THIS
if (st > lastScrollTop){

    $('div#search-apartments #content-inner #search-box').css({'-webkit-transform':'translate3d(0, '+movepx+'px, 0)','-moz-transform:translate3d(0, '+movepx+'px, 0)'});
} else {

    $('div#search-apartments #content-inner #search-box').css({'-webkit-transform':'translate3d(0, '+movepx+'px, 0)','-moz-transform:translate3d(0, '+movepx+'px, 0)'});
}

A: Thank you guys.
Alex, yours didn't work somehow but Sohail, yours works perfectly. I just extended your solution for IE and Opera and made this out of it:
$('div#search-apartments #content-inner #search-box').attr('style', '-webkit-transform:translate3d(0, '+movepx+'px, 0);-moz-transform:translate3d(0, '+movepx+'px, 0);-ms-transform:translate3d(0, '+movepx+'px, 0);-o-transform:translate3d(0, '+movepx+'px, 0)');
Again, thank you