text:
Q: How to set up a Spring Batch single reader with multiple itemwriters? I've a situation where I've to perform DB operations to 2 different databases as shown below.
stepBuilderFactory.get("some text")
                  .<POJO,POJO>chunk(200)
                  .reader(dataReader)
                  .writer(writeToDB1)
                  .writer(writeToDB2)
                  .faultTolerant()
                  .skipLimit(10)
                  .skip(DataAccessException.class)
                  .build();

Only the second writer is getting executed, ignoring the first writer. Can this can be achieved using Spring Batch 3.x & Spring Boot 1.5.x?

A: CompositeItemWriter is what you need. It allows you to compose delegate writers to write items to multiple destinations.
When your delegate writers are ItemStreams (which is apparently the case for you), you need to register them as streams in the step so that their callback methods from the ItemStream interface are properly called at the necessary points of the step lifecycle (or in short, so that their ItemStream contract is correctly honored). You can find more details on this in the Registering ItemStream with a Step section of the reference documentation.
Hope this helps.


text:
Q: How to read a set of characters from a file and interpret it   switch (secondLine) {
                    case "EEEEEEEEEEEE":
                        System.out.println("12 mistakes");
                        break;
                    case "............":
                        System.out.println("All test passed");
                        break;
                    //If a student fails 1-11 then check the file for the thirdLastLine and return the integer
                    default:

                        System.out.println("You failed some test and here is your result: " + secondLine);

                        break;

I want to be able to indicate the E's and failure and the exact position within the set of characters. the compiler would return something like E..E....E..E
Thank you

A: You can iterate over the String in order to find the indexes of Es and also calculate the amount.
int failures = 0;
for (int i = 0; i < secondLine.length(); i++)
{
    char c = secondLine.charAt(i);
    if (c == 'E') { failures++; }
    ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is a map that preserves lines and fixes the origin necessarily linear? Let $V$ and $W$ be vector spaces over a field $\mathbb{F}$ with $\text{dim }V \ge 2$. A line is a set of the form $\{ \mathbf{u} + t\mathbf{v} : t \in \mathbb{F} \}$. A map $f: V \to W$ preserves lines if the image of every line in $V$ is a line in $W$. A map fixes the origin if $f(0) = 0$.
Is a function $f: V\to W$ that preserves lines and fixes the origin necessarily linear?

A: Consider $V=W=\Bbb F_2^k$. Then, since a subset is a line if and only if it contains (at most) two points, any bijective map that sends $0$ to $0$ does the trick. However, there are $(2^k-1)!$ such maps, while the bijective linear maps are less than that for $k\ge 3$.

A: You may be interested in this paper
   Affinity of a Permutation of a Finite Vector Space
It discusses the problem of how many k-flats (cosets of a k-dimentional subspace) of an n-dimensional vector space over a finite field must be preserved by a permutation to force the permutation to preserve all k-flats.  See the references for the history of this problem for other fields. And, by the way, Vilmos Totik and Wen-Xiu Ma proved (personal communication) that if f is a transformation of Euclidean n-space, n  > 1, such that for all but countably many lines L the image f(L) is a line, then the image of any line is a line, hence f is an affine transformation.

A: Let me give an example in the Euclidean plane.
The function $f\colon\mathbb R^2\to\mathbb R$ given by $f(x,y)=x^3$ maps lines to lines.
A vertical line $x=a$ is mapped to the line $a^3$ — points are lines by the OP's definition.
Any other line is of the form $\{(t,a+bt);t\in\mathbb R\}$ for some $a,b\in\mathbb R$.
The image of any such line is $\mathbb R$.
Thus $f$ maps lines to lines, and it clearly fixes the origin.
Non-linearity is evident.
This $f$ can be promoted to a function $g\colon\mathbb R^2\to\mathbb R^2$ by letting $g(x,y)=(f(x,y),0)$.
This inherits the desired properties and is a function between two-dimensional spaces.

Below is a previous, erroneous answer. I left it here as a warning example. My actual answer is above.
I can delete this if it would be more appropriate.
Let me give an example with infinite fields.
The real line $\mathbb R$ is an infinite dimensional vector space over $\mathbb Q$.
Lines — other than the origin — are translations of the rationals ($r+\mathbb Q$ for some $r$).
Take the function $g\colon\mathbb R\to\mathbb R$,
$$
g(x)
=
\begin{cases}
x, & x\in\mathbb Q\\
0, & x\notin\mathbb Q.
\end{cases}
$$
The image of the line $r+\mathbb Q$ is the line $\mathbb Q$ if $r\in\mathbb Q$ and $\{0\}$ if $r\notin\mathbb Q$.
Therefore $g$ preserves lines and fixes the origin.
But it is not linear: $5=g(5)\neq g(5-\pi)+g(\pi)=0$.
This is not a valid example because I had misidentified lines.
For example, $2+\pi\mathbb Q$ is a line but its image $\{0,2\}$ is not.
A weaker statement is true: the image of every line is either a line or a set containing the origin and a non-zero rational number.


text:
Q: How to call a method for all instances of an object I need to run a method belonging to all instances of an object. For example, if I had the method fullName(), which concatenates .firstName and .secondName, I would like to do it for both instances of the object in the code:
<script>
    function x(firstName, secondName) {
        this.firstName = firstName;
        this.secondName = secondName;
        this.fullName = function() {
            console.log(this.firstName + this.secondName); //this should output result of both john.fullName() and will.fullName()
        }
    }
    var john = new x("John ", "Smith");
    var will = new x("Will ", "Adams");
</script>

How is this accomplished in javascript? Preferably, it would be without specifying the number of instances, and instead just running the method for all instances that have been created. Thanks in advance.

A: It's possible, but be aware that any x created will never be garbage collected
Originally I had the following code
var x = (function() {
    var objs = [];
    var x = function x(firstName, secondName) {
        this.firstName = firstName;
        this.secondName = secondName;
        objs.push(this);
        this.fullName = function() {
            objs.forEach(function(obj) {
                console.log(obj.firstName + obj.secondName); //this should output result of both john.fullName() and will.fullName()
            });
        };
    };
})();
var john = new x("John ", "Smith");
var will = new x("Will ", "Adams");
will.fullName();

however, I thought about it and think this makes more sense
var x = (function() {
    var objs = [];
    var x = function x(firstName, secondName) {
        this.firstName = firstName;
        this.secondName = secondName;
        objs.push(this);
        this.fullName = function() {
            console.log(this.firstName + this.secondName); //this should output result of both john.fullName() and will.fullName()
        };
    };
    x.fullName = function() {
        objs.forEach(function(obj) {
            obj.fullName();
        });
    }
    return x;
})();
var john = new x("John ", "Smith");
var will = new x("Will ", "Adams");
x.fullName();


text:
Q: Is there a way to assign individual Snakemake rules their own jobscripts? Say I have two Snakemake rules within the same workflow, with different environment/memory requirements. Outside of Snakemake, I would submit two different jobs to the cluster with different options specified depending on the needs of the job. Is there a way to specify different jobscripts for different rules to replicate this within a Snakemake pipeline?

A: Empty strings can be used for options that you want to toggle on and off for different rules.
rule one:
  params:
    pe=""

rule two:
  params:
    pe="-pe sharedmem 4"

And at the command line:
snakemake --cluster "qsub {params.pe}"


text:
Q: TwitterKit does not compile with Xcode 6.3 I added TwitterKit from Fabric to an app under Xcode 6.3.
The app would compile before I added TwitterKit's Run Script build phase step but once I added TwitterKit it failed with this error during Debug builds:

2015-02-23 11:22:32.382 run[53735:1513077] Fabric.framework/run 1.3.13
  2015-02-23 11:22:32.388 run[53735:1513077]
Fabric: dSYM Error
Unable to process fabrictest.app.dSYM at path /Users/mfoouser/Library/Developer/Xcode/DerivedData/fabrictest/Build/Products/Debug-iphonesimulator/fabrictest.app.dSYM
  Make sure your project build settings are generating a dSYM file. DEBUG_INFORMATION_FORMAT should be set to dwarf-with-dsym for all configurations. This could also be a timing issue, make sure the Fabric run script build phase is the last build phase and no other scripts have moved the dSYM from the location Xcode generated it.
Command /bin/sh failed with exit code 1

Anyone find a way around this?

A: This was a simple fix. Just do as the error state, turn on dSYM generation for your debug build.
Change your Build Settings from this:

To this:

Then choose Build again. It should now compile and run.

A: This didn't work for me since it was already set to 'with dSYM' and it didn't build as well. After more digging and trying things out, it seems like the issue (for me at least) is under Build Settings > Generate Debug Symbols, which was set to No by default. I changed it to Yes and it worked like a charm.

A: You can follow below steps  ,it worked for me.

*

*open build setting of your project and search for "Generate debug symbol" and set it to Yes.
As in the below screenshot

*Search for debug information format in build setting and search for  "Debug information format" then set "Debug information format" to "DWARF with dSYM file"

A: No one of proposed answers worked out for me.
Deleted both Fabric.framework and Crashlytics.framework which were added via Fabric app and added them again through Cocoapods.
**It doesnt mean that Cocoapods is only workaround, but probably that they should be re-added to project again.

A: What worked for me was the previous answers combined:
1- Change "Build Settings -> Debug Information Format -> Debug" value to "DWARF with dSYM File"
2- Change "Build Settings -> Generate Debug Symbols" value to "Yes"
3- Remove Fabric and Crashlytics frameworks and install again


text:
Q: Why is Python 3 (or later) better than Python 2? I learned Python as my first serious (non BASIC) language about 10 years ago. Since then, I have learned lots of others, but I tend to 'think' in Python. When I look at the list of changes I do not see one I need this feature. I usually say to myself, hmm that would been a good way of doing it, but why change it now?
Things like changing the default floor division could be a real pain to change for big projects. It seems like the major players are dragging their feet. What is the key feature that would make me want to invest in another learning curve?

A: A good discussion of this can be found in the python wiki; Should I use Python 2 or Python 3 for my development activity?

A: As a key feature, a lot of people seem to be pretty exited about (supposedly) transparent unicode support.  They changed it from str (8-bit char array/default string type) and unicode (unicode string), to str (default (unicode compatable) string) and bytes (binary data as 8-bit 'string').
(I think seperation of byte lists from strings is great idea, but I also hate unicode, so if anything, this would be a worse for me personally.)

A:
Things like changing default floor
  division could be a real pain to
  change for big projects.

If you had started making the change 8 years ago when Python 2.2 was introduced with // and from __future__ import division, it wouldn't be a pain now.  Personally, I'm glad to finally get rid of old-style division!
My second-favorite feature of Python 3.x is the str/bytes distinction.  Besides making Unicode support easier, bytes is far more convenient for database BLOBs than buffer was.

A: On Teaching Programming With Python 3.0, though a bit dated, is one of the best articles I've read on the advantages of Py3k.


text:
Q: Print JPEG File Using JSP Is there a JSP script I can run to point to a JPEG file on the local filesystem to be printed to the Windows default printer?  Thanks.
Edit:
I have the file on my server already.
How would I load the file into a browser to run window.print()?
Thanks

A: You will need a java applet if you don't want a server round trip. The applet is required so that you can:

*

*Access the local file system.

*Access the printer natively.

The user will need to grant the applet privileges.
Be aware that printing from java is notoriously hard.

A: You would have to get them to upload the image to your server, then put the jpeg on a page with JavaScript to call window.print().  It's a security violation for webpages to just start reading the local filesystem.


text:
Q: Dynamically added form elements This question is basically for my understanding, so kindly guide me. I dont require any code but just the approach for solving this type of problem.
I am using jquery to dynamically add form elements. For example, I want user to enter his favourite movie. I have given him an add button to add more movies. Now if user adds 10 times for 10 movies, how will i save this data to database ? i mean i will have only one column for movie but user is entering 10 (some might add 100) so how is this data stored ?
I have asked this question to basically understands how to save data when the form elements are dynamically added ? shall i save them to column movies and seperate them by commas or something else ?

A: There are many approach to solve this problem. One solution to this is AJAX. say example you are using php
1) Sort form data with each use press button; jQuery Form.
2) a php function to process sql queries.
3) call php function in ajax in success method.
4) store value in database.

A: In the form elements that you add, you would make the name= value into an array, so that the various identical items could be processed.
For example, suppose you are cloning a table row. Suppose this is the template row that you are cloning:

        Movie Name: <input type="text" name="mov[]" />

After the form was posted, the data would appear something like this:
POST DATA:
Array
(
    [mov] => Array
         (
             [0] =>           (the initial, template row would have no value)
             [1] => Gladiator (whatever user typed in)
             [2] => Troy      (the next movie entered by user...

The code I used to view the POST output above looks like this:
If (empty($_POST)===false) {
    echo '
';
    echo 'POST DATA:
';
    print_r($_POST);
    echo '
*********************************************************

';
    echo 'UPLOADED FILES:
';
    print_r($_FILES);
    echo '
';
    die('Dying immed inside IF EMPTY($_POST)===FALSE...');
}


text:
Q: rstan packages install from github i dont know why i have this error.
since i had aleardy set all of the environment variable, rtools, r, rstudio and home path to D:\DANNY HUANG\Documents correctly
p.s. i set the installation program's path to D disk since i don't have enough space in OS disk,

> install.packages("rstan", repos = "https://cloud.r-project.org/", dependencies = TRUE)

trying URL 'https://cloud.r-project.org/bin/windows/contrib/4.0/rstan_2.21.2.zip'
Content type 'application/zip' length 5225165 bytes (5.0 MB)
downloaded 5.0 MB

package 'rstan' successfully unpacked and MD5 sums checked

The downloaded binary packages are in C:\Users\DANNY HUANG\AppData\Local\Temp\Rtmp2D2Wbi\downloaded_packages

>example(stan_model, package = "rstan", run.dontrun = TRUE)

Loading required package: StanHeaders
Loading required package: ggplot2
Error: package or namespace load failed for 'rstan':
 .onLoad failed in loadNamespace() for 'processx', details:
  call: loadNamespace(name)
  error: there is no package called 'ps'


text:
Q: Problem loading csv files to sql server through visual studio I am getting below error while loading csv files into sql server (version 12.0.5571), I am using visual studio 10 for uploading data. Below are the errors which I am getting, need some help to figure out where am i going wrong.

[OLE DB Destination [529]] Error: SSIS Error Code DTS_E_OLEDBERROR.
  An OLE DB error has occurred. Error code: 0x80004005. An OLE DB record
  is available.  Source: "Microsoft SQL Server Native Client 11.0"
  Hresult: 0x80004005   Description: "Conversion failed when converting
  the nvarchar value '"201' to data type int.".
[OLE DB Destination [529]] Error: SSIS Error Code
  DTS_E_INDUCEDTRANSFORMFAILUREONERROR.   The "OLE DB
  Destination.Inputs[OLE DB Destination Input]" failed because error
  code 0xC020907B occurred, and the error row disposition on "OLE DB
  Destination. Inputs[OLE DB Destination Input]" specifies failure on
  error. An error occurred on the specified object of the specified
  component.  There may be error messages posted before this with more
  information about the failure.
[SSIS.Pipeline] Error: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The
  ProcessInput method on component "OLE DB Destination" (529) failed
  with error code 0xC0209029 while processing input "OLE DB Destination
  Input" (542).  The identified component returned an error from the
  ProcessInput method. The error is specific to the component, but the
  error is fatal and will cause the Data Flow task to stop running.
  There may be error messages posted before this with more information
  about the failure.
[Flat File Source [264]] Error: The attempt to add a row to the Data
  Flow task buffer failed with error code 0xC0047020.
[SSIS.Pipeline] Error: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The
  PrimeOutput method on Flat File Source returned error code 0xC02020C4.
  The component returned a failure code when the pipeline engine called
  PrimeOutput(). The meaning of the failure code is defined by the
  component, but the error is fatal and the pipeline stopped executing.
  There may be error messages posted before this with more information
  about the failure.

A:
OLE DB Destination [529]] Error: SSIS Error Code DTS_E_OLEDBERROR. An
  OLE DB error has occurred. Error code: 0x80004005. An OLE DB record is
  available. Source: "Microsoft SQL Server Native Client 11.0" Hresult:
  0x80004005 Description: "Conversion failed when converting the
  nvarchar value '"201' to data type int.".

The value "201 cannot be converted to INT because it starts with a double quote character.
Perhaps, this is a sign that text qualifier to be  as the double quote, similar to:

Otherwise, consider changing the failing column mapping from a numeric to a string type


text:
Q: Why is my if/then statement running through both sets of actions? For some reason this code is running the if statement and then the else statement as if there is no logic at all and I had just written the commands out one after the other. The really weird thing is that it's working perfectly fine in JS Fiddle so I can't even really re-create the problem.
    $('.acc-trigger').click(function () {
    if (!$(this).next().children('li.sideBarSubNav ul').is(":visible")) {
        $('.subnavReveal').text('►');
        $('li.sideBarSubNav ul').slideUp(300);
        $(this).children('span').text('▼');
        $(this).next().children('li.sideBarSubNav ul').slideDown(300);
    } else {
        $(this).children('span').text('►');
        $(this).next().children('li.sideBarSubNav ul').slideUp(300);
    }
});

JS FIddle of working code - http://jsfiddle.net/QNjR7/


text:
Q: Looping foreach/else statement I have an foreach statement in php, the code checks if an ip is in any of the ranges given, if it is echo 1, this works fine.
However i would like to add an else for this, so if the ip does not match any of the arrays then echo 2.
This is not working as it seems to echo 2 for each of the ranges it does not match so it echos 222 which is undesired.
How do i do have it so if in range echo 1 else if not in range echo 2
$range = (object) array();
    $range->name = 'test1';
    $range->lower = '10.1.5.78';
    $range->upper = '10.1.5.78';
    $public_ip_ranges[] = $range;

    $range = (object) array();
    $range->name = 'test2';
    $range->lower = '146.127.0.0';
    $range->upper = '146.127.255.255';
    $public_ip_ranges[] = $range;

    if (($lngIP=ip2long($ip)) < 0) $lngIP += 4294967296;

    foreach ($public_ip_ranges as $ip_range) {
       if (($lngLow=ip2long($ip_range->lower)) < 0) $lngLow += 4294967296;
       if (($lngHigh=ip2long($ip_range->upper)) < 0) $lngHigh += 4294967296;
       if($lngIP >= $lngLow and $lngIP <= $lngHigh) {
           echo 1;
        } else {
            echo 2;
            break
        }
    };

A: You can do something like this:
$range = (object) array();
$range->name = 'test1';
$range->lower = '10.1.5.78';
$range->upper = '10.1.5.78';
$public_ip_ranges[] = $range;

$range = (object) array();
$range->name = 'test2';
$range->lower = '146.127.0.0';
$range->upper = '146.127.255.255';
$public_ip_ranges[] = $range;

if (($lngIP=ip2long($ip)) < 0) $lngIP += 4294967296;

foreach ($public_ip_ranges as $ip_range) {
   if (($lngLow=ip2long($ip_range->lower)) < 0) $lngLow += 4294967296;
   if (($lngHigh=ip2long($ip_range->upper)) < 0) $lngHigh += 4294967296;
   if($lngIP >= $lngLow && $lngIP <= $lngHigh) {
        $result = 1;
        break;
    } else {
        $result = 2;
        break;
    }
}
echo $result;

On this case you are just printing $result as last result of loop. There are also breaks, if you dont want to continue.


text:
Q: cocos installation: AttributeError: 'dict' object has no attribute 'has_key' I am following the tutorial on my mac. I have all env paths set correctly but when I start a new project I am getting an error.
I have 2 pythons installed 3.4 and 2.7; is it a reason why I have a problem?
I wrote:
cocos$ cocos new HelloWorld -p com.myname.HelloWorld -l cpp -d / Users/dev/cocos/cocosProjects/HelloWorld

and I received the following error:
Traceback (most recent call last):
  File "/Users/dev/cocos/cocos2d-x-3.10/tools/cocos2d-console/bin/cocos.py", line 904, in
    if not _check_python_version():
  File "/Users/dev/cocos/cocos2d-x-3.10/tools/cocos2d-console/bin/cocos.py", line 868, in _check_python_version
    print(MultiLanguage.get_string('COCOS_PYTHON_VERSION_TIP_FMT') % (major_ver, minor_ver))
  File "/Users/dev/cocos/cocos2d-x-3.10/tools/cocos2d-console/bin/MultiLanguage.py", line 52, in get_string
    fmt = cls.get_instance().get_current_string(key)
  File "/Users/dev/cocos/cocos2d-x-3.10/tools/cocos2d-console/bin/MultiLanguage.py", line 46, in get_instance
    cls.instance = MultiLanguage()
  File "/Users/dev/cocos/cocos2d-x-3.10/tools/cocos2d-console/bin/MultiLanguage.py", line 100, in init
    if self.cfg_info.has_key(cur_lang_key):
AttributeError: 'dict' object has no attribute 'has_key'

A: I installed python2.7.11 once again and since then I could use cocos new to build a new project; aliasing python as python2 did not work before; I still have access to my 3.4 version for other applications but 2.7 is my default one which was the problem before.
I hope it will help those who have similar problem.
thank you all for having a look


text:
Q: MySQL List some field from a single table and COUNT all particular field reference from another table The subject of my question is a bit confusing because I'm running out of words to suit the general and technical description of it.
In a less technical terms, what I'm trying to accomplish specifically is:

List all churches and their corresponding booking status from a service they are offering with the following fields:

*

*Church id AS id

*Church name AS name

*Count of pending status from all services they are offering AS pendingCount

*Count of fully booked status from all services they are offering AS bookedCount
The structure of associate tables are as follows:
Church
+---------+---------------+
| id(int) | name(varchar) |
+---------+---------------+

Services
+---------+---------------+---------------+
| id(int) | name(varchar) | churchId(int) |
+---------+---------------+---------------+

Bookings
+---------+-----------------+----------------+
| id(int) | status(varchar) | serviceId(int) |
+---------+-----------------+----------------+

What I have come up so far is this, which I'm totally have no idea why it is compiling but produces a negative result:
SELECT
    churches.id,
    churches.name,
    pending.count AS pendingCount,
    booked.count AS bookedCount
FROM
    churches
INNER JOIN
    services
ON
    services.churchId = churches.id
LEFT JOIN
    (SELECT
        COUNT(bookings.id) AS `count`,
        bookings.serviceId
     FROM
        bookings
     WHERE
        bookings.status = 'pending'
     GROUP BY
        bookings.serviceId)
     AS pending
ON
    pending.serviceId = services.id
LEFT JOIN
    (SELECT
        COUNT(bookings.id) AS `count`,
        bookings.serviceId
     FROM
        bookings
     WHERE
        bookings.status = 'fully booked'
     GROUP BY
        bookings.serviceId)
     AS booked
ON
    booked.serviceId = services.id

Sample output

A: I would use conditional aggregation for this. It is a way to sum a number of rows that meet a certain value. In this case, we can use aggregation for SUM(b.status = 'fullyBooked') and SUM(b.status = 'pending') and group by church id like this:
SELECT c.id, c.name,
    SUM(b.status = 'pending') AS pendingCount,
    SUM(b.status = 'fully booked') AS bookedCount
FROM bookings b
RIGHT JOIN services s ON s.id = b.serviceId
RIGHT JOIN churches c ON c.id = s.churchid
GROUP BY c.id;

To reiterate, by using SUM(condition) and grouping by a certain id value, you are counting the number of times that condition is true for that id value.

EDIT:
I have added a RIGHT OUTER JOIN to this query so that churches without any bookings will be returned as well.

A: select c.id, c.name,
       SUM(b.status = 'pending') pendingCount,
       SUM(b.status = 'fully booked') bookedCount
from   church c
-- Left join here if you want all churches whether or not they offer a service
left join services s on (c.id = s.churchId)
-- Left join here if you want all churches w/ a service, but may have no bookings
left join bookings b on (s.id = b.serviceId)
group by c.id, c.name;

A: Try
SELECT
    churches.id,
    churches.name,
    count(case when bookings.status = 'pending' then 1 else null end) AS pendingCount,
    count(case when bookings.status = 'fully booked' then 1 else null end) AS bookedCount
FROM
    churches
INNER JOIN
    services
ON
    services.churchId = churches.id
LEFT JOIN bookings on bookings.serviceId=services.id
group by
    churches.id,
    churches.name,


text:
Q: PERL what is next element to $_ in for loop I want to compare 2 consecutive elements of loop
@arr=qw(1 2 3 3 4);
foreach(@arr)
{
if($_ == $_+1)
  {
  print "yes";
  }
}

What should i use instead of $_+1 in this case

A: You have to loop over indices,
my @arr = qw(1 2 3 3 4);
foreach (0 .. $#arr-1) {
  my ($current, $next) = @arr[$_, $_+1];

  if ($current == $next) {
    print "yes";
  }
}

A: I'd do it the plain old C way:
for( my $i=0; $i<@arr-1; $i++ ){
   if( $arr[$i] == $arr[$i+1] ){
      print "yes\n";
   }
}

Or in another style:
print "Yes\n" for grep{ $arr[$_] == $arr[$_+1] }(0..$#arr-1);

A: The FP solution would use pairwise from List::MoreUtils:
pairwise {
    say "yes" if $a == $b;
} @arr @{[ @arr[1..$#arr] ]}

(the @{[ ... ]} is annoying, but pairwise requires a true array and array slices aren't (you can't take references to them)).
(NB: $b will be undefined on the last iteration through the array, which may be what you want).

A: Yes, it is possible to do this with a range-based foreach loop, and without dealing with indices.  But instead of looking ahead, you keep track of where you've been; the number you got on the previous iteration. And avoid print on the first iteration.
{
  my $prev;
  foreach ( @arr ) {
    print "yes ($prev==$_)\n" if defined $prev && $prev == $_;
    $prev = $_;
  }
}

This assumes that there are no 'undef' elements in @arr.  If there may be, use a different sentinel to detect first iteration, or just iterate over indices as shown in other answers.
If your loop makes use of next you might want to put the thing that absolutely has to happen at the end of each iteration into a continue{...} block.
{
  my $prev;
  foreach ( @arr ) {
    next unless defined $prev && $prev == $_;
    print "yes ($prev==$_)\n";
  }
  continue {
    $prev = $_;
  }
}

The outer block isn't strictly necessary; it just serves to constrain the scope of our temporary $prev variable.
Keep in mind that with Perl it's possible that merely accessing an element in an array could have a side effect (thanks to the magic of tied variables).  So it wouldn't necessarily be a great idea (from the standpoint of language design) for foreach to offer a "peek_next" feature.


text:
Q: How to retry a request in Moya with RxSwift? I'm pretty new to RxSwift and, I am using Moya with RxSwift for networking in my app. I have the following function which is used for every request, for a given ProviderType.
open func request(for target: ProviderType) -> Observable<Response> {

    return provider.rx.request(target)
        .filterSuccessfulStatusCodes()
        .asObservable()
        .catchError { [weak self] error in
          guard let self = self else {
            return Observable.error(error)
          }
          return Observable.error(self.handleError(with: error))
    }
}

This works pretty well, but now I want to retry the request when the request fails with a status code of 401, after fetching the refresh token. I found this comment on a GitHub issue which tells how it can be achieved but I am still confused how it will work in my case (the comment does not provide context related to how the refresh token mechanism works).

A: I wrote an article about how to handle retrying when encountering an invalid token. The article goes into more depth but the TLDR is that you need to use the retryWhen operator instead of catchError.
By using retryWhen you can listen for the appropriate error, and attempt to refresh the token when the 401 comes in. If you get a new token, then it's just a matter of emitting a value from the closure's Observable. If refreshing the token fails, then simply emit an error with the reason why.
Also, at the beginning of the stream, you need some way of inserting the refreshed token.
https://medium.com/@danielt1263/retrying-a-network-request-despite-having-an-invalid-token-b8b89340d29


text:
Q: Looking for an efficient way to convert a dataframe (or matrix) to a triplet I have a sample dataframe as follows,
import pandas as pd
import datetime

start = datetime.datetime.now()
print('Starting time,'+str(start))
dict1 = {'id':['person1','person2','person3'], \
         'person1':['A','','', ], \
         'person2':['B','E',''], \
         'person3':['C','F','G',], }
demo = pd.DataFrame(dict1)
demo
demo.set_index(["id"], inplace=True)
demo

Out:

        person1 person2 person3
person1    A       B       C
person2            E       F
person3                    G

My target format is as follows,
    target_1    target_2    target
0   person1     person1       A
1   person1     person2       B
2   person1     person3       C
3   person2     person1       E
4   person2     person2       F
5   person3     person3       G

Now I want to convert it into a triple, and I can think of using a loop to iterate over each element, but I think this may not be efficient, especially for large data sets, since I am new to python, so I want to find a more efficient way.
Any help is appreciated.

A: Don't use loop. Let's do stack to reshape the dataframe
demo[demo != ''].stack().rename_axis(['target_1', 'target_2']).reset_index(name='target')

Result
  target_1 target_2 target
0  person1  person1      A
1  person1  person2      B
2  person1  person3      C
3  person2  person2      E
4  person2  person3      F
5  person3  person3      G

A: for i in demo.index.tolist():
    for j in demo.columns.values.tolist():
        print(demo.loc[i][j])


text:
Q: How index will work on separate date and time column in PostgreSQL I have two separate columns in Postgres Database for Date and time
I had Index in Date column and time column. As earlier I need to filter the data using date filter only Index worked perfectly. But In recent requirement I need to filter the data using both date and time filter.
when I filter the data by combing date and time like
concat(date_column, ' ', time_column) ::timestamp>='{var_date_time}' Date  and time Index does not work . It takes time to fetch the data.
any way where I can create index by combining both Date and time columns?

A: You need to create an index on exactly the expression you are going to use in your WHERE clause. You don't need to cast between a text and a timestamp, just add the two columns:
where date_column + time_column >= ...

Needs the following index:
create index on the_table ( (date_column + time_column) );

You might want to think about changing that into a single column in the long run.

A: That is probably not a good way to store your data.  It would be better as a single timestamptz column.
With your existing table and index, you can use a tuple comparison:
WHERE (date_column,time_column)>(date_constant,time_constant);

It is not clear to me if your existing structure is one multi-column index or two single-column indexes.  Either way, it should use (one of) the indexes, but the multi-column would be better.

A: Is your recent requirement for date + time a replacement for the existing or an addition to the existing.  If replacing the current date only requirement then replacing with a single column, as suggested, is the likely the best solution. However, if this is an additional requirement there is an alternative: add a timestamp as as a generated column then create an index on that column:
alter table <table> add ts_col timestamp generated always as (date_col+time_col) stored;
create index test_ts_col_ndx on <table> (ts_col);

With that your existing queries and dml statements do not change, you only need the new queries where date+time  is required. ( see demo)


text:
Q: quanteda: producing an output for several targets using textstat_keyness similarly to textstat_frequency I have a corpus with 2 document variables: group and interest.
I am interested in identifying the key features for a given combination of interest&group (the target) versus the rest of the corpus using textstat_keyness and I want to replicate this for any possible combination of interest and group.
I can easily do this once in the following way:
data_trim@docvars$focus <- 0
data_trim@docvars$focus[data_trim@docvars$group=="One of the Groups"
& data_trim@docvars$interest=="One of the interests"] <- 1 #I created the

keyness <- dfm(data_trim, groups = "focus")
k_sustainability <- textstat_keyness(keyness, target ="1")

however I d like to find an easy way to produce results for any possible combinations of group and target without the need of manually doing this.
I know that textstat_frequency function allows me to select  groups = c("group", "interest")
and produces an output with the most frequent words for any combination of "group" & "interest".
is there any way to do the same with textstat_keyness?
(I show an example of how the textstat_frequency output looks like)
textstat_frequency(dt_tfidf, n = 20, groups = c("group", "interest"), force=TRUE)

feature     frequency   rank      docfreq      group
 ...          ...        1          ..         group1 & interest1
                         2                     group1 & interest1
                         3                     group1 & interest1
                         .                     ....
                         .
                         1                     group2 & interest1
                         2                     group2 & interest1
                         .                      .
                         .
                         18                     group100 & interest100
                         19                     group100 & interest100
                         20                     group100 & interest100

so I want something similar using textstat_keyness in order to obtain something like this (i.e. having the top 20 scoring features, and the corresponding group alongside identifiable by the columns rank and group as I have in textstat_frequency):
feature    chi2         p           n_target        n_reference rank    group
 ...         ..             .. ...      ..           ...          1.    group1 & interest1
  ....

A: textstat_keyness() identifies the keywords most associated with a target "document" from a dfm, compared to all other documents.  So for your comparison of combinations, you will need first to create a grouped dfm according to the combination of your groups.  Then you can loop through the dfm and create a comparison for each group against all others.
Here is how to do it:
library("quanteda")
## Package version: 1.5.2

docvars(data_corpus_irishbudget2010, "govopp") <-
  ifelse(docvars(data_corpus_irishbudget2010, "party") %in% c("FF", "Green"),
    "Government", "Opposition"
  )
dfmatgr <- dfm(data_corpus_irishbudget2010, groups = c("govopp", "party"))
head(dfmatgr, nf = 5)
## Document-feature matrix of: 5 documents, 5 features (16.0% sparse) and 4 docvars.
##                   features
## docs               when  i presented the supplementary
##   Government.FF       9 90         1 933             7
##   Opposition.FG      19 42         1 802             1
##   Government.Green    9 33         0 224             0
##   Opposition.LAB     25 76         0 856             0
##   Opposition.SF      28 31         1 783             2

That creates the groups, which in this case are by government and opposition and party.  (Your example may have overlapping groups, but since I cannot reproduce it, I used an example from one of the built-in corpora.)
Now we create a data.frame and loop through the targets.  For presentation I've only recorded the top 2 keywords, but you can change this to 20 or whatever you prefer.
df <- data.frame()
for (g in docnames(dfmatgr)) {
  df_temp <- head(textstat_keyness(dfmatgr, target = g), 2)
  df_temp[["target"]] <- g
  df <- rbind(df, df_temp)
}

df
##         feature      chi2            p n_target n_reference           target
## 1          2010  59.14626 1.465494e-14       41          14    Government.FF
## 2        scheme  51.30431 7.910339e-13       31           8    Government.FF
## 11    taoiseach 116.89154 0.000000e+00       49          18    Opposition.FG
## 21          not  39.15371 3.917181e-10      127         259    Opposition.FG
## 12 enterprising 102.69108 0.000000e+00        9           0 Government.Green
## 22           we  67.76028 2.220446e-16       97         521 Government.Green
## 13       fianna  66.59467 3.330669e-16       47          25   Opposition.LAB
## 23         fáil  65.23011 6.661338e-16       44          22   Opposition.LAB
## 14        state  59.81864 1.043610e-14       42          32    Opposition.SF
## 24         care  32.97959 9.313121e-09       18          10    Opposition.SF

Note:  I strongly discourage accessing docvars using e.g. data_trim@docvars$focus -- use docvars() instead since this will always work.  If we change the object structure, your code will break.  (And in forthcoming v2, we make it possible to access docvars using $.)


text:
Q: Class variable set by BackgroundWorker not persisting. I am brand new to the idea of BackgroundWorkers, so this has me a little perplexed.
So I created a new WPF Application and created a BackgroundWorker and List class variable:
public partial class MainWindow : Window
{
    private BackgroundWorker bw = new BackgroundWorker();
    private List<int> tempList = new List<int>();
    ...

Then I use the BackgroundWorker to populate that list: (In the same class btw)
    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        Random r = new Random();
        for (int j = 1; j <= 100; j++)
        {
            for (int i = 0; i < 1000; i++)
            {
                tempList.Add(r.Next(100));
            }
            ...
        }
    }

Now here is the part that's getting me...
The code that populates that list seems to be working fine. When I step through its execution, *it behaves as I have intended until the exact moment the code exits the bw_DoWork method.* After that point, it reverts back to an empty list. I changed the list to static at one point but nothing changed.
So why is this List not persisting throughout the programs execution?
I am(was) almost certain that this is some issue with the list being allocated in different memory regions for each thread, but I simply know far too little about about BackgroundWorker and MultiThreading in general to diagnose it myself.
Any help would be appreciated.

A: Before you start using more expensive options such as locking or thread safe collections. Try out Threading Tasks. If they work then you have some kind of a problem with your BackgroundWorker, if they don't then your code touches the list somewhere and you'll have to trace that.. (I just think Tasks are so much easier to work with)
private void bw_DoWork()
    {
        Task.Factory.StartNew(
            () =>
            {
                 var r = new Random();
                for (int j = 1; j <= 100; j++)
                {
                    for (int i = 0; i < 1000; i++)
                    {
                        tempList.Add(r.Next(100));
                    }
                    //the rest of whaterver you're doing...
                }
            });
    }

A: @Stephen Marsh like @Douglas said you need to wait until work is finish.
See this:
// this execute the DoWork asynchronously.
bw.RunWorkerAsync();
// asynchronously means the next line may be executed
// before the DoWork fill the list. In fact can be executed
// before the DoWork begin.
MessageBox.Show("Without wait: " + tempList.Count.ToString());

To correct you can add this line before call RunWorkerAsync:
bw.RunWorkerCompleted += bw_RunWorkerCompleted;

and put this in any place of the MainWindows class.
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    MessageBox.Show("Completed: " + tempList.Count.ToString());
}

In my tests always the result was:
"Without wait: 0"
"Completed: 100000"


text:
Q: Why isnt the signal getting blocked? When I raise SIGUSR2 inside the SIGUSR1 handler, shouldn't it get blocked ? This code prints "second - Inside first"
void
hand1(int s) {
    kill(getpid(), SIGUSR2);
    printf("Inside first");
}

void
hand2(int s) {
    printf("second - ");
}

main() {
    signal(SIGUSR1, hand1);
    signal(SIGUSR2, hand2);
    kill(getpid(), SIGUSR1);
}

A:
When I raise SIGUSR2 inside the SIGUSR1 handler, shouldn't it get blocked ?

No.  This is what's happening:
time  signal_mask  code
----  -----------  ----
 0         -       main:signal(SIGUSR1, hand1)
 1         -       main:signal(SIGUSR2, hand1)
 2         -       main:kill(getpid(), SIGUSR1)
 3    USR1         hand1:kill(getpid(), SIGUSR2)
 4    USR1|USR2    hand2:printf("second - ")
 5    USR1         hand1:printf("Inside first")
 6         -       main:...

But don't use signal(), instead prefer sigaction().  The former doesn't guarantee handler semantics on all platforms, the latter does.
Also, sigaction makes explicit which signals are blocked during the handler and which are not.  If you wanted to block all signals during your handler (and I'd generally recommend that as it is easier to reason about the behavior of a function you know won't be interrupted), you could do something like:
int handle_signal(int sig, void (*handler)(int)) {
  struct sigaction sa = { .sa_flags = 0 };

  sigfillset(&sa.sa_mask); // block everything during handler
  sa.sa_handler = handler;

  return sigaction(sig, &sa, NULL);
}


text:
Q: Not validating fields when one is not null - hibernate
Do u have any ideas how to validate one object in this case?
I have class A which is built of two another classes B and C:
public class A{
private B b;
private C c;
}

In that case I would like to validate all fields from object B, which looks like this:
public class B{
private String name;
private Long number;
}

This kind of object A is being passed into my Controller as request object, so that I'd like to validate it before it's sent.
The point is that I'd like to validate name and number objects when they are both passed but if any of them is null then I'd just like to validate the one which is not null.

Do you guys have any ideas how to do that? I made @Valid on A object as well as on B field but it shows no ConstraintValidatonException.

Problem solved - Validation doesn't work on Restcontroller method but after passing it on Service, everthing works well. I'm going to investigate it in a free time.

A: I would leave a comment but I'm unable to so here is my answer:
Why dont you create a validate method in class B which you can call in class A.


text:
Q: Red https with cross without reason (Apache + mod_ssl) I just added mod_ssl with a signed certificate, but I can't figure why Google chrome is marking my connection as untrusted
screenshot:

although, another website has almost the same details, but Google chrome is not marking it as untrusted:

Can someone help me, why google chrome is marking my website as untrusted?
EDIT 1 (Adding certificate information)

A: Per Google's note on SHA-1 deprecation,

Sites with end-entity certificates that expire on or after 1 January 2017, and which include a SHA-1-based signature as part of the certificate chain, will be treated as "affirmatively insecure". Subresources from such domain will be treated as "active mixed content".
The current visual display for "affirmatively insecure" is a lock with a red X, and a red strike-through text treatment in the URL scheme.


text:
Q: Can't get rid of __pycache__ After noticing the pycache folder i decided to ignore them adding pycache\ in gitignore but it doesn't seem to work (it works in the root folder but not recursively in subfolder utilities) ...
Any idea ?


text:
Q: .htaccess sub links not effecting I want to make dynamic links to seo friendly links so i had created a htaccess rules as follow
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^product/category/([a-z0-9_-]+)?$  products.php?category=$1  [NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^products/uicat/([a-z0-9_-]+)?$  products.php?uicat=$1  [NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (index|about|products) $1.php [L]

I'm running centos 7 with apache and PHP 7.3 and i have enabled Allowoverride ALL and options:
Options Indexes FollowSymLinks ExecCGI Includes MultiViews

If i rename rewrite rule to
RewriteRule ^testproducts/uicat/([a-z0-9_-]+)?$  products.php?uicat=$1  [NC,L]

it does work so i don't know what i'm doing wrong and i'm not really comfortable with these htaccess rules so all helps appreciated.

A:
Options Indexes FollowSymLinks ExecCGI Includes MultiViews

You need to remove MultiViews from the Options directive.
By enabling MultiViews mod_negotiation will trigger an internal subrequest for products.php (having requested /products) - before your mod_rewrite directives are able to process the request, so will not include the URL parameters.
You probably want to remove Indexes as well. And do you really need ExecCGI and Includes?

Aside:
Do you need all the filesystem checks? Could a request of the form /products/category/something map to a file or directory? Bear in mind that your regex already excludes a file extension.

RewriteRule (index|about|products) $1.php [L]

This is matching index, about or products anywhere in the requested URL-path - this is too general, since you are rewriting to a file in the current directory.


text:
Q: SQL select for xml explicit -- need help defining alternate structure when value is null I have the following SQL query that I'm having trouble explicitly defining the shape for
select tableName, uqName, col1, col2
from someTable

I would like to select the results into XML as below. I need the col1 and col2 to show up as children and tableName and uqName to show up as attributes. If col1 or col2 is null then I need to specify an IsNull attribute. Otherwise the value is selected as a text node as the child of the Col element
One row returned from the above SQL would look like this:
<UniqueKey Name="UniqueKeyName" TableName="TableName" >
  <Col Name="col1" IsNull="true" />
  <Col Name="col2">ABC</Col>
</UniqueKey>

How can I explicitly define this XML shape using SQL Server 2008 R2?

A: declare @T table
(
  tableName varchar(20),
  uqName varchar(20),
  col1 varchar(10),
  col2 varchar(10)
)

insert into @T values
('TableName', 'UniqueKeyName', null, 'ABC')
insert into @T values
('TableName', 'UniqueKeyName', null, null)
insert into @T values
('TableName', 'UniqueKeyName', '123', '456')

select uqName as "@Name",
       tableName as "@TableName",
       (select 'col1' as "@Name",
               case when col1 is null then 'true' end as "@IsNull",
               col1 as "*"
        for xml path('Col'), type),
       (select 'col2' as "@Name",
               case when col2 is null then 'true' end as "@IsNull",
               col2 as "*"
        for xml path('Col'), type)
from @T
for xml path('UniqueKey')

Result:
<UniqueKey Name="UniqueKeyName" TableName="TableName">
  <Col Name="col1" IsNull="true" />
  <Col Name="col2">ABC</Col>
</UniqueKey>
<UniqueKey Name="UniqueKeyName" TableName="TableName">
  <Col Name="col1" IsNull="true" />
  <Col Name="col2" IsNull="true" />
</UniqueKey>
<UniqueKey Name="UniqueKeyName" TableName="TableName">
  <Col Name="col1">123</Col>
  <Col Name="col2">456</Col>
</UniqueKey>


text:
Q: Data filtering & requests: fetch all entries or split data? I am in a situation I cannot decide which approach is the most optimal (performance wise) while being maintainable at the same time (in the sense of having a clear logic).
The question is laid in the context of a Django web app, but I figure it applies to any related scenario.
In my scenario we are visiting a particular route that displays many matches in a league or tournament associated to a particular season:
URL: season/<season_id>/
Associated Django ORM query: season.match_set.all()
A season has many divisions, and of course, matches are made up of teams. The client can filter by division and/or by team. These filters can also be included in the URL (so users can share it, already filtered), i.e. season/<season_id>/#division=<division_name>, so matches belonging to the specified division are filtered.
However, even when visiting a route including a filter, the entire query is executed: season.match_set.all().
And here is what I cannot decide about. In terms of efficiency, it would be way better to just fetch the matches related to that division:
season.match_set.filter(division=division)

However, it might be pretty common that users use the filters in the page, switch between them, etc. Which, if we use the second approach, would obviously mean additional requests which would also mean extra database hits to retrieve the filtered matches. This would not happen with the first approach since we have all the data set since the beginning: just one request and one database hit (although heavier).
We could try to optimize the second approach by storing filtered data as requested; i.e. if we have a season with three divisions and the user filters by Division 1 (request 1), we store that somewhere (in the client side I figure), then if he/she filters by Division 2 (request 2) we do the same and add it to the existing data, and finally if the user filters by Division 1 again we just get it from the stored data and we can spare ourselves from performing request 3.
However, I have concerns about having a clear logic and code as I mentioned before, because this last optimization approach can easily get really funky and unreliable.
My question: what is the to-go approach? This is a fairly common scenario so I figure there must be a consensus on what is the most efficient approach: fetching all database entries and performing just one request or performing multiple requests and database queries and get data as it is being requested?

A: No, there isn't a consenus. You have to use your own judgement.
The reason there isn't a consensus is that different solutions are appropriate in different situations. What you're confronting is a question of trade-offs - multiple orthogonal requirements that are all important, but cannot all be satisfied simultaneously. Here are some of the trade-offs involved:

*

*memory usage vs. speed: Caching the results of one query for reuse by subsequent queries increases the peed of subsequent queries (not the first one) at the price of using more memory. How to resolve this trade-off depends on how much you value fast responses vs. the cost of buying more RAM.

*speed of the first query vs. speed of queries in general: fetching all results even for a filtered query takes longer than fetching a subset, but it offers the potential of speeding up subsequent queries. How to resolve this trade-off depends on how many first queries vs. subsequent queries you expect, or on how important fast replies vs consistently-timed replies are to your users (ask a UX expert: paradoxically, people may prefer a consistently not-very-fast response to a sometimes-fast-sometimes-slow one).

*convenience of use vs. programming complexity: computing the result of one query from the stored results of a previous query can speed up your response by eliminating expensive I/O, but it requires mpore complicated programming with more potential for missed deadlines and defects. Is the complexity worth its price? This is a question only project management can answer. If the project has a hard requirement "must answer withtin 100ms 99% of the time" then the additional logic might be indispensible. If the hardest requirement is "must be live tomorrow" it might not be.
You can see that these are all questions you can answer better than we can. We can only suggest questions to ask yourself.


text:
Q: Return length of strings in array with ruby I'm a beginner to programming and I was given this problem to solve with ruby:
Given an array containing some strings, return an array containing the length of those strings. You are supposed to write a method named 'length_finder' to accomplish this task.
I wrote:
def length_finder(input_array)
    a = [ ]
    input_array.each { |n| puts n.length.to_i }
    a << n
    a
end

I got an error undefined local variable or method `n'. What's wrong with the code?

A: Since this is an assignment, I won't give a direct answer to your problem.  Instead, I'll show something similar.  Suppose you wanted to create an array consisting of the first character of each word in a given array:
def first_char(x)
  x.map {|s| s[0]}
end

y = first_char(["abc", "xyz", "def"])      # y => ["a", "x", "d"]

Replace s[0] with a suitable manipulation for your problem.
Try this (and your own method) in irb, the interactive Ruby environment. Exploring is one of the best ways to learn, and irb makes exploring easy.

A: Following your particular approach, it should be
def length_finder(input_array)
    a = []
    input_array.each do |n|
        a << n.length
    end
    a
end

In your code, you are defining n inside a block and printing its size. You don't want to print its size. You want to put it in a. You get an error saying it is undefined because you are doing a << n outside the scope.

A: First looking at your error, if you look closely, scope of n is only in each block, however you are trying to use it outside it's scope, thats why you are getting this error and second mistake is in a you should be appending n.length, which you want in the output, correct these two and you got a working code:
def length_finder(input_array)
    a = [ ]
    input_array.each { |n| puts n.length.to_i
                           a << n.length }
    a
end

however, this can be done in one line, using map or inject and the fact that ruby returns the output of last executing statement in a function. I will encourage you the try the one line solution for this.

A: what you exactly need is just the following three lines of code:
def array_length(input_array)
  length = []
  input_array.each{ |a| length << a.length}
  length
end

A: Using Map method of Ruby gives one liner solution -
def length_finder(input_array)
  input_array.map { |s| s.length }
end


text:
Q: setkeys in a class throws missing \begin{document} Using the following syntax in a class, throws error
Missing \begin{document}.
\define@key{pictures}{foo}{Foo is #1}

% set default values for the keys
\setkeys{pictures}{foo=2} % This line throws error

What am i missing here?


text:
Q: Fatal error within Woocommerce "wc-template-functions.php" file I have tried to edit wc-template-functions.php in my store and did something wrong.
Now I am getting Fatal Error on 281 line.

Fatal error: Uncaught Error: Class 'Constants' not found in /home/kidsandm/oliverthedog/wp-content/plugins/woocommerce/includes/wc-template-functions.php:282 Stack trace: #0 /home/kidsandm/oliverthedog/wp-includes/class-wp-hook.php(292): wc_generator_tag('<meta name="gen...', 'xhtml') #1 /home/kidsandm/oliverthedog/wp-includes/plugin.php(212): WP_Hook->apply_filters('<meta name="gen...', Array) #2 /home/kidsandm/oliverthedog/wp-includes/general-template.php(4728): apply_filters('get_the_generat...', '<meta name="gen...', 'xhtml') #3 /home/kidsandm/oliverthedog/wp-includes/general-template.php(4650): get_the_generator('xhtml') #4 /home/kidsandm/oliverthedog/wp-includes/general-template.php(4627): the_generator('xhtml') #5 /home/kidsandm/oliverthedog/wp-includes/class-wp-hook.php(292): wp_generator('') #6 /home/kidsandm/oliverthedog/wp-includes/class-wp-hook.php(316): WP_Hook->apply_filters(NULL, Array) #7 /home/kidsandm/oliverthedog/wp-includes/plugin.php(484): WP_Hook->do_action(Array) #8 /home/kidsandm/oliverthedog/wp-includes/gen in /home/kidsandm/oliverthedog/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 282

Before that I also had warning at the top that said:

Warning: The use statement with non-compound name 'AutomatticJetpackConstants' has no effect in /home/kidsandm/hondamarine/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 11

but I have hide that line thinking it might help.
What I have change in file?
Additional information.
I was thinking it will change the name of it on front-end as well.

// Additional information tab - shows attributes.
if ( $product && ( $product->has_attributes() || apply_filters( 'wc_product_enable_dimensions_display', $product->has_weight() || $product->has_dimensions() ) ) ) {
$tabs['additional_information'] = array(
'title'    => __( 'Additional information', 'woocommerce' ),
'priority' => 20,
'callback' => 'woocommerce_product_additional_information_tab',
);
}

Line 1798.
I have tried to find a code only to replace it, and I found one but did not help.
Now, that code might not be original because I could not find it on GitHub.
Thanks a lot!

A: It just happened to me too, I tried to edit the code for the same reason, I searched a lot about this problem and I solved it when I downloaded the plugin in zip form and manually upload it and install it, now its working fine for me and all data still in place (categories, products, etc.)!
I had the following 2 errors:
Fatal Error: Uncaught error: Class 'Constants' not found in /Users/anastasiades/Local Sites/pisinaspa/app/public/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 282
Error: Class 'Constants' not found in /Users/anastasiades/Local Sites/pisinaspa/app/public/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 282
Steps:
1. Backup data in woocommerce
2. Download plugin here
3. On WordPress go to Plugins >> Add new >> Upload plugin
4. Choose Reinstall >> Install now
5. "Replace current with uploaded"
I recommend a good backup of the products and other data before doing this.
Peace!


text:
Q: Calendar, mouseover on day >> show what's in the row that contains that date I have the following simple list in a sheet named "Pipeline":

Whenever a date is entered in column E, those dates get formatted in another sheet named "Calendar" (same document), where I have a calendar that looks like this:

This is the conditional formatting formula: =match(B1,indirect("Pipeline!E:E"),0)
To this point, all good.
Now, when I am in "Calendar", I would like to output the topic from sheet "Pipeline" respective to the date I mouseover, or I select.
For example, if I now select cell V16 in "Calendar", which corresponds to date "18 Jun", I need "Retargeting for Ho" (value of cell A10 in sheet "Pipeline") to be output somewhere.
I don't quite care how. It may be a cell in the the Calendar sheet, or mouseover. Really, the output format is not that necessary.
Hope someone can help.
Thanks in advance.
A.

A: Approach
This behavior is achievable through an event programming technique. In Google Sheets you can trigger functions based on these events:

*

*Document open

*Document edit

*Document selection

For this purpose you can use the onSelectionChange(e) function. A handler for the Document selection event.
To handle these events you will need an Apps Script project. You can easily bound one to your Spreadsheet going to Tools>Script Editor.
Output representation
I think that on Google Sheets you can benefit of the Note UI representation to show the wanted information based on the selected cell content.
Code:
Here is an example on how to handle the selection event to append a Note UI element to the selected cell:
function onSelectionChange(e) {
  let date = e.range.getValue().toString(); // I will explicitly cast the date object to string to ensure the comparison will work
  let range = e.range; // This will return a range of exactly one cell: The selected one
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let pipeline = ss.getSheetByName('Pipeline');
  let pipelineRows = pipeline.getDataRange().getValues(); // I will load all the Pipline table in a multidimensional array to get the title information
  let title = pipelineRows.filter(row => row[5].toString() == date).map(row => row[1]); // I will filter the Pipeline Rows by date and extract the title
  range.setNote(title); // Finally I will append the extracted title to a note in the selected cell.
}

Reference
Triggers
Event Object
SpreadsheetApp


text:
Q: Error to get return of url in spring boot application with javascript I'm trying to get the return of the request in the url, with javascript, but I'm having problems.
I have the follow code:
Controller:
@GetMapping("/linguagens")
@ResponseBody
public Map<String, Linguagem> linguagens(){
    Map<String, Linguagem> linguagens = new HashMap<>();
    linguagens.put("linguagem", new Linguagem("Java", true));
    return linguagens;
}

HTML page:
            <button id="verLinguagens">Ver linguagens</button>

JavaScript code:
$('#verLinguagens').click(function (e) {
e.preventDefault();
$.get("/linguagens")
    .done(function (data) {
        $('#linguagens').html("Linguagens: " + data.linguagem)
        console.log(data.linguagem)
        console.log(data)
    });

});
In my page show the result, but show like this:
Linguagens: [object Object]

how can I show the correct result? like this
{
"Linguagem": {
    "nome": "Java",
    "compilada": true
}

}
Thanks!

A: It works!!
Linguagens: {"nome":"Java","compilada":true}

but, like this, I can put each value of key in some label?
like, value "java" in label with id "javaLabel"?

A: You can use JSON.stringify(data) to convert the data to a json representation.

A: Would this give you what you're after?

var data = {
    "Linguagem": {
        "nome": "Java",
        "compilada": true
    }
};

console.dir(data);
var pretty = JSON.stringify(data, null, '\t');
document.getElementById('content').innerHTML = pretty;


text:
Q: Wordpress Contact form 7 - dropdown issue due to too many options I've been encountering an error when having too many options in a drop down. It simply freezes if there are over 222 options.
I'm running on PHP 5.3.5, but this also happens when running on PHP 5.3.13. Curiously, this issue DOES NOT happen when using 5.2.27.
I've been trying to back trace the error, and I believe it's got something to do with the preg_replace_callback() function called inside do_shortcode () in /includes/shortcodes.php on row 62.
Has any of you encountered the same issue, and do you happen to know how to solve it?
Thanks


text:
Q: How do you make a 3D city population graphic? I want to make a graphic that has the shape of a country, finds all the cities of that country, gets their coordinates and populations and turns that into a SmoothHistogram3D with the population being the z value.
I tried this, but apparently that's not how it works:
SmoothHistogram3D[
 DeleteCases[
  CityData[#, "Coordinates"] & /@ CityData[{All, "Mexico"}],
  Missing["NotAvailable"]],
 DeleteCases[CityData[#, "Population"] & /@ CityData[{All, "Mexico"}],
   Missing["NotAvailable"]]]

A: Something like this is probably what you're after:
dat = DeleteCases[({CityData[#, "Population"],
    CityData[#, "Coordinates"]} & /@
    CityData[{All, "Mexico"}]), {___, _Missing, ___}];
func = PDF[SmoothKernelDistribution[
    WeightedData[dat[[All, 2]], dat[[All, 1]]]], {x, y}];
ra = func[[2, 0, 1]];
Plot3D[Log10@func, {x, ra[[1, 1]], ra[[1, 2]]}, {y, ra[[2, 1]],
    ra[[2, 2]]}, PlotRange -> {-5, All}]

Note that you were deleting the Missing cases for the Population and Coordinates separately, but these two lists of data do not correspond to the same lists of cities, you can see this by checking that their lengths are different. The expression above only includes cities that have both datum.
I took the log of the function to get better depth contrast, otherwise the image is dominated by huge spikes from the very largest cities.


text:
Q: JQuery DataTable Add Row with empty textbox In JQuery Datatable plugin, i have populated some data.
Now i need to add a new empty row with empty textboxes below the existing dataTable rows.
I tried using the below code piece, its adding the row as undefined
$('#eventTable').DataTable().row.add([
            counter + '.1',
            counter + '.2',
            counter + '.3',
            counter + '.4',
            counter + '.5',
            counter + '.5',
            counter + '.5'
    ]).draw(false);

Is there is any way to add a new empty row with text boxes.


text:
Q: Windows Phone SDK Network I am getting used to the Windows Phone SDK in Visual Studio.
Right now I am writing a simple web browser so that I can build off of it in the future in C#.
What I am having an issue with is - if the phone doesn't have any signal:

*

*I don't want the application to redirect to the generic could not find the website that you are looking for.

*I would like it to redirect to a new page that I have control over.

So my basic question is this - is there a way to detect whether the phone has a connection to the network - or better yet if the phone redirects to a new website?
I need that because I could potentially catch the error and display something like you aren't connected to a network please try again once you have connected.

A: Yes you can find whether your phone is connected with network or not in windows phone
try this
add a name space using Microsoft.Phone.Net.NetworkInformation;
if (DeviceNetworkInformation.IsNetworkAvailable)
{
MessageBox.Show("Network");
}
else
{
MessageBox.Show("No Network");
}


text:
Q: How to get clang-tidy to disable coloured output A recent change to run-clang-tidy.py means that the underlying clang-tidy command is now always run with -use-color. The question is how to disable that.
I use this script with the Sonarqube Community C++ plugin and this cannot handle the extra colourisation characters - FTR it reports that all the files cannot be found in the associated repo.
I have tried adding extra parameter -config '{"UseColor":false}' but it made no difference.
Short term, I will probably locally modify the python script. Long term, I wonder if there is a better approach?

A: This issue is now fixed in LLVM's main branch and should be resolved in the next release. The old default behavior has been restored and you'll be able to explicitly opt in or out of colored output using the -use-color option.
As a short-term fix, you can strip out the ANSI escape characters that enable colored output yourself. See Removing colors from output for instructions.


text:
Q: WP Widget instances and options When I activate my plugin I add some values to the options database, e.g.
add_option('code','55');

How do I update that value or use it in the widget? I only see "instances" now, like the example on this page:
http://wpcoderz.com/creating-a-multi-instance-widget-with-wordpress-2-8/
I've gone through all of the widget API, but no go.

A: Ryan, the code for a widget isn't special, so to obtain the value of options set with add_option(), just use get_option() as usual - and update_option() to update it.
Not sure what you meant by 'instances' - the link seems broken.


text:
Q: Youtube iframe not showing in UIWebView I have an iframe within the html string,

this works in a browser but not in my UIWebView(in the webview it is just blank where the iframe should be).
Any ideas?
Thanks.

A: I'm afraid your video URL is not valid. Write the following code into your viewDidLoad:

NSString *embedHTML = @"";
[self.webview loadHTMLString:embedHTML baseURL:nil];


text:
Q: Possible polygons in uniform polyhedra
Summary: What are the possible regular polygons that can be created by the orbit of a 3D point under $O_h$ or $I_h$?

I've been reading about uniform polyhedra for a while now. Something that has stricken me as odd is that, excluding prisms and antiprisms, there are only certain regular polygons that can appear on a uniform polyhedron. When the symmetry group of the figure is a subgroup of $O_h$, the possible number of sides are 3, 4, 6 and 8. Likewise, when the symmetry group is a subgroup of $I_h$, the corresponding numbers of sides are 3, 4, 5, 6 and 10. And moreover, polyhedra with more than 4 sides are always invariant under some rotation of the group. One could prove this by looking at the classification of uniform polyhedra, but that feels like cheating. Instead, I'd like to prove the more general fact that the orbit of a point under one of these groups can only create the corresponding regular polygons.
I've tried looking at the individual symmetries of a regular $n$-gon creating a counterexample, trying to prove they must be contained in the greater symmetry group, to no avail. I've also tried more combinatorial approaches, as well as stuff with vectors, but those just seem to lead to humongous casework. I'm completely stuck at the moment. Any help?

A: $O_h = [3,4]$ has 2-gonal, 3-gonal and 4-gonal rotational symmetry axes. So clearly you could generate a regular triangle and a square ($n$-gon). But when placing the edges somewhat more apart you also can generate a hexagon and an octagon ($2n$-gon).
Same for $I_h = [3,5]$, it has 2-gonal, 3-gonal and 5-gonal rotational symmetry axes. So clearly you could generate a regular triangle and a regular pentagon ($n$-gon). But when placing the edges somewhat more apart you also can generate a square, a hexagon and a decagon ($2n$-gon).
--- rk


text:
Q: PHP/MySQL: Parse html and upload media I have a site created with PHP 4.3 and MySQL. I need a way so a client can send an HTML file to the server and have it parsed and sections inserted into the database. During parsing, any images or other media found will need to be uploaded to the server.
I am not really sure what is the best way to go about this. I was thinking of maybe using jQuery and Ajax to parse the content but what can I do to get the media?
Do you have any better suggestions on how to accomplish this?

A: This is quite a large question. I've pointed you to some resources that might help.
For Html Parsing -> http://simplehtmldom.sourceforge.net/
Easy way to download images and other media -> http://au1.php.net/manual/en/function.file-get-contents.php
Uploading original html5 file -> http://www.w3schools.com/php/php_file_upload.asp
Good luck


text:
Q: Improve ANT Ivy build process I have a project setup with apache-ant Ivy. The project has several modules like
commons,user,order,billing,reports and so on. I need to improve the build process. I am new to ANT Ivy.
Background
Module compiling sequence is defined in the main build.xml in as a
macro definition.
 <macrodef name="components">
    <attribute name="target" />
    <sequential>
        commons,user,order,billing,reports
    </sequential>

Technologies of the project are spring 2.5 , hibernate3.5 , struts2.
The project maintains a repository of jars.
i.  cache (Project module.jars , external jars like spring)
ii. external (external jars like spring,hibernate,jdom)
iii. internal(project module jars)
Final build deploy as a war to the application server. This project has a big code base.
To compile it takes around 9 minutes.
I need to reduce the build time , improve the build process. Please advice me with
 a. suitable possible approaches

 b. checklist and possible tools

that I can use to analyse time consuming places and improve the build time.


text:
Q: PDEs: Classical solutions and abstract differential equations I am trying to better understand the relationships between classical solutions for PDEs and for abstract differential equations. In particular, let us consider a very simple case: the transport equation
$$
u_t=u_x\qquad \forall (x,t)\in (0,1)\times\mathbb{R}_{>0}
$$
Let $u^\star\colon\mathcal{C}^1((0,1)\times\mathbb{R}_{>0};\mathbb{R})$ be a solution to the above PDE. Now, we know that the above PDE can be rewritten as the following abstract differential equation
$$
\dot{u}=Au
$$
where $A\colon\mathcal{D}(A)\rightarrow\mathcal{C}^0((0,1);\mathbb{R})$ is the standard differential operator. Now, here is my question: Let $t\mapsto v(t)=u^\star(t,\cdot)$, where $u^\star$ is the solution to the above transport PDE, can one claim that for all $t\in\mathbb{R}_{>0}$, $\dot{v}(t)=Av(t)$?
Thanks!!


text:
Q: If $y =\sin \log (x^2+2x+1)$ then $(x+1)^2 y^{(n+2)}+(2n+1)(x+1)y^{(n+1)}+(x^2+4)y^{(n)}=0$ How to prove this?

If $y =\sin \log (x^2+2x+1)$, and $y'=y^{(1)}$, $y''=y^{(2)}$, and so on, prove that $(x+1)^2 y^{(n+2)}+(2n+1)(x+1)y^{(n+1)}+(x^2+4)y^{(n)}=0 $

Finding $y'$ is simple, but $y''$ and other higher terms seems difficult. Any short solution for this approach?

A: $y=\sin 2\log(x+1)
=2\sin\log(x+1)\cos\log(x+1)$.
Apply Leibnitz's formula for the n-th derivative of a product and look term-by-term.


text:
Q: How does a transformer operate with a short in the windings I'm trying to learn more about transformers that are failing. From my understanding transformers create heat. From too much load or current on the secondary side of a step-down transformer, the heat can damage the insulation and cause a short on some of the secondary side turns.
Now that we have a short in one or a few of the windings. How does the transformer behave under normal rated conditions? Say the secondary had 90 turns and now has 88 turns from two shorts. It seems the transformer should almost behave the same as when it had 90 windings. This is the part I think I'm wrong. Do the shorted windings increase current heat loss? Do the shorted windings increase eddy current/hysteresis loss? Or do the two shorted windings have really minimal effect?
If it is true that a few shorts can have large negative effects, they would cause more heat and could potentially lead to more insulation damage? My other assumption is that extra heat from the damaged secondary would be noticed in a decrease of output voltage because the transformer is getting very hot then its internal resistance will increase.

A: A shorted turn is usually catastrophic for a transformer. Very high currents flow in the shorted turn, leading to further insulation breakdown and dramatic temperature rise.
This keeps getting worse until the safety thermal fuse embedded in the winding opens, or the shorted turn melts open.
After that, that transformer must be discarded.

A: So the key here is the difference between shorts on the primary winding and the secondary, which each behave very differently. Your intuition about shorting only 2 windings being negligible makes some sense if we are talking about the primary, in fact we do that with inductors all the time to adjust its inductance, just short out part of the inductor.
Consider that in a secondary however that if you short the entire secondary, as one would expect, you will get thermal runaway just as shorting any power source directly might cause. You will have huge currents running through that will burn everything up as its limited only by the resistance of the wire.
But consider now a secondary with 2 turns shorted and 98 behaving normally. In this case you have the 98 acting as a normal secondary, nothing special there. But the 2-turns that are shorted acts like a second secondary (for lack of a better term) but this secondary is shorted and just like shorting any secondary will induce a large current flow limited only by the wire resistor and ultimately thermal runaway.
So in short, the reason a short on the secondary will be so devastating so quickly is because the shorted portion will act like an independent secondary that has its outputs shorted and thus induce high current and glowing red wire.


text:
Q: How can I make an entity as in my case toStrict? how to use the toStrict for the exception is Substream Source cannot be materialized more than once
and here is my source
  val fileUploadRote = {
(post & extractRequestContext & entity(as[String])) { (request, textReq) =>
  extractRequestContext {
    formFieldMultiMap { fields =>
      println("There are " +
        s"form fields ${fields.map(x => x._1 + " -> " + x._2.size).mkString(", ")}")
      var companyId = fields.get("companyId").getOrElse(List.empty)
      var subCompanyId = fields.get("subCompanyId").getOrElse(List.empty)

      ....................//File Upload code
    }
  }
}

}


text:
Q: XModMap Key Remapping Not Totally Working I have a Mac Keyboard I am using with new version of Ubuntu. Whenever in a web browser, I try and hit the F5 key to naturally refresh the page but in Ubuntu this key seems to be mapped to Keyboard Brightness Down.
I verified this by running xev and hitting my F5 key and the keycode was mapped to XF86KeyboardBrightnessDown. I then went into another terminal and attempted to map it to a regular F5 with the command `xmodmap -e "keycode 237 = F5". The new problem is, when I hit F5 just once or multiple times, the default keyboard brightness behavior is still there, and F5 now only refreshes the page in a browser if I hold F5 down for a bit.
I assume holding it down expires the event triggering of F5 to the OS, however in a browser like chrome, when the key is held down the events are still firing, and it eventually refreshed the page. So I assume right when the OS stops listening for the key, the browser is still listening at a higher level and default browser functionality of F5 kicks in.
How can I totally eliminate the default behavior of the F5 key to the OS?? Is what I want to do possible?
Edit:
Also if I map F5 functionality to another key that has no default behavior like my F13 Key (which is mapped to XF86Tools but doesn't do anything) it instantly refreshed the page in a browser, I just have this issue with this key that right on a press, tries to modify the keyboard brightness which doesn't exist.

A: Take a look at xbindkeys.
Create at $HOME/.xbindkeysrc and make sure to launch xbindkeys on startup.
"COMMAND IN HERE"
  F5

If you need to emulate another key press with the F5 key, look into xdotool.  I unfortunately don't have much experience with that one.

A: This can be related to "FN" key being activated by default. If this is your case, try to press "FN" key and F5 or whatever key you need. If you don't care about advanced settings, you can check bios settings for settings related to "FN" key. reboot (or restart) your pc and press apropriate key, maybe "del(ete)" or "F2" by default. And try. And sorry for bad english.


text:
Q: Videoview in scrollview issue I have googled a lot to solve this issue but it doesn't works in any case. Have tried everything as mentioned in Android::VideoView inside a ScrollView and Android Scrollview having videoview is giving problem.
The problem is when i put the video view in scrollview it doesn't works, but when remove the scrollview it works absolutely fine.
Here is the example code :
// xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_video"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start" />

    <ScrollView
        android:id="@+id/scrl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_video" >

        <VideoView
            android:id="@+id/videoView_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>

</RelativeLayout>

And the Java code, MainActivity class
package com.practice.videoviewexample;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
import android.widget.VideoView;

public class MainActivity extends Activity {

    private VideoView videoView_exhibit;
    private Button btnVideo;

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

        videoView_exhibit = (VideoView) findViewById(R.id.videoView_1);
        btnVideo = (Button) findViewById(R.id.btn_video);

        Uri video = Uri.parse("android.resource://" + getPackageName() + "/"+ R.raw.abc);
        videoView_exhibit.setVideoURI(video);
        videoView_exhibit.start();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Can anyone help? Thanx in advance!

A: This is a known limitation of VideoView.
Check this : VideoView inside ScrollView
Hope this helps.

A: By changing VideoView attributes android:layout_width and android:layout_height to fixed dp size (100dp) VideoView shown up.

A: Try Adding :
 android:background="#0000"

to the videoView

A: I didn't managed to get the VideoView working inside a ScrollView, but instead in some cases it is possible to scale the VideoView depending on the available vertical space by setting the VideoView's size attributes to:
<VideoView
            android:id="@+id/myVideoView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>

This will scale the VideoView and keep the aspect ratio of the video.


text:
Q: How to filter data using a Dimension values in R? I want to get Custom data from GA using R, for a dimension ga:productSKU using limited values only, but every time when i use
get_ga(id, metrics = met, dimensions = dim,
       start.date = '7daysAgo', end.date = 'today')

It gives data for all the products.
How can i filter out values from GA only i require and not corresponding to all the elements?. I have tried list_filters() function but i does no good and when i tried
get_ga(id, metrics = met,dimensions = dim,
       start.date = '7daysAgo', end.date = 'today',
       filters = ga:productSKU%3D%3D1435678)

Error: unexpected symbol in "get_ga(id,metrics = met,dimensions = dim,start.date = '7daysAgo',end.date = 'today', filters=ga:productSKU%3D%3D1435678"

where 1435678 is a productSKU i get an error.

A: filters param should be a character string:
get_ga(id, metrics = met,dimensions = dim,
       start.date = '7daysAgo', end.date = 'today',
       filters = "ga:productSKU==1435678")


text:
Q: How to make smooth rotation I want to make smooth rotation of a compass, like i have in my Android app :
https://www.dropbox.com/s/md93ys92938njaf/2014-07-31%2012.24.19.mov
To be the same in my iOS app
However this is my current state: https://www.dropbox.com/s/kk6l3atkg7oc0k2/VID_20140731_122703.mp4
-(void)rotate:(UIView *)v angle:(float)angle{

    CGFloat duration = 0.5;//animated ? 0.5 : 0.01;

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = [[v.layer presentationLayer] valueForKeyPath:@"transform.rotation.z"];
    animation.toValue = @(angle);
    animation.duration = duration;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = 0;
    animation.removedOnCompletion = NO;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [v.layer setAnchorPoint:CGPointMake(0.5, 0.60)];
    [v.layer addAnimation:animation forKey:@"transform.rotation.z"];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{

    float oldRad =  -manager.heading.magneticHeading * M_PI / 180.0f;

    float newRad =  -newHeading.magneticHeading * M_PI / 180.0f;

    [self rotate:_myLocationButton.imageView angle:newHeading.magneticHeading];
    LogInfo(@"%f (%f) => %f (%f)", manager.heading.trueHeading, oldRad, newHeading.trueHeading, newRad);

}

How to make the rotation smoother, and around the center point of the star ?
EDIT:
the actual problem:1. it rotates TOO QUICKLY
                   2. it stops in the wrong position
see video https://www.dropbox.com/s/lv4uyhe7oidq5m3/VID_20140731_133116.mp4
edit:
log output values:
2014-07-31 14:24:10.702 App[1040:60b] I,-[WBGoogleMapViewController rotate:fromAgnle:angle:]:160

previousValue:-0.504699 newValue:-0.999089

2014-07-31 14:24:10.704 App[1040:60b] I,-[WBGoogleMapViewController locationManager:didUpdateHeading:]:151

manager.heading.trueheading: 61.573509 (oldRad: -0.999089) => newHeading.trueHeading:61.573509 (newRad:-0.999089)

2014-07-31 14:24:10.705 App[1040:60b] D,-[Prefs getLocation]:81

coordinate:31.2719341228076,34.83940961773958

2014-07-31 14:24:14.525 App[1040:60b] I,-[WBGoogleMapViewController rotate:fromAgnle:angle:]:160

previousValue:-0.999089 newValue:-0.909013

2014-07-31 14:24:14.527 App[1040:60b] I,-[WBGoogleMapViewController locationManager:didUpdateHeading:]:151

manager.heading.trueheading: 56.412567 (oldRad: -0.909013) => newHeading.trueHeading:56.412567 (newRad:-0.909013)

2014-07-31 14:24:14.528 App[1040:60b] D,-[Prefs getLocation]:81

coordinate:31.2719341228076,34.83940961773958

2014-07-31 14:24:14.759 App[1040:60b] I,-[WBGoogleMapViewController rotate:fromAgnle:angle:]:160

previousValue:-0.828879 newValue:-0.724668

2014-07-31 14:24:14.761 App[1040:60b] I,-[WBGoogleMapViewController locationManager:didUpdateHeading:]:151

manager.heading.trueheading: 45.850368 (oldRad: -0.724668) => newHeading.trueHeading:45.850368 (newRad:-0.724668)

2014-07-31 14:24:14.763 App[1040:60b] D,-[Prefs getLocation]:81

coordinate:31.2719341228076,34.83940961773958

2014-07-31 14:24:18.406 App[1040:60b] I,-[WBGoogleMapViewController rotate:fromAgnle:angle:]:160

previousValue:-0.724668 newValue:-0.814539

2014-07-31 14:24:18.408 App[1040:60b] I,-[WBGoogleMapViewController locationManager:didUpdateHeading:]:151

manager.heading.trueheading: 50.999573 (oldRad: -0.814539) => newHeading.trueHeading:50.999573 (newRad:-0.814539)

2014-07-31 14:24:18.409 App[1040:60b] D,-[Prefs getLocation]:81

coordinate:31.2719341228076,34.83940961773958

2014-07-31 14:24:18.553 App[1040:60b] I,-[WBGoogleMapViewController rotate:fromAgnle:angle:]:160

previousValue:-0.460764 newValue:-0.912728

2014-07-31 14:24:18.555 App[1040:60b] I,-[WBGoogleMapViewController locationManager:didUpdateHeading:]:151

manager.heading.trueheading: 56.625385 (oldRad: -0.912728) => newHeading.trueHeading:56.625385 (newRad:-0.912728)

2014-07-31 14:24:18.556 App[1040:60b] D,-[Prefs getLocation]:81

coordinate:31.2719341228076,34.83940961773958

2014-07-31 14:24:18.963 App[1040:60b] I,-[WBGoogleMapViewController rotate:fromAgnle:angle:]:160

previousValue:-0.912728 newValue:-1.015497

2014-07-31 14:24:18.965 App[1040:60b] I,-[WBGoogleMapViewController locationManager:didUpdateHeading:]:151

manager.heading.trueheading: 62.513649 (oldRad: -1.015497) => newHeading.trueHeading:62.513649 (newRad:-1.015497)

2014-07-31 14:24:18.966 App[1040:60b] D,-[Prefs getLocation]:81

coordinate:31.2719341228076,34.83940961773958

A: You can simply do with below code
[UIView animateWithDuration:0.5 animations:^{
        _mapTransform = CGAffineTransformMakeRotation(angle);
        _mapScrollView.transform = _mapTransform;
    } completion:^(BOOL finished) {

    }];

But maintain the current angle of view so when you will invoke the method to rotate by an angle then you can get the difference of angle that needs to be rotated.

A: Try setting -
[v.layer setAnchorPoint:CGPointMake(0.5, 0.50)];

instead of -
[v.layer setAnchorPoint:CGPointMake(0.5, 0.60)];

A: -(void)rotate:(UIView *)v fromAngle:(float)from angle:(float)angle{

    if( from == angle){
        return;
    }
//to keep rotation in the same direction
    if(abs(toRad(from)-toRad(angle))>=6){
        if(from>angle){
            angle +=360;
            LogTrace(@"add");
        }else {
            angle-=360;
            LogTrace (@"subtract");
        }
    }

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = @(-toRad(from));
    animation.toValue = @(-toRad(angle));
    LogInfo(@"from:%f to:%f",-toRad(from),-toRad(angle));
    animation.duration = 0.0f;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = 0;
    animation.removedOnCompletion = NO;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    [v.layer setAnchorPoint:CGPointMake(0.5, 0.494)];
    [v.layer addAnimation:animation forKey:@"transform.rotation.z"];
}


text:
Q: Django design patterns for radio buttons with additional fields I'm not sure what these kinds of fields are technically called, but they're the ones where you have a group of radio selects, and each one can some additional fields that only get validated if its associated radio is selected.
Field Label:
(*) Option 1
( ) Option 2 [Additional Field]
( ) Option 3 [Another Field], [Maybe Two]

The key things I'm looking for:
1) Any existing solution for aiding in the rendering of such fields. ie grouping the additional fields with their options.
2) (not as important) any shortcuts for handling the validation, ie only bother validating the additional fields if their option is selected.
Normally when I do this kind of thing I end up having to manually write a lot of the HTML which is a wheel I'd rather avoid having to keep re-inventing.

A: On the client side, you can use some js, for example (with jQuery):
$('input[name=your_radio_field_name]').change(function() {
    switch ($(this).val()) {
        case 'option1_value':
            $('input[name=extra_field_for_option2], input[name=extra_field_for_option3]').hide();
            break;
        case 'option2_value':
            $('input[name=extra_field_for_option2]').show();
            $('input[name=extra_field_for_option3]').hide();
            break;
        // and so on ...
    }
})

On server side, you could have such field validation functions:
def clean_extra_field_for_option2(self):
    if self.cleaned_data.get('your_radio_field_name') != 'option_2_value':
        return None
    return self.cleaned_data.get('extra_field_for_option2')

def clean_extra_field_for_option3(self):
    if self.cleaned_data.get('your_radio_field_name') != 'option_3_value':
        return None
    return self.cleaned_data.get('extra_field_for_option3')

Of course, if you have this case a lot, you should first try something simple like this, and then refactor.