text:
Q: From a pair to a list in lambda calculus / scheme I'm learning a bit about lambda calculus (which is very neat) and have defined the following in scheme for how a pair would be done:
; PAIR
; λabf.fab
(define PAIR (lambda (a) (lambda (b) (lambda (f) ((f a) b)))))
(define mypair ((PAIR 1) 2))

; FIRST
; λab.a
(define FIRST (lambda (a) (lambda (b) a)))

; SECOND
; λab.b
(define SECOND (lambda (a) (lambda (b) b)))

(display "First is: ")     (display (mypair FIRST))
(display " | Second is: ") (display (mypair SECOND))

First is: 1 | Second is: 2

How would one abstract this further to create a data structure of a list, for example, to make something like [1 2 3 4 5] instead of just [2 3] ?
The best I've been able to do by myself is to sort of hardcode these, for example, for five:
(define five (
    (PAIR 1) (
      (PAIR 2) (
        (PAIR 3) (
          (PAIR 4) 5)))))

(display (five FIRST)) (display ((five SECOND) FIRST)) (display (((five SECOND) SECOND) FIRST)) (display ((((five SECOND) SECOND) SECOND) FIRST)) (display ((((five SECOND) SECOND) SECOND) SECOND))

12345

Is there a more 'general' solution for this?

A: Normal LISP lists are not [1 2 3], they are (1 . (2 . (3 . ()))). They are created with (cons 1 (cons 2 (cons 3 '()))) so the exact equal list in lambda calculus would be ((PAIR 1) ((PAIR 2) ((PAIR 3) ...)))
Now a standard lisp implementation usually prints (1 2 3), but that is some funky magic done by the printer. Its rule is that if the cdr is a list you can omit the dot and one set of parentheses. When you are using lambda calculus to model data the REPL will always show lambda/closure objects so you need utility functions that understands the structure and displays a visualization that corresponds. This is not par of lambda calculus as for it it is OK to just satisfy the axioms:
(car (cons a b)) ; ==> a
(cdr (cons a b)) ; ==> b

list is a auxiliary function that cons chain the arguments. You could indeed make something similar for pairs but it is not a part of lambda calculus:
(define TRUE (lambda (p) (lambda (q) p)))
(define NIL (lambda (x) TRUE))

(define (ch-list . args)
  (let helper ((lst (reverse args)) (result NIL))
    (if (null? lst)
        result
        (helper (cdr lst)
                ((PAIR (car lst)) result)))))

A: As Sylwester says. Lists are not arrays, they are chains of conses, ending in a special nil or () object.  That means that to build such things you need both cons and this special object.
I have a toy language implemented in Racket called 'oa' (one argument), which, as of a few minutes ago, you can find here.  In its purest variant the syntax of functions is, for instance (λ x x): there are no parens around the argument because why would there be?  There is define to give things names as well, but that's pretty much it.  Here is an implementation of conses in this language:
(define true (λ x (λ y x)))
(define false (λ x (λ y y)))

(define cons (λ h (λ t (λ s ((s h) t)))))
(define car (λ l (l true)))
(define cdr (λ l (l false)))
(define nil (λ l true))
(define null? (λ l (l (λ h (λ t false)))))

Conveniently (but also annoyingly), oa uses the normal Racket reader, so you can read numbers, even though they have no semantics in the language.  So, for instance
> (cdr ((cons 1) 1))
1

To make, say, a three element list of an element:
(define three-elt
  (λ e
    ((cons e)
     ((cons e)
      ((cons e)
       nil)))))

> (three-elt 1)
#<λ>
> (car (three-elt 1))
1
> (cdr (cdr (cdr (three-elt 1))))
{nil}: (λ l true)

(There is some special, flaky, magic which will let it print the names of things which have been defined as in the last case.)
Given definitions of zero, zero?, succ and pred (successor and predecessor), and a conditional function, cond, which looks like (((cond test) if-true) if-false), you can then write a dirty version of nth:
(define nth
  (λ n (λ c
         (((cond (zero? n))
           (car c))
          ((nth (pred n)) (cdr c))))))

This is dirty because it uses nth free, but you can fix that with a combinator: I like U, so:
(define U
  ;; The U combinator
  (λ f (f f)))

(define nth
  (U (λ t
       (λ n
         (λ c
           (((cond (zero? n))
             (car c))
            (((U t) (pred n)) (cdr c))))))))

With either of these:
> ((nth (succ zero)) ((cons true) ((cons false) nil)))
{false}: (λ x (λ y y))
> ((nth zero) ((cons true) ((cons false) nil)))
{true}: (λ x (λ y x))

What I don't think you can do is implement list as such, because even if you added special magic to express nospread functions like list you then already need to have turned all its arguments into a list.  But I might be wrong about that.
All of the above functions exist in examples/lc.rkt in oa.


text:
Q: mysql error: Table "mysql"."innodb_table_stats" not found I'm getting the following error in mysql 5.6 community edition:
: Error:
Table "mysql"."innodb_table_stats"
 not found. InnoDB: Recalculation
of persistent statistics requested for table "mydatabase"."mytable"
but the required persistent statistics storage is not present or is corrupted.
Using transient stats instead.

how do I fix this error?

A: I ran into this issue on a production server recently and the most common answers I found involving dropping tables, deleting files etc. made me feel a little uneasy!
So I thought it might be useful to point out for people reading this in future that in my case the actual cause of the error was my root partition filling up. I had been making a mysql dump at the time and saved it to the wrong place. So the solution was just to free up some disk space and restart the service.
It might be an idea to check that this is not the case for you before moving onto the standard solutions which involve messing around with the structure of MYSQL and have the potential to be a little riskier.
Good Luck,

A: Read this mysql doc to learn more about Persistent Statistics.
To disable this feature, add innodb_stats_persistent = 0 to my.cfg and restart your mysql server.

A: This solved my problem.

/*    temporary fix for problem with windows installer for MySQL
  5.6.10 on Windows 7 machines.   I did the procedure on a clean installed MySql, and it worked for me, at least it stopped   lines of
  innodb errors in the log and the use of transient innodb tables. So,
  do it at   your own risk..

*

*drop these tables from mysql:
   innodb_index_stats
   innodb_table_stats    slave_master_info
   slave_relay_log_info
   slave_worker_info

*delete all .frm & .ibd of the tables above.

*run this file to recreate the tables above (source five-tables.sql).

*restart mysqld.
   Cheers,    CNL
  */

CREATE TABLE `innodb_index_stats` (
  `database_name` varchar(64) COLLATE utf8_bin NOT NULL,
  `table_name` varchar(64) COLLATE utf8_bin NOT NULL,
  `index_name` varchar(64) COLLATE utf8_bin NOT NULL,
  `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `stat_name` varchar(64) COLLATE utf8_bin NOT NULL,
  `stat_value` bigint(20) unsigned NOT NULL,
  `sample_size` bigint(20) unsigned DEFAULT NULL,
  `stat_description` varchar(1024) COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`database_name`,`table_name`,`index_name`,`stat_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin STATS_PERSISTENT=0;

CREATE TABLE `innodb_table_stats` (
  `database_name` varchar(64) COLLATE utf8_bin NOT NULL,
  `table_name` varchar(64) COLLATE utf8_bin NOT NULL,
  `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `n_rows` bigint(20) unsigned NOT NULL,
  `clustered_index_size` bigint(20) unsigned NOT NULL,
  `sum_of_other_index_sizes` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`database_name`,`table_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin STATS_PERSISTENT=0;

CREATE TABLE `slave_master_info` (
  `Number_of_lines` int(10) unsigned NOT NULL COMMENT 'Number of lines in the file.',
  `Master_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the master binary log currently being read from the master.',
  `Master_log_pos` bigint(20) unsigned NOT NULL COMMENT 'The master log position of the last read event.',
  `Host` char(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT '' COMMENT 'The host name of the master.',
  `User_name` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The user name used to connect to the master.',
  `User_password` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The password used to connect to the master.',
  `Port` int(10) unsigned NOT NULL COMMENT 'The network port used to connect to the master.',
  `Connect_retry` int(10) unsigned NOT NULL COMMENT 'The period (in seconds) that the slave will wait before trying to reconnect to the master.',
  `Enabled_ssl` tinyint(1) NOT NULL COMMENT 'Indicates whether the server supports SSL connections.',
  `Ssl_ca` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The file used for the Certificate Authority (CA) certificate.',
  `Ssl_capath` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The path to the Certificate Authority (CA) certificates.',
  `Ssl_cert` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the SSL certificate file.',
  `Ssl_cipher` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the cipher in use for the SSL connection.',
  `Ssl_key` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the SSL key file.',
  `Ssl_verify_server_cert` tinyint(1) NOT NULL COMMENT 'Whether to verify the server certificate.',
  `Heartbeat` float NOT NULL,
  `Bind` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'Displays which interface is employed when connecting to the MySQL server',
  `Ignored_server_ids` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The number of server IDs to be ignored, followed by the actual server IDs',
  `Uuid` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The master server uuid.',
  `Retry_count` bigint(20) unsigned NOT NULL COMMENT 'Number of reconnect attempts, to the master, before giving up.',
  `Ssl_crl` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The file used for the Certificate Revocation List (CRL)',
  `Ssl_crlpath` text CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The path used for Certificate Revocation List (CRL) files',
  `Enabled_auto_position` tinyint(1) NOT NULL COMMENT 'Indicates whether GTIDs will be used to retrieve events from the master.',
  PRIMARY KEY (`Host`,`Port`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT='Master Information';

CREATE TABLE `slave_relay_log_info` (
  `Number_of_lines` int(10) unsigned NOT NULL COMMENT 'Number of lines in the file or rows in the table. Used to version table definitions.',
  `Relay_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the current relay log file.',
  `Relay_log_pos` bigint(20) unsigned NOT NULL COMMENT 'The relay log position of the last executed event.',
  `Master_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the master binary log file from which the events in the relay log file were read.',
  `Master_log_pos` bigint(20) unsigned NOT NULL COMMENT 'The master log position of the last executed event.',
  `Sql_delay` int(11) NOT NULL COMMENT 'The number of seconds that the slave must lag behind the master.',
  `Number_of_workers` int(10) unsigned NOT NULL,
  `Id` int(10) unsigned NOT NULL COMMENT 'Internal Id that uniquely identifies this record.',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT='Relay Log Information';

CREATE TABLE `slave_worker_info` (
  `Id` int(10) unsigned NOT NULL,
  `Relay_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `Relay_log_pos` bigint(20) unsigned NOT NULL,
  `Master_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `Master_log_pos` bigint(20) unsigned NOT NULL,
  `Checkpoint_relay_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `Checkpoint_relay_log_pos` bigint(20) unsigned NOT NULL,
  `Checkpoint_master_log_name` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `Checkpoint_master_log_pos` bigint(20) unsigned NOT NULL,
  `Checkpoint_seqno` int(10) unsigned NOT NULL,
  `Checkpoint_group_size` int(10) unsigned NOT NULL,
  `Checkpoint_group_bitmap` blob NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT='Worker Information';

A: same issue but crash table 'gtid_slave_pos', Create gtid_slave_pos
CREATE TABLE `gtid_slave_pos` (
  `domain_id` int(10) unsigned NOT NULL,
  `sub_id` bigint(20) unsigned NOT NULL,
  `server_id` int(10) unsigned NOT NULL,
  `seq_no` bigint(20) unsigned NOT NULL,
  PRIMARY KEY (`domain_id`,`sub_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Replication slave GTID state';

A: This turned out to be a permission problem for me. Since this was on a development machine where permissions are not locked down, I was able to fix it easily enough:
sudo chmod -R 775 /usr/local/mysql/data

...if that solves it for you, then great. But if the problem is on a production machine, you may wish to investigate permissions a little more thoroughly than my solution.
maybe you would like to try this instead:
sudo chown mysql.mysql -R /usr/local/mysql/data

A: If you're running Debian Linux:
My solution to this problem was after dropping the mysql.innodb_table_stats file and removing the associated .frm and .ibd files, I ran this:
dpkg-reconfigure mariadb-server-10.1

It recreates the innodb_* tables for you but for whatever reason had trouble doing it with the files already there (from a previous install).
I consider this safer as the columns and their names may have changed since the answer above was written.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix problems with accent in words in code in R I have a problem while coding in R. I have to use some cities names, and they have accent. But once I runned the code, the letter become ? and the code doesn't work anymore.
What I have :
c_fill$city[c_fill$city == "SART?NE"] <- "SARTENE"
What I want :
c_fill$city[c_fill$city == "SARTÈNE"] <- "SARTENE"
Thanks for your help.

A: I think you can recreate the script (copy and paste) and save it with the encoding "UTF-8".


text:
Q: cvs - how do I find out if I need a new directory without `cvs up`? I have written a shell script to show me what files need patching without actually doing a cvs up. It's just a simple cvs stat parser.
But, it doesn't tell me if a new directory would come down with a new cvs up -d.
Is there a way to find out if I'm missing directories that would be created with the next cvs up -d?

A: The -n switch shows me missing directories:
cvs -n up -d

The -n switch does not actually run cvs up -d; it just shows the effects of running the command.


text:
Q: Orbit stabilizer theorem gives a homeomorphism for algebraic groups? Let $k$ be a local field of characteristic zero, and $G$ a linear algebraic group over $k$.  Let $X$ be a variety over $k$, and $G \times X \rightarrow X$ a group action defined over $k$.  When we pass to the $k$-rational points, we get a continuous action of $G(k)$ on $X(k)$.

1 .  Are the $G(k)$-orbits always closed in $X(k)$?
2 .  If $x_0 \in X(k)$, is the natural continuous map $G(k)/\textrm{Stab}(x_0) \rightarrow G(k).x_0$ a homeomorphism?

A: For the first question, the answer is in general no.  For example, $\textrm{GL}_n(\mathbb{R})$ acts continuously on $\mathbb{R}^n$, and there are two orbits, the zero vector and its complement.
However, if $G$ is a topological group acting continuously on a topological space $X$, then the quotient sapce $G \setminus X$ is Hausdorff if and only if all orbits are closed.  This is because a point in $G \setminus X$ is closed if and only if its preimage is closed in $X$.
For the second question, the answer is yes.  Since $k$ is locally compact Hausdorff, so are $G(k)$ and $X(k)$, and $G(k)$ has a countable basis.  So there is a more general result we can apply.  This is from J.S. Milne's notes on modular forms.
Lemma 1: If $G$ is a nonempty locally compact Hausdorff topological space, and $G$ is the countable union of closed sets $V_n$, then at least one of the $V_n$ contains a nonempty open set.
Proof: Suppose no $V_n$ contains a nonempty open set.  Let $U_1$ be a nonempty open set in $G$ whose closure is compact.  Then $U_1 \not\subseteq V_1$, which means $U_1 \cap V_1 \subsetneq U_1$.  Now $U_1 \cap V_1$ is closed in $U_1$, so we can find a nonempty open set $U_2 \subseteq U_1$ whose closure $\overline{U_2}$ is contained in $U_1$ and disjoint from $U_1 \cap V_1$.  This is because compact sets form a neighborhood basis of any point.
Now $U_2 \not\subseteq V_2$, so $U_2 \cap V_2 \subsetneq V_3$, and we can find an open $U_3$ whose closure $\overline{U_3}$ is compact and disjoint from $U_2 \cap V_2$.
Iterating, we have open sets $U_1 \supseteq U_2 \supseteq \cdots$ with compact closures $\overline{U_1} \supseteq \overline{U_2} \supseteq \cdots$ such that $\overline{U_i}$ is disjoint from $U_{i-1} \cap V_{i-1}$ for $i \geq 2$.  The intersection of the compact sets $\overline{U_i} : i = 2, 3, ...$ must be nonempty.  Let $p$ be in this intersection.  For each $i \geq 1$, we have $p \in U_i$.  And for each $i \geq 2$, we have $p \not\in U_{i-1} \cap V_{i-1}$.  Hence $p$ is not in any of the $V_i$, which is impossible.  $\blacksquare$
Lemma 2: Let $G$ be a locally compact Hausdorff topological group with a countable basis, acting continuously on a locally compact Hausdorff space $X$.  If $x_0 \in X$, then the natural map $G/ \textrm{Stab}(x_0) \rightarrow G.x_0$ is a homeomorphism.
Proof: We may replace $X$ by the orbit of $x_0$ and assume $G$ acts transitively on $X$.
Let $H$ be the stabilizer of $x_0$.  The universal property of quotients gives us a continuous bijection $G/H \rightarrow X$, which we need to show is open.
Let $U$ be open in $G$.  Let $gx_0$ be a point of $Ux_0$.  We need to find an open neighborhood $W$ of $gx_0$ which is contained in $Ux_0$.  Of course, we can choose $g$ to be in $U$.
Standard topological group shenanigans gives us a neighborhood $V$ of $1_G$ such that $V = V^{-1}$, and $gV^2 \subseteq U$.  Furthermore, we can choose $V$ to be compact.  Since $G$ has a countable basis, it is easy to see that $G$ is the union of countably many translates $g_nV$ for some $g_n \in G$.
Each $g_nV$ is compact, hence so is the image $g_nVx_0$.  So $X$ is the countable union of the closed sets $g_nVx_0$.  By the first lemma, one of the closed sets $g_nVx_0$ contains a nonempty open set.  These closed sets are translated around homeomorphically by $G$.  So this means that $Vx_0$ must contain a nonempty open set $W$.  Let $hx_0 \in W$ for some $h \in V$.  Then $gx_0 = gh^{-1}hx_0$ lies in the open set $gh^{-1}W$.  But since $V^2 \subseteq U$, we have $$gh^{-1}W \subseteq gV^2x_0 \subseteq gVx_0 \subseteq Vx_0 \subseteq Ux_0$$

A: This is an addendum to the answer provided by D_S.
I think you missed an assumption in Lemma 2: You have to assume that the orbit $G.x$ is locally compact itself (or assume a transitive action, like Milne does). Otherwise the lemma won't hold. You might regard the action of $\mathbb{Z}$ (with discrete topology) on $\mathbb{R}^2$ by rotation with an irrational angle.
Since the stabilizer of the point $x_0=\begin{pmatrix}1\\0\end{pmatrix}$ is trivial, Lemma 2 would imply that $G.x_0 \cong \mathbb{Z}$. But the orbit of $x_0$ is dense in $S^1$ and has non-constant convergent series, which $\mathbb{Z}$ does not have.


text:
Q: C# upcasting of one type in a two-type generic doesn't work I prepared a sample application of a problem I have in a big WPF application.
The issue I have is with upcasting the second type of the TreeColumn instance obsTreeColumn to a Collection.
As you can see when I do this with just one type the upcast works fine.
The method DoSomethingWithColumn needs to be able to work with any type of collection as the second generic type of the parameter collection.
public class TreeColumn<T, TValue>  where TValue : Collection<T> {
    // A lot happens in here...
}

public class Data {
    public int Id { get; set; }
    public int Code { get; set; }
    // And much more...
}

class Program {
    static void Main(string[] args) {
        var expander = new TreeExpander<Data>();
        var obsTreeColumn = new TreeColumn<Data, ObservableCollection<Data>>();
        var colTreeColumn = new TreeColumn<Data, Collection<Data>>();

        var obsCollection = new ObservableCollection<Data>();
        var colCollection = new Collection<Data>();

        expander.DoSomethingWithColumn(obsTreeColumn);
        expander.DoSomethingWithColumn(colTreeColumn);
        expander.DoSomethingWithCollection(obsCollection);
        expander.DoSomethingWithCollection(colCollection);
        Console.ReadKey();
    }
}

class TreeExpander<T> where T : class {

    private int _rowCounter;

    public void DoSomethingWithColumn(object column) {

        // WHY ISN'T THIS CAST WORKING WITH A TreeColumn<T, ObservableCollection<T>>????
        var cast2 = column as TreeColumn<T, Collection<T>>;
        WriteLine("Cast to 'TreeColumn<T, Collection<T>>': ");
        WasCastSuccess(cast2);

        WriteLine("");
    }

    public void DoSomethingWithCollection(object collection) {

        var cast2 = collection as Collection<T>;
        WriteLine("Cast to 'Collection<T>': ");
        WasCastSuccess(cast2);

        WriteLine("");
    }

    private void WasCastSuccess(object o) {
        WriteLine(o != null ? "PERFECT!" : "Cast didn't work :(");
    }

    private void WriteLine(string msg) {
        _rowCounter++;
        Console.WriteLine(_rowCounter.ToString("00")+": "+msg);
    }
}

The console output is:
01: Cast to 'TreeColumn<T, Collection<T>>':
02: Cast didn't work :(
03:
04: Cast to 'TreeColumn<T, Collection<T>>':
05: PERFECT!
06:
07: Cast to 'Collection<T>':
08: PERFECT!
09:
10: Cast to 'Collection<T>':
11: PERFECT!
12:

I need to come up with something so line 2 of the output reads PERFECT!

A: Use out keyword to specify that the type parameter is covariant.
public interface ITreeColumn<T, out TValue> where TValue : Collection<T>
{
    // A lot declared in here..
}

public class TreeColumn<T, TValue> : ITreeColumn<T, TValue> where TValue : Collection<T>
{
    // A lot happens in here..
}


text:
Q: InMobi SDK 7 Android | InMobi needs to be initialized before calling Interstitial Request I have integrated InMobi 7.2.9 in my App and initialize it like this:
  JSONObject consent = new JSONObject();
  try {
      consent.put(InMobiSdk.IM_GDPR_CONSENT_AVAILABLE, true);
  } catch (JSONException e) {
      Log.d(TAG, "Init InMobiSDK failed");
      e.printStackTrace();
  }
  InMobiSdk.init(cordova.getActivity(), accountID, consent);
  InMobiSdk.setLogLevel(InMobiSdk.LogLevel.DEBUG);

After that I initialize my Interstitial like this:
mInterstitialAd = new InMobiInterstitial(cordova.getActivity(), placementId,
   new InterstitialAdEventListener() {
       @Override
       public void onAdLoadSucceeded(InMobiInterstitial inMobiInterstitial) {
            super.onAdLoadSucceeded(inMobiInterstitial);
            Log.d(TAG, "onAdLoadSuccessful");
            if (!inMobiInterstitial.isReady()) {
              Log.d(TAG, "onAdLoadSuccessful inMobiInterstitial not ready");
            }
       }

       @Override
       public void onAdLoadFailed(InMobiInterstitial inMobiInterstitial, InMobiAdRequestStatus inMobiAdRequestStatus) {
           super.onAdLoadFailed(inMobiInterstitial, inMobiAdRequestStatus);
           Log.d(TAG, "Unable to load interstitial ad (error message: " + inMobiAdRequestStatus.getMessage());
       }

       @Override
       public void onAdReceived(InMobiInterstitial inMobiInterstitial) {
           super.onAdReceived(inMobiInterstitial);
           Log.d(TAG, "onAdReceived");
       }

       @Override
       public void onAdClicked(InMobiInterstitial inMobiInterstitial, Map<Object, Object> map) {
           super.onAdClicked(inMobiInterstitial, map);
           Log.d(TAG, "onAdClicked " + map.size());
       }

       @Override
       public void onAdWillDisplay(InMobiInterstitial inMobiInterstitial) {
           super.onAdWillDisplay(inMobiInterstitial);
           Log.d(TAG, "onAdWillDisplay " + inMobiInterstitial);
       }

       @Override
       public void onAdDisplayed(InMobiInterstitial inMobiInterstitial) {
           super.onAdDisplayed(inMobiInterstitial);
           Log.d(TAG, "onAdDisplayed " + inMobiInterstitial);
       }

       @Override
       public void onAdDisplayFailed(InMobiInterstitial inMobiInterstitial) {
           super.onAdDisplayFailed(inMobiInterstitial);
           Log.d(TAG, "onAdDisplayFailed " + "FAILED");
       }

       @Override
       public void onAdDismissed(InMobiInterstitial inMobiInterstitial) {
           super.onAdDismissed(inMobiInterstitial);
           Log.d(TAG, "onAdDismissed " + inMobiInterstitial);
       }

       @Override
       public void onUserLeftApplication(InMobiInterstitial inMobiInterstitial) {
           super.onUserLeftApplication(inMobiInterstitial);
           Log.d(TAG, "onUserWillLeaveApplication " + inMobiInterstitial);
       }

       @Override
       public void onRewardsUnlocked(InMobiInterstitial inMobiInterstitial, Map<Object, Object> map) {
           super.onRewardsUnlocked(inMobiInterstitial, map);
           Log.d(TAG, "onRewardsUnlocked " + map.size());
       }
   });

   Log.d(TAG, "Start to load Interstitial");
   mInterstitialAd.load();

To init the InMobi SDK I use the accountID from my InMobi Account and placementID for my Interstitial Ad.First I init my InMobi and after that I load the Interstitial. But somehow Im always getting the Erro:

You need to initialize InMobi first before calling Interstitial Ads. Call ignored.

I used this sample code from inmobi but somehow InmobiSdk.init doesnt work.


text: Q: Can I create a Windows service exe with certain permissions so that a non admin user can start or stop that service? Local user has created the service exe Service1.exe using Service1.sln. Then local user has another application say App.exe. From App.exe the local user wants to start the service "Service1.exe" but he is not able to because local user is not an administrator. So, is it possible to build the Service1.exe in such a way that the local user will be able to start the service. App.exe is in C++ and Service1.exe is in C#. I know that I can give the admin permission into the App.exe using a manifest file but I want to somehow give it in Service1.exe so that App.exe can start the service Service1.exe. Is it possible?


text:
Q: Devise registration confirmation I have a User and an Admin role in my project. I created my authentication with Devise.
In my admin role I don't have any confirmation. In my User model I have the following:
devise :database_authenticatable, :confirmable, :recoverable,
       :rememberable, :trackable, :validatable, :timeoutable, :registerable

# Setup accessible (or protected) attributes for your model
attr_accessible :email, :username, :prename, :surname, :phone, :street, :number, :location,
                :password, :password_confirmation

My migration looks like:
class DeviseCreateUsers < ActiveRecord::Migration
  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      t.confirmable
      t.recoverable
      t.rememberable
      t.trackable
      t.timeoutable
      t.validateable
      t.string  :username
      t.string  :prename
      t.string  :surname
      t.string  :phone
      t.string  :street
      t.integer :number
      t.string  :location

      t.timestamps
    end

    add_index :users, :email,                :unique => true
    add_index :users, :confirmation_token,   :unique => true
    add_index :users, :reset_password_token, :unique => true
    add_index :users, :username,             :unique => true
    add_index :users, :prename,              :unique => false
    add_index :users, :surname,              :unique => false
    add_index :users, :phone,                :unique => false
    add_index :users, :street,               :unique => false
    add_index :users, :number,               :unique => false
    add_index :users, :location,             :unique => false
  end

  def self.down
    drop_table :users
  end
end

In my routes.rb I added following statements:
map.devise_for :admins
map.devise_for :users, :path_names => { :sign_up => "register", :sign_in => "login" }

map.root :controller => "main"

After user registration I am redirected to the controller main with the flash notice, "You have signed up successfully," and I am logged in. But I don´t want to be logged in, because I have not confirmed my new user account yet.
If I open the console I see in the logs the confirmation mail text, but I am already logged in. I can´t explain why. Does anyone have an idea?
If I copy out the confirmation-token from the logs and confirm my account, I can log in, but if I don´t confirm, I also can log in.

A: In config/initializers/devise.rb there is a line to set the amount of time a user has to confirm before they're locked out.
config.confirm_within = 2.days

If you set that to 0, you should get the desired outcome.


text:
Q: Compute a Quadratic discriminant analysis (QDA) in R assuming not normal data and missing information In this course, the professor is saying that we can compute a QDA with missing data points and non-normal data (even if this assumption can be violated).
But the problem is that I don't know any function in R that can accommodate both the missing data points and the non-normal data. A QDA, from what I know is only interesting if you have heteroscedasticity. But it still need non-missing data points and normal data.
In the library MASS, they are saying:

na.action
A function to specify the action to be taken if NAs are found. The default action is for the procedure to fail. An alternative is
na.omit, which leads to rejection of cases with missing values on any
required variable. (NOTE: If given, this argument must be named.)

But actually, it means that we are just going to remove all the NAs. Right?
Do you know a way to compute a QDA that can use non-normal data and missing data points (NAs)?
For the NAs, I guess I just have to add na.action = "na.exclude". Is that correct? If I want to predict the class of a data point but missing one information for a dimension, how can I predict the class?
Is the QDA in R a Bayesian approximation as said here or it uses the frequentist approach?


text:
Q: Several If Statements in an access 2007 vba subroutine. Curious if there is another way? First let me premise with I am very new to access vba.
My question is I have several if then else statements in a row for example
If Me.txtRevenuePerHour.Value < 90 Then
    Me.chkRPH.Value = -1
    Me.chkRPH.Enabled = "False"
End If

If Me.txtLoadTime.Value < 0.25 Then
    Me.chkLT15.Value = -1
    Me.chkLT15.Enabled = "False"
End If

I was wondering if there is another way besides rewriting the if statements over and over again.  If not then I will accept that but just curious if there is another way.
The if statements check a checkbox control if certain conditions are met.  Most are different conditions but some are the same
Thank you ahead of time

A: The code for each if uses completely different objects and conditions in the If clause and inside the If blocks different objects are used as well.
There is no way to generalize the If itself, thought the body of the If may be:
Untested code:
Sub DisableAndSetToMinusOne(ctrl As Control)
  ctrl.Value = -1
  ctrl.Enabled = "False"
End Sub

If Me.txtRevenuePerHour.Value < 90 Then
    DisableAndSetToMinusOne(Me.chkRPH)
End If

If Me.txtLoadTime.Value < 0.25 Then
    DisableAndSetToMinusOne(Me.chkLT15)
End If


text:
Q: Scala Eclipse file>new has  I downloaded the Scala IDE for Mac 64 bit from http://scala-ide.org/download/sdk.html
I open the program, click File > New and see .
The Coursera tutorial I'm in says that I should see the option to create a new Scala project. It looks like I have the IDE but not the SDK?

A: The simplest reason to get this behavior would be if all perspectives are closed.
Most of the menus in Eclipse are contextual, and File > New is empty if there is no current perspective.
To open a perspective, use Windows > Open Perspective > Other..., then select Scala and OK. Then File > New contains the list of the Scala related wizard.


text:
Q: Why do I get an error for incorrect number of arguments? I have:
import datetime
class Animal(object):

    def __init__(self, dob, carnivore):
        self.__dob = dob
        self.__carnivore = carnivore

    @property
    def dob(self):
        return self.__dob

    @dob.setter
    def dob(self, dob):
        self.__dob = dob

    @property
    def carnivore(self):
        return self.__carnivore

    @carnivore.setter
    def carnivore(self, carnivore):
        self.__carnivore = carnivore

    def __str__(self):
        return "DOB: " + str(self.__dob) + "\nCarnivore: " + str(self.__carnivore)

My second  class:
import Species.Animal as Animal
import datetime as date

class Amphibian(Animal):

    def __init__(self, dob=date.datetime.now(), carnivore=False, *characteristics):
        super(Animal, self).__init__(dob, carnivore)
        self.__characteristics = []
        for characteristic in characteristics:
            self.__characteristics.append(characteristic)

    @property
    def characteristics(self):
        return self.__characteristics

    @characteristics.setter
    def characteristics(self, characteristic):
        self.__characteristics.append(characteristic)

    def __str__(self):
        characteristics = ""
        for characteristic in self.__characteristics:
            characteristics += str(characteristic)
        return characteristics

Using:
amphibian = Amphibian(date.date(1979, 1, 12), True, "BackBone", "Cold Blooded")
print(amphibian)

I get the error:

Traceback (most recent call last):   File
  "C:/Users/Daniel/PycharmProjects/ObjectOrientedSpecies/Species/Amphibian.py",
  line 7, in
      class Amphibian(Animal): TypeError: module.__init__() takes at most 2 arguments (3 given)

I am new to Python so I'm not sure what good OO Practices are.

A: There are two issues I can see. Firstly you should call super on the class name of the class you are calling super in (that is a bit of a mouthful) so that line should be super(Amphibian, self).__init__(dob, carnivore) and not super(Animal, self).__init__(dob, carnivore). Python will find the baseclass Animal itself.
However the main problem is that the class Animal is (almost certainly) in a file called "Animal.py". Python makes a module called Animal automagically when it sees a file called "Animal.py" (and does something similar for all other ".py" names. So your class Animal is, in fact inside a module called Animal.
Therefore when you do import Species.Animal as Animal you are importing the module not the class inside it. So when you do class Amphibian(Animal): your Amphibians are inheriting from the class module not from the class Animal. You need to change your import to the following to get the class Animal instead: from Species.Animal import Animal.
In terms of your style I don't really see the point of having lots of decorated getters and setters if there is nothing going on inside them except simple getting and setting. Just get rid of the underscores in front of the atribute names and use them directly. You only need to use the getters and setters if something else has to happen to do the getting and setting.


text:
Q: wordpress custom theme import and export options for sample data I am Created WordPress custom theme as per Html template. it was worked fine.
now I am trying to create custom export/import functionality for my custom created theme. but I don't have found a better solution for that.
so my question is how to create export/import theme options?

A: Assuming that you're moving between one environment and the next (EG: dev -> Staging > Production) as a new install then you could export the database and do a find and replace on the current url with the new one.
eg:
find all > https://dev.example.com
replace all > https://www.example.com
Make sure you do not include the trailing slash after the TLD (.com etc) or you'll miss some urls and it won't work.
If these options are an update to an existing site you'd be better to manually transfer them over.

A: You don't have to export and import the tables from the database; you don't have to build an export/import function for your theme either. There is an Export tool built in WordPress under the Tools menu and in the same sub-menu you'll find the Import tool as well. The process is pretty straightforward:

*

*export the posts;

*make a new WP installation in the a directory;

*copy/install and activate the plugins if you used any on the development installation;

*copy your theme and activate it (this is important if you have some custom post types or custom fields associated with it or with the plugins);

*go to the Import screen and install the WordPress tool, it's the last in the list of tools;

*activate the tool and then upload the exported file.

Sidenote, exporting and importing data is not a functionality that's associated with the WordPress themes. :)
Also, the process of manual export and import of tables is tricky as there are many connections between the tables, unique ID and many more thing that can go wrong.
If you want to read more on the Export and the Import take a look in the Codex: the export screen; the import screen and some bonus read for  the import.
Happy migrating!


text:
Q: hide a component inside BrowserRouter in React when i move to a new route So i have a layout like this:
             <BrowserRouter>

                     <MainHeader />
                     <Homepage />
                     <Route exact path='/' component={Placeholder} />
                     <Route path='/placeholder' component={Placeholder} />
                     <Route path='/address_checker' component={Address_Checker} />
                     <Route path='/availability_checker' component={Availability_Checker} />
                     <Route path='/usage_checker' component={Usage_Checker} />
                     <Route path='/device_checker' component={Device_Checker} />
                     <Route path='/payment_checker' component={Payment_Checker} />
                     <Route path='/result' component={Result} />

                     <Route path='/login' component={Login} />

             </BrowserRouter>

When I route to any other path besides '/', I want to hide the Homepage component. However, I have no idea how to do this, and my google search has proved fruitless.

A:
When I route to any other path besides '/', I want to hide the
  Homepage component. However, I have no idea how to do this, and my
  google search has proved fruitless.

Hello. Your architecture is flawed.
        <BrowserRouter>

                 <Route exact path='/' component={Homepage} />
                 <Route path='/placeholder' component={Placeholder} />
                 <Route path='/address_checker' component={Address_Checker} />
                 <Route path='/availability_checker' component={Availability_Checker} />
                 <Route path='/usage_checker' component={Usage_Checker} />
                 <Route path='/device_checker' component={Device_Checker} />
                 <Route path='/payment_checker' component={Payment_Checker} />
                 <Route path='/result' component={Result} />

                 <Route path='/login' component={Login} />

         </BrowserRouter>

Try this. Just have the routing component be a child of MainHeader so that the header is active everywhere. Same for footer etc.

A: If you want to display the component Homepage only on path / and nowhere else, change your prop component to render and render Placeholder and Homepage.
Or Create a Component which renders both and pass that as component.
Doc for render props.
<BrowserRouter>

        <MainHeader />
        <Route exact path='/' render={props => (
            <React.Fragment>
                <Homepage/>
                <Placeholder/>
            </React.Fragment>
        )}/>
        <Route path='/placeholder' component={Placeholder} />
        <Route path='/address_checker' component={Address_Checker} />
        <Route path='/availability_checker' component={Availability_Checker} />
        <Route path='/usage_checker' component={Usage_Checker} />
        <Route path='/device_checker' component={Device_Checker} />
        <Route path='/payment_checker' component={Payment_Checker} />
        <Route path='/result' component={Result} />

        <Route path='/login' component={Login} />

</BrowserRouter>


text:
Q: Add animation to netbeans-generated jFrame I'm new to java and I'm trying to add an animation to a jFrame that I created using the Netbeans design editor. The idea is that there will be a background image and the animation will play on top of it. I'd also like to have other components that start out hidden and are displayed on top of the finished animation.
After some research on stackoverflow, I managed to create the animation I wanted. However, I can't figure out how to implement it into the Netbeans-generated jFrame I've created. As mainly a python user, all this method and class business is still a little confusing to me.
Here's my code for the animation:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AnimationTest extends JPanel{

int height = 1;

AnimationTest() {
    setPreferredSize(new Dimension(1000,618));
    ActionListener al = (ActionEvent ae) -> {
        repaint();
        if(height < 190) {
            height ++;
        }
    };
    Timer timer = new Timer(10,al);
    timer.start();
}

public void paintComponent(Graphics g) {
    Color c = (Color.BLACK);
    g.setColor(c);
    g.fillRect(0, 309 - height, 1000, 2*height);
}

public static void main(String[] args){
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame window = new JFrame("");
            window.getContentPane().add(new AnimationTest());
            createWindow(window);
        }
    });
}

public static void createWindow(JFrame window){
    window.pack();
    window.setLocationByPlatform(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
}

}

UPDATE: I tried replacing new JFrame with new AnimationFrame (the JFrame form I made using netbeans). Now the JFrame works but the JPanel isn't added (or isn't displayed). What is the right way to add the JPanel?


text:
Q: UITableViewCell button tags return desired IndexPath in UISearchController, not FetchedResultsController I implemented an NSFetchedResultsController on a UITableView in a Core Data project in Swift 2.0. Additionally, I have a UISearchController implemented. Everything works perfectly with the exception of the behavior I'm encountering on my custom UITableViewCell buttons.
When UISearchController is active, the customTableViewCell's buttons work as they should. If I click the same button when the fetchedResultsController is displaying its results, the method thinks Index 0 is the sender, regardless of which button I click.
func playMP3File(sender: AnyObject) {

    if resultsSearchController.active {
        // ** THIS WORKS **
        // get a hold of my song
        // (self.filteredSounds is an Array)
        let soundToPlay = self.filteredSounds[sender.tag]
        // grab an attribute
        let soundFilename = soundToPlay.soundFilename as String
        // feed the attribute to an initializer of another class
        mp3Player = MP3Player(fileName: soundFilename)
        mp3Player.play()
    } else {

        // ** THIS ALWAYS GETS THE OBJECT AT INDEX 0 **
        let soundToPlay = fetchedResultsController.objectAtIndexPath(NSIndexPath(forRow: sender.tag, inSection: (view.superview?.tag)!)) as! Sound
        // OTHER THINGS I'VE TRIED
        // let soundToPlay = fetchedResultsController.objectAtIndexPath(NSIndexPath(forRow: sender.indexPath.row, inSection: (view.superview?.tag)!)) as! Sound
        // let soundToPlay: Sound = fetchedResultsController.objectAtIndexPath(NSIndexPath(index: sender.indexPath.row)) as! Sound
        let soundFilename = soundToPlay.soundFilename as String
        mp3Player = MP3Player(fileName: soundFilename)
        mp3Player.play()
    }
}

Here's an abbreviated version of my cellForRowAtIndexPath to show I'm setting up the cells' buttons:
let customCell: SoundTableViewCell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! SoundTableViewCell

if resultsSearchController.active {
    let sound = soundArray[indexPath.row]
    customCell.playButton.tag = indexPath.row
} else {
    let sound = fetchedResultsController.objectAtIndexPath(indexPath) as! Sound
    customCell.playButton.tag = indexPath.row
}

    // add target actions for cells
    customCell.playButton.addTarget(self, action: "playMP3file:", forControlEvents: UIControlEvents.TouchUpInside)

I've tried a few other approaches I've found here, such as translating CGPoints to IndexPaths, etc. without much luck. Everything that looked promising in the compiler crashed when I clicked the button in the simulator.
Thank you for reading.
Update
Installed Xcode 7.1, rebooted, cleaned caches, nuked derived data, did a cold boot.
Solution
Tags will get the job done in many cases (such as getting the location in an Array) and get lots of votes here, but as I've learned, they don't work all the time. Thank you to Mundi for pointing me towards a more robust solution.
// this gets the correct indexPath when resultsSearchController is not active
let button = sender as! UIButton
let view = button.superview
let cell = view?.superview as! SoundTableViewCell
let indexPath: NSIndexPath = self.tableView.indexPathForCell(cell)!
let soundToPlay = fetchedResultsController.objectAtIndexPath(indexPath) as! Sound

A:
I've tried a few other approaches I've found here, such as translating CGPoints to IndexPaths, etc. without much luck.

Translating points is indeed the most robust solution. This answer contains the correct code.


text:
Q: Unit testing spring rest controller error handling I have a spring rest controller as detailed below
@RestController
@RequestMapping(value = "/data")
public class DataController {

private final IDataService service;
private static final Logger LOG = Logger.getLogger(DataController.class);

/**
 * The Constructor.
 *
 * @param service
 *            the service
 */
@Autowired
public DataController(final IDataService service) {
    this.service = service;
}

// Country
/**
 * Find all countries.
 *
 * @return the response entity< list< country>>
 */
@RequestMapping(value = "/country", produces = Util.APPLICATION_JSON_UTF8_STRING, method = RequestMethod.GET)
public ResponseEntity<List<Country>> findAllCountries() {
    List<Country> countries = new ArrayList<>();
    try {
        countries = this.service.findAllCountries();
        return new ResponseEntity<>(countries, null, HttpStatus.OK);
    } catch (final Exception e) {
        LOG.error(e.getMessage(), e);
        return new ResponseEntity<>(countries, null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

I have a unit test using Mockito and Mock Mvc which tests the successful path
public class DataControllerTest implements IAbstractController {

private MockMvc mockMvc;

@Mock
private IDataService serviceMock;

@InjectMocks
private DataController dataController;

@Autowired
WebApplicationContext wac;

/**
 * Sets the up.
 *
 * @throws Exception
 *             the exception
 */
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.standaloneSetup(this.dataController).build();
}

 @Test
public void testFindAllCountries() throws Exception {

    final Country first = new CountryBuilder().id(3L).name("USA").regionId(1L).active(true).build();
    final Country second = new CountryBuilder().id(66L).name("India").regionId(2L).active(true).build();
    final Country third = new CountryBuilder().id(1L).name("United Kingdom").regionId(4L).active(true).build();

    when(this.serviceMock.findAllCountries()).thenReturn(Arrays.asList(first, second, third));

    final ResultActions ra = this.mockMvc.perform(get("/data/country.do")).andExpect(status().isOk())
        .andExpect(content().contentType(Util.APPLICATION_JSON_UTF8)).andExpect(jsonPath("$", hasSize(3)))
        .andExpect(jsonPath("$[0].id", is(3))).andExpect(jsonPath("$[0].name", is("USA")))
        .andExpect(jsonPath("$[0].regionId", is(1))).andExpect(jsonPath("$[0].active", is(true)))
        .andExpect(jsonPath("$[1].id", is(66))).andExpect(jsonPath("$[1].name", is("India")))
        .andExpect(jsonPath("$[1].regionId", is(2))).andExpect(jsonPath("$[1].active", is(true)))
        .andExpect(jsonPath("$[2].id", is(1))).andExpect(jsonPath("$[2].name", is("United Kingdom")))
        .andExpect(jsonPath("$[2].regionId", is(4))).andExpect(jsonPath("$[2].active", is(true)));

    Assert.assertNotNull(ra);
    verify(this.serviceMock, times(1)).findAllCountries();
    verifyNoMoreInteractions(this.serviceMock);

}

However, I am struggling to test the catch block where an error response is returned. What are the best practices around this? Can anyone advise?
FYI the Abstract controller just contains annotations
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public interface IAbstractController {

}

So the test I am trying is
@Test(expected = Exception.class)
public void testFindAllCountriesThrowsException() throws Exception {
    Mockito.doThrow(new RuntimeException()).when(this.serviceMock.findAllCountries());
    this.mockMvc.perform(get("/data/country.do"));
}

Whilst this test passes, accorrding to the coverage infor from EclEmma, my catch block is still not being covered by the test

A: you have to get a error message in terms of error handling
MvcResult mvcResult = resultActions.andExpect(status().isForbidden()).andReturn();
String errMsg = mvcResult.getResponse().getErrorMessage();

A: In your test, try using
Mockito.doThrow(new RuntimeException()).when(this.serviceMock).findAllCountries());

If you encounter a compile error, you might also use
when(this.serviceMock.findAllCountries()).thenThrow(new RuntimeException());


text:
Q: GWT - how can I make the buttons equally take up a panel (programmatically)? I have a HorizontalPanel and I added two Buttons to it.
The HorizontalPanel is already as wide as its parent.
I want each Button to take a half of the HorizontalPanel. How can I do it programmatically?
Or maybe am I using the wrong panel? Any advice would be appreciated.
I tried setWidth("50%"). It looks strange. I also tried other panels e.g. FlowPanel. I just cannot figure it out...

A: Use setWidth("100%") instead of setWidth("50%") for both the Buttons and then add it to HorizontalPanel.


text:
Q: Flatten list in dictionary pandas I have following json data

{
    "accountId": 999998,
    "actionTime": 1528381455013,
    "additionalInformation": {
        "eS": [
            {
                "labels": [
                    "R"
                ],
                "sc": 1.0,
                "title": "Company"
            },
            {
                    "labels": [
                        "Slurpee"
                    ],
                    "sc": 1.0,
                    "title": "Product"
                }
        ]
    },
    "apiStatus": "Removed fields because of resyndication policy",
    "archived": false,
    }

I want to flatten data of additionalInformation.eS. Final columns I want in my csv (through dataframe.to_csv)is :
label, title, accountId, actionTime
["R"], Comapny, 999998, 1528381455013
["Slurpee"], Product,  999998, 1528381455013
I have tried:

data_frame = json_normalize(data, record_path=["additionalInformation"], meta=[["eS", "label"]], errors='ignore')

data_frame = json_normalize(data, record_path=["additionalInformation", "eS"], meta=["label"], errors='ignore')

I have referred Stackoverflow answer and pandas document for json_normalize function
Most example covered have list of dictionary as record_path, my example has dictionary values as list.
Please help.
Thanks

A: I'm sure there is a less verbose way to do this, but here is an option:
from pandas.io.json import json_normalize

data = {
    "accountId": 999998,
    "actionTime": 1528381455013,
    "additionalInformation": {
        "eS": [{
                "labels": [
                "R"
                ],
                "sc": 1.0,
                "title": "Company"
            },
            {
                "labels": [
                    "Slurpee", "other"
                ],
                "sc": 1.0,
                "title": "Product"
            }
        ]

    },
    "apiStatus": "Removed fields because of resyndication policy"
}

ac = data['accountId']
at = data['actionTime']
r = json_normalize(data['additionalInformation'], record_path = 'eS')

r['accountId'] = ac
r['actionTime'] = at

r = r.drop('sc', axis = 1)

r

Gives:


text:
Q: Drawing circle with gradient color in python opencv How can I draw a circle on an image with gradient colors(something like Gaussian circle) in python using OpenCV?
The circle should have a specific size, (x, y) and color.


text:
Q: Insert random data from one column to a column in another table I'm wanting to insert random data from one field into another.  I'm unsure of the syntax for this completely, So I'm thinking
icdtbl.icd_id = primary key
icdjxn.icd_id = foreign key
  insert into icdjxn (icd_id,patiendID)

    select top 5000 icd_id from icdtbl order by newid(),select top 5000 patientID from patientTbl order by newid()

edited for the entirety of what i was looking for.

A: insert into icdjxn (icd_id)
select top 5000 icd_id from icdtbl order by newid()

You don't use the word values when using a select.


text: Q: Desplegar Proyecto con Bitnami Django Stack Estoy tratando de desplegar mi proyecto hecho en Django en un servidor apache, pero me da ciertos problemas con el modulo wsgi, pues uso python 2.7 para 64 bits y no encuentro un modulo wsgi para esta arquitectura, solo para 32 y no puedo reinstalar python porque me da problemas el proyecto con las librerias, encontre bitnami django stack e instalo el proyecto de prueba, uso la documentacion pero no logro hacer el despliegue de mi proyecto en este servidor, alguien lo ha hecho, o conocen otra manera de hacer el despliegue para windows?


text:
Q: Graded Vector Spaces (definition) I am studying Algebraic Operads with the book Algebraic Operads, by Jean-Louis Loday and Bruno Vallette and I'm having a little problem with the definition of graded vector space. My advisor and I disagree on the definition. The book defines it this way:

my advisor thinks it is equivalent to saying that $V = \bigoplus_{n\in \mathbb{Z}} V_n$. I believe that they are different. In nLab (Graded Vector Spaces) I found the following definition

which strengthens my argument.
Finally, who is correct? Can anyone suggest me any other reference about graded vector spaces?

A: There are two different categories:

*

*The category $\mathsf{gVec}$ where objects are vector spaces $V$ equipped with a decomposition $V \cong \bigoplus_{n \in \mathbb{Z}} V_n$, and morphisms are linear maps respecting the decomposition;

*The category $\mathsf{Vec}^\mathbb{Z}$ of families of vector spaces $\{ V_n \}_{n \in \mathbb{Z}}$ and morphisms $f : \{V_n\} \to \{W_n\}$ are families of linear maps $\{f_n : V_n \to W_n\}_{n \in \mathbb{Z}}$.

These two categories are equivalent; you can construct an explicit equivalence $\mathsf{Vec}^\mathbb{Z} \to \mathsf{gVec}$ given by $\{V_n\} \mapsto V_\bullet = \bigoplus_{n \in \mathbb{Z}} V_n$. So it makes no difference to consider graded vector spaces from the first point of view or from the second point of view.


text:
Q: unity character attached to game object I'm quite new to Unity and there is one thing i couldn't think of how to make it and i couldn't exact information either so here i am. (sorry, my English is not perfect)
what i want to do is attaching a character to game object.
In my game, player(user) will control or steer the game object and the character attached to the game object just Looks as if it's riding or driving the game object.
(to help you understand, maybe you can imagine that player control a skateboard and there is a character on it)
So far, I tried 2 ways -
1. I made character as child of the game object, and gave an animation to the character but i found out it is not looks very natural.
2. I made a ragdoll and tried to attach it to the game object by using fixed joint between the game object and the character's feet but in playing mode, only ragdoll's feet was moving with the game object.
So I wonder if there is a good way to do it.
Anybody can give me an advice? I would so appreciate it.
Thanks in advance.

A: Your solutions is here, and its called IK:
 1https://docs.unity3d.com/Manual/InverseKinematics.html
Invere kinematics isn't an easy topic and you will have to test it a lot(of course you could find some workarounds) but if you want the most elegant solution give it a try.


text:
Q: Are SSL and Kerberos compatible to each other on Hive Server? My Hive server is SSL as well as Kerberos enabled. But when I try to connect to hiverserver2 via beeline using following command:
*!connect jdbc:hive2://**hostnameOfServer**:10000/hive;ssl=true;sslTrustStore=**keystorePath**;trustStorePassword=**passwordfor keystore**;principal=**Kerberos hive principal** **database username** **database password** org.apache.hive.jdbc.HiveDriver*

I get following error :

Error: Could not open client transport with JDBC Uri:  jdbc:hive2://hostnameOfServer:10000/hive;ssl=true;sslTrustStore=keystorePath;trustStorePassword=passwordfor
  keystore;principal=Kerberos hive principal database username
database password org.apache.hive.jdbc.HiveDriver: Invalid status 21 (state=08S01,code=0)

Also I tried using following command on beeline:
jdbc:hive2://**hostnameOfServer**:10000/hive;principal=**Kerberos hive principal**?transportMode=https;httpPath=cliservice;auth=kerberos;sasl.qop=auth.

But got same error.
Are ssl and kerberos compatible to each other?

A: Yes it is compatible from version Hive-2.0.0. Check the below JIRA task for more information
https://issues.apache.org/jira/browse/HIVE-14019


text:
Q: Strange CORBA RMi exception org.omg.CORBA.MARSHAL: Error sending fragment we have a heavy load EJB application running on WebSphere 6.1. Lately, we've been having a lot of connection problems, Client application (standalone java app) gets the exception below and the request is not completed. The server is up and running, pings are fine and other clients can connect and send requests, so it is not a connection issue. We couldn't reproduce this problem on our test servers. Could anyone please help us figure out what's causing this problem? Is there some WebSphere config param we're missing?
EDIT We also found that during times when the server gives this exception we can not telnet on that port either. So it means our server-side ORB is not working properly?
Thank you.
 Caused by: java.rmi.MarshalException: CORBA MARSHAL 1229125820 No; nested exception is:
    org.omg.CORBA.MARSHAL: Error sending fragment  vmcid: IBM  minor code: 8BC  completed: No
    at com.sun.corba.se.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:197)
    at javax.rmi.CORBA.Util.mapSystemException(Util.java:67)
    at com.xyz.facade.ejb.api.remote._FnoDataFacadeRemote_Stub.findDocs(_FnoDataFacadeRemote_Stub.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.xyz.app.util.locator.RemoteServiceInterceptor$1.call(RemoteServiceInterceptor.java:200)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:269)
    at java.util.concurrent.FutureTask.run(FutureTask.java:123)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
    at java.lang.Thread.run(Thread.java:595)
Caused by: org.omg.CORBA.MARSHAL: Error sending fragment  vmcid: IBM  minor code: 8BC  completed: No
    at com.ibm.rmi.iiop.IIOPOutputStream.sendFragment(IIOPOutputStream.java:196)
    at com.ibm.rmi.iiop.CDROutputStream.completeFragment(CDROutputStream.java:666)
    at com.ibm.rmi.iiop.CDROutputStream.alignAndReserve(CDROutputStream.java:643)
    at com.ibm.rmi.iiop.CDROutputStream.writeOctetArrayPiece(CDROutputStream.java:1100)
    at com.ibm.rmi.iiop.CDROutputStream.write_octet_array(CDROutputStream.java:1076)
    at com.ibm.rmi.iiop.CDROutputStream.writeRepositoryId(CDROutputStream.java:2445)
    at com.ibm.rmi.iiop.CDROutputStream.writeString(CDROutputStream.java:2737)
    at com.ibm.rmi.iiop.CDROutputStream.fast_write_value_internal(CDROutputStream.java:1580)
    at com.ibm.rmi.iiop.CDROutputStream.fast_write_value(CDROutputStream.java:1623)
    at com.ibm.rmi.iiop.CDROutputStream.fast_write_value(CDROutputStream.java:1554)
    at com.ibm.rmi.io.IIOPOutputStream.writeValueType(IIOPOutputStream.java:1142)
    at com.ibm.rmi.io.IIOPOutputStream.writeObjectField(IIOPOutputStream.java:1090)
    at com.ibm.rmi.io.IIOPOutputStream.outputClassFields(IIOPOutputStream.java:1021)
    at com.ibm.rmi.io.IIOPOutputStream.outputObject(IIOPOutputStream.java:1005)
    at com.ibm.rmi.io.IIOPOutputStream.writeSerializable(IIOPOutputStream.java:1050)
    at com.ibm.rmi.io.IIOPOutputStream.simpleWriteObjectInternal(IIOPOutputStream.java:427)
    at com.ibm.rmi.io.IIOPOutputStream.simpleWriteObjectLoop(IIOPOutputStream.java:455)
    at com.ibm.rmi.io.IIOPOutputStream.simpleWriteObject(IIOPOutputStream.java:512)
    at com.ibm.rmi.io.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:159)
    at com.ibm.rmi.iiop.CDROutputStream.write_value(CDROutputStream.java:1502)
    at com.ibm.rmi.iiop.CDROutputStream.write_value(CDROutputStream.java:1522)
    at com.ibm.rmi.iiop.ClientRequestImpl.write_value(ClientRequestImpl.java:857)
    ... 11 more

A: Enable the ORBRas=all trace string and reproduce the problem.  trace.log should contain the root cause of the exception.  My guesses would be either a network I/O error or a product defect.

A: Would it be an option to use JacORB as client ORB?


text:
Q: Twitter Bootstrap Setting Input text fluid size won't work Here is my site's body: (With twitter bootstrap 2.0)

Header

      <form class="well form-search">
        <input type="text" class="span7 input-large search-query" />
        <button type="submit" class="span3 btn btn-primary" >Search</button>
      </form>

I want the text and the submit button to be centered and be fluid 7:3, but when I set the span class to them they break to a new line, the text on the first line and the input submit on the other line.
What could/should I do in order to make them be on the same horizontal line?

A: Update version 2.1.0 has been released, so you should check the offset solution below, as it is provided by default in this version (and probably future ones)

It appears that bootstrap does not make input span float : github forms.less
So here is what you could use :
.form-span input[type="text"][class*="span"] { float: left; }

Edit
For fluidity, you need to use a .container-fluid because .container has a fixed size (which makes fixed the fluid grid inside).
For the centering, I see 2 solutions:
Using inline text centering : (definitely not the best choice)
.inline-center { text-align: center!important; }
.inline-center [class*="span"] { float: none!important; display: inline-block!important; }

Or you can use the fluid .offsetX classes, which will be available very soon in the version 2.1 or in this gist
<input type="text" class="offset1 span7 input-large search-query" />
<button type="submit" class="span3 btn btn-primary" >Search</button>

Demo (jsfiddle)


text:
Q: How to extract all the integers from a string and convert it to a specified char value in Java? The problem statement is to find the numbers between a String and find the appropriate character for the given number. To be specific, 0 represents 'a', 1 represents 'b', 2 represents 'c'... like so on. And then again 26 represents 'a', 27- 'b', 28- 'c'....goes on like this.
For better understanding:
Input String: ab1ab

Output: b

Explanation: there is one integer value '1' in the string which represents 'b'.
Input String 2: abcd00hdjhs1224

Output: ac

Explanation: there are two integer values '00' and '1224' which represent 'a' and 'c' respectively.
The problem with my solution was that when I was storing the integer values into int or long data type, large values threw NumberFormatException.
What would be a better approach to overcome this problem? More than a programming problem it's algorithmic problem. How can I achieve the solution without worrying about the large number or the BigInteger class?
Note: If multiple integers occur then the whole is considered as one integer value.(That is where the problem occurs for me)

A: The modulus operation is distributive over addition and multiplication. i.e.

*

*(A+B)%n = (A%n + B%n) %n

*(A*B)%n = (A%n * B%n) %n

What is it good for?
Assume "abcdefgh" represents a large number where a-h are the digits of that number. It is obvious that :

*

*abcdefgh = (abcde * 1000 + fgh) or

*abcdefgh = (a * 10000000 + bcdefgh) or

*abcdefgh = (a*10000000 + b*1000000 + c*100000 + d*10000 + e*1000 + f*100 + g*10 + h)

As you are only interested in the reaults of yourDigits%26 you can scan every number found in your input string from left to right and multiply by 10 and add the next number and take the modulo and store this as new answer until you reach the end of the string:
public static void main(String[] args) {
    System.out.println(mapNumbersToCharsAndConcat("ab1ab"));
    System.out.println(mapNumbersToCharsAndConcat("abcd00hdjhs1224"));
}
static String mapNumbersToCharsAndConcat (String input){
    char[] myChars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    StringBuilder sb = new StringBuilder();
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(input);
    while(m.find()){
        String num = m.group();
        sb.append(myChars[modFromString(num)]);
    }
    return sb.toString();
}
static int modFromString(String num){
    int res = 0;
    for (int i = 0; i < num.length(); i++){
        res = (res * 10 + (int)num.charAt(i) - '0') % 26;
    }
    return res;
}

A:
Note: If multiple integers occur then the whole is considered as one integer >value.(That is where the problem occurs for me)

This is not the problem you don't have to keep the whole integer.
Suppose I give you 1872368486184712442 and ask you to divide by 26 what will you do ?
Yes exactly this is the key point to solve this problem.
here is the simple snippet of code
String ans="",s1="1abb00hjsdj";
for(int i=0;i<s1.length();i++){
  if(s1.charAt(i)>='0' && s1.charAt(i)<='9'){
    int num=0;
    while(i<s1.length() && s1.charAt(i)>='0' && s1.charAt(i)<='9'){
      num=(num*10+s1.charAt(i)-'0')%26;
      i++;
    }
    ans=ans+Character.toString((char)('a'+num));
  } else {
    continue;
  }
}
System.out.println(ans);

A: I think you need to care about digits only, reading digits, parsing them, and then repeat.
It's O(N) time complexity.
Your algorithm would be like:
String chars = "abcdefghijklmnopqrstuvwxyz";
String str = "abcd00hdjhs1224";
StringBuilder result = new StringBuilder();
int index = 0;
while (index < str.length()) {
     StringBuilder number = new StringBuilder();
     int charIndex = -1;
     while (index < str.length() && Character.isDigit(str.charAt(index))) {
            number.append(str.charAt(index));
            index++;
        }

        if (!number.toString().isEmpty()){
            charIndex = Integer.parseInt(number.toString()) % 26;
        }

     if (charIndex != -1){
         result.append(chars.charAt(charIndex));
     }
     index++;
}

You didn't mention the constraint of digits nor the constraint of your string length.


text:
Q: Trying to set file upload limit in mup/nginx-proxy I am running into a file upload error with files > 10M. I have followed the advice here: http://meteor-up.com/docs.html#advanced-configuration which says how to set it in the nginx proxy by setting the clientUploadLimit: '50M'
I pushed the changes using mup proxy reconfig-shared, and it told me it had restarted the proxy. It didn't work, I still get the 413 (Request Entity Too Large) error.
I checked inside the nginx-proxy docker instance, and the file /etc/nginx/conf.d/my_proxy.conf has the correct entry client_max_body_size 50M. I restarted the EC2 box to make sure, but it's still not working.
This article https://www.tecmint.com/limit-file-upload-size-in-nginx/ suggests that the setting needs to go inside a http block, like this:

By default, Nginx has a limit of 1MB on file uploads. To set file upload size, you can use the client_max_body_size directive, which is part of Nginx's ngx_http_core_module module. This directive can be set in the http, server or location context.

http {
    client_max_body_size 100M;
}

I can't see how to achieve this, as the .conf file is read only and somehow locked.
Any ideas on how to proceed?
I suppose I could try a custom nginx.conf file, but I'm not sure what should go in there, and in fact whether it will even improve the situation.
Any help is appreciated :)

A: I'm happy to report that I solved it... I will explain how.
I was setting the limit in the nginx reverse proxy in the mup.js file
  proxy: {
    domains: 'website.com,www.website.com',
    shared: { clientUploadLimit: '50M' }
  }

But it turns out that there is an option to set it for each independent server like this:
  proxy: {
    domains: 'website.com,www.website.com',
    clientUploadLimit: '50M'
  }

The limit was being set to 10M by default. I found it by shelling into the nginx-proxy docker image and doing a search with the command grep -R client_max_body_size /etc/nginx and it showed me all the places where it was set (for each vhost)
So I changed the mup.js file for my server, did a mup stop, and a mup setup (to re-do the settings) and then a mup deploy

A: Now this is speculation but have you tried going to the docker container's root shell changed the permissions to give write permission to root or your user chmod 760 /etc/nginx/nginx.conf and edit the nginx file there?


text:
Q: Probability of the maximum of n binomial random variables being less than n Suppose $x_1$, $x_2$, ..., $x_n$ are independent binomial random variables with parameters $p$ and $n$. Now what is the probability of $P[\text{max}(x_{1}, x_{2}, ..., x_{n})<n]$? I think we can simplify the question to each $x_i$ being less than $n$, i.e. $(P[x_{i}<n])^n$. then, $(\binom{n}{x}p^{x}(1-p)^{n-x})^{n}<n$. But I do not know how to proceed.

A: $$\mathbb{P}[X_i<n]=1-\mathbb{P}[X_i=n]=(1-p^n)$$
Thus
$$\mathbb{P}[\max\{X_1,\dots,X_n\}<n]=\mathbb{P}[X_1<n]^n=(1-p^n)^n$$


text:
Q: Nodejs dynamic OG tags Using Express. Here's the route. It basically just passes the url params into a template that renders the OG tags.
router.get('/share/:redirectURL/:title/:description/:img', function (req, res) {

    var url = req.protocol + '://' + req.get('host') + req.originalUrl; // points to this endpoint

    res.render('share', {
        url: url,
        title: decodeURIComponent(req.params.title),
        img: decodeURIComponent(req.params.img),
        description: decodeURIComponent(req.params.description),
        redirectURL: decodeURIComponent(req.params.redirectURL)
    });

});

module.exports = router;

And here's the share template that it renders to.
doctype html
html
    head
        meta(property="og:url", content="#{url}")
        meta(property="og:image", content="#{img}")
        meta(property="og:title", content="#{title}")
        meta(property="og:description", content="#{description}")
        meta(property="og:type", content="article")

    body
        script.
            location.replace("#{redirectURL}");

...and it works! But it only works LOCALLY. As soon as I upload to the server, things go awry.
works: http://localhost/share/http%3A%2F%2Fgoogle.com/Hear%20some%20music./http%3A%2F%2F201.23.456.789%2F%2Fassets%2Fimgs%2Ffavicons%2Ficon1024.png
doesn't work: http://123.45.678.910/share/http%3A%2F%2Fgoogle.com/Hear%20some%20music./http%3A%2F%2F201.23.456.789%2F%2Fassets%2Fimgs%2Ffavicons%2Ficon1024.png
Something upstream is partially decoding the url BEFORE it gets to the Express router. The result is this confused, useless thing.
http://123.45.678.910/share/http:/google.com/Hear%20some%20music./http%3A%2F%2F201.23.456.789%2F%2Fassets%2Fimgs%2Ffavicons%2Ficon1024.png

A: Switched to query parameters and it works!


text:
Q: How to define unknown prop warnings for a component? Is it good practice / possible to generate unknown prop warnings for a component? I think it would help to recognize quickly errors in the code. As far as I know props not defined in propTypes will just be ignored.
For example if I have a Box component that accepts a color prop, the following prop would not generate a warning/error:
<Box colour="red">1</Box>

This is just a simple example, but sometimes there are multiple props and such naming that mistakes can happen.


text:
Q: Spy on an attribute/function of a private variable with Jasmine I have a function with variable functionality based on file it reads, which is controlled via a Map it keeps in memory:

file1.ts

function f1(x: number): number {
  // do far-reaching things
  return 1;
}

function f2(x: number): number {
  // do different far-reaching things
  return 2;
}

function f3(x: number): number {
  // do still-different far-reaching things
  return 3;
}

const myMap: Map<string, (number) => number> = new Map<string, () => void>([
  ['key1', f1],
  ['key2', f2],
  ['key3', f3],
]

export function doThing(filename: string): number {
  // open file, make some database calls, and figure out the name of a key
  // ...
  let fileToExecute = myMap.get(key);
  return fileToExecute(someValueDerivedFromFile);
}

f1, f2, and f3 all do much more than shown here, and each requires a lot of mocks to be tested successfully.
As the code grows more developed and use cases continue, there will be an arbitrary number of functions that might need to be called, based on an expanding set of inputs. doThing() is complicated and takes its information from a lot of different sources, including both the contents of given file and a database, which helps it choose which file to execute. From a client's point of view, doThing() is the only function it cares about. Thus, it's the only one exported by this file.
I'm trying to test the mechanism in doThing() that figures out what key it should use. I don't want to mock f1, f2, and f3 specifically - I want to present many more options, pointed to by other things I'm mocking for doThing(). However, to check if it's calling the correct fake method, I need to figure out which fake method it's calling. My attempted solution uses typecasting to try to pull the private myMap out of the file and then spy on its get() method:

file1.spec.ts

import * as file1 from '../src/file1'
...
it("calls the correct fake method", () => {
  // lots of other mocks
  let spies = [
    jasmine.createSpy('f1spy').and.returnValue(4),
    jasmine.createSpy('f2spy').and.returnValue(5),
    jasmine.createSpy('f3spy').and.returnValue(6),
    ...
  ]
  let mockMap = spyOn((file1 as any).myMap, 'get').and.callFake((key) => {  // this fails
    var spy;
    switch(key) {
      case 'key1': spy = spies[0]; break;
      case 'key2': spy = spies[1]; break;
      case 'key3': spy = spies[2]; break;
      ...
    }
    return spy;
  }

  result = file1.doThing(...);

  expect(spies[0]).not.toHaveBeenCalled();
  expect(spies[1]).toHaveBeenCalledWith(7);
  expect(spies[2]).not.toHaveBeenCalled();
});

However, I get an error on the annotated line above: Error: <spyOn> : could not find an object to spy upon for get(). Upon further investigation (i.e. the step-by-step debugger), it turns out that the file1 object I imported only has doThing(), and doesn't have any of its other private variables.
How do I successfully mock the key-value transformation here - which means, in this case, spying on attributes of a private variable, so I can get my spies in the right place? Either replacing myMap entirely or replacing myMap.get() would be an option, if either is possible.

A: *

*Jasmine, as far as I know, doesn't use any compiler-kind magic, so it's impossible for Jasmine to get access to you private variables.

*

From a client's point of view, doThing() is the only function it cares about. Thus, it's the only one exported by this file.

but this doesn't mean that you should deprive your tests from the access to over staff. Instead you can create two files
file1.ts - for a client
import { doThing } from "./file1_implementation"
export doThing

and file1_implementation.ts - for your tests
export function f1(...) ...
export function f2(...) ...
export function f3(...) ...
export const myMap ...
export function doThing(...) ...

then in file1.spec.ts you can use file1_implementation.ts and you'll have access to everything you need
import * as file1 from '../src/file1_implementation'
...

A: General idea: use rewire.
Using rewire, we will override your private functions with spy functions.
However, your const myMap needs to be modified. Because when you do ['key1', f1] - it stores current implementation of f1, so we can't override it after myMap was initialized. One of the ways to overcome this - use ['key1', args => f1(args)]. This way, it will not store f1 function, only the wrapper to call it. You might achieve the same by using apply() or call().
Example implementation:
file1.ts:
function f1(): number {
  // do far-reaching things
  return 1;
}

const myMap: Map<string, (x: number) => number> = new Map([
  ['key1', (...args: Parameters<typeof f1>) => f1(...args)],
]);

export function doThing(): number {
  const key = 'key1';
  const magicNumber = 7;
  const fileToExecute = myMap.get(key);
  return fileToExecute(magicNumber);
}

file1.spec.ts:
import * as rewire from 'rewire';

it('calls the correct fake method', () => {
  const spies = [jasmine.createSpy('f1spy').and.returnValue(4)];

  const myModule = rewire('./file1');

  myModule.__set__('f1', spies[0]);

  myModule.doThing();

  expect(spies[0]).toHaveBeenCalledWith(7);
});

In order to use rewire with typescript, you might want to use babel, etc.
For proof of concept, I'm just going to compile it:
./node_modules/.bin/tsc rewire-example/*

and run tests:
./node_modules/.bin/jasmine rewire-example/file1.spec.js

Which will run successfully:
Started
.

1 spec, 0 failures

UPDATE
Without modifications to myMap:
file1.spec.ts:
import * as rewire from 'rewire';

it('calls the correct fake method', () => {
  const spies = [
    jasmine.createSpy('f1spy').and.returnValue(4),
    jasmine.createSpy('f2spy').and.returnValue(5),
    // ...
  ];

  const myModule = rewire('./file1');

  const myMockedMap: Map<string, (x: number) => number> = new Map();

  (myModule.__get__('myMap') as typeof myMockedMap).forEach((value, key) =>
    myMockedMap.set(key, value)
  );

  myModule.__set__('myMap', myMockedMap);

  // ...
});

A: Can you just make file1 into a class? Then you can definitely access its private methods / attributes from jasmine.
so file1 becomes:
export class FileHelper {

  private f1 () : void {}
  private f2 () : void {}
  private f3 () : void {}

  private myMap: Map<whatever, whatever>;

  public doThing () : void {}

}

then in your spec:
let mapSpy: jasmine.Spy;
let myFileHelper: FileHelper;

beforeEach(() => {
  myFileHelper = new FileHelper();
  mapSpy = spyOn(<any>myFileHelper, 'myMap').and.callFake(() => {
    //whatever you were doing
  });
});

it('should do whatever', () => {

});


text:
Q: Error: Request failed with status code 405 , payload return HTML not JSON like intended I'm setting up a webapps using Node JS + React + NGINX on AWS
and then when i want to access the url /auth
it return me some HTML code instead of JSON like i wanted to be
i tested the code on LOCALHOST and it works fine
I tried to set the folder permission, because i think maybe user permission is the problem
I also tried editing some stuff on the Nginx.conf
below is my app.conf for the nginx
upstream webapp{
    server 127.0.0.1:3018;
}

server_names_hash_bucket_size 64;
server_names_hash_max_size 512;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name 127.0.0.1;
        server_name_in_redirect off;

    if ($http_x_forwarded_proto = 'http'){
       return 301 https://$host$request_uri;
    }

   location / {
        root /home/website/client/build;
        try_files $uri /index.html;
        log_not_found off;
        access_log off;
    }

    #error_page  405     =200 $uri;

    if ( $http_user_agent ~* (nmap|nikto|wikto|sf|sqlmap|bsqlbf|w3af|acunetix|havij|appscan) ) {
        return 403;
    }
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block;";
    add_header Strict-Transport-Security "max-age=2592000; includeSubDomains" always;
}

action     {…}

payload: Object { isAuth: false, error: true }

type: "auth_member"

i expect the output code like this one
but instead the web give me something else

A: you have to define the upstrem location to be proxed to:
 # this is an example you can modify the path on as you get it
 location /api {
       proxy_pass http://webapp;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection 'upgrade';
       proxy_set_header Host $host;
       proxy_cache_bypass $http_upgrade;
    }


text:
Q: How to cross clock domains efficiently? I have a question regarding sending a short duration signal from  a faster clock domain to a slower clock domain. I am trying to implement a dual frame  buffer in a  dual port (dual clock) RAM. Once an entire Frame has been stored, the write clock side asserts the FrameFull register. At the end of each current display frame, the display requests a new frame,
which if available, sets the read pointer for the RAM accordingly and is also  used to deassert the FrameFull Signal so that a new frame can be loaded while this most recent one is being displayed.
The read side is operating at 50 MHz.
The write side is operating at 27 MHz.
In order to synchronize the FrameFull Signal from the write domain, I have read that its best to use a couple of synchronizing flip flops and since the FrameFull remains asserted until the buffer is switched, I think this isn't very problematic (because the FrameFull signal can't be missed).
The SwitchSuccesful signal is asserted in the read clock domain when a new Frame is requested and the FrameFull is 1, indicating buffer exchange. Now, this SwitchSuccesful needs to be sampled by the write domain so that FrameFull can be reset to 0 and can then start storing a new frame. I have thought about it and decided to use a 16-bit shift register, which, when buffers are switched, will reset to 16'hFF and then shift left with a zero being concatenated.I could then use a bitwise OR, and synchronize the result of the bitwise OR with Flip Flops in the write domain before sampling the signal. Will this be sufficient to prevent missing the SuccesfulSwitch and metastability?
CODE :
always @ (posedge read_clock)
begin
    if(SwitchRequest) begin
          case (Frame_FullSync1, Frame_Read)
          2'b00 : begin rd_ptr <= /*Some Value*/ Frame_Read <= 0; end           //Restore to Previous 0.
          2'b01 : begin rd_ptr <= /*Some Value*/ Frame_Read <= 1; end           //Restore to Previous 1.
          2'b10 : begin rd_ptr <= /*Some Value*/ Frame_Read <= 1; LE <= 1; end  //Load new ----- 0 to 1.
          2'b11 : begin rd_ptr <= /*Some Value*/ Frame_Read <= 0; LE <= 1; end  //Load new ----- 1 to 0.
          endcase
    end
    if(LE) LE <= 0;
end

always @ (posedge read_clock)  begin
    //Frame Full Synchronization from write domain to read domain
    Frame_FullSync1 <= Frame_FullSync0;
    Frame_FullSync0 <= FrameFull;
    //LE was asserted for 1 clock cycle when buffer switch was succesful
    if(LE) Sync <= 16'hFF;
    else   Sync <= Sync {Sync[15 : 1],1'b0};
end

assign SwitchSuccesful = |Sync;

always @ (posedge write_clock) begin
    //Synchronization of bitwise OR
    SwitchSuccesfulSync0 <= SwitchSuccesful;
    SwitchSuccesfulSync1 <= SwitchSuccesfulSync0;
end

A: Assuming the data of interest changes on the falling edge of the 27Mhz clock and is sampled on the rising edge, the approach with minimal delay would be to have a divide-by-two clocked by the 27MHz clock whose output flips on the rising edge, feed the output of that into a double synchronizer which samples on the falling edge of the 50MHz clock, and capture everything else on the rising edge of the 50MHz clock.
If two consecutive falling edges of the 50Mhz clock report opposite states for the divide-by-two output, that implies that the real edge must have happened somewhere within that interval.  The data will have been sampled at a time halfway between those 50MHz clock events, within about 10ns of when the 27MHz clock occurred.
Sampling everything on the same edge of the 50MHz clock may not be sufficient to allow reliable decoding of events.  Consider the following two scenarios, with the first line representing 50MHz clock events and the latter representing 30MHz clock events (the same principles would apply at 27); both lines have a scale of 3.3ns per character
|-----|-----|-----|-----|-----|--  -- 50Mhz clock rising edges
-|---------|---------|---------|-  -- 30Mhz clock rising edges
_x---------x_________x---------x_  -- 30MHz/2, changing on rising edges
______x---------x_________x------  -- 30MHz/2, changing on falling edges
000000x111111111x222222222x333333  -- Data words, changing on 30Mhz fall

Consecutive samples of the divided 30Mhz clocks and data words would yield:
_-__--_--_  30MHz/2, changing on rising edges, then sampled @50Mhz rising
_x-__-x_--  30MHz/2, changing on falling edges, then sampled @50Mhz rising
0x1223x455  Data, sampled @50Mhz rising

There is no spot relative to observed edges on either form of the 30MHz clock where the output would be guaranteed to be clean.  On the other hand, if the
"30Mhz/2 rising" signal were sampled on falling edges of the 50Mhz clock, that would yield, relative to the data:
--_x-__-x_  30Mhz/2, changing on rising edges, sampled @50Mhz falling
0x1223x455  Data, sampled @50Mhz rising

If a 30Mhz clock coincided with a falling edge of the 50Mhz clock, there may be 20ns worth of uncertainty as to when the edge occurred, but the same data would be present on the cycles before and after, so such uncertainty wouldn't matter.

A: I couldn't exactly follow the entire scenario you described, but if the question just boils down to "what's a good way to pass a single clock cycle pulse into a different clock domain", considered this: Instead of generating a pulse, simply toggle the signal. Pass this toggled signal into the other clock domain using meta-stability registers. In the other clock domain, implement an edge detection circuit that will generate a single clock cycle pulse on level changes. That's it, pulse passed. This will only work reliably if the signal changes relatively infrequently (I'd say a maximum frequency of once every 4 of the slower clock cycles) in order to let the meta-stability registers settle out.

A: Since the person asking the original question has clarified that the RAM can use independent clocks for writing and reading, I would like to suggest a nice approach for passing events between clock domains: construct a ring of flip flops, with two or three in each domain, one inversion going around the ring, and a latch-enable on one of the flops in the sending domain.  Something like:

simulate this circuit – Schematic created using CircuitLab
(I used a D flop and a mux to simulate a D flop with latch-enable control).
READY will be high when the device is ready for an event in the source domain.  After a source-domain clock cycle where STROBE and READY are both high, READY will go low and remain low until the event has been processed and acknowledged.  The OUT signal in the destination clock domain will be high for exactly one clock cycle in that domain after an event is triggered.  Note that even if the source clock were to stop on the cycle after STROBE and READY were high, the event would still propagate to the destination domain.  The circuit could be made to allow faster turnaround time on events, by feeding REG1 off REG5 rather than REG6, and moving REG2 to the output of XOR2 (to avoid metastability, there should be two CLK1-based flops between the REG6 signal and the READY output, but one of them could be after the XOR).  I think the behavior of the circuit as drawn is probably less confusing.  The left domain will show "ready" if a strobe would be effective on the next cycle, and will not become ready again until the right-hand domain has actually had a clock cycle where OUT was high.


text:
Q: ionic framework sync data and work offline I'm developing an app using ionic framework, and it will fetch some data from an API which was built using laravel, save it in a database so when the user is offline he can continue use the app, I did a little research on the internet and found a plugin called pouchDB, is it recommended for what I need? what is the best way to do it?

A: PouchDb is sure a good solution to provide data synchronization to your app.
But depending from what you need to do you could choose between several PaaS that provide natively data synchronization and offline capabilities(along with many other features like oAuth2 authentication and push notification).
I have worked with a few i can suggest:

*

*Parse

*Firebase

*Microsoft Azure mobile services
All these platforms provide clients to work with for all native mobile environments and javascript.

A: Depending on the amount of data you wish to cache, you can save it in local storage.
The logic would be like this:

*

*Make an $http request to your API

*In the .success stringify the response and store in local storage

*In the .error parse the stored local storage response

*Populate the same $scope variable from both the .success and .error
This way if your requests succeed (the device has internet and the API is functional) the data is stored.  Otherwise, the requests fail (no internet or other reason), use the stored data.
An example of this can be seen here:
https://www.thepolyglotdeveloper.com/2014/06/saving-data-with-ionicframework/
However, like mentioned in a previous answer, PouchDB is a great option if you have a CouchDB database setup.  Here are a few Ionic tutorials for syncing solutions:
https://www.thepolyglotdeveloper.com/2014/12/syncing-data-firebase-using-ionic-framework/
http://devgirl.org/2014/12/30/sync-data-using-pouchdb-in-your-ionic-framework-app/
Regards,


text:
Q: touchesBegan in custom UITableViewCell, touchesEnded in UIView I am trying to mimic a drag n drop of an image from a UITableView to a UIView. Both the UITableView and UIView are on the same view, side by side.
My approach:
is to fire the touchesBegan event inside the UITableView (i.e. when a cell is touched/selected) and fire the touchesEnded event when the touch ends in the UIView.
The problem:
So I created a custom UITableViewCell that contains a UIImageView and a couple of UILabels. And I set the User Interaction Enabled for this UIImageView. Then to receive the touchesBegan event, I did override the touchesBegan method inside the custom UITableViewCell class; and now I am able to receive the touchesBegan event from the cell.
The problem is
I am not getting the touchesEnded event when the touch ends on the UIView. Note that I already implemented the touchesEnded method inside the view controller class (not in the custom class); and if I start and stop a touch within this UIView, I see the touchesEnded being fired.
Is there anything I am missing here?
Using Xcode 4.6 (4H127), testing on iPad 2 with iOS 6.1.3

A: This will not work that way. You will need to utilize the touch methods on the parent view that contains both of your subviews. Could look abstractly like this:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    if ([self touchOnCell:touches]) { //check to see if your touch is in the table
        isDragging = YES;             //view cell
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    //do your dragging code here
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    if (isDragging && [self touchOnDropView:touches]) {
        //do your drop code here
    }
}

now if this doesnt work like that alone you might want to implement the hitTest on the tableView and if the touch is in the dragging object's region, then return the parent view.
hope this helps


text:
Q: Mediastore.Audio.Media get recetly added songs similar to native player I am trying to get the last 20 songs which were added to my phone.
I tried this
  String[] proj = {"*"};
  Uri psUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

  String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
  String sortOrder = MediaStore.Audio.Media.DATE_ADDED;
  Cursor psCursor = contentResolver.query(psUri, proj, selection, null, sortOrder);

  if(psCursor == null){
            return false;
  }

But this is returning songs be some other sorting. It is different from what my native music player is showing.
I also tried doing DATE_MODIFIED but that is also returning the same result.
How can I fix this

A: Try
String sortOrder = MediaStore.Audio.Media.DATE_ADDED + " ASC";

or
String sortOrder = MediaStore.Audio.Media.DATE_ADDED + " DESC";


text:
Q: Value not showing when sub folder is coming This is my table
tag  enabled

bank   1
WT     1
Credit 1
Debit  1
EMI    1

My query is:
    $sql = "SELECT * FROM payment WHERE enabled = '1'";
    $result = mysql_query($sql);
    while($data = mysql_fetch_assoc($result)) {
        $gateway='';
        if($data['tag']=='credit') {
            $gateway='/'.getPaymentGateway($data['gateway'],'tag');
        }

        include('payment/'.$data['tag'].$gateway.'/display.php');

        ...
    }

The problem is, it shows until credit, not showing debit and EMI.
That's because, the credit has sub folder.
The function getPaymentGateway is:
function getPaymentGateway($id,$field) {
    $sql = "SELECT * FROM    payment_gateway  WHERE id = '".$id."'";
    $result = mysql_query($sql);
    $data = mysql_fetch_assoc($result);
    return   $data[$field];

}

A: you dont need to do assoc, you are not joining any tables keep it simple.
 if(!$result){
      // error with query
      return mysql_error();
    }else{
      while($data = mysql_fetch_array($result)){
        $gateway='';
        if($data['tag']=='credit') $gateway='/'.getPaymentGateway($data['gateway'],'tag');
        include('payment/'.$data['tag'].$gateway.'/display.php');
     }
    }