text:
Q: Second Android Native Page focus Issue While trying to automate android native application , Appium is not identify or focus on any single element on second page of native application after automating first page login functionality successfully .I have tried with all wait method and driver. context method but it is now working .I have tried to debug the code with so many wait time but it is not working .When i put a break point after automating first page and tried to debug the application then i observed that if i put any manual action on second page (open window and close same window )then appium is allowing to identify the second page also but i didn't understand why it is happening .By automation script, i am unable to do anything on second page .Could any team help me for the same? Page source code for second page :- "
i have tried with below method for identify the second page..
  driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));

         ICapabilities caps = driver.Capabilities;

         String context = driver.Context;
         Console.WriteLine("Current context", context);
         driver.Context = ("NATIVE_APP");
         String afterloginsource   = driver.PageSource;

         Console.WriteLine("After loginv page source :- ", afterloginsource);

         TouchAction t = new TouchAction(driver);
         t.Tap(100, 100).Perform();

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2400));

         String loginsource = driver.PageSource;

         Console.WriteLine("Befor login page source :- ",loginsource);

         driver.HideKeyboard();
         //enter valid account
         driver.FindElementById("com.Testing:id/userid").SendKeys("00229715");//uat02
        // driver.HideKeyboard();
         /////driver.FindElement(By.XPath("//android.widget.EditText[@index='1']")).SendKeys("17765919"); ////upn02

         ///enter valid password

         driver.FindElementById("com.Testing:id/password").SendKeys("1");

         ///click login button

         driver.FindElementById("com.Testing:id/login").Click();
         driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
         driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));

         ICapabilities caps = driver.Capabilities;

         String context = driver.Context;
         Console.WriteLine("Current context", context);
         driver.Context = ("NATIVE_APP");
         String afterloginsource   = driver.PageSource;

         Console.WriteLine("After loginv page source :- ", afterloginsource);

         TouchAction t = new TouchAction(driver);
         t.Tap(100, 100).Perform();
AndroidElement expandList = driver.FindElementById("com.Testing:id/btn_more_options");
         expandList.Click();  Or  //((IJavaScriptExecutor)driver).ExecuteScript("mobile: scroll", scrollObject);
         //IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
         //IWebElement hiddenButton = driver.FindElementById("com.Testing:id/enableNotify");
         //String script = "arguments[0].click();";

         //js.ExecuteScript(script, hiddenButton);

it is giving error as nosuchelement exception for any element on second page.

A: NoSuchElement states for inability to find the element. It strongly seems for me that xpath locators to webelements on the page are incorrect.
I do recommend to try out remote debugging just to ensure the locators are organized correctly. And using remote debugging tool - You may also check the locators on-the-fly there.
As an  option B) -  I could also recommend to take a quick glance towards SeeTest automation tool. The link above guide on how to set up project from scratch, and here is public documentation for SeeTest.


text:
Q: Delphi FMX TIdFTP onWork, onWorkBegin, onWorkEnd not working I've been fighting with TIdFTP and Delphi FMX for a while and I don't get good results, so, I don't really know what to do.
So, the thing that I want to do is to show a ProgressBar while GETTING and POSTING with TIdFTP. I've seen some codes online, that I've adapted, but nothing works.
But the problem is not only that the ProgressBar doesn't work. The problem goes much further:
I tried to make an easier functionality, that only makes Visible:= true and Visible:= false when the IdFTP is working.
So, I thought: If I make a get or a post, the TIdFTP events OnWorkBegin, OnWork and OnWorkEnd should capture the action and make it visible/invisible.
So, the code I put was that:
procedure TF_FTP.IdFTP1WorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
begin
  ProgressBar1.Visible := true;
end;

procedure TF_FTP.IdFTP1Work(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
begin
  ProgressBar1.Visible := true;
end;

and
procedure TF_FTP.IdFTP1WorkEnd(ASender: TObject; AWorkMode: TWorkMode);
begin
  ProgressBar1.Visible := false;
end;

This is the code I use to make the FTP request:
procedure ActualitzaInfo(ruta_loc, ruta_rem: String);
var myFile: TextFile;
    data: String;
begin
  with F_FTP do
  begin

    // Connection
    IdFTP1.Username := '<my-user>';
    IdFTP1.Password := '<my-password>';
    IdFTP1.Host := '<my-host>';

    // Clear lists
    LB_Curts.Items.Clear;
    LB_Llargs.Items.Clear;

    try
      // Connect
      IdFTP1.Connect;
      mida_ftp := IdFTP1.Size(ruta_rem);
      try
        //GET
        IdFTP1.Get(ruta_rem, ruta_loc, True, False);
      finally
        IdFTP1.Disconnect;
      end;
      ShowMessage('Downloaded!');
    except
      ShowMessage('Error downloading!');
      exit;
    end;

    //Fill lists
    CarregaControls(ruta_loc);
  end;
end;

What happened is, at the first get, the ProgressBar was visible because in the Form Design it is set as Visible. When it finishes, the ProgressBar gets invisible. Ok, well. But when I try to make another get or post, the ProgressBar never appears again.
If I make the ProgressBar invisible at the Form design, it never shows up.
I tried putting the Visible/Invisible on other IdFTP events, as onConnected-onDisconnected, onBeforeGet-onAfterGet, ... nothing seems to work. In addition, when I'm downloading the files, the Form freezes.
I don't know what is happening, I'm running on Android64.
Thank you in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Instantiating a Collection Backbone I have a router class which actually has separate hashes for views and collections as mentioned below. How do i set the url parameter of the collection when i take the instance in a view render method.
The Router Class
Router = (function() {
      'use strict';

      var
        viewHash = {},collectionsHash = {},
        EvtCalRouter, startRouter;

        // Set up the Backbone Router.
      // Evaluates URL with parameters and maps them to functions contained within the Router.
      // This enables us to do things like allow users to bookmark search results.
      // See "http://backbonejs.org/#Router" for more info.
      EvtCalRouter = Backbone.Router.extend({

        // Define the Routes we care about.
        // See "http://backbonejs.org/#Router-routes" for more info.
        routes : {
          ""       : "home",
          "route1" : "route1"
       }
 buildSearchScreen : function() {
collectionsHash['events'] = ESPN.apps.ADTG.EC.EventsCollection.newInstance({
        });

    },
startRouter = function() {
    new EvtCalRouter();
    Backbone.history.start();
     };

    // Start routing functionality
  $(document).ready(startRouter);

  // For any module that needs to know...
  $(document).ready( function() {
    $(document).trigger( ESPN.apps.ADTG.EC.events.ecInit );
  });

  //-------------------------------------------------------------------------------------------------------------------
  // Public API
  //-------------------------------------------------------------------------------------------------------------------

  return {
getCollection : function(name){return collectionsHash[name]||{};}
          };

})();

The Collection Class Goes Here
    The Collection Class is defined like this

      The Collection Class

        Collection = (function(){

        var Events;

        Events = Backbone.Collection.extend({

              initialize: function(props){
              this.url = props.url;
              alert(this.url);
            }
        });

        return {
            newInstance : function(options) { return new Events(options); }
        };
    })();

A:
How do i set the url parameter of the collection when i take the
  instance in a view render method.

You should be able to pass an url in your options hash:
Collection.newInstance({url: "your url"});

BUT.
To initialize a collection, you need to pass an array of models, so you need to change your collection defintion:
Collection = (function(){

  var Events;

  Events = Backbone.Collection.extend({

    initialize: function(models, options){
      this.url = options.url;
      alert(this.url);
    }
  });

  return {
    newInstance : function(models, options) { return new Events(models, options); }
  };
})();

I'm not sure why you want to have a dynamic url for your collection though. :/
and you probably want to define which model the collection is for...but well, you can pass it thru options as well.
Collection.newInstance([
  //array of models...
], {
  url: "meh"
});

EDIT:
If you need dynamic urls but most part of it are still the same, you can define url as a function:
Events = Backbone.Collection.extend({
  url: function(urlOptions) {
    return 'yourDomain/resources?'+ urlOptions; // just return the url as a string
  }
});

jsfiddle example:
jsfiddle.net/sbjaz/13


text:
Q: how to split set values and Insert each row in Trigger PL/SQL? i have one order table. i need before inserting order table, create and using triggers insert given below format.

example:

question:
id   value  1   2,5,8
answer:
id   value  1   2 1   5 1   8

A: Triggers in Oracle have mode "INSTEAD OF" which is exactly what you need, but the problem is that you can't use "INSTEAD OF" trigger on a simple table, it's only available for views. So the only option I see for you is to wrap your table in a view. For example you have a table:
create table my_table(c_id number, c_value varchar2(5))

Rename it and create view with old table' name:
rename my_table to my_table_old;

create view my_table as select * from my_table_old;

All existing queries to my_table should work with this view, including updates and deletes. Now we can create INSTEAD OF trigger:
create or replace trigger t_my_table
instead of insert on my_table
for each row
declare
  qid number;
begin
  insert into my_table_old
  select :new.c_id, regexp_substr (:new.c_value, '[^,]+', 1, level) as part
  from dual
  connect by level <= length (regexp_replace (:new.c_value, '[^,]+'))  + 1;
end;

This hierarchial query will turn comma-separated string into a table with single value in a row.
OK, let's check if it works:
SQL> insert into my_table values (1, '2,5,8');

1 row created.

SQL> select * from my_table;

      C_ID C_VALUE
---------- ---------------
         1 2
         1 5
         1 8

Simple single-value insert will also work:
SQL> insert into my_table values (2, '100');

1 row created.

SQL> select * from my_table;

      C_ID C_VALUE
---------- ---------------
         1 2
         1 5
         1 8
         2 100

Note that using of trigger will affect performance of insert queries for a bit.

A: You can amend the regex to suit your exact requirements but the following performs effectively as per your question:
CREATE OR REPLACE TRIGGER XX_ORDER_TRG
BEFORE INSERT ON XX_ORDER_TBL
FOR EACH ROW
DECLARE

l_num1 NUMBER;
l_num2 NUMBER;
l_num3 NUMBER;

BEGIN

/* If the whole string in value matches 3 single digits separated by commas */
IF  REGEXP_LIKE(:new.value,'^(\d{1},\d{1},\d{1})$') THEN
    /* Split the value into its 3 separate digits - Capture Groups are not supported natively*/
    l_num1 := REGEXP_SUBSTR(:new.value,'\d{1}',1,1);
    l_num2 := REGEXP_SUBSTR(:new.value,'\d{1}',1,2);
    l_num3 := REGEXP_SUBSTR(:new.value,'\d{1}',1,3);

    :new.value := l_num1;
    INSERT INTO XX_TBL (id, value) VALUES (:new.id, l_num2);
    INSERT INTO XX_TBL (id, value) VALUES (:new.id, l_num3);

END IF;

END;


text:
Q: Deny an access to shared memory from non-forked processes I need to create a shared memory segment which contains some secret data. I use shmget and shmat functions to access the segment with 0600 rights. I want to share this segment of memory with forked processes only. I tried to create another application which tried to access this segment and it was unsuccessful, so it looks like it's working as I want.
But when I run the application which created the segment again, it can access the segment. How is it possible? Is a good idea to store secret data into shared memory?

A: You can mmap() shared and anonymous memory region by providing MAP_SHARED and MAP_ANONYMOUS flags in parent process. That memory will be accessible only to that process and its children. As memory segment is anonymous, no other processes will be able to refer to it, let alone access/map it:
void *shared_mem = mmap(NULL, n_bytes, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);

Parent process should create shared memory segment using mmap(). That memory segment is inherited by any child process created by fork(). Child process can simply use shared_mem pointer inherited from parent to refer to that memory segment:
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
    void *shared_mem = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);

    pid_t pid = fork();
    if (pid > 0) {
        // parent
        // use shared_mem here

    } else if (pid == 0) {
        // child
        // use shared_mem here

    } else {
        // error
    }
    return 0;
}

A: The shared seg doesn't belong to a process, it belongs to a user. Effectively settings 0600 only allows that user for RW (and root), however any other process running as this user will have the same access.
Create a specific user, to be "used" (logged in) only for this purpose.

Is it a good idea to have secret data in a shared memory segment?

Think of the segment as a file - maybe a bit less easy to access (need to know IPC) - except it will disappear when the system shuts down.
Is it a good idea to store secrets in a file? Maybe not if the data is clear text.
In a file or in a shared mem segment, data encryption would be an improvement.
See this page for detailed explanations on how you can control a shmem segment.

OTOH if what you need is only to have a process exchanges information with her children, see processes piping. In this case the secret data is stored within the processes heap/stack memory, and is more difficult to reach by external processes owned by the same user. But the user "owning" the process may also read a process memory (via a core dump for instance) and search for the secret data. Much less easier, but still possible.

Note that in this case, if the secret data is available in the parent process before fork() is performed, children will automatically inherit of it.
Again, anyway, think encryption.


text:
Q: Can AD Data Connector API calls impact other currently executing APIs? Can AD Data Connector API calls impact other currently executing APIs?
The existing projects will remain in 360 and only new projects will utilize ACC.
Here is our potential scenario:

*

*ACC will be using the DC API approach

*360 API pipeline continues in tandem with ACC API based on amount of work to transition dashboard/reports

Does anyone have any experience or information?
Will this cause resource issues like throttling, data locking, etc. OR are they actually two different data capture streams and will Not impact each other?
Searched on AD but didn't see any specific information.


text:
Q: Fastest way to blur everything around a point in postprocess I am using Ogre3D and it's compositors.
Basically, I am wondering what will be the fastest way to blur everything around a dynamic point in the viewport. The point is given by the 2D screen coordinates. The farther a pixel is from that point, the more blurred it should be.
To give you an idea of how much blur it is supposed to have, if the blurring point is exactly in the middle of the screen, the edges should be maximally blurred. So the blurriness coefficient of a pixel could be thought of as
MIN (
  (normalizedDistanceBetween(pixel, blurringPoint)/0.5),
  1.0 )
So I am assuming the right way to go is to first make the completely blurred version of the scene using a shader. That part I have already.
Now, how to mix this blurred image with the original scene? I see two ways:

*

*Input the original and the blurred version to the compositor shader, let it calculate the distance and the result of the above formula, mix using the result.

*Setup an additional render-to-texture pass, which would use the above formula to render the "mixing texture". The point of this is that the mixing texture can be much smaller than the screen, even maybe 16x16, it won't have much difference on the result. Then, input the original scene, the blurred version and the mixing texture to the final compositor shader, which would simply sample a value from the mixing texture for each pixel and use that to mix the 2 scene versions together.

Does the second method make any sense? Would it have any noticeable performance gain than the first one? (Even a couple fps?) Or does creating an additional RTT pass and texture mitigate all the performance won by not calculating a (rather simple) distance function for every output pixel? I am assuming that the screen size is something normal, like 1024x768, ie, much larger than the 16x16 mixing texture. Or is there any other simpler method?

A: Either version may have a performance edge.  Unless you're doing something particularly inefficient, both ways should be fairly fast.
If you're really concerned about it, you should implement both, and benchmark them.

If you aren't doing this already, you may be able to speed up your effect by generating your blurred buffer at half-resolution.  This requires a good resampling filter to avoid aliasing when reading the original scene(I recommend at least a [1,3,3,1] Gaussian, and possibly wider, like [1,5,10,10,5,1]).
In fact, if you want a particularly wide maximum blur, you could repeat the process, generating a multiresolution image pyramid.  (once you've downsampled your original, everything becomes much cheaper because half-resolution means 1/4 the pixels)

Another possible speedup (again, if you haven't tried it already):  since your compositor is doing straight-up alpha-blending with your original image, it doesn't actually need to sample it.  Instead, you can output an alpha channel, render to the original buffer, and use the rasterizer function to do the final compositing.


text:
Q: Fastest way to index large sorted hash file I am building a file-based index for the sorted haveibeenpwned passwords text file and it got me wondering what's the fastest way to do this?
I figured a good way to build a quickly grep-able index would be split the sorted file into 256 files named with the first two hex digits (i.e. FF.txt, FE.txt, etc).  I found ripgrep rg to be about 5 times faster than grep on my computer.  So I tried something like this:
for i in {255..0}
do
    start=$(date +%s)
    hex="$(printf  '%02x' $i  | tr [:lower:] [:upper:])"
    rg "^$hex" pwned-passwords-ntlm-ordered-by-hash-v4.txt > ntlm/$hex-ntlm.txt
    echo 0x$hex completed in $(($(date +%s) - $start)) seconds
done

This is the fastest solution I could come up with.  ripgrep is able to create each file in 25 seconds.  So I'm looking at about 100 minutes to create this index.  When I split the job in half, and run them in parallel, each pair of files is created in 80 seconds.   So it seems best to just let ripgrep work its magic and work in series.
Obviously, I won't be indexing this list too often, but it's just fun to think about.  Any thoughts on a faster way (aside from using a database) to index this file?

A: ripgrep, like any other tool that's able to work with unsorted input files at all, is the wrong tool for this job. When you're trying to grep sorted inputs, you want something that can bisect your input file to find a position in logarithmic time. For big enough inputs, even a slow O(log n) implementation will be faster than a highly optimized O(n) one.
pts-line-bisect is one such tool, though of course you're also welcome to write your own. You'll need to write it in a language with full access to the seek() syscall, which is not exposed in bash.

A: You are reading through the file 256 times, doing a full file scan every time.  Consider an approach that reads the file once, writing each line into an open file descriptor.  I'm thinking python would be an easy choice of implementation (if that's your thing).  You could optimize by keeping the file open until you hit a new hex code at the beginning of the line.  If you want to be even more clever, there is no need to go through the sorted file line by line.  Based on Charles Duffy's hint, you could create a heuristic for sampling the file (using seek()) to get to the next hex value.  Once the program has found the byte offset of the next hex value, the block of bytes can be written to the new file.  However, since this is tagged as 'bash' let's keep the solution set in that domain:
while
  read line
do
  hex=${line:0:2}
  echo $line >> ntlm/$hex-ntlm.txt
done < pwned-passwords-ntlm-ordered-by-hash-v4.txt

A: I wrote a Python3 script that solves fast binary-search lookups in the hash file without having to create an index. It doesn't directly address your question (indexing) but probably solves the underlying problem that you wanted to solve with an index - to quickly look up individual hashes. This script checks hundreds of passwords in seconds.
import argparse
import hashlib

parser = argparse.ArgumentParser(description='Searches passwords in https://haveibeenpwned.com/Passwords database.')
parser.add_argument('passwords', metavar='TEST', type=str, help='text file with passwords to test, one per line, utf-8')
parser.add_argument('database', metavar='DATABASE', type=str, help='the downloaded text file with sha-1:count')
args = parser.parse_args()

def search(f: object, pattern: str) -> str:

    def search(left, right: int) -> str:
        if left >= right:
            return None

        middle = (left + right) // 2
        if middle == 0:
            f.seek(0, 0)
            test = f.readline()
        else:
            f.seek(middle - 1, 0)
            _ = f.readline()
            test = f.readline()

        if test.upper().startswith(pattern):
            return test
        elif left == middle:
             return None
        elif pattern < test:
            return search(left, middle)
        else:
            return search(middle, right)

    f.seek(0, 2)
    return search(0, f.tell())

fsource = open(args.passwords)
fdatabase = open(args.database)
source_lines = fsource.readlines()
for l in source_lines:
    line = l.strip()
    hash_object = hashlib.sha1(line.encode("utf-8"))
    pattern = hash_object.hexdigest().upper()
    print("%s:%s" % (line, str(search(fdatabase, pattern)).strip()))
fsource.close()
fdatabase.close()


text:
Q: JavaScript horizontal movement Dears if its possible to help me with the code below , i am trying to make a simple PacMan movement with javascript , i need the PacMan to move from left to right and from right to left , as appear i did the movement from left to right but i tried to move it back from right to left with no luck , so if its possible to replace the movement from up to down into right to left it will be perfect , please your advice on what can i do or add , also i have 4 images of PacMan with two different direction and two mouth action how can i apply it with the movement ?

<title>PacMan</title>

 <input type=button onClick=timer() value='Start'>
 <input type=button onClick=reset1() value='Reset'>

A: You could use a state, which reperesents the actual state of the movement and use an object, which reflects the apperance, steps, borders and next state.
If a min or max value is not present, then is works as not given. If a value exists, then it goes into check and either an increment/decrement by step is performed or the next state is selected.
The images reflect the direction.

var states = {
        left: {
            min: { x: 0 },
            step: { x: -1 },
            img: img('https://dummyimage.com/32/fff/000&text=←'),
            nextState: 'down'
        },
        down: {
            max: { y: 180 },
            step: { y: 1 },
            img: img('https://dummyimage.com/32/fff/000&text=↓'),
            nextState: 'right'
        },
        right: {
            max: { x: 600 },
            step: { x: 1 },
            img: img('https://dummyimage.com/32/fff/000&text=→'),
            nextState: 'up'

        },
        up: {
            min: { y: 0 },
            step: { y: -1 },
            img: img('https://dummyimage.com/32/fff/000&text=↑'),
            nextState: 'left'
        },
    },
    state = 'down',
    interval;

function img(src) {
    var image = new Image;
    image.src = src;
    return image;
}

function move() {
    var image = document.getElementById('PacMan'),
        x = image.offsetLeft,
        y = image.offsetTop;

    if (
        (!states[state].min || !('x' in states[state].min) || x > states[state].min.x) &&
        (!states[state].max || !('x' in states[state].max) || x < states[state].max.x) &&
        (!states[state].min || !('y' in states[state].min) || y > states[state].min.y) &&
        (!states[state].max || !('y' in states[state].max) || y < states[state].max.y)
    ) {
        x += (states[state].step.x || 0);
        y += (states[state].step.y || 0);
        image.style.left = x + "px";
        image.style.top = y + "px";
    } else {
        state = states[state].nextState;
        image.src = states[state].img.src;
        document.getElementById('msg').innerHTML = state;
    }
}

function timer() {
    document.getElementById('msg').innerHTML = state;
    document.getElementById('PacMan').src = states[state].img.src;
    move();
    interval = setInterval(move, 10);
}

function reset() {
    var image = document.getElementById('PacMan');
    clearInterval(interval);
    state = 'down';
    image.src = states[state].img.src;
    image.style.left = 0 + "px";
    image.style.top = 0 + "px";
}

<input type="button" onClick="timer()" value="Start">
<input type="button" onClick="reset()" value="Reset">


text:
Q: \hyperref to a \label doesn't work ("empty destination key") In one of my documents, I used the combination of \label with \hyperref. Now, I fail for some reason.
I included the package:
\usepackage[colorlinks=true,urlcolor=blue,linkcolor=blue]{hyperref}

Created a label somewhere in my text:
\label{key1}

And referenced it from the text:
\hyperref[key1]{there}

But xelatex gives me this:
Package hyperref Warning: Empty destination name,
(hyperref)                using `UNDEFINED' on input line 66.

What am I doing wrong?
EDIT: Minimal working example:
\documentclass[a4paper, 12pt]{article}

\usepackage{xltxtra}
\usepackage[colorlinks=true,urlcolor=blue,linkcolor=blue]{hyperref}

\begin{document}

  Some text. \label{key1} Continuing.

  Some more text (\hyperref[key1]{goto}).

\end{document}

A: It seems that \label can be attached only to sections or subsections (or some other environments, like figures). To be able to reference arbitrary points in text, I needed to define "phantom section":
\phantomsection
\label{key1}

A: The repositories are out of date- your example works fine in texlive 2011 available at
http://www.tug.org/texlive/acquire-netinstall.html
Please see Martin's answer to Best way to install packages for TeXLive in Ubuntu?
You don't need to build the deb packages yourself, texlive 2011 comes with very easy executables that do all of the work for you. Once you have texlive 2011 installed, you can update it using tlmgr update --self --all


text:
Q: Elegantly implementing 'map (+1) list' in ruby The short code in title is in Haskell, it does things like
list.map {|x| x + 1}

in ruby.
While I know that manner, but what I want to know is, is there any more elegant manners to implement same thing in ruby like in Haskell.
I really love the to_proc shortcut in ruby, like this form:
[1,2,3,4].map(&:to_s)
[1,2,3,4].inject(&:+)

But this only accept exactly matching argument number between the Proc's and method.
I'm trying to seek a way that allow passing one or more arguments extra into the Proc, and without using an useless temporary block/variable like what the first demonstration does.
I want to do like this:
[1,2,3,4].map(&:+(1))

Does ruby have similar manners to do this?

A: If you just want to add one then you can use the succ method:
>> [1,2,3,4].map(&:succ)
=> [2, 3, 4, 5]

If you wanted to add two, you could use a lambda:
>> add_2 = ->(i) { i + 2 }
>> [1,2,3,4].map(&add_2)
=> [3, 4, 5, 6]

For arbitrary values, you could use a lambda that builds lambdas:
>> add_n = ->(n) { ->(i) { i + n } }
>> [1,2,3,4].map(&add_n[3])
=> [4, 5, 6, 7]

You could also use a lambda generating method:
>> def add_n(n) ->(i) { i + n } end
>> [1,2,3,4].map(&add_n(3))
=> [4, 5, 6, 7]

A: Use the ampex gem, which lets you use methods of X to build up any proc one one variable. Here's an example from its spec:
["a", "b", "c"].map(&X * 2).should == ["aa", "bb", "cc"]

A: You can't do it directly with the default map. However it's quite easy to implement a version that supports this type of functionality. As an example Ruby Facets includes just such a method:
require 'facets/enumerable'

[1, 2, 3, 4].map_send(:+, 10)
=> [11, 12, 13, 14]

The implementation looks like this:
def map_send(meth, *args, &block)
  map { |e| e.send(meth, *args, &block) }
end

A: In this particular case, you can use the following:
[1, 2, 3, 4].map(&1.method(:+))

However, this only works because + is not associative. It wouldn't work for -, for example.

A: Ruby hasn't built-in support for this feature, but you can create your own extension or use small gem 'ampex'. It defines global variable X with extended 'to_proc' functionality.
It gives you possibility to do that:
[1,2,3].map(&X.+(1))

Or even that:
"alpha\nbeta\ngamma\n".lines.map(&X.strip.upcase)

A: If you just want to add 1, you can use next or succ:
[1,2,3,4].map(&:next)
[1,2,3,4].map(&:succ)


text:
Q: jQuery mobile image gallery default vertical scroll issue I have an image gallery with a series of thumbs. Both are loaded dynamically depending on how many images are associated with a product. You can click on a thumb to get that series of images. On a mobile device you can swipe left and right to see all the images. That all works fine.
Here's my issue: When you try to scroll down the page and you happen to be touching one of the main images you get stuck and the page doesn't move. For the life of me I cannot figure out a work around for this. I am wondering if anyone has ever encountered this and figured out a solution. I think there could be a way to control this via the touch-punch.js but cannot figure it out. Thank you.
Here is my simplified gallery HTML:

/a>
/a>
/a>
/a>
/a>

css:
#productGalleryWrap {
overflow: hidden;
margin: 7px 10px 0;
}

#productGalleryWrap .productGalleryInner {
white-space: nowrap;
}

#productGalleryWrap .productGalleryInner li {
display: inline;
}

#productGalleryWrap .productGalleryInner img {
display: inline;
width: 50%;
}

I am using touch-punch.js to control the horizontal drag. Here is the code:
(function ($) {

  // Detect touch support
  $.support.touch = 'ontouchend' in document;

  // Ignore browsers without touch support
  if (!$.support.touch) {
return;
  }

      var mouseProto = $.ui.mouse.prototype,
      _mouseInit = mouseProto._mouseInit,
      touchHandled;

  /**
   * Simulate a mouse event based on a corresponding touch event
   * @param {Object} event A touch event
  * @param {String} simulatedType The corresponding mouse event
  */
  function simulateMouseEvent (event, simulatedType) {

    // Ignore multi-touch events
    if (event.originalEvent.touches.length > 1) {
     return;
   }

    event.preventDefault();

    var touch = event.originalEvent.changedTouches[0],
        simulatedEvent = document.createEvent('MouseEvents');

// Initialize the simulated mouse event using the touch event's coordinates
simulatedEvent.initMouseEvent(
  simulatedType,    // type
  true,             // bubbles
  true,             // cancelable
  window,           // view
  1,                // detail
  touch.screenX,    // screenX
  touch.screenY,    // screenY
  touch.clientX,    // clientX
  touch.clientY,    // clientY
  false,            // ctrlKey
  false,            // altKey
  false,            // shiftKey
  false,            // metaKey
  0,                // button
  null              // relatedTarget
    );

    // Dispatch the simulated event to the target element
event.target.dispatchEvent(simulatedEvent);
  }

  /**
   * Handle the jQuery UI widget's touchstart events
   * @param {Object} event The widget element's touchstart event
   */
  mouseProto._touchStart = function (event) {

   var self = this;

    // Ignore the event if another widget is already being handled
    if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
      return;
    }

    // Set the flag to prevent other widgets from inheriting the touch event
touchHandled = true;

    // Track movement to determine if interaction was a click
self._touchMoved = false;

    // Simulate the mouseover event
simulateMouseEvent(event, 'mouseup');

    // Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');

    // Simulate the mousedown event
simulateMouseEvent(event, 'mousedown');
  };

            mouseProto._touchMove = function (event) {

    // Ignore event if not handled
    if (!touchHandled) {
  return;
    }

// Interaction was not a click
this._touchMoved = true;

// Simulate the mousemove event
simulateMouseEvent(event, 'mousemove');
  };

   /**
   * Handle the jQuery UI widget's touchend events
   * @param {Object} event The document's touchend event
   */
  mouseProto._touchEnd = function (event) {

// Ignore event if not handled
if (!touchHandled) {
  return;
}

// Simulate the mouseup event
simulateMouseEvent(event, 'mouseup');

// Simulate the mouseout event
simulateMouseEvent(event, 'mouseout');

// If the touch interaction did not move, it should trigger a click
if (!this._touchMoved) {

  // Simulate the click event
  simulateMouseEvent(event, 'click');
}

// Unset the flag to allow other widgets to inherit the touch event
touchHandled = false;
  };

  /**
   * A duck punch of the $.ui.mouse _mouseInit method to support touch events.
   * This method extends the widget with bound touch event handlers that
   * translate touch events to mouse events and pass them to the widget's
   * original mouse event handling methods.
   */
  mouseProto._mouseInit = function () {

var self = this;

// Delegate the touch handlers to the widget's element
self.element
  .bind('touchstart', $.proxy(self, '_touchStart'))
  .bind('touchmove', $.proxy(self, '_touchMove'))
  .bind('touchend', $.proxy(self, '_touchEnd'));

// Call the original $.ui.mouse init method
_mouseInit.call(self);
  };

})(jQuery);

Please let me know if more info is needed. Thanks.

A: Kind of late answer but I had this same problem on a current project I'm working on.
Comment out:
event.preventDefault();

Add this after:
document.ontouchmove = function(e) {
    var target = e.currentTarget;
    while(target) {
        if(checkIfElementShouldScroll(target))
            return;
        target = target.parentNode;
    }

    e.preventDefault();
};

Dolla dolla bills y'all.
Code taken from this thread: document.ontouchmove and scrolling on iOS 5


text:
Q: Count the non-decreasing sequences of positive integers below a given one, for component-wise ordering How do you find the number of unique integer sequences of a nondecreasing sequences length $n$ with these conditions?
$$ a_{n+1} \geq a_{n}$$
Possible rephrasing: Given a particular nondecreasing sequence of length $n$ $\{a_1,a_2, \ldots,a_n\}$, how many nondecreasing sequences $\{b_1,b_2, \ldots ,b_n\}$ are there in which $b_i \leq a_i$ for $1 \leq i \leq n$?
The sequence is sorted low to high and the next number is same or higher.
[1,2,3,4,5] or [1,1,2,2,5] or [5,5,5,5,5]
The permutations must be lower than the sequence, but same or higher than the number before it.
For [1,2,3,4,5] there are 42 unique combinations.
1,1,1,1,1
1,1,1,1,2
1,1,2,2,5
1,1,3,4,5
1,2,3,4,5

1,1,3,2,4 - no because 2 is less than 3
1,3,3,4,5 - no because 3 is greater than 2 in 1,*2*,3,4,5

For 5,5,5,5,5 there are 126 unique sequences.
1,1,1,1,1
1,2,3,4,5
5,5,5,5,5

Brute force counting looks like
for a = 1 to 5
 for b = a to 5
   for c = b to 5
      for d = c to 5
         for e = d to 5
               count++
               print a,b,c,d,e

For [5] the count is 5.
For [1,5] or [1,1,1,1,5] the count is 5.
For [5 repeating n times]
n count
1 5
2 15
3 35
4 70
5 126
6 210
7 330
8 495
9 715
10 1001

I tried summation of summation of summation. $n(n+1)(n+2)(n+3)/2*3*4$
3 summations counts sequences length 5 and limits are $n,n,n,n,n$.
4 summations counts 6.
5 summations counts 7.
I don't know how to subtract sequences if the limits are $1,2,3,4,5$.
how do you get $\frac{10!}{5!6!} = 42$ from $1,2,3,4,5$ and $\frac{9!}{4!5!} = 126$ from $5,5,5,5,5$?

A: Answering this question in general is probably just too difficult, so I'll just restate the problem into a maybe more understandable form. If you arrange $a_1$ squares in a first row, then $a_2$ squares in a second row (left aligned), and so on until a last row of $a_n$ squares, the you have an upside-down version of the Young diagram for the partition $(a_n,\ldots,a_2,a_1)$. What you are looking for is the number of ways to remove some boxes from the ends of these rows, so that the remainder is still an upside-down Young diagram. The actual question also requires that the first column is entirely retained (since it implicitly discriminates against $0$), but you can obtain that by chopping off the first column from the Young diagram; I will assume this is done so that we are now allowed to remove all boxes from certain rows if we like. Then the number is equal to the number of lattice paths from top-left to bottom right across the Young diagram, staying within its bounds.
The number of such paths is a known number in certain cases. When the Young diagram is a rectangle of sides $k$ and $l$, then the number is the binomial coefficient $\binom{k+l}k$ (our lattice path has $k$ horizontal and $l$ vertical steps, which can be intermixed in any way). If the Young diagram is an equilateral triangle shape with $n$ squares on a side, the number is the Catalan number $C_{n+1}$ (extending the paths with an initial vertical edge and a final horizontal edge, one gets a lattice paths of length $2(n+1)$ staying to one side of a diagonal line, counting of which is one of the interpretations of that Catalan number).


text:
Q: Django: don't cache particular view? As per the title...
Is there a way I can force a particular view (actually a particular JSON-formatted set of results, that will be served to Ajax queries) NEVER to cache in Django?
Thanks!

A: To be sure, decorate it with @never_cache:
from django.views.decorators.cache import never_cache

@never_cache
def myview(request):
    # ...

As in The per-view cache documentation.

A: Django does not cache views unless you specify a per-view cache.
If you have problems with (cached) Ajax responses, try to add a timestamp to your URL:
e.g. /my_view?ts=23432453453
So you can be sure that your browser does not cache the Ajax responses.


text:
Q: Email address as rdn in Active Directory Application Mode - ADAM Is it OK to use an email address as the CN attribute in ADAM (I don't mean the email/mail attribute)?
I have a requirement that calls for ADAM for authentication and the user's email address as the CN (e.g. CN=jsmith@yahoo.com and CN=mary@gmail.com). It seems odd to have an "@" character in the CN property but I tested it and authentication works fine. I can't find anything online to suggest an email address should not be used as the CN except that and ADAM CN cannot have more than 64 characters which could potentially be an issue in rare cases. Also, Softerra LDAP browser won't allow me to add a UPN with multiple "@" characters although this project doesn't include UPN in the scope.
Sanity check before we pull the trigger.
Thanks, Jim

A: I would advise against that. The attribute used to bind is the RDN. If you lookup your object class in the LDS schema, you will find that cn is the RDN (the display name of the attribute is rDNAttID).
IIRC the only way to change the RDN is to have it set to what you want when the schema is imported.
That leaves you two choices :

*

*Create a new objectClass that has mail as the RDN, and add that objectClass to your users

*Do a search-and-bind

I really have no idea if option #1 will work.
Option #2 is how I always do it. Your application will :

*

*Search for a user based on an attribute (make sure it is indexed)

*If there is more than one match, deny authentication.

*If there is only one match, use the distinguishedName of the object you found and the supplied password to bind.

+The limits imposed by Softerra are not in AD-LDS. You can create a user named @@@@@@@@@ easily with LDP (pardon my French) :

Gives the following result :
-----------
***Calling Add...
ldap_add_s(ld, "cn=@@@@@@@@@,OU=stuff,DC=example,DC=com", [2] attrs)
Added {cn=@@@@@@@@@,OU=stuff,DC=example,DC=com }.
-----------


text:
Q: Iplimage to List I am trying to pass a set of iplimage from OpenCV to another program (.net) that does not use iplimage but uses
    list of byte[]
instead through c++/cli.
Any idea how to add/convert iplimage to the
    list of byte[]   ?
Thanks.

A: If you want to copy exact pixels from iplimage.imageData, you can use Marshal.Copy
to copy data from an IntPtr (imageData) to a managed array (byte[]).
But since imageData is uncompressed, you might want to use imencode or cvEncodeImage to compress it to a intermediate buffer and then copy that to a byte[] with above code.

A: Before doing anything else, take the time to learn how an IplImage is created, and what kind of information it stores.
Then, notice that the pixels of the image can be accessed through the member imageData, which is an unsigned char*:
IplImage* image = cvLoadImage("starwars.jpg", 0);
int img_sz = image->width * image->height * image->nChannels;
unsigned char* data = (unsigned char*) malloc(img_sz);
memcopy(data, image->imageData, img_sz);

You'll have to do a similar procedure to convert it to byte[]. By the way, this post]2 shows (among other things) how to convert an IplImage* to a SDL_Surface*.

A: Firstly, I would recommend that you switch to the C++ API of OpenCV if possible - it offers a lot more flexibility and features as compared to the old C interface.
In the C++ interface, a snippet to perform the above task would be:
cv::Mat image = cv::imread(imname);
uchar *ptr = (uchar*)image.data

You can use your ptr( an 8 bit unsigned byte data ) wherever you want - do remember that modifying this data will modify the actual image. If you do not want that to happen, take a copy of the data using memcpy.

A: If I understand you right you search something like this :
IplImage* image = cvLoadImage("image.bmp");
std::list<unsigned char*> bytes;
for (int i=0;i<image->height;i++)
 {
   bytes.push_back(image->imageData + image ->widthStep*i);
 }

you could test that this works doing the following (I access here the first pixel of the second row):
std::list<unsigned char*>::iterator it = bytes.begin();
it++;
*(*it) = 22;
int a = *((unsigned char*)(image->imageData + image->widthStep*1));

I didn t find no way to do things like this with the new cv::Mat object. You can transform the image to std::vectors but there is no way to transform the image to a row std::vector/std::list.
But if you remain use the cv::Mat class you can try the cv::Ptr<Pixelformat> that also gives access to the row pointers.


text:
Q: Optimizing code, removing "for loop" I'm trying to remove outliers from a tick data series, following Brownlees & Gallo 2006 (if you may be interested).
The code works fine but given that I'm working on really long vectors (the biggest has 20m observations and after 20h it was not done computing) I was wondering how to speed it up.
What I did until now is:
I changed the time and date format to numeric double and I saw that it saves quite some time in processing and A LOT OF MEMORY.
I allocated memory for the vectors:
[n] = size(price);
 x = price;
    score = nan(n,'double');           %using tic and toc I saw that nan requires less time than zeros
    trimmed_mean = nan(n,'double');
    sd = nan(n,'double');
    out_mat = nan(n,'double');

Here is the loop I'd love to remove. I read that vectorizing would speed up a lot, especially using long vectors.
for i = k+1:n
    trimmed_mean(i) = trimmean(x(i-k:i-1 & i+1:i+k),10,'round');  %trimmed mean computed on the 'k' closest observations to 'i' (i is excluded)
    score(i) = x(i) - trimmed_mean(i);
    sd(i) = std(x(i-k:i-1 & i+1:i+k)); %same as the mean
    tmp = abs(score(i)) > (alpha .* sd(i) + gamma);
    out_mat(i) = tmp*1;
end

Here is what I was trying to do
trimmed_mean=trimmean(regroup_matrix,10,'round',2);
score=bsxfun(@minus,x,trimmed_mean);
sd=std(regroup_matrix,2);
temp = abs(score) > (alpha .* sd + gamma);
out_mat = temp*1;

But given that I'm totally new to Matlab, I don't know how to properly construct the matrix of neighbouring observations. I just think it should be shaped like: regroup_matrix= nan (n,2*k).
EDIT: To be specific, what I am trying to do (and I am not able to) is:
Given a column vector "x" (n,1) for each observation "i" in "x" I want to take the "k" neighbouring observations to "i" (from i-k to i-1 and from i+1 to i+k) and put these observations as rows of a matrix (n, 2*k).
EDIT 2: I made a few changes to the code and I think I am getting closer to the solution. I posted another question specific to what I think is the problem now:
Matlab: Filling up matrix rows using moving intervals from a column vector without a for loop
What I am trying to do now is:
[n] = size(price,1);
x = price;
[j1]=find(x);
matrix_left=zeros(n, k,'double');
matrix_right=zeros(n, k,'double');
toc
matrix_left(j1(k+1:end),:)=x(j1-k:j1-1);

matrix_right(j1(1:end-k),:)=x(j1+1:j1+k);

matrix_group=[matrix_left matrix_right];
trimmed_mean=trimmean(matrix_group,10,'round',2);
score=bsxfun(@minus,x,trimmed_mean);
sd=std(matrix_group,2);
temp = abs(score) > (alpha .* sd + gamma);
outmat = temp*1;

I have problems with the matrix_left and matrix_right creation.
j1, that I am using for indexing is a column vector with the indices of price's observations. The output is simply
j1=[1:1:n]

price is a column vector of double with size(n,1)

A: For your reshape, you can do the following:
idxArray = bsxfun(@plus,(k:n)',[-k:-1,1:k]);
reshapedArray = x(idxArray);

A: Thanks to Jonas that showed me the way to go I came up with this:
idxArray_left=bsxfun(@plus,(k+1:n)',[-k:-1]);           %matrix with index of left neighbours observations
idxArray_fill_left=bsxfun(@plus,(1:k)',[1:k]);          %for observations from 1:k I take the right neighbouring observations, this way when computing mean and standard deviations there will be no problems.
matrix_left=[idxArray_fill_left; idxArray_left];        %Just join the two matrices and I have the complete matrix of left neighbours
idxArray_right=bsxfun(@plus,(1:n-k)',[1:k]);            %same thing as left but opposite.
idxArray_fill_right=bsxfun(@plus,(n-k+1:n)',[-k:-1]);
matrix_right=[idxArray_right; idxArray_fill_right];
idx_matrix=[matrix_left matrix_right];                  %complete index matrix, joining left and right indices
neigh_matrix=x(idx_matrix);                             %exactly as proposed by Jonas, I fill up a matrix of observations from 'x', following idx_matrix indexing
trimmed_mean=trimmean(neigh_matrix,10,'round',2);
score=bsxfun(@minus,x,trimmed_mean);
sd=std(neigh_matrix,2);
temp = abs(score) > (alpha .* sd + gamma);
outmat = temp*1;

Again, thanks a lot to Jonas. You really made my day!
Thanks also to everyone that had a look to the question and tried to help!


text:
Q: Usar request.user para llenar un campo en forms.py Quiero usar el usuario que se encuentra logueado para llenar un campo del archivo forms.py.
forms.py
from django import forms
from .models import Meeting
import datetime
import pytz

class MeetingForm(forms.ModelForm):

    class Meta:
        model = Meeting
        fields = [
            'host',
            'titulo',
            'descripcion',
            'comienzo',
            'cierre',
            'ciudad',
            'direccion',
            'categoria'
        ]

    def clean(self):
        now = datetime.datetime.now()
        now = pytz.utc.localize(now)

        comienzo = self.cleaned_data['comienzo']
        cierre = self.cleaned_data['cierre']

        if comienzo < now or cierre <= comienzo:
            raise forms.ValidationError('Fechas invalidas!')

        return super(MeetingForm, self).clean()

models.py
class Meeting(models.Model):
    titulo      = models.CharField(max_length=100)
    descripcion = models.TextField(max_length=500)
    host        = models.ForeignKey(Perfil, on_delete=models.CASCADE, related_name='host')
    publicado   = models.DateTimeField(auto_now_add=True)
    comienzo    = models.DateTimeField()
    cierre      = models.DateTimeField()
    asistentes  = models.ManyToManyField(Perfil, related_name='asistentes')
    ciudad      = models.ForeignKey(Ciudad, on_delete=models.CASCADE)
    direccion   = models.CharField(max_length=255)
    categoria   = models.ForeignKey(Categoria, on_delete=models.CASCADE)
    en_curso    = models.BooleanField(default=False)
    culminado   = models.BooleanField(default=False)

    class Meta:
        ordering = ['-publicado']

    def __str__(self):
        return self.titulo

    def get_absolute_url(self):
        return reverse('meetings:meeting-detail', kwargs={'pk': self.pk})

views.py
class MeetingCreateView(LoginRequiredMixin, CreateView):
    login_url = 'login'
    model = Meeting
    form_class = MeetingForm
    template_name = 'meetings/create.html'

Lo que quiero lograr es que al guardar el formulario automaticamente use el usuario de request.user para llenar el campo host. Anteriormente en otro proyecto lo habia hecho de la siguiente manera:
class TaskCreate(LoginRequiredMixin, CreateView):
    model = Task
    fields = ['title', 'description']
    success_url = reverse_lazy('list')

    def form_valid(self, form):
        form.instance.user = self.request.user #Utiliza el id del usuario que se encuentra en la sesion para
                                                #llenar el campo 'user' del formulario

        return super(TaskCreate, self).form_valid(form)

Pero no se de que manera podria lograr lo mismo en un archivo forms.py

A: Una forma de lograrlo es sobrescribiendo el método save() de tu formulario, para hacer esto primero es necesario pasar el request al formulario de esta manera:
class MeetingCreateView(LoginRequiredMixin, CreateView):
    login_url = 'login'
    model = Meeting
    form_class = MeetingForm
    template_name = 'meetings/create.html'

    def get_form_kwargs(self):
        form_kwargs = super(MeetingCreateView, self).get_form_kwargs()
        form_kwargs.update({"request": self.request})
        return form_kwargs

Posteriormente en tu formulario necesitas sacar el request en el método init de esta manera:
class MeetingForm(forms.ModelForm):
    # Tu codigo va aqui

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        super(MeetingForm, self).__init__(*args, **kwargs)

Por ultimo necesitas sobrescribir el método save() del formulario, quedándote este de esta manera:
class MeetingForm(forms.ModelForm):

    def clean(self):
        now = datetime.datetime.now()
        now = pytz.utc.localize(now)

        comienzo = self.cleaned_data['comienzo']
        cierre = self.cleaned_data['cierre']

        if comienzo < now or cierre <= comienzo:
            raise forms.ValidationError('Fechas invalidas!')

        return super(MeetingForm, self).clean()

    def save(self, commit=True):
        obj = super(MeetingForm, self).save(commit=False)
        user = None
        if self.request:
            if hasattr(self.request, "user"):
                # Almacenar el usuario
                user = self.request.user
        if commit:
            # Almacenar el usuario en host
            obj.host = user
            obj.save()
        return obj

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        super(MeetingForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Meeting
        fields = [
            'host',
            'titulo',
            'descripcion',
            'comienzo',
            'cierre',
            'ciudad',
            'direccion',
            'categoria'
        ]


text:
Q: Get string between two regex matches I am trying to find a regex string pattern for a Java function to process tweets. After much cleaning, now my data format is: "tweet;device;tweet;device..."
The example data format is as below,

RT @blah1: blahbla;some device1 RT @blah2: blabla;some dev2 @blah3:
  blahblah;some dev3

Problems:
I want to get the string between "RT @blah1:" and ";some device" iteratively.
Thanks a lot in advance.

A: The String class offers many ways to manipulate Strings.
In this case you could use the split()-method:
split by ; and then split by :

A: public static void main(String[] args) {
    String s = "RT @blah1: blahbla;some device1 RT @blah2: blabla;some dev2 @blah3: blahblah;some dev3";

    for (String part : s.split(";")) {
        if (part.contains(":")) {
            System.out.println(part.split(":")[1]);
        }
    }
}

If : and ; are not good enough to split you could replace them in split() by some regular expressions.

A: I agree with the comment of the answers above, i.e. use string.split() first.
If you insist on using REGEX, use the following:
(?:^[^@]+@[^:]+:\s)([^;]+)

Example: https://regex101.com/r/cOmKhU/1
Explanation:

*

*(?:^[^@]+@[^:]+:\s) -> Non capturing Group, starting at the beginning of the line with more than 1 non-@, followed by @, more than one non-: and 1 whitespace

*([^;]+) -> capturing Group, all characters (except for :) until the next :


text:
Q: React Js best practice - onClick event I worked with 3 different scenarios to call a function using onClick event, but I was never sure about which one I should stick with, I will demonstrate my question with a basic example but let's imagine our tFunction is more complicated than updating a state.
const [state, setState] = useState("");

1st scenario  :
const tFunction = (e) => {
const tValue = e.target.getAttribute("name");
setState(tValue)};

<button name={"some data"} onClick={tFunction}>Press me</button>

2nd scenario  :
  const tFunction = (value) => {setState(value)};

  <button onClick={() => tFunction("some data")}> Press me </button>

3rd scenario  :
  <button onClick={() => setState("some data")}> Press me </button>

My question is : what is the best scenario that I should always follow?
demo

A:
Using an arrow function in render creates a new function each time the
component renders, which may break optimizations based on strict
identity comparison.

(From React documentation: https://reactjs.org/docs/faq-functions.html)
Thus, you should go 1st scenario.

A: The first scenario makes you code run faster and can be reusable for other buttons, so I suggest the first scenario


text:
Q: UIManagedDocument initWithURL blows with NSArray error I am completely flummoxed. This code:
 NSFileManager *fileManager=[NSFileManager defaultManager];
    NSURL *documentURL=[fileManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
    documentURL = [documentURL URLByAppendingPathComponent:@"TrackerDB"];
    self.document = [UIManagedDocument alloc];
    self.document = [self.document initWithFileURL:documentURL];

produces this error:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
(I separated the alloc and init into two lines so I could see where it's blowing. It's the initWithFileURL that bombs, as soon as I hit "step into.")
self.document, by the way, is a @property (strong,nonatomic) UIManagedDocument * and the URL is:
@"file://localhost/Users/rick/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/3FEA801E-9279-45A7-9606-853124A111C4/Documents/TrackerDB"
which is exactly as expected. So, as I said, I'm baffled. Am I missing something obvious?

A: As the error you are getting relates to passing a nil pointer to a NSMutableArray method and you aren't working with arrays here, I would say the issue is most likely not with your code. I also read through it and couldn't find a problem. The issue is most likely with your simulator, which can have problems from time to time. It is a good idea to reset the settings and create a new build. The issue is handled well here, and directly relates to this same issue when working with Core Data.


text:
Q: Cannot get ImageResizer to resize my Pdf I've just started using ImageResizer to create thumbnails for my images using the code from their website below.
private void CreateThumbnail()
{
    Dictionary<string, string> versions = new Dictionary<string, string>();
    //Define the versions to generate
    versions.Add("_thumb", "width=100&height=100&crop=auto&format=jpg"); //Crop to square thumbnail
    versions.Add("_medium", "maxwidth=100&maxheight=100&format=jpg"); //Fit inside 400x400 area, jpeg
    versions.Add("_large", "maxwidth=1900&maxheight=1900&format=jpg"); //Fit inside 1900x1200 area

    //Loop through each uploaded file
    foreach (string fileKey in HttpContext.Current.Request.Files.Keys)
    {
        HttpPostedFile file = HttpContext.Current.Request.Files[fileKey];
        if (file.ContentLength <= 0) continue; //Skip unused file controls.

        //Get the physical path for the uploads folder and make sure it exists
        string uploadFolder = MapPath("~/Images");
        if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);

        //Generate each version
        foreach (string suffix in versions.Keys)
        {
            //Generate a filename (GUIDs are best).
            string fileName = Path.Combine(uploadFolder, "AssetID" + suffix);

            //Let the image builder add the correct extension based on the output file type
            fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
        }
    }
}

However, when I apply this code to a Pdf it crashes with the error 'File may be corrupted, empty, or may contain a PNG image with a single dimension greater than 65,535 pixels.'
What changes do I need to make to enable sizing a Pdf? I've gone through their documentation and although it seems that it will create a Thumbnail from a Pdf, the examples are all using images.
This is the list of Plugins including PdfRenderer

A: The PdfiumRenderer or PdfRenderer plugin (whichever you chose) is not installed. Thus, the primary decoder is failing to decode the image.
You must install a PDF plugin for this to work.
PdfiumRenderer is the better of the two.
See http://imageresizing.net/docs/v4/plugins/pdfiumrenderer


text:
Q: Apache Camel Grace Period Pattern I'm using Apache Camel and I need to ingest 'requests' in order to perform some actions asynchronously. I do so by using the REST component and putting the requests in a queue (ActiveMQ). However, within the next 'x' minutes, I might receive a message that makes the former request obsolete. I need a kind of grace period in which the first request might be removed before it is processed.
How can I implement this in Camel?
B.t.w.: I expected an high load (number of messages)


text:
Q: One Note for Mac Images not Showing Now that One Note as come out for Mac I was trying it out but already have a problem in that all the images I insert do not render - I get just an outline and a red cross)

*

*Tried jpg / png

*Via Copy/Paste and insert option

This is the result

Am I doing something incorrect or perhaps have some setting I could change to fix this?
Update:
Now I tried something else. I when to the online version and insert the image there. Now the app keeps crashing trying to sync.
I think it's just to soon to start using this. It's sad because the notebook/sections/pages concept is really good in my opinion


text:
Q: Concatanate tuples in list of tuples I have a list of tuples that looks something like this:
tuples = [('a', 10, 11), ('b', 13, 14), ('a', 1, 2)]

Is there a way that i can join them together based on the first index of every tuple to make a each tuple contain 5 elements. I know for a fact there isn't more that 2 of each letter in the tuples, Ie more than 2 'a's or 'b's in the entire list. The other requirement is to use Python2.6. I cant figure out the logic to it. Any help is greatly appreciated.
Desired Output:
tuples = [('a', 10, 11, 1, 2), ('b', 13, 14, 0, 0)]

I have tried creating a new list of first elements and adding the other elements to it but then I only have a list and not list of tuples.
EDIT to provide previous tried code,
Created a new list: templist, resultList = [], []
Populate templist with the first element in every tuple:
for i in tuples:
    templist.append(i[0])

elemlist = list(set(templist))

for i in elemlist:
    for j in tuples:
        if i == j[0]:
            resultlist.append((i, j[1], j[2]))

This just returns the same list of tuples, How can i hold onto it and append every j[1] j[2] that corresponds to correct j[0]

A: Assuming there are only one or two of every letter in the list as stated:
import itertools

tuples = [('a', 10, 11), ('b', 13, 14), ('a', 1, 2)]

result = []
key = lambda t: t[0]
for letter,items in itertools.groupby(sorted(tuples,key=key),key):
    items = list(items)
    if len(items) == 1:
        result.append(items[0]+(0,0))
    else:
        result.append(items[0]+items[1][1:])
print(result)

Output:
[('a', 10, 11, 1, 2), ('b', 13, 14, 0, 0)]


text:
Q: NSDateFormatter - set device language as locale? I'm trying to get the iPhone to display dates formatted by an NSDateFormatter in the current device language.
I have tried setLocale:[NSLocale currentLocale], but that only returns 5 instead of May (or Mai, as I want it to be).
EDIT: currentLocale shows May (english). systemLocale shows 5 (I think systemLocale is Norwegian), and autoupdatingCurrentLocale shows May as well.
Any help is appreciated. Thanks! :)
NEVERMIND - The simulator played a trick with me, it works on a real device. #

A: I had forgotten to set the Region Format to my local region format :)


text:
Q: Java Script - Extract number from string
Possible Duplicate:
How might I extract the number from a number + unit of measure string using JavaScript?

How to extract number from string like this in JS.
String: "Some_text_123_text" -> 123

A: JSFiddle Demo
var s = "Some_text_123_text";
var index = s.match(/\d+/);
document.writeln(index);

A: try this
var string = "Some_text_123_text";
var find = string.split("_");
for(var i = 0; i < find.length ; i ++){
 if(!isNaN(Number(find[i]))){
  var num = find[i];
 }
}

alert(num);

A: try this working fiddle
var str = "Some_text_123_text";
var patt1 = /[0-9]/g;
var arr= str.match(patt1);
var myval = arr.join("");


text:
Q: Errors in Rspec with rails 3.2 (DEPRECATION WARNING) I'm starting autotest  'rspec=true autotest'
and I have error (rake db:test:prepare is performed):
DEPRECATION WARNING: Calling set_table_name is deprecated. Please use self.table_name = 'the_name' instead. (called from include at /my_project_name/app/models/ckeditor/asset.rb:2)
DEPRECATION WARNING: Factory.define is deprecated; use the FactoryGirl.define block syntax to declare your factory. (called from  at /my_project_name/spec/factories.rb:2)
DEPRECATION WARNING: Factory.define is deprecated; use the FactoryGirl.define block syntax to declare your factory. (called from  at /my_project_name/spec/factories.rb:9)
/usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:in `require': cannot load such file -- capybara/rspec (LoadError)
My gemfile:
source 'https://rubygems.org'

gem 'rails', '3.2.6'
gem 'pg', '0.14.0' # БД
gem 'therubyracer', '0.10.1'
gem 'jquery-rails', '2.0.2'

gem 'paperclip', '3.1.2'
gem 'ckeditor', '3.6.3'

group :assets do
  gem 'sass-rails',   '3.2.5'
  gem 'coffee-rails', '~> 3.2.2'
  gem 'uglifier', '>= 1.2.6'
end

group :development do
  gem 'rspec-rails', '2.11.0'
  gem 'annotate', '2.4.0'
end

group :test do
  gem 'rspec-rails', '2.11.0'
  gem 'factory_girl_rails', '3.5.0'
end

What's wrong? It's works in rails 3.1!

A: First one is deprecate message emitted by rails. It is introduced in 3.2 as I remember. Edit as directed.
Latter two are the message FactoryGirls is emitting and not rails. I guess you updated it also from old version. To eliminate error, just edit your project files as directed.

A: Solved! I just upgraded to the latest version of the gem Ckeditor


text:
Q: \foreach with animation in tikz I'm trying to modify the animation presented here Example: Sine and Cosine functions animation to include phase, so the rotation will start each time at different angle i.e, phase =[0, 45 ,-45] so I used foreach as below, the original animation is shown in Example: Sine and Cosine functions animation, but the code didn't work (please uncomment the related commands to animation to check the error I'm getting).
\documentclass[tikz]{standalone}
\usepackage{tikz}

\begin{document}
%\newcounter{theangle}
%\setcounter{theangle}{0}
    \begin{tikzpicture}
        \def\angle{45};
        \fill[fill=red] (0,0) -- plot [domain=0:pi/180*\angle] (\x,{sin(\x r)}) -- (pi/180*\angle,0) -- cycle;
    \end{tikzpicture}

    %\begin{animateinline}[loop, poster = first,controls]{40}
     %
     %\foreach \angle in {0,45,-45}
     %\whiledo{\angle<359}{

    \foreach \angle in {0,10,...,360}
    {
        \begin{tikzpicture}
        %\fill[blue!50] (-1,0) arc (0:\angle:1) -- (-2,0) -- cycle;
        %\fill[blue!50] plot[smooth,domain=0:\angle] (pi/180*\x,{sin(\x)}) |- (0,0);
        \def\radangle{pi/180*\angle};

        \fill[blue!50] (-1,0) arc (0:\angle:1) -- (-2,0) -- cycle;
        %\fill[fill=red] (0,0) -- plot [domain=0:\radangle] (\x,{sin(\x r)}) -- (\radangle,0) -- cycle;

        \draw (-2,0) +(\angle:1) circle (2pt) -- (pi/180*\angle,{sin(\angle)}) circle (2pt);
        \draw (-3.5,0) -- (7,0);
        \foreach \deg in {90, 180, 270, 360}
            \draw (pi/180*\deg,2pt) -- (pi/180*\deg,-2pt) node[below] {$\deg^\circ$};
        \draw (0,-1.2) -- (0,1.2);
        \foreach \y in {-1,-0.5,0.5,1}
        \draw (2pt,\y) -- (-2pt,\y) node[left] {$\y$};
        \draw plot[smooth,domain=0:360] (pi/180*\x,{sin(\x)});
        \draw (-2,0) circle (1);
        \end{tikzpicture}
            %
     %   \stepcounter{theangle}
     %    \ifthenelse{\theangle<359}{\newframe}{
     %            \end{animateinline}}
    }

\end{document}

A: The example makes use of \clist_map_inline:nn from LaTeX3 instead of TikZ's \foreach to iterate over the comma-separated list of phase shifts. For some reason, \foreach does not work inside animateinline.
Some pauses (\newframe*) are placed at suitable animation points; click the play button or the animation widget in order to continue:

(A Chromium-based browser is recommended for viewing the SVG version, as Firefox is a bit slow.)
\documentclass{standalone}

\usepackage[T1]{fontenc}
\usepackage{tikz,animate}

\ExplSyntaxOn
\let\clistMap\clist_map_inline:nn
\ExplSyntaxOff

\newcommand{\drawit}[2]{% #1 angle (0<=#1<=360)
  \begin{tikzpicture}   % #2 phase shift

  \pgfmathsetmacro\angleRad{pi/180*(#1+#2)}
  \pgfmathsetmacro\angleDeg{#1+#2}

  \pgfmathsetmacro\unshiftedRad{pi/180*(#1)}

  \fill[blue!50] (-2,0) -- ++(#2:1) arc (#2:\angleDeg:1) -- cycle;

  \draw (-2,0) +(\angleDeg:1) circle (2pt) -- (\unshiftedRad,{sin(\angleDeg)}) circle (2pt);
  \draw (-3.5,0) -- (7,0);
  \foreach \deg in {90, 180, 270, 360}
      \draw (pi/180*\deg,2pt) -- (pi/180*\deg,-2pt) node[below] {$\deg^\circ$};
  \draw (0,-1.2) -- (0,1.2);
  \foreach \y in {-1,-0.5,0.5,1}
  \draw (2pt,\y) -- (-2pt,\y) node[left] {$\y$};
    \draw plot[smooth,domain=0:360] (pi/180*\x,{sin(\x+#2)});
  \draw (-2,0) circle (1);
  \node [anchor=north east] at (current bounding box.north east) {$\varphi=#2^\circ$};
  \end{tikzpicture}%
}

\begin{document}

\begin{animateinline}[controls]{30}
  \clistMap{0,45,-45}{%
    \drawit{0}{#1}
    \newframe*
    \multiframe{360}{i=1+1}{\drawit{\i}{#1}}%
    \ifthenelse{#1=-45}{}{\newframe*}%
  }
\end{animateinline}

\end{document}


text:
Q: How can I programmatically see what requests (e.g. API or resource requests) are being made by a website In Chrome, you can go to developer tools > network tab to see all the requests the website is making.
What would be a good way to get the list of these requests programmatically? I guess I can grab the content of the site, grab all the URLs that are in the page and parse them, but that seems a bit tedious, especially if the requests are being made from a JS file.
Is there an easier way?

A: On the server side, there's the access log that will have request information for all requests made against it.  It might take some configuration to save all the fields you want to use (method, POST data, cookies, time, remote client address) but this is more efficient than trying to do things from a browser.  Each web server has a different way of configuring its log files.


text:
Q: What is PHP SoapClient port? $client = new SoapClient("http://www.mobilywebservices.com:86/SMSWebService/SMSIntegration.asmx?wsdl");
What is PHP SoapClient port because my local network used firewall and closed all ports.

A: SOAP is an XML schema.
It usually runs over HTTP (port 80), however.
Use the search: What port number does SOAP use?
Also mentioned in the thread: it uses port no.8084 To the firewall,
The URL http://www.mobilywebservices.com:86/SMSWebService/SMSIntegration.asmx?wsdl
you are trying to connect to has :86 behind it so it uses port 86 try this
Check if SOAP is installed with <?php phpinfo() ?>


text:
Q: Split columns in R I have  a huge set of data with 35k + Rows of data. i import this data from a .csv file in R and do the same in Excel. In excel it shows me 8 different headings of columns with 35k Rows. But in R, it shows me only one column name with all the column names in one big column. I have tried with the following R code:
> YR1999 <- read.csv("~/Desktop/---/---/YR1999.csv", header=TRUE, quote="\"")

> class(YR1999)
[1] "data.frame"

> names(YR1999)
[1] "SYMBOL.......SHORT_NAME...........INFO_4THE.OPENING_RATE.HIGH_RATE..LOW_RATE.CURR_RATE.CURR_TURNOVER"

> dim(YR1999)
[1] 35647     1
> colnames(YR1999) <- c("Symbol", "Stock Name", "Date", "Open-Rate","High-Rate", "Low-Rate", "Current-Rate", "Turnover")
Fehler in `colnames<-`(`*tmp*`, value = c("Symbol", "Stock Name", "Date",  :
  Attribut 'names' [8] muss dieselbe Länge haben wie der Vektor [1]

In Excel I see for each column name a different column but in R I dont. I would like to separate this one name to 8 columns as in the original data, can any one suggest me how can I do this?

A: Just try read.csv("~/Desktop/---/---/YR1999.csv", sep=";", header=TRUE, quote="\"") or read.csv("~/Desktop/---/---/YR1999.csv", sep=",", header=TRUE, quote="\""). You can actually look up in the excel which separation (";" or ",") is used.

A: Please try this
install.packages("do")
library(do)
col_split(x = YR1999[,1],split = '-')


text:
Q: Intermediate output should be in [-1, 1] but tanh activation saturates - solution? I am prediction a set of coordinates on a grid at an intermediate layer of my neural network. This coordinates should be in range [-1, 1]. My idea was to use a tanh activation function to achieve that - but unfortunately, by doing so after a few steps the output is always -1 or 1. I read, that this can be prevented by using a batch normalization before the tanh. This does indeed work, but at a cost - it forces all predicted coordinates towards the centre, which is a huge and a wrong bias, as I am predicting body landmarks, which are not necessarily in the middle of the image.
Does anyone have an idea, what I can do? The way I predict the coordinates is the following:
class Encoder(nn.Module):
    def __init__(self, n_parts, n_features, residual_dim, reconstr_dim, depth_s, depth_a, device, p_dropout=0.2, c=16, dim=64):
        super(Encoder, self).__init__()
        self.preprocessor = PreProcessor(residual_dim, reconstr_dim)
        self.k = n_parts
        self.dropout = nn.Dropout(p_dropout)
        self.tanh = nn.Tanh()
        self.relu = nn.ReLU()
        self.relu = nn.LeakyReLU()
        self.bn1 = nn.BatchNorm2d(c * self.k)
        self.bn2 = nn.BatchNorm2d(2 * n_parts)
        self.hg_shape = Hourglass(depth_s, residual_dim)
        self.to_channels = Conv(residual_dim, c * n_parts, kernel_size=3, stride=1, bn=False, relu=False)
        self.mu = nn.Conv2d(in_channels=c * n_parts, out_channels=2 * n_parts, kernel_size=dim, groups=n_parts)

    def forward(self, img):
        bn = img.shape[0]
        img_preprocessed = self.preprocessor(img) # shape [bn, 256, 64, 64]

        # Get Shape Representation
        img_shape = self.hg_shape(img_preprocessed)
        img_shape = self.dropout(img_shape)
        img_c = self.to_channels(img_shape)
        img_c = self.relu(self.bn1(img_c))
        mu = self.mu(img_c)
        mu = self.tanh(mu).reshape(bn, self.k, 2)

        return mu


text:
Q: Load template or view depending upon a $_GET variables content I am designing a Q & A website use php. Here is the directory structure:
+include
  db.php
  user.php
  template.php
  ...
  question.php
+public
  +images
  +styles
.htaccess
index.php
...

I want to use index.php 's REQUEST_STRING to load a template.
For example: index.php?page=signin will load the function get_signin_template() in template.php. And will show the visitor a URL like http://example.com/signin/.
Here are my questions:

*

*How to load different templates in index.php (what should do in this file)?

*How to rewrite the url (using apache mod_rewrite)?

A: Answer to Question 1
$valid_templates = array('signin', 'logout', 'home');
if(isset($_GET['page'])
   and in_array($_GET['page'], $valid_templates)) {
    $function_name = 'get_' . $_GET['page'] . '_template';
    $template = call_user_func($function_name);
}

See call_user_func() in the PHP manual and the in_array() function in the PHP manual.
I think it is also worth mentioning that I would not do it this way myself. Mapping URLs directly to functions is an inflexible way of doing things.
The reason I have added the $valid_templates array is to ensure the user doesn't attempt to change the URL in an attempt to call a nonexistant function etc. You would need to add each page/template function to it.
If you really like this way of working then I would recommend you check out Limonade as it uses a similar dispatch method as the one you are attempting to setup (the following example is from their official site):
require_once 'vendors/limonade.php';
dispatch('/', 'hello');
  function hello()
  {
      return 'Hello world!';
  }
run();

But is a little safer and easier to manage in my opinion. Plus all the "hard" plumbing work has been done and you can just focus on adding your pages.
Another similar option is Slim, which looks like this:
require 'Slim/Slim.php';
Slim::init();
Slim::get('/hello/:name', function ($name) {
    echo "Hello $name";
});
Slim::run();

Example from their site.
Answer to Question 2
Something along these lines in your .htaccess file should work for your rewriting needs.
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

A: 1.for index.php?page=signin
$urlEnd=$_GET['page'];
require('path_to_file'.$urlEnd);//Require your file
header('Location: index.php?/$urlEnd');//WARNING!!! HEADER MUST go befor any echo's


text:
Q: Rotating text with tex4ht i want to rotate text within a table, which works fine when generating a pdf document, but not when using tex4ht. Is there a way to fix this?
MWE:
\documentclass{book}
\usepackage{mwe}

\begin{document}

\rotatebox{90}{text}

\end{document}

A: We can use the CSS transform property together with rotate() function to rotate boxes in HTML. You can try the following configuration file graphicx.4ht:
% graphicx.4ht (2017-10-21-16:16), generated from tex4ht-4ht.tex
% Copyright 2003-2009 Eitan M. Gurari
% Copyright 2009-2017 TeX Users Group
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either
% version 1.3c of this license or (at your option) any
% later version. The latest version of this license is in
%   http://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions
% of LaTeX version 2005/12/01 or later.
%
% This work has the LPPL maintenance status "maintained".
%
% The Current Maintainer of this work
% is the TeX4ht Project <http://tug.org/tex4ht>.
%
% If you modify this program, changing the
% version identification would be appreciated.
\immediate\write-1{version 2017-10-21-16:16}

   \let\Gin:esetsize\Gin@esetsize
\def\Gin@esetsize{%
   \ifx \Gin@ewidth\Gin@exclamation
      \let\Gin:ewidth\Gin@ewidth
   \else
      \setlength\tmp:dim\Gin@ewidth
      \edef\Gin:ewidth{\the\tmp:dim}%
   \fi
   \ifx \Gin@eheight\Gin@exclamation
      \let\Gin:eheight\Gin@eheight
   \else
      \setlength\tmp:dim\Gin@eheight
      \edef\Gin:eheight{\the\tmp:dim}%
   \fi
   \Gin:esetsize
}
\DeclareGraphicsRule{.png}{bmp}{.xbb}{}
\DeclareGraphicsRule{.jpg}{bmp}{.xbb}{}
\DeclareGraphicsRule{.gif}{bmp}{.xbb}{}
\DeclareGraphicsRule{.pdf}{bmp}{.xbb}{}
\DeclareGraphicsRule{.svg}{bmp}{.xbb}{}

\NewConfigure{rotatebox}{2}
\pend:def\Grot@box{\a:rotatebox}
\append:def\Grot@box{\b:rotatebox}

\Configure{rotatebox}{\HCode{}}{\HCode{}}
\Css{.rotatebox{
  display: inline-block;}}

\Hinput{graphicx}
\endinput

The important code is the following:
\NewConfigure{rotatebox}{2}
\pend:def\Grot@box{\a:rotatebox}
\append:def\Grot@box{\b:rotatebox}

\Configure{rotatebox}{\HCode{}}{\HCode{}}
\Css{.rotatebox{
  display: inline-block;}}

A new tex4ht configuration, rotatebox has been declared and the configuration hooks have been inserted to the \Grot@box command, which is used to draw the rotated box. The hooks are then configured to insert the  element with style="transform: rotate(-\Grot@angle deg);" CSS style. This style enables the rotation. The \Grot@angle command contains the rotation angle, which must be negative for some reason in the CSS.
The following TeX code:
\documentclass{book}
\usepackage{mwe}

\begin{document}

normal text
\rotatebox{90}{text}
\rotatebox{190}{some longer text}
normal text continues

\end{document}

will be rendered in this way in HTML:

In PDF, it looks a bit different:

The problem is that things started to go wrong when I tried to use a different point of rotation than the center, so I think this is the best we can get.
Edit:
If your Epub viewer doesn't support rotations (just a proof of the poor support ebooks still receive), you can convert the rotated text to an image. Try the following config file:
\Preamble{xhtml,svg}
\Configure{rotatebox}{\Picture+{}}{\EndPicture}
\begin{document}
\EndPreamble

The result:


text:
Q: Avoiding undefined offset error I have following function
function getSum($array){
    if(is_array($array)) {
        $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
        $sum = 0;
        foreach ($iterator as $key => $value) {
            $sum += $value;
        }
    } else{
        $sum = $array;
    }
    return $sum;
}

And I'm using it like this
$teams = array();
$teams[1]['AREA I']['blue'] = 30;
$teams[1]['AREA I']['green'] = 25;
$teams[1]['AREA II']['blue'] = 15;
$teams[2]['AREA I']['blue'] = 40;

echo getSum($teams); //output: 110
echo getSum($teams[1]); //output: 70
echo getSum($teams[1]['AREA I']); //output: 55
echo getSum($teams[1]['AREA I']['blue']); //output: 30

How to avoid error Undefined offset when using like getSum($teams[2]['AREA IV'] (key AREA IV not set)? In this case I want that function returns zero.

A: Since the error occurs before the getSum function is called, there is no way you can change that function so that it would work.
However, if you are willing to change the arguments that are passed to getSum, you could get around that. You could pass the array without further keys specifications (to avoid the potential error) and specify the key(s) as a second argument. Then leave it to getSum to try to get to that value if it exists, like this:
function getSum($array, $path = array()){
    // process second argument:
    foreach ($path as $key) {
        if (!is_array($array) || !isset($array[$key])) {
            return 0; // key does not exist, return 0
        }
        $array = $array[$key];
    }
    if(is_array($array)) {
        $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
        $sum = 0;
        foreach ($iterator as $key => $value) {
            $sum += $value;
        }
    } else{
        $sum = $array;
    }
    return $sum;
}

$teams = array();
$teams[1]['AREA I']['blue'] = 30;
$teams[1]['AREA I']['green'] = 25;
$teams[1]['AREA II']['blue'] = 15;
$teams[2]['AREA I']['blue'] = 40;

// pass an optional 2nd argument:
echo getSum($teams); //output: 110
echo getSum($teams, [1]); //output: 70
echo getSum($teams, [1,'AREA I']); //output: 55
echo getSum($teams, [1,'AREA I','blue']); //output: 30
echo getSum($teams, [2, 'AREA IV']); // no error, output: 0


text:
Q: How to calculate actual font point size in iOS 7 (not the bounding rectangle)? Edit: The linked "duplicate" question only deals with calculating text rectangle. I need to calculate actual font size after label scaled it, NOT the string size.
This method is now deprecated:
size = [self sizeWithFont:font // 20
              minFontSize:minFontSize // 14
           actualFontSize:&actualFontSize // 16
                 forWidth:maxWidth
            lineBreakMode:self.lineBreakMode];

How can I calculate font size of a UILabel now in iOS 7 when it shrunk the size of the text to fit in?

A: Distilled from Julius Bahr's answer on this page, this method works perfectly for getting the actual font size after it has been automatically adjusted:
- (CGFloat)getActualFontSizeForLabel:(UILabel *)label
{
    NSStringDrawingContext *labelContext = [NSStringDrawingContext new];
    labelContext.minimumScaleFactor = label.minimumScaleFactor;

    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:label.text attributes:@{ NSFontAttributeName: label.font }];
    [attributedString boundingRectWithSize:label.frame.size
                                   options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                   context:labelContext];

    CGFloat actualFontSize = label.font.pointSize * labelContext.actualScaleFactor;
    return actualFontSize;
}

I am using this in my application to get the font sizes for three different labels for which I need to keep the sizes in synch while still allowing them to auto-shrink for localized translations that can be quite a bit longer than their original English counterparts.
I call that method once for each label, and then if they are not all the same value, I set the label's font sizes to the minimum of the three.

A: The use of minFontSize was deprecated on UILabel in iOS 6, and on the NSString drawing additions in iOS 7.  If you want to use it and find the actual font size used, you need to use the deprecated method you mentioned in your question.
The replacement for minFontSize is minimumScaleFactor.  If you want to find the actual scale factor used, you need to create an NSStringDrawingContext and pass it in the boundingRectWithSize:options:attributes:context: message, like this:
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
context.minimumScaleFactor = 0.7;
[label.text boundingRectWithSize:CGSizeMake(maxWidth, HUGE_VAL)
    options:NSStringDrawingUsesLineFragmentOrigin
    attributes:@{
        NSFontAttributeName: font
    } context:context];
CGFloat actualFontSize = font.pointSize * context.actualScaleFactor;

A: Expanding on Ferran's answer
To expand to fill width or height, whichever it hits first
Swift version
func getFontSizeToFitFrameOfLabel(label: UILabel) -> CGFloat
{
    var initialSize : CGSize = label.text!.sizeWithAttributes([NSFontAttributeName : label.font])

    if initialSize.width > label.frame.size.width ||
       initialSize.height > label.frame.size.height
    {
        while initialSize.width > label.frame.size.width ||
              initialSize.height > label.frame.size.height
        {
            label.font = label.font.fontWithSize(label.font.pointSize - 1)
            initialSize = label.text!.sizeWithAttributes([NSFontAttributeName : label.font])
        }
    } else {
        while initialSize.width < label.frame.size.width &&
              initialSize.height < label.frame.size.height
        {
            label.font = label.font.fontWithSize(label.font.pointSize + 1)
            initialSize = label.text!.sizeWithAttributes([NSFontAttributeName : label.font])
        }
        // went 1 point too large so compensate here
        label.font = label.font.fontWithSize(label.font.pointSize - 1)
    }
    return label.font.pointSize;
}

Then do something like this to use it (say your label is named title1Label)
 title1Label.frame = CGRect(x: 0.0, y: 0.0, width: view.frame.size.width, height: view.frame.size.height)
 // sets font to some nonzero size to begin with, it will change up or down to fit the label's frame
 title1Label.font = UIFont(name: "Super Mario 256", size: 45.0)
 title1Label.font = title1Label.font.fontWithSize(getFontSizeToFitFrameOfLabel(title1Label))
 // resize height to be a little larger than the font height
 title1Label.frame.size.height = title1Label.font.pointSize*1.3

Objective C version:
- (CGFloat) maxFontSize:(UILabel *)label{
   CGSize initialSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];

   if (initialSize.width > label.frame.size.width ||
       initialSize.height > label.frame.size.height)
   {
       while (initialSize.width > label.frame.size.width ||
              initialSize.height > label.frame.size.height)
       {
           [label setFont:[label.font fontWithSize:label.font.pointSize - 1]];
           initialSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
       }
   } else {
       while (initialSize.width < label.frame.size.width &&
              initialSize.height < label.frame.size.height)
       {
           [label setFont:[label.font fontWithSize:label.font.pointSize + 1]];
           initialSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
       }
       // went 1 point too large so compensate here
       [label setFont:[label.font fontWithSize:label.font.pointSize - 1]];
   }
   return label.font.pointSize;
}

A: My specific quest has been to size the font on 2 labels equally with adjustsFontSizeToFitWidth enabled.
The solution works on iOS 6 and 7.
+ (void)sizeLabelFontToMinSizeFor:(UILabel *)label1 and:(UILabel *)label2 {

NSStringDrawingContext *labelContext = [NSStringDrawingContext new];
labelContext.minimumScaleFactor = label1.minimumScaleFactor;

NSAttributedString *attributedString1 = [[NSAttributedString alloc] initWithString:label1.text attributes:@{NSFontAttributeName : label1.font}];
// the NSStringDrawingUsesLineFragmentOrigin and NSStringDrawingUsesFontLeading options are magic
[attributedString1 boundingRectWithSize:label1.frame.size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:labelContext];

CGFloat actualFontSize1 = label1.font.pointSize * labelContext.actualScaleFactor;

labelContext = [NSStringDrawingContext new];
labelContext.minimumScaleFactor = label2.minimumScaleFactor;

NSAttributedString *attributedString2 = [[NSAttributedString alloc] initWithString:label2.text attributes:@{NSFontAttributeName : label2.font}];
[attributedString2 boundingRectWithSize:label2.frame.size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:labelContext];

CGFloat actualFontSize2 = label2.font.pointSize * labelContext.actualScaleFactor;

CGFloat minSize = MIN(actualFontSize1, actualFontSize2);

label1.font = [UIFont fontWithName:RCDefaultFontName size:minSize];
label2.font = [UIFont fontWithName:RCDefaultFontName size:minSize];
}

A: Next code doesn't support minFontSize and lineBreakMode so if you need them you should improve it by yourself:
CGSize NSString_sizeWithFont(NSString * str, UIFont *font) {
    CGSize result;
    if (NO == [str respondsToSelector: @selector(sizeWithAttributes:)]) {
        // legacy way
        result = [str sizeWithFont: font];
    } else {
        // modern way
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:
                               font, NSFontAttributeName, nil];
        result = [str sizeWithAttributes: dict];
    }
    return result;
}

UIFont * NSString_calcActualFont(NSString * str, UIFont * initialFont,
                                 CGSize sizeLimit, CGSize * actualSize)
{
    const CGSize curSize = NSString_sizeWithFont(str, initialFont);

    CGFloat actualFontSize = initialFont.pointSize;
    actualFontSize *= MIN(sizeLimit.width / curSize.width, sizeLimit.height / curSize.height);

    UIFont * actualFont = [initialFont fontWithSize: floorf(actualFontSize)];
    *actualSize = NSString_sizeWithFont(str, actualFont);

    return actualFont;
}

A: I have the same problem, I need to know the actual size to make that the others UILabels in my UIView match.
I know that it's not a perfect solution, but perhaps it's useful for you.
My solution is: instead of use adjustsFontSizeToFitWidth I calculate "manually" the size.
CGSize initialSize = [_label.text sizeWithAttributes:@{NSFontAttributeName:_label.font}];
while ( initialSize.width > _label.frame.size.width ) {
    [_label setFont:[_label.font fontWithSize:_label.font.pointSize - 1]];
    initialSize = [_label.text sizeWithAttributes:@{NSFontAttributeName:_label.font}];
}
CGFloat actualSize = _label.font.pointSize;

A: Simple solution for one-line UILabel:
//myLabel - initial label

UILabel *fullSizeLabel = [UILabel new];
fullSizeLabel.font = myLabel.font;
fullSizeLabel.text = myLabel.text;
[fullSizeLabel sizeToFit];

CGFloat actualFontSize = myLabel.font.pointSize * (myLabel.bounds.size.width / fullSizeLabel.bounds.size.width);

//correct, if new font size bigger than initial
actualFontSize = actualFontSize < myLabel.font.pointSize ? actualFontSize : myLabel.font.pointSize;

A: Erik van der Neut's code worked for me, so I translated it in Swift and wrapped it in a UILabel extension:
extension UILabel {

    public func actualFontSize()-> CGFloat {
        let context = NSStringDrawingContext()
        context.minimumScaleFactor = self.minimumScaleFactor

        let attributedString = NSAttributedString(string: self.text ?? "", attributes: [NSFontAttributeName: self.font])
        attributedString.boundingRectWithSize(self.frame.size, options: [.UsesLineFragmentOrigin], context: context)

        return (self.font.pointSize * context.actualScaleFactor)
    }
}


text:
Q: Flutter playing audio slower the animation I have used following animation plugin. I draw around 100-120 boxes on screen. Each box contains a single character. Each character animates from start to target character. E-g I have an array [A,B..Z,0,1..9]. There are list of messages which are need to show and animate. E-g following messages needs to show on screen. ['THIS IS 1', 'LINE IS 2.']. Now first box will animate from A to T and second box will animate from A to H and so on. FlipPanel.builder is used for animation and its working fine.
https://pub.dev/packages/flip_panel
For audio
https://pub.dev/packages/just_audio
Now, I have to play audio along side the animation just like tick tick. Here comes the problem when we play audio then animation becomes slower and jerky otherwise its fine.
I guess no need to show build method because it only creates boxes with nested listviews and then add FlipPanel.builder widget. Please check the below initState which plays audio.
Note: I already tried to direct call AudioTimer.start() but did not get success so I tried to run on other thread thats why calling AudioDriver(); Please also note that asset loading done on previous page i-e on intro page then we navigate to home page. Any idea if we can execute it on thread etc?
class _MyHomePageState extends State<MyHomePage> {

  ServiceModel? model;
  BuildContext? _context;

  @override void initState() {
    super.initState();

    WidgetsBinding.instance!.addPostFrameCallback((_) async {
        //get next messages but same page will be reopened
        var tmp = await DataSource.getNextPage();

        setState(() {
          model = tmp;
         });
        //after 9 seconds, refresh page for new messages
        FixAppTimer.checkTimer(_context!, Duration(seconds: 9), '/home');

        AudioDriver();
        //AudioTimer.start();

    });

  }

class AudioDriver{
  AudioDriver(){
    scheduleTimeout(300);
  }

  Timer scheduleTimeout([int milliseconds = 10000]) =>
    Timer(Duration(milliseconds: milliseconds), handleTimeout);

  void handleTimeout() async {
    AudioTimer.scheduleTimeout(9000);
    await AudioTimer.start();
  }
}

class AudioTimer{

  //static int duration;
  static final player = AudioPlayer();

  static load() async {
    await player.setAsset('assets/flap3.wav');
    //await player.setSpeed(2.0);
    await player.setLoopMode(LoopMode.all);
  }

  static Future start() async {
     // scheduleTimeout(9000);
    await player.play();
  }

  static Timer scheduleTimeout([int milliseconds = 10000]) =>
    Timer(Duration(milliseconds: milliseconds), handleTimeout);

  static void handleTimeout() {
    player.stop();
  }

}


text:
Q: Clientdataset fechando após abrir Estou utilizando o delphi xe6 faz alguns dias e estou quebrando a cabeça com um problema.
Tenho aqui o trio: SQLDataSet -> ClientDataSet -> DataSetProvider.
Quando abro meu formulário, chamo o cdsPessoas.Open (ClientDataSet).
Até aí tudo bem, ele exibe meus registros tudo certo. Mas na hora que eu chamo o cdsPessoas.Append, ele me retorna o erro dizendo que o ClientDataSet não está ativo. O problema é que em nenhum momento eu fecho ele, ou seja, não sei por que diabos ele está fechando sozinho.
Utilizo esses componentes dentro de um data module junto com mais dois ClientDataSet e SQLDataSet fazendo o Master\Detail. Já tentei tirar o master\detail, mas não é o problema, até porque os dados são exibidos corretamente.
Alguém tem alguma idéia do que pode ser?

A: Considerando as informações fornecidas, não sou capaz de apontar uma resposta direta ao problema, então procurarei ajudar de outra forma, com uma ideia.
Em situações como esta o que eu faço é compilar a aplicação com Debug DCUs ativo e colocar um tratador de evento, neste caso, em AfterClose do Dataset em questão. Então recrio a situação de problema e quando o Delphi parar no breakpoint eu avalio o CallStack, que nesse caso vai mostrar toda a sequência de chamadas que culminou com a situação.
Normalmente eu encontro um código meu, um tratador de evento que tinha esquecido ou mesmo um bug que é responsável pelo caso. Algumas vezes trata-se de um comportamento normal do componente que eu não havia compreendido bem ou então o uso de uma propriedade da forma errada.
Seja como for, com o CallStack eu geralmente consigo entender o que está provocando o comportamento estranho e resolvo o caso.
Experimente!