Q: Add RSS feed to a section of a View in Codeigniter I am completely new to Codeigniter and am trying to add an RSS feed to a section of my Home view as follows. I have asked this question already but I wasn't clear in how I presented my code so I have submitted it again. I have researched this on multiple forums especially this one and I am going round in circles but cant find an answer.
Home View
The home view contains a header image, a nav bar, a jumbotron and a login form. It also has the following section into which I want to add the RSS content.

Latest News

<?php

// RSS FEED HERE

?>

I have one controller called "User that has the following code in its index function
User Controller Code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller{

public function __construct()
{

  parent::__construct();
  $this->load->model('user_model');
  $this->load->library('rssparser');

}

 public function index()
 {

  if(($this->session->userdata('user_name')!=""))
  {
   $this->welcome();
  }

 else
 {

 $data['title']= 'Home';
 $this->load->view('include/header',$data);
 $this->load->view('pages/home.php', $data);
 $this->load->view('include/footer',$data);

 }

}

Controller method in User Controller to get RSS data
The rss feed results are currently being stored in an unordered list
 public function get_news()
 {

 // Get 6 items from latest news
 $this->rssparser->set_feed_url('http://www.datadomain.com');  // get feed
 $this->rssparser->set_cache_life(30);  // Set cache life time in minutes
 $rss = $this->rssparser->getFeed(6);

 echo '
';

foreach ($rss as $item)

{
   echo '
';
   echo $item['title'];
   echo '
';

   echo '
';
   echo $item['description'];
   echo '
';

   echo '
';
   echo $item['link'];
   echo '
';

   echo '
';
   echo $item['pubDate'];
   echo '
';
}

echo '
';
}

If I insert the following into my index function in my controller I can get the feed on my homepage but it appears at the top of the page and not in the section I need it in.
$data['rss'] = $this->get_news();

I have tried adding $rss into the section of the view in my Home page but I just get an undefined variable error.
I would appreciate if someone could help shed some light on this for me as I cant find a solution.
Other methods and views used in my project
Controller method Welcome()
public function welcome()
{
 $data['title']= 'Welcome';
 $this->load->view('include/header',$data);
 $this->load->view('pages/welcome_view.php', $data);
 $this->load->view('include/footer',$data);
 }

welcome_view
This view represents the members area of the application. It doesn't hold any real content at the minute because the application is at the early stages of construction.

<img class="img-responsive" src="<?php echo site_url('../images/black_header.jpg'); ?>"   />

 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs- example-navbar-collapse-1">
  Toggle navigation

  </button>
  <a class="navbar-brand" href="<?php echo site_url('user/index') ?>">Premier Games

<a href="<?php echo site_url('user/index') ?>">Home

<a href="<?php echo site_url('user/register') ?>">Register

Signed in as <?php echo $this->session->userdata('user_name'); ?>

<?php echo $this->session->userdata('user_name'); ?>, Welcome Back

This section represents the area that only logged in members can access.

<?php echo anchor('user/logout', 'Logout'); ?>

A: Typically, you do the html parsing in a view. Not sure if you are loading a view... it isn't clear whether we are working with a logged in user or not.
Let's assume we are not dealing with a logged in user and are calling
 $data['title']= 'Home';
 $this->load->view('include/header',$data);
 $this->load->view('pages/home.php', $data);
 $this->load->view('include/footer',$data);

The easiest way to do it would be to just dump the data into the view and do the layout/parsing there:
controller:
$data['title']= 'Home';
$data['rss'] = $this->get_news();
$this->load->view('include/header',$data);
$this->load->view('pages/home.php', $data);
$this->load->view('include/footer',$data);

pages/home.php

<?php
echo '
';

foreach ($rss as $item)

{
   echo '
';
   echo $item['title'];
   echo '
';

   echo '
';
   echo $item['description'];
   echo '
';

   echo '
';
   echo $item['link'];
   echo '
';

   echo '
';
   echo $item['pubDate'];
   echo '
';
}

echo '
';
?>

controller get_news():
public function get_news()
{
    // Get 6 items from GAA latest news
    $this->rssparser->set_feed_url('http://www.rte.ie/rss/gaa.xml');  // get feed
    $this->rssparser->set_cache_life(30);  // Set cache life time in minutes
    $rss = $this->rssparser->getFeed(6);
    return $rss;
}


Q: PowerShell Expression interpreter on variables In response to this question, the original requester wanted to know

In PowerShell, is there a way, after typing a long or complicated
  command, to commit that command into the history buffer, but not
  execute it?

My solution however was purely for fun, but I wondered how / why it worked on the back end.
Answer
$VariableName = "Windows Command"

Then, to execute:
Invoke-Expression "$VariableName"

An example with Ping:

I was also able to use PowerShell expressions in the exact same way:

PS H:> $Outlooks = "Get-Process -Name Outlook -Verbose | fl StartTime, Threads"
  PS H:> Invoke-Expression "$Outlooks"

My Theory
Essentially, I believe what is happening is that we are creating a string for the first variable (Exactly what it looks like, straight forward), and then when we invoke our variable inside " " it forces the interpreter to expand the variable, causing it to call the right command.
Is my understanding of how this works accurate? References preferred.

A: Yep, that seems to be exactly what is happening (BTW you don't even need quotes around the command string while invoking).
As per the help description of the cmdlet (obtained via get-help Invoke-Expression -full):

iex [-Command] <String> [<CommonParameters>]
Invoke-Expression [-Command] <String> [<CommonParameters>]
The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged.
An expression is a statement that can be evaluated and produces a result, such as a Windows PowerShell command.

If the command stored in the string variable is not too complex you can also use the call operator (&) as follows:
& $string

Further details courtesy this page:

If the result of the expression is an empty array, invoke-expression will output $null
Invoke-Expression can be used to perform string expansion but if the string is supplied by an end-user you need to ensure that it does not contain malicious code/expressions.


Q: Why can't we simply substitute the input variable into the output of a function? Sorry if this question has been asked before. I'm not sure how to phrase this question properly (hence I couldn't find any fruitful results on Google).
We know that the following holds true for $|x| < 1$,
$$
\frac{1}{1-x} = \sum_{i=0}^\infty x^i = 1 + x + x^2 + \ldots
$$
If we substitute $x^2$ as the variable into both sides of the equation, we obtain:
$$
\frac{1}{1-x^2} = \sum_{i=0}^\infty x^i = 1 + x^2 + x^4 + \ldots
$$
which is also true.
However, if we try the same with integration, we will get a different outcome.
The following holds true by basic law of integration:
$$
\int x dx = \frac{x^2}{2} + C
$$
where C is an arbitrary constant.
If we substitute $x^2$ as the variable into both sides of the equation, we obtain:
$$
\int x^2 dx = \frac{x^4}{2} + C
$$
which is clearly wrong.
My question is, $ x $ is meant to be an arbitrary input for a function. Hence, (I think) we could substitute $ x $ with anything and simply plug the new variable into the output as well. Although this is evidently false in the integration example, it works for the example using geometric series. Why does this claim hold true sometimes and fail in other situations (just like in the 2 examples given above)?

A: You can substitute $x^2$ as the variable, but you need to substitute it everywhere it appears.  In the OP's example, you did not substitute it into the $dx$.  $$\int x^2 d(x^2)=\int 2x^3dx=\frac{x^4}{2}+C$$

A: You can for a function...  but not for integration,  which,  apparently,  isn't a function...
When you substitute into an integral, or a differential equation for that matter, the chain rule comes into play...
Hence your example... (you've substituted $y=g(x)$, where $g(x)=x^2$ into an integral,  and $g'(x)=2x\not =1$, so this throws a wrench in the works)
They use words like "operator" or "transform" in situations like this,  i think...


Q: Cordova APP - Is it possible to show camera feed in a container? I am using ionicFramework with Cordova to build an App. My requirement is to show (front) camera feed inside my app (say at top right corner of the app).
Unfortunately "cordovaCapture" is not working for me. "navigator.camera" just opens camera view, but my requirement is to show its feed in a container so its also not fitting in requirement.
I tried backgroundvideo plugin also.
Please help me in understanding, Is it possible to access camera feed without going native app approach ? Please share any leads.
Thanks in Advance.

A: I'll just point you to the right direction:

*

*https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview

*https://github.com/donaldp24/CanvasCameraPlugin
Try these plugins (in order) and lemme know if either of them worked out for you.


Q: What's a functional replacement for if-then statements? I've been learning F# and functional programming and trying to do things the functional way. However, when it comes to rewriting some code I'd already written in C# I get stuck at simple if-then statements (ones that only do something, not return a value). I know you can pull this off in F#:
if expr then do ()

However, I thought this was an imperative approach to coding? Maybe I've not learned enough about functional programming, but it doesn't seem functional to me. I thought the functional approach was to compose functions and expressions, not simply execute statements one after the other which is what if-then seems to encourage.
So, am I missing something and if-then is perfectly fine in the functional world? If not, what is the functional equivalent of such a statement? How could I take an if-then and turn it functional?
Edit: I might've asked the wrong question (sorry, still fairly new to functional programming): Let's take a real world example that made me even ask this:
if not <| System.String.IsNullOrWhiteSpace(data) then do
    let byteData = System.Text.Encoding.Unicode.GetBytes(data)
    req.ContentLength <- int64 byteData.Length
    let postStream : System.IO.Stream = req.GetRequestStream()
    postStream.Write(byteData, 0, byteData.Length)
    postStream.Flush()
    postStream.Dispose()

The body of that if-then doesn't return anything, but I don't know how I could make this more functional (if that's even possible). I don't know the proper technique for minimizing imperative code. Given F#'s nature it's fairly easy to just transport my C# directly, but I'm having difficulties turning it functional. Every time I reach such an if statement in C#, and I'm trying to transport it to F#, I get discouraged that I can't think of a way to make the code more functional.

A: It's considered functional if your if statement has a return value and does not have side effects.
Suppose you wanted to write the equivalent of:
if(x > 3) n = 3; else n = x;
Instead of doing that, you use the return statement from the if command:
let n = (if x > 3 then 3 else x)
This hypothetical if is suddenly functional because it has no side effects; it only returns a value.  Think of it as if it were the ternary operator in some languages:  int n = x>3?3:x;

A: An important point that hasn't been mentioned so far is the difference between if .. then .. else and if .. then without the else branch.
If in functional languages
The functional interpretation of if is that it is an expression that evaluates to some value. To evaluate the value of if c then e1 else e2 you evaluate the condition c and then evaluate either e1 or e2, depending on the condition. This gives you the result of the if .. then .. else.
If you have just if c then e, then you don't know what the result of the evaluation should be if c is false, because there is no else branch! The following clearly does not make sense:
let num = if input > 0 then 10

In F#, expressions that have side-effects like printf "hi" return a special value of type unit. The type has only a single value (written as ()) and so you can write if which does an effect in just a single case:
let u = if input > 0 then printf "hi" else ()

This always evaluates to unit, but in the true branch, it also performs the side-effect. In the false branch, it just returns a unit value. In F#, you don't have to write the else () bit by hand, but conceptually, it is still there. You can write:
let u = if input > 0 then printfn "hi"

Regarding your additional example
The code looks perfectly fine to me. When you have to deal with API that is imperative (like lots of the .NET libraries), then the best option is to use the imperative features like if with a unit-returning branch.
You can use various tweaks, like represent your data using option<string> (instead of just string with null or empty string). That way, you can use None to represent missing data and anything else would be valid input. Then you can use some higher-order functions for working with options, such as Option.iter, which calls a given function if there is a value:
maybeData |> Option.iter (fun data ->
    let byteData = System.Text.Encoding.Unicode.GetBytes(data)
    req.ContentLength <- int64 byteData.Length
    use postStream = req.GetRequestStream()
    postStream.Write(byteData, 0, byteData.Length) )

This is not really less imperative, but it is more declarative, because you don't have to write the if yourself. BTW: I also recommend using use if you want to Dispose object auotmatically.

A: There are two observations that can assist in the transition from imperative to functional ("everything is an expression") programming:

*

*unit is a value, whereas an expression returning void in C# is treated as a statement. That is, C# makes a distinction between statements and expressions. In F# everything is an expression.

*In C# values can be ignored; in F# they cannot, therefore providing a higher level of type safety. This explicitness makes F# programs easier to reason about and provides greater guarantees.

A: There's nothing wrong with if-then in functional world.
Your example is actually similar to let _ = expr since expr has side effects and we ignore its return value. A more interesting example is:
if cond then expr

which is equivalent to:
match cond with
| true -> expr
| false -> ()

if we use pattern matching.
When the condition is simple or there is only one conditional expression, if-then is more readable than pattern matching. Moreover, it is worth to note that everything in functional programming is expression. So if cond then expr is actually the shortcut of if cond then expr else ().
If-then itself is not imperative, using if-then as a statement is an imperative way of thinking. From my experience, functional programming is more about the way of thinking than concrete control flows in programming languages.
EDIT:
Your code is totally readable. Some minor points are getting rid of redundant do keyword, type annotation and postStream.Dispose() (by using use keyword):
if not <| System.String.IsNullOrWhiteSpace(data) then
    let byteData = System.Text.Encoding.Unicode.GetBytes(data)
    req.ContentLength <- int64 byteData.Length
    use postStream = req.GetRequestStream()
    postStream.Write(byteData, 0, byteData.Length)
    postStream.Flush()

A: It's not the if-expression that's imperative, it's what goes in the if-expression. For example, let abs num = if num < 0 then -num else num is a totally functional way to write the abs function. It takes an argument and returns a transformation of that argument with no side effects. But when you have "code that only does something, not return a value," then you're writing something that isn't purely functional. The goal of functional programming is to minimize the part of your program that can be described that way. How you write your conditionals is tangential.

A: In order to write complex code, you need to branch at some point.  There's a very limited number of ways you can do that, and all of them require a logical flow through a section of code.  If you want to avoid using if/then/else it's possible to cheat with loop/while/repeat - but that will make your code far less reasonable to maintain and read.
Functional programming doesn't mean you shouldn't execute statements one after the other - it simply means that you shouldn't have a mutable state.  Each function needs to reliably behave the same way each time it is called.  Any differences in how data is handled by it need to be accounted for by the data that is passed in, instead of some trigger that is hidden from whatever is calling the function.
For example, if we have a function foo(int, bool) that returns something different depending on whether bool is true or false, there will almost certainly be an if statement somewhere in foo().  That's perfectly legitimate.  What is NOT legitimate is to have a function foo(int) that returns something different depending on whether or not it is the first time it is called in the program.  That is a 'stateful' function and it makes life difficult for anyone maintaining the program.

A: My apologies for not knowing F#, but here is one possible solution in javascript:
function $if(param) {
    return new Condition(param)
}

function Condition(IF, THEN, ELSE) {
    this.call = function(seq) {
        if(this.lastCond != undefined)
            return this.lastCond.call(
                sequence(
                    this.if,
                    this.then,
                    this.else,
                    (this.elsif ? this.elsif.if : undefined),
                    seq || undefined
                )
            );
         else
            return sequence(
                this.if,
                this.then,
                this.else,
                (this.elsif ? this.elsif.if : undefined),
                seq || undefined
            )
    }

    this.if   = IF ? IF : f => { this.if = f; return this };
    this.then = THEN ? THEN : f => { this.then = f; return this };
    this.else = ELSE ? ELSE : f => { this.else = f; return this };
    this.elsif = f => {this.elsif = $if(f); this.elsif.lastCond = this; return this.elsif};
}

function sequence(IF, THEN, ELSE, ELSIF, FINALLY) {
    return function(val) {
        if( IF(val) )
            return THEN();

        else if( ELSIF && ELSIF(val) )
            return FINALLY(val);

        else if( ELSE )
            return ELSE();

        else
            return undefined

    }
}}

The $if function returns an object with the if..then..else..elsif construct, using the Condition constructor.
Once you call Condition.elsif() you'll create another Condition object - essentially creating a linked list that can be traversed recursively using sequence()
You could use it like:
var eq = val => x => x == val ? true : false;

$if( eq(128) ).then( doStuff ).else( doStuff )
.elsif( eq(255) ).then( doStuff ).else( doStuff ).call();

However, I realize that using an object is not a purely functional approach. So, in that case you could forgo the object all together:
sequence(f, f, f, f,
    sequence(f, f, f, f
        sequence(f, f, f)
    )
);

You can see that the magic is really in the sequence() function.
I won't try to answer your specific question in javascript. But I think the main point is that you should make a function that will run arbitrary functions under an if..then statement, then nest multiples of that function using recursion to create a complex logical chain. At least this way you will not have to repeat yourself ;)
This code is just a prototype so please take it as a proof of concept and let me know if you find any bugs.


Q: Unable to install fail2ban on Ubuntu 16.04 LTS server! I installed a new Ubuntu 16.04 LTS server.
I want to protect it with fail2ban, but when I try to install the package I get an error.
How do I resolve this problem?
> apt-get install fail2ban
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances
Lecture des informations d'état... Fait
fail2ban is already the newest version (0.9.3-1).
0 mis à jour, 0 nouvellement installés, 0 à enlever et 0 non mis à jour.
1 partiellement installés ou enlevés.
Après cette opération, 0 o d'espace disque supplémentaires seront utilisés.
Souhaitez-vous continuer ? [O/n] o
Paramétrage de fail2ban (0.9.3-1) ...
Job for fail2ban.service failed because the control process exited with error code. See "systemctl status fail2ban.service" and "journalctl -xe" for details.
invoke-rc.d: initscript fail2ban, action "start" failed.
dpkg: erreur de traitement du paquet fail2ban (--configure) :
 le sous-processus script post-installation installé a retourné une erreur de sortie d'état 1
Des erreurs ont été rencontrées pendant l'exécution :
 fail2ban
E: Sub-process /usr/bin/dpkg returned an error code (1)

> systemctl status fail2ban.service
 fail2ban.service - Fail2Ban Service
   Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; vendor preset: enabled)
   Active: inactive (dead) (Result: exit-code) since mar. 2016-11-15 16:02:23 CET; 2min 43s ago
     Docs: man:fail2ban(1)
  Process: 11301 ExecStart=/usr/bin/fail2ban-client -x start (code=exited, status=255)

nov. 15 16:02:23 MBjumpbox systemd[1]: fail2ban.service: Control process exited, code=exited status=255
nov. 15 16:02:23 MBjumpbox systemd[1]: Failed to start Fail2Ban Service.
nov. 15 16:02:23 MBjumpbox systemd[1]: fail2ban.service: Unit entered failed state.
nov. 15 16:02:23 MBjumpbox systemd[1]: fail2ban.service: Failed with result 'exit-code'.
nov. 15 16:02:23 MBjumpbox systemd[1]: fail2ban.service: Service hold-off time over, scheduling restart.
nov. 15 16:02:23 MBjumpbox systemd[1]: Stopped Fail2Ban Service.
nov. 15 16:02:23 MBjumpbox systemd[1]: fail2ban.service: Start request repeated too quickly.
nov. 15 16:02:23 MBjumpbox systemd[1]: Failed to start Fail2Ban Service.

/var/log/fail2ban.log is empty:
ls -l /var/log/fail2ban.log
-rw-r----- 1 root adm 0 nov.  15 16:02 /var/log/fail2ban.log

A: OK finally I resolve it with :

*

*apt-get remove fail2ban

*apt-get autoremove

*apt-get install fail2ban

A: Resolved by the following.
apt-get remove fail2ban
apt-get autoremove
rm -rf /etc/fail2ban/
apt-get install fail2ban

A: The user editable file is jail.local.  Jail.conf on the 16.04 version needs to be copied to a new jail.local file.  You then manually "diff" the old .local and the new .local file and copy any changes in manually.
This fixed the problem for me!


Q: Example 7.2.19 from Casella & Berger (EM algorithm) $X_1, ..., X_n \sim Poi(\tau_i), Y_1, ..., Y_n \sim Poi(\beta\tau_i).$ $X$ and $Y $are mutually independent. However, $X_1$ is missing. I would like to use the EM algorithm to estimate $\beta$ and $\tau_i$. The expected complete-data log likelihood is shown on the top of page 329 in the red box

I do not understand why $\beta^{(r+1)} = \frac{\sum_{i=1}^{n}y_i}{\tau_1^{(r)}+\sum_{i=2}^{n}x_i}$. I differentiated the expected complete-data log likelihood function and got $\beta^{(r+1)} = \frac{\sum_{i=1}^{n}y_i}{\sum_{i=1}^{n}\tau_i}$. I am pretty new to EM algorithm and I don't known where I got wrong. Thanks a lot to anyone who can give me a hint.

A: You're on the right track. In the full likelihood function (7.2.11), after taking derivative on all the $\tau_i$'s, you'll find that $\Sigma_{i=1}^{n}\tau_i = \frac{\Sigma_{i=1}^{n}{(x_i+y_i)}}{\beta+1}$. Replace $\Sigma_{i=1}^{n}\tau_i$ in your results with $\frac{\Sigma_{i=1}^{n}{(x_i+y_i)}}{\beta+1}$ and you'll get the same results as the authors.

A: I am trying to solve this EM problem, and I got the exactly same answer as yours. So, I believe we are correct and the answer in the book is a typo. My answer is
$\beta^{(r+1)} = \frac{\Sigma_{i=1}^{n}y_i}{\Sigma_{i=1}^{n}\tau_i^{(r)}}$
$\tau_1^{(r+1)} = \frac{y_1+\tau_1^{(r)}}{1+\beta^{(r+1)}}$
$\tau_i^{(r+1)} = \frac{y_i+x_i}{1+\beta^{(r+1)} }$ for $i=2,3,\ldots,n$


Q: Google Spreadsheet Script Trigger: This app is blocked I am trying to create a trigger for a script in google spreadsheet and upon trying to save the trigger I am getting the following error:

This app is blocked This app tried to access sensitive info in your
Google Account. To keep your account safe, Google blocked this access.

I don't have G-Suite, I don't have an organization, I am simply using my personal Gmail account. I don't have the special account protection thing enabled. I tried using different scripts, even an empty script.
What could be the problem here? I have used scripts and add-ons in the past, but haven't needed triggers yet. Is there another way to run a script daily or monthly, without this trigger functionality?

A: There is currently a bug
I recommend oyu to "star" it to increase visibility, so it hopefully gets fixed soon.

A: Try this:
Unable to open Google xlsx spreadsheet / Also Google Drive permission Blocked
The same solution logic can solve this problem.
[ ]


Q: How to call method on a child React.Component from a parent React.FunctionalComponent? How can I call a method on a child component from a parent component? I'm not sure it matters but my parent component is a functional component and the child is a class component. I'm hoping that the switch to function components doesn't mean that all class-based components need to be upgraded?
The parent component looks like this:
const Home: React.FC = () => {
    const grid = useRef();
    const buttonClick = () => {
        // I want to be able to call a method on <MyGrid> here to
        // tell it to reload the grid (for example)
        grid.current!.reconfigure();
    };

    return (
        <React.Fragment>
            <JqxButton onClick={buttonClick}>Refresh Grid</JqxButton>
            <MyGrid ref={grid} />
        </React.Fragment>
    );
};

This actually works, though not without errors (which don't seem to crash the app in code sandbox, but it won't compile in VS Code offline). The 'ref' property on MyGrid shows this error:
Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: MyGrid | null) => void) | RefObject<MyGrid> | null | undefined'.
  Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<MyGrid>'.
    Types of property 'current' are incompatible.
      Type 'undefined' is not assignable to type 'MyGrid | null'.ts(2322)

My call to grid.current!.reconfigure() results in this error:
Property 'reconfigure' does not exist on type 'never'.

I've created a code sandbox with the full setup of the parent and child components here: https://codesandbox.io/s/react-fc-call-child-component-14rr3


Q: How to access a variable from another script in another gameobject through GetComponent? I've searched around and I just can't get this to work. I think I just don't know the proper syntax, or just doesn't quite grasp the context.
I have a BombDrop script that holds a public int. I got this to work with public static, but Someone said that that is a really bad programming habit and that I should learn encapsulation. Here is what I wrote:
BombDrop script:
 <!-- language: c# -->

 public class BombDrop : MonoBehaviour {

 public GameObject BombPrefab;

 //Bombs that the player can drop
 public int maxBombs = 1;

 // Update is called once per frame
 void Update () {

 if (Input.GetKeyDown(KeyCode.Space)){

         if(maxBombs > 0){
         DropBomb();

         //telling in console current bombs
         Debug.Log("maxBombs = " + maxBombs);
         }
   }

 }

 void DropBomb(){

     // remove one bomb from the current maxBombs
     maxBombs -= 1;

     // spawn bomb prefab
     Vector2 pos = transform.position;
     pos.x = Mathf.Round(pos.x);
     pos.y = Mathf.Round(pos.y);
     Instantiate(BombPrefab, pos, Quaternion.identity);

 }
}

So I want the Bomb script that's attached to the prefabgameobject Bombprefab to access the maxBombs integer in BombDrop, so that when the bomb is destroyed it adds + one to maxBombs in BombDrop.
And this is the Bomb script that needs the reference.
 public class Bomb : MonoBehaviour {
 // Time after which the bomb explodes
 float time = 3.0f;

 // Explosion Prefab
 public GameObject explosion;

 BoxCollider2D collider;

 private BombDrop BombDropScript;

 void Awake (){

     BombDropScript = GetComponent<BombDrop> ();
 }

 void Start () {

     collider = gameObject.GetComponent<BoxCollider2D> ();

     // Call the Explode function after a few seconds
     Invoke("Explode", time);

 }

 void OnTriggerExit2D(Collider2D other){

     collider.isTrigger = false;
 }

 void Explode() {
     // Remove Bomb from game
     Destroy(gameObject);

     // When bomb is destroyed add 1 to the max
     // number of bombs you can drop simultaneously .
     BombDropScript.maxBombs += 1;

     // Spawn Explosion
     Instantiate(explosion,
                 transform.position,
                 Quaternion.identity);

In the documentation it says that it should be something like
BombDropScript = otherGameObject.GetComponent<BombDrop>();

But that doesn't work. Maybe I just don't understand the syntax here. Is it suppose to say otherGameObject? Cause that doesn't do anything. I still get the error : "Object reference not set do an instance of an object" on my BombDropScript.maxBombs down in the explode()

A: You need to find the GameObject that contains the script Component that you plan to get a reference to. Make sure the GameObject is already in the scene, or Find will return null.
 GameObject g = GameObject.Find("GameObject Name");

Then you can grab the script:
 BombDrop bScript = g.GetComponent<BombDrop>();

Then you can access the variables and functions of the Script.
 bScript.foo();

I just realized that I answered a very similar question the other day, check here:
Don't know how to get enemy's health

I'll expand a bit on your question since I already answered it.
What your code is doing is saying "Look within my GameObject for a BombDropScript, most of the time the script won't be attached to the same GameObject.
Also use a setter and getter for maxBombs.
public class BombDrop : MonoBehaviour
{
    public void setMaxBombs(int amount)
    {
        maxBombs += amount;
    }

    public int getMaxBombs()
    {
        return maxBombs;
    }
}

A: use it in start instead of awake and dont use Destroy(gameObject); you are destroying your game Object then you want something from it
void Start () {
     BombDropScript =gameObject.GetComponent<BombDrop> ();
     collider = gameObject.GetComponent<BoxCollider2D> ();

     // Call the Explode function after a few seconds
     Invoke("Explode", time);

 }

void Explode() {
//..
  //..
//at last
Destroy(gameObject);
 }

if you want to access a script in another gameObject you should assign the game object via inspector and access it like that
 public gameObject another;
void Start () {
     BombDropScript =another.GetComponent<BombDrop> ();
}

A: Can Use this :
entBombDropScript.maxBombs += 1;

Before :
Destroy(gameObject);

I just want to say that you can increase the maxBombs value before Destroying the game object. it is necessary because, if you destroy game object first and then increases the value so at that time the reference of your script BombDropScript will be gone and you can not modify the value's in it.


Q: How to setup content range in NGINX? I use django framework and I try to setup NGINX that server play video in browser chunk by chunk.
nginx.conf
proxy_cache_path /tmp/mycache keys_zone=mycache:100m;
server {
            listen 80;
            server_name localhost;

                proxy_cache mycache;
                slice              1m;
                proxy_cache_key    $host$uri$is_args$args$slice_range;
                proxy_set_header   Range $slice_range;
                proxy_http_version 1.1;
                proxy_cache_valid  200 206 1h;

            location / {
                include proxy_params;
                proxy_pass http://unix:/run/gunicorn.sock;
                       }

            location /vid/ {
                alias /home/affil/videos/;
               }
}

When I try locally

127.0.0.1/vid/test.mp4

, the video starts in browser as partial (206). Fast load.
When I try
http://[my_server_external_ip]/vid/test.mp4

, content range disappear and video starts playing after long time preload.
What's wrong with settings?


Q: C# Access to the path is denied... Client.Download(filelink, path) I've a problem with my code:
when I try to download a file from dropbox, and put it in my Roaming folder something goes wrong, here's the error Log:
System.Net.WebException: An exception occurred during a WebClient request. --->              System.UnauthorizedAccessException: Access to the path'C:\Users\Marco\AppData\Roaming\.maycraft' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at System.Net.WebClient.DownloadFile(Uri address, String fileName)
   --- End of inner exception stack trace ---
   at System.Net.WebClient.DownloadFile(Uri address, String fileName)
   at System.Net.WebClient.DownloadFile(String address, String fileName)
   at MayCraftLauncher.Program.downloadExist() in c:\Users\Marco\Desktop\MayCraftLauncher\C# SourceCode\MayCraftLauncher\MayCraftLauncher\Program.cs:line 71

Obviously I tried to run Visual Studio with administator rights, but nothing...
And here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Security.Principal;
using System.IO;
using System.IO.Compression;
using Ionic.Zip;

namespace MayCraftLauncher
{
    class Program
    {

        public static System.Threading.Thread existDownloading = new System.Threading.Thread(downloadExist);

        public static string userName = Environment.UserName;
        public static string path = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft\Exist";
        public static string maypath = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft";

        static void Main(string[] args)
        {
            folderExist();
        }

        static void check1()
        {
            while (!Directory.Exists(maypath))
            {
                System.Threading.Thread.Sleep(5000);
            }

                existDownloading.Start();
        }

        static void folderExist()
        {
            if (!Directory.Exists(maypath))
            {
                System.Diagnostics.Process.Start(@"C:\Users\Marco\Desktop\MayCraftLauncher.jar");
                check1();
            }
            else
            {
                fileExist();
            }
        }

        static void fileExist()
        {
            if (File.Exists(path)) //Determina se è la prima volta che l'applicazione viene eseguita
            {
                Console.WriteLine("Exist");
                Console.ReadLine();
            }
            else
            {
                existDownloading.Start();
                Console.WriteLine("Downloading...");
            }
        }

        static void downloadExist()
        {
            WebClient Client = new WebClient();
            DateTime btime = DateTime.Now;
            path = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft\";
            string publicLinkExist = @"https://dl.dropbox.com/u/35356155/minecraft/download/Exist";
            //string publicLinkMods = @"https://dl.dropbox.com/u/35356155/minecraft/download/mods.7z";
            string publicLinkMods = @"https://dl.dropbox.com/u/35356155/minecraft/download/mcp.7z";
            try
            {
                //----------------File downloading-------------------
                Client.DownloadFile(publicLinkExist, path);
                DirectoryInfo dev = Directory.CreateDirectory(path);
                string devpath = @"C:\Users\" + userName + @"\AppData\Roaming\.maycraft";
                Client.DownloadFile(publicLinkMods, devpath);
                DateTime atime = DateTime.Now;
                Console.WriteLine("Downloading time: " + atime.Subtract(btime).TotalSeconds + " sec.");

                //---------------Files Extracion-------------------
                using (ZipFile zip = ZipFile.Read(devpath))
                {
                    zip.ExtractAll(path);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                System.IO.File.WriteAllText(@"C:\Users\Marco\Desktop\log.txt", e.ToString());
                Console.ReadKey();
            }
            existDownloading.Abort();
        }

    }
}


Q: NSMutableArray not responding to removeObjectAtIndex: I think i've run into a confused state where i'm doing something fundamentally wrong, but i cannot understand what and why this is happening.
Picture 1: A property of a My class. A NSMutableArray.

Picture2: The code block i want to execute, i want to remove the eleventh object.

Picture3: The debug console shows me that i have 30 objects within my array.

And now, here i was, thinking that this would be an easy task. Since, i've removed and replaced objects at indexes in other NSMutableArrays within my source-code.
Here comes Picture4:

I believe this is telling me that NSMutableArray doesn't respond to removeObjectAtIndex.
Does anyone know what in the heck i'm doing wrong? I'm totally confused.
And no, this is not homework...even if one could believe so. I do.

EDIT:
The error was made during parsing of the objects that went into the dagArray.
Instead of [tempPeriod.dagArray addObject:object] i was doing something completely different.
I was working with a different array and added objects to that array, and when the parser was finished i used tempPeriod.dagArray = [theOtherArray copy] which resulted in this error. theOtherArray was still a NSMutableArray which still confused me. But my best guess is that copy does something with the NSMutableArray rendering it unable to perform those selectors. But i could be completely wrong.
Thanks for shining some thoughts into this.

A: actually it says that NSArray doesn't respond to removeObjectAtIndex. Which would be true.
Could it be that you define it as NSMutableArray, but initialise it in a wrong way?
Where do you init the array, is it possible that the current array is actually a NSArray?
because:
NSMutableArray *anArray = [[NSArray alloc] initWithObject:anObject];

is possible, but would result in runtime errors when you select the wrong selectors.

A: You need to use -mutableCopy if you want a mutable copy of an array. Using -copy, even on a mutable array, will give you an immutable array.


Q: Why the sunset is red and a possible experiment? Before downvoting: I have read some of the answers and will cite them as well.
Not trying to debunk physics or create conspiracies. I love physics but I don't understand it.
Background
This is more or less the model in my mind:

*

*We see the sky blue because blue light is scattered more relative to the rest of the wavelengths composing light, due to its shorter wavelength. Blue light ends up traveling in the atmosphere rather than going through it, and so we get blue all around. The phenomenon is called Rayleigh Scattering.

*Heuristically we can accept that, once you subtract blue from white light, you get yellow. The sun then has to be white, and we just see it yellow.
Now, for the redness of the sunset, I understand this:

When the sun is near the horizon, it the path of the light through the
atmosphere (and in particular through layers which have a higher
concentration of dust particles) is longer, thus the scattering away
of the non-red components is more pronounced.

That is from the current accepted answer.
I also took a look at Rayleigh Scattering to Hyperphysics.
And I remember a lecture (I think it is by Walter Lewin) where a dense smoke is shine with white light and you see it blue. And the light source should look yellow (through the smoke).
Question
I wonder the following: Suppose we have a massive room with movable walls (maybe also mirrors) full of air or smoke.
Would we see different colors, using white light as a source, as we increase the length of the room (same density of the gas), and the path of the light through it? From blue to red?

A: For particle spacing much larger than wavelength, one can treat each individual particle interaction as a discrete, isolated scattering event. The probability of the scattering event varies according to $\lambda ^{-4}$, where $\lambda$ is wavelength (larger wavelengths are redder, smaller wavelengths are bluer).
For any given photon of a particular wavelength, it is equally likely to scatter on its first close encounter with a particle as on its trillionth. However, given the very strong wavelength dependence of the probability, the smaller-wavelength photons have a much higher probability of scattering on every interaction and will tend to scatter early. For something that scatters only very weakly, like the atmosphere, this means that the small wavelengths constitute most of the scattered light across the whole sky (hence the sky being blue from horizon to horizon). For something like dense smoke, the effect can be pronounced over short distances.
Head on, the color of a white light through a particulate scattering medium will dim and redden with increasing distance. For the scattered visible beam, it will become bluer with increasing angle (0 degrees being head on, 90 degrees being side on), but redder and dimmer with increasing distance.
An example of this can be seen in the video on this news article from about 2:05 to 2:20 - although cameras are even more unreliable than the naked eye for recording the true color and brightness of lights, so take the following with due skepticism.
The camera approaches the white-light headlights of two emergency vehicles at a fairly consistent 30-degree angle as it gets closer while going around a curve. At first the lights appear to be dim orange and the beams, also dim orange, are barely visible. As the camera is getting closer, still at about 30 degrees, the color of the lights is shifting to yellow-white while the beams are clearly visible and are white in color. As the vehicle with the camera passes the emergency vehicles, the angle between the camera and the beam increases, and the color of the lights shifts to their true white color while the color of the beams is blue (although in real life it was likely not as vivid as what the camera recorded). Meanwhile, the red-tinted light-bar on the fire truck doesn't shift noticeably in color during the clip.

A: Not sure I follow, if you filled a room with an atmosphere, not just oxygen. And had a white light shone from one end to the other, assuming the light is not reflected from the walls and is absorbed mostly. Say a black wall.
The colour on the other end of the wall, will get less and less blue .[ White-blue].
Not only will it get less and less blue, as the distance light travels through the atmosphere increases, the scattering of all of the other colours is also more defined.
Red gets scattered less than any other colour so there is a point where the only remaining colour is red


Q: Sqlite Database Error: The FMDatabase  is not open. I'm getting this Error "The FMDatabase  is not open". Even after i open my database first before executing query. Here's the code of instance of database which i'm using to open database.
var instance = ModelManager()

class ModelManager: NSObject {

var database: FMDatabase? = nil
var database2: FMDatabase? = nil
var resultSet: FMResultSet!

class func getInstance(sqllite:String) -> ModelManager {
    if(instance.database == nil){
        instance.database = FMDatabase(path: Util.getPath(sqllite))
    }
    return instance
}
class func getInstance2(sqllite:String) -> ModelManager {
    if(instance.database2 == nil){
        instance.database2 = FMDatabase(path: Util.getPath(sqllite))
    }
    return instance
}

}
and this is the the code where i am getting error.
   func saveImageAudio(audioFile:String?,imageFile:String?,isImage:Bool){

    guard (instance.database?.open())! else {
        return
    }

    let fileName = isImage == true ? imageFile : audioFile
    var paramName = isImage == true ? "imageList" : "audioList"
    let countParam = isImage == true ? "imageCount" : "audioCount"
    let time = Util.DateTime()

    guard increaseLastNo(isImage: isImage) else {
        return
    }

    do {

        let FileArray = getImageAudiolist(isImagelist: isImage)

        var query = ""
        var values:[Any] = []

        if FileArray.count == 0 {
            query = "update RoomSectionDetails set \(paramName) = ?, \(countParam) = 1 ,modified_dtm = ? where  pda_guid = ? and roomName = ? and sectionID = ? and dead = ?"
            values = [fileName!,time,pda_guid,roomName,sectionId,0]
        }else{
            query = "update RoomSectionDetails set \(paramName) = \(paramName) || ?, \(countParam) = \(countParam) + 1, modified_dtm = ? where  pda_guid = ? and roomName = ? and sectionID = ? and dead = ?"
            values = [",\(fileName!)",time,pda_guid,roomName,sectionId,0]
        }

        try instance.database?.executeUpdate(query, values: values)

        paramName = isImage == true ? "lastImageNo" : "lastAudioNo"

        if !isImage {
            self.updateAudioDuration()
        }
    } catch  {
        print("Error while Saving Image Audio in DB")
    }
     instance.database?.close()
   }

Please give the solution for this problem. I wasn't closing database ever time after firing queries. that causes cpu usages more then 200. So now i'm closing database. but i am getting this error. Thanks for Help.

A: I found the Solution for this problem. I am having method inside method which closing the database. Because of that error coming. Thanks for help.


Q: Scrolling divs not scrolling to bottom of content I have 2 scrolling divs (outlined in red) that will not scroll to the their respective bottoms. I can't seem to seem to figure out what to tweak to fix it.
The thick outlined box is a simulated browser window.
http://jsfiddle.net/jsk55rfb/4/

HTML

CSS
.container {
    height: 500px;
    width: 500px;
    border: solid 3px black;
    overflow: hidden;
}

.header {
    height: 25px;
    background-color: #333;
    right: 0;
    left: 0;
}

.sidebar {
    position: fixed;
    top: 0;
    bottom: 0;
    width: 75px;
    margin-top: 35px;
    border: solid 1px grey;
}

.main {
    height: 100%;
    padding-left: 75px;
}

.main-container {
    width: 65%;
    height: 100%;
}

.main-content {
    height: 100%;
    overflow-y: scroll;
    border: solid 1px red;
}

.main-header {
    height: 20px;
    border: 1px solid black;
}

.detail-container {
    float: right;
    width: 35%;
    height: 100%;
    border: solid 1px grey;
}

.top-info {
    padding: 75px 0;
}

.items-container {
    height: 100%;
    overflow-y: scroll;
    border: solid 1px red;
}

.item {
    padding: 100px 0;
}

.blue { background-color: blue; }
.orange { background-color: orange; }
.grey { background-color: grey; }
.purple { background-color: purple; }

.content {
    width: 65%;
    height: 100%;
}

A: You have a fixed height for the container and overflow set to hidden. Since the divs exceed that height, the overflow can't be seen.
Try this:

.container {
    height: 500px;
    width: 500px;
    border: solid 3px black;
    overflow: scroll;
}

.header {
    height: 25px;
    background-color: #333;
    right: 0;
    left: 0;
}

.sidebar {
    position: fixed;
    top: 0;
    bottom: 0;
    width: 75px;
    margin-top: 35px;
    border: solid 1px grey;
}

.main {
    height: 100%;
    padding-left: 75px;
}

.main-container {
    width: 65%;
    height: 100%;
}

.main-content {
    height: 100%;
    overflow-y: scroll;
    border: solid 1px red;
}

.main-header {
    height: 20px;
    border: 1px solid black;
}

.detail-container {
    float: right;
    width: 35%;
    height: 100%;
    border: solid 1px grey;
}

.top-info {
    padding: 75px 0;
}

.items-container {
    height: 100%;
    overflow-y: scroll;
    border: solid 1px red;
}

.item {
    padding: 100px 0;
}

.blue { background-color: blue; }
.orange { background-color: orange; }
.grey { background-color: grey; }
.purple { background-color: purple; }

.content {
    width: 65%;
    height: 100%;
}

A: I could solve this with some javascript. This should addapt to any content size of your other blocks as long as the markup structure doesn't change.
Good luck!
$(function(){
//creating vars based on jquery objects
$itemsContainer = $('.items-container');
$mainContent = $('.main-content');

$container = $('.container');
$header = $('.header');
$mainHeader = $('.main-header');

//calculating heights
var containerH = $container.height();
var headerH = $header.height();
var mainHeaderH = $mainHeader.height();

//assigning new height to main-content class
$mainContent.css("height", (containerH - headerH - mainHeaderH) + "px");

//similar operation for items-container
//creating vars based on jquery objects
$topInfo = $('.top-info');

//calculating heights
var topInforH = $topInfo.outerHeight(); //since in your example top-info has no content only padding, you will need to use the method outerHeight instead of height

//assigning new height to main-content class
$itemsContainer.css("height", (containerH - headerH - topInforH) + "px"); });

By the way, I updated your jsfiddle with my solution, so you can test it.

A: When you use a height of 100% it sets it to the full height regardless of other sibling elements. So they are at 100% of the parent element but then the headers are pushing them down. You will have to use fixed heights on all elements. Or set one to 20% and other to 80% etc.
.main-content { width: 452px; }
.items-container {width: 352px; }


Q: how to remove space between numbers in ASP.Net using RegEx I need to remove the space between the numbers using RegEx means I want to make a formated number from the input like {lhs: \"1000 U.S. dollars\",rhs: \"58 740.6015 Indian rupees\",error: \"\",icc: true} I tried the following expression Regex regex = new Regex("rhs: \\\"(\\d+.\\d*)"); but its give me a error "Input format not correct"  so how can I remove the space between the numbers
P.S The currency name will change each time it called

A: use the following expression
string value = Regex.Replace(response.Split(',')[1], "[^.0-9]", "");


Q: Error using Play Framework debug command I try to launch my play project in debug mode with the play debug command, and it display me an error I can't resolve, despite of Google research... I found many topics about it, but no solution worked for me. Tried to change debug port, run as administrator, disable firewall..
Error message :
ERROR: transport error 202: bind failed: Permission denied
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:750]
FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

NOTE : On my computer, Windows Kernel is using port 9999
Have you got the same error and found a fix for it ?

A: You could try

*

*Deactivating any antivirus or firewall;

*Check ports in use by netstat command

*Changing play.bat debug port (at play's folder root) and save it

Hope it helps


Q: Deploy WAR to TomEE server I built my JavaEE project & got my-service.war file. I want to deploy it to TomEE server.
I have successfully installed TomEE (I can start & stop TomEE server successfully).
I copy my-service.war to
<TomEE_Home>/webapps/

Then, I start TomeEE server.
I open my browser, and put URL http://localhost:8080/my-service
But I get HTTP Status 404 page.
(Then, I checked under /webapps/ that, my-server.war has been unzipped by server, because I see my-server folder there.)
What do I miss for deploying my WAR to TomEE server?
=====server logs =====
I got checked /logs/catalina.2016-08-16.log , I see these errors:
webapps/my-service/WEB-INF/classes/ looking all classes to find CDI beans, maybe think to add a beans.xml if not there or add the jar to exclusions.list
...
org.apache.catalina.core.StandardContext.startInternal Context [/my-service] startup failed due to previous errors
16-Aug-2016 13:51:46.311 INFO [localhost-startStop-1] org.apache.openejb.assembler.classic.Assembler.destroyApplication Undeploying app: /Users/xichen/Dev-tools/apache-tomee-webprofile-7.0.1/webapps/my-service

A: You should check logs/catalina.date.log and logs/localhost..log files.
If you are under unix execute:
grep SEVERE logs/*

to get the errors.
The real error associated with
Context [/my-service] startup failed due to previous errors

Is before in the logs


Q: Estudiando angular y ng new nombre_app no funciona. Que estoy haciendo mal? Me devuelve el siguiente error:
alberto@linuxdell:~/Escritorio/angular$

    ng new --name=02spa --version=7.1.4

? Would you like to add Angular routing? No
? Which stylesheet format would you like to use? CSS

Error: **Schematic input does not validate against the Schema**: {"name":"02spa","version":"7.1.4","routing":false,"style":"css"}
Errors:

  Data path ".name" should match format "html-selector".

Tambien probe con el comando:
ng new nombre_app

y da el mismo error.

Estas son las versiones que tengo:
Angular CLI: 7.1.4
Node: 10.14.2
OS: linux x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.11.4
@angular-devkit/core         7.1.4
@angular-devkit/schematics   7.1.4
@schematics/angular          7.1.4
@schematics/update           0.11.4
rxjs                         6.3.3
typescript                   3.1.6

gracias.

A: Esto es una respuesta bastante corta. No uses un nombre que comience con un número para tu proyecto.

A: Estas utilizando nombre_app. Debes quitar el guion bajo, carácter que no esta permitido usa un nombre de solo caracteres alfabéticos o alfanuméricos y el problema estará solucionado


Q: Faithfully exact base-change and split extensions Suppose $R \to S$ is a homomorphism of rings (unital, but not necessarily commutative) and $\mathcal{C}$ is an abelian subcategory of the category of left $R$-modules such that the functor $S \otimes_R -$ is faithfully exact when restricted to $\mathscr{C}$. (This means that a short exact sequence in $\mathcal{C}$ is exact if and only if its image under $S \otimes_R -$ is exact. See Ishikawa's Faithfully Exact Functors... for a few standard equivalent formulations.)
Does it then follow that an exact sequence
$$0 \to A \to B \to C \to 0$$
in $\mathcal{C}$ is split if and only if
$$0 \to F(A) \to F(B) \to F(C) \to 0$$
is split?
The "only if" dirction is obvious, so the question is about the "if" direction. If $R$ and $S$ are commutative and every $M \in \mathcal{C}$ is finitely presented, this is true and is proved in Hochster's lecture notes here. It seems like a very formal statement, but Hochster's lecture notes, it's proved by considering the base change map
$$S \otimes_R \mathrm{Hom}_R(-,-) \to \mathrm{Hom}_S(S \otimes_R -, S \otimes_R -),$$
which doesn't make sense for non-commutative $R$ and $S$.
For what I have in mind, $R$ and $S$ are not commutative. But they are relatively nice, so if it helps to assume the rings are left noetherian or left coherent or something along those lines, that's just fine.


Q: How do i download patches on Trainz Simulator 2010 It says my version is out of date and that I can download the patches on the forums so I click the link and it comes up with the downloads available. When I try to download the patch it opens up a window and does nothing. What should I do?

A: The patches for Trainz 2010 can be found on the official N3V page.
You need to find what version you are currently running, and then download and install patches in sequence to bring your build numbers up. So, if your build is currently 41491 (the original retail release), you'd need to download and run the following files in order:

*

*http://dgdl.auran.com/TS2010Download/41491_to_41615.exe

*http://download.ts2009.com/patch/41615_to_42203.exe

*http://download.ts2009.com/patch/42203_to_43434.exe

*http://download.ts2009.com/patch/43434_to_44088.exe

*http://download.ts2009.com/patch/44088_to_49933.exe
You should then be able to "autopatch" to v. 46170 from within the initial game screen. Then apply the following patch:

*

*http://download.ts2009.com/patch/46170_to_49938.exe
And that should make you up-to-date for Trainz 2010.
The web servers are a bit slow to respond when clicking on these links, but you should be able to click them, then select "save" and run them.
This only works for retail versions of Trainz, or those purchased directly from N3V (Auran). Games purchased on Steam or other digital distribution means are not supported by N3V.


Q: Saving activity into pdf file I need to save Activity content into .pdf file. Something like a screenshot. I can save individual views of a activity into file using this code:
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(600,300, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
View content = findViewById(R.id.editText1);
content.draw(page.getCanvas());
document.finishPage(page);

But how to save (printscreen) whole activity, not just a views?
Thank you.

A: You can take a screenshot of the current activity using the given code
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
    fos = new FileOutputStream(imagePath);
    bitmap.compress(CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
} catch (FileNotFoundException e) {
    Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
    Log.e("GREC", e.getMessage(), e);
}

}
and make sure give write permissions of the storage in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


Q: How to find a Window which should be visible on Ubuntu 14.04 In Ubuntu 14.04 I have Keepass2 in my Launchbar. I do execute Keepass and I can see it is executing by a small arrow. With statement :
ps - fu bernard | grep keepass2

results into :
bernard   2433  1697  0 16:31 ?        00:00:15 /usr/bin/cli /usr/lib/keepass2/KeePass.exe
bernard   3263  3212  0 17:00 pts/0    00:00:00 grep --color=auto keepass2

So Keepass is running.
Also with alt-tab I see Keepass. If I click on the Keepass icon still I am not switched to Keepass.
The same happened to me with XAMPP from https://www.apachefriends.org, and to the Ubuntu update manager. So it seems a general Ubuntu 14.04 problem.
With alt-tab I can switch to the running Firefox windows, so alt-tab itself seems to work.
I execute this in Virtualbox client. If I switch to other VB client, when I come back the Window is sometimes visible.

A: It seems to be a unity bug. If you try to restart unity it works correctly.
Hit Alt + F2 and type unity --replace to restart unity.
After this, I think it will be OK....  :)


Q: Java Web Start return value - workaround I know that returning a value from a JWSapp to the "calling" page cannot be done.
However, I use this JWSapp to get user ID from its biometric information.
The idea is that when you try to login, a button allows to launch the JWSapp that will deal with the biometric tasks and then return the user's idea.
Still, as I said, from a JWSapp I cannot send back the id to auto-complete the field. I found this post: Returning a value from a java web start application but I really need to keep the JWS (external constraints)...
So there's my question: is there any workaround to get the id back?
Thank you in advance :)


Q: Storyboard vs. iOS Simulator WYSIWYG This is my problem:

        Left side: iOS Simulator      Right side: Storyboard / Interface Builder

Any ideas? Thanks
... UI Elements placed in IB appears shifted up in Simulator
Maybe a better solution than this ... I have two xibs with the exact same look, one is shifted up, the other one works fine.

A: OK, however. My workaround is to change the view hierarchy and set the UIImageView behind the UINavigationItem. Seems to work.


Q: Missing MySQL DLL? I've recreated the Northwind Spring/NHibernate example that comes with Spring.NET, but with MySQL rather than SQLServer. I've almost got it working I think, but I'm getting this when I try to use Hibernate to load something from the database
A first chance exception of type 'System.IO.FileNotFoundException'
occurred in mscorlib.dll NHibernate.Util.ReflectHelper:
ERROR lambda_method - Could not load type
MySql.Data.MySqlClient.MySqlCommand, MySql.Data.
System.IO.FileNotFoundException: Could not load file or assembly
'MySql.Data' or one of its dependencies.
The system cannot find the file specified.
File name: 'MySql.Data'

Every project (DAO, Service, Web) has a reference to the MySQL.Data DLL so I'm a bit unsure what's going on.
Can anyone help me please?

A: Make sure that MySQL.Data.dll actually got copied to the output folder. And that you are using right platform (x32 vs x64 bit) and right version of .NET (2,3,3.5 vs 4). If everyhing seems fine, enable Fusion Logging and take a look at this article:

For FileNotFoundException:  At the bottom of the log will be the paths
  that Fusion tried probing for this assembly. If this was a load by
  path (as in Assembly.LoadFrom()), there will be just one path, and
  your assembly will need to be there to be found. Otherwise, your
  assembly will need to be on one of the probing paths listed or in the
  GAC if it's to be found.
You may also get this exception if an unmanaged dependency or internal
  module of the assembly failed to load. Try running depends.exe on the
  file to verify that unmanaged dependencies can be loaded. Note that if
  you re using ASP.NET, the PATH environment variable it's using may
  differ from the one the command line uses. If all of them could be
  loaded, try ildasm.exe on the file, double-click on "MANIFEST" and
  look for ".file" entries. Each of those files will need to be in the
  same directory as the manifest-containing file.


Q: How can I set a System.env variable in Android Studio? In my build.gradle file in Android Studio using NDK, I have the following code. The app builds if I run it from the terminal with "./gradlew --assembleDebug" since I have set the path for ANDROID_NDK_HOME to /Users/chenige/Desktop/android-ndk-r9, but it will not build from inside Android Studio. From inside Android Studio, System.env.ANDROID_NDK_HOME is "null". Does anybody know why/how I can fix this?
    task buildNative(type: Exec) {
    if (System.env.ANDROID_NDK_HOME != null) {
        def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
        commandLine ndkBuild

    } else {
        doLast {
            println '##################'
            println 'Skipping NDK build'
            println 'Reason: ANDROID_NDK_HOME not set.'
            println '##################'
        }
    }
}

}

A: Android Studio doesn't read environment variables, so this approach won't work. Also, using the projectDir scheme in settings.gradle will probably cause problems. Android Studio has a limitation that all of its modules need to be located underneath the project root. If you have libraries that are used in multiple projects and they can't be placed under a single project root, the best advice is to have them publish JARs or AARs to a local Maven repository that individual projects can pick up.
read more Environment variable in settings.gradle not working with Android Studio

A: It works for me with the follwoing steps:

*

*Set your variable in Windows

*Reboot

*reach it in gradle build: "$System.env.MYVARIABLE"


Q: Programmatic Views how to set unique id's? I am creating in my app bunch of programmatic Views. As it appeared to be they all by default have the same id=-1. In order to work with them I need to generate unique id's.
I have tried several approaches - random number generation and based on current time, but anyway there's no 100% guarantee that different Views will have different id's
Just wondering is there any more reliable way to generate unique ones? Probably there's special method/class?

A: Just want to add to Kaj's answer, from API level 17, you can call
View.generateViewId()
then use the View.setId(int) method.
In case you need it for targets lower than level 17, here is its internal implementation in View.java you can use directly in your project:
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

/**
 * Generate a value suitable for use in {@link #setId(int)}.
 * This value will not collide with ID values generated at build time by aapt for R.id.
 *
 * @return a generated ID value
 */
public static int generateViewId() {
    for (;;) {
        final int result = sNextGeneratedId.get();
        // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
        int newValue = result + 1;
        if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
        if (sNextGeneratedId.compareAndSet(result, newValue)) {
            return result;
        }
    }
}

ID number larger than 0x00FFFFFF is reserved for static views defined in the /res xml files. (Most likely 0x7f****** from the R.java in my projects.)
From the code, somehow Android doesn't want you to use 0 as a view's id, and it needs to be flipped before 0x01000000 to avoid the conflits with static resource IDs.

A: Just an addition to the answer of @phantomlimb,
while View.generateViewId() require API Level >= 17,
this tool is compatibe with all API.
according to current API Level,
it decide weather using system API or not.
so you can use ViewIdGenerator.generateViewId() and View.generateViewId() in the
same time and don't worry about getting same id
import java.util.concurrent.atomic.AtomicInteger;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;

/**
 * {@link View#generateViewId()}要求API Level >= 17,而本工具类可兼容所有API Level
 *

 * 自动判断当前API Level,并优先调用{@link View#generateViewId()},即使本工具类与{@link View#generateViewId()}
 * 混用,也能保证生成的Id唯一
 *

 * =============
 *

 * while {@link View#generateViewId()} require API Level >= 17, this tool is compatibe with all API.
 *

 * according to current API Level, it decide weather using system API or not.

 * so you can use {@link ViewIdGenerator#generateViewId()} and {@link View#generateViewId()} in the
 * same time and don't worry about getting same id
 *
 * @author fantouchx@gmail.com
 */
public class ViewIdGenerator {
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    @SuppressLint("NewApi")
    public static int generateViewId() {

        if (Build.VERSION.SDK_INT < 17) {
            for (;;) {
                final int result = sNextGeneratedId.get();
                // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
                int newValue = result + 1;
                if (newValue > 0x00FFFFFF)
                    newValue = 1; // Roll over to 1, not 0.
                if (sNextGeneratedId.compareAndSet(result, newValue)) {
                    return result;
                }
            }
        } else {
            return View.generateViewId();
        }

    }
}

A: Regarding the fallback solution for API<17, I see that suggested solutions start generating IDs starting from 0 or 1. The View class has another instance of generator, and also starts counting from number one, which will result in both your and View's generator generating the same IDs, and you will end up having different Views with same IDs in your View hierarchy. Unfortunately there is no a good solution for this but it's a hack that should be well documented:
public class AndroidUtils {

/**
 *  Unique view id generator, like the one used in {@link View} class for view id generation.
 *  Since we can't access the generator within the {@link View} class before API 17, we create
 *  the same generator here. This creates a problem of two generator instances not knowing about
 *  each other, and we need to take care that one does not generate the id already generated by other one.
 *
 *  We know that all integers higher than 16 777 215 are reserved for aapt-generated identifiers
 *  (source: {@link View#generateViewId()}, so we make sure to never generate a value that big.
 *  We also know that generator within the {@link View} class starts at 1.
 *  We set our generator to start counting at 15 000 000. This gives us enough space
 *  (15 000 000 - 16 777 215), while making sure that generated IDs are unique, unless View generates
 *  more than 15M IDs, which should never happen.
 */
private static final AtomicInteger viewIdGenerator = new AtomicInteger(15000000);

/**
 * Generate a value suitable for use in {@link View#setId(int)}.
 * This value will not collide with ID values generated at build time by aapt for R.id.
 *
 * @return a generated ID value
 */
public static int generateViewId() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return generateUniqueViewId();
    } else {
        return View.generateViewId();
    }
}

private static int generateUniqueViewId() {
    while (true) {
        final int result = viewIdGenerator.get();
        // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
        int newValue = result + 1;
        if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
        if (viewIdGenerator.compareAndSet(result, newValue)) {
            return result;
        }
    }
}

}

A: Since support library 27.1.0 there's generateViewId() in ViewCompat
ViewCompat.generateViewId()

A: Create a singleton class, that has an atomic Integer. Bump the integer, and return the value when you need a view id.
The id will be unique during the execution of your process, but wil reset when your process is restarted.
public class ViewId {

    private static ViewId INSTANCE = new ViewId();

    private AtomicInteger seq;

    private ViewId() {
        seq = new AtomicInteger(0);
    }

    public int getUniqueId() {
        return seq.incrementAndGet();
    }

    public static ViewId getInstance() {
        return INSTANCE;
    }
}

Note that the id might not be unique, if there already are views that have ids in the view 'graph'. You could try to start with a number that is Integer.MAX_VALUE, and decrease it instead of going from 1 -> MAX_VALUE


Q: \textsc on a path with decoration [Original question]
\documentclass[tikz,border=5pt]{standalone}
\usetikzlibrary{decorations.text}
\begin{document}
\begin{tikzpicture}
    \node [circle, draw=red, fill=red!30] (N1) at (0,0) {A};
  \node [circle, draw=red, fill=green!30] (N2) at (5,0) {B};
  \draw [red,->] [postaction={decoration={raise=3pt, text along path, text={|\textsc|Text||},text align=center}, decorate}] (N1.north) to [out=45,in=135] (N2.north);
\end{tikzpicture}
\end{document}

I want \textsc works. Any help?
[Updated]
After CarLaTeX's answer, I got:
\documentclass[tikz,border=5pt]{standalone}
\usetikzlibrary{decorations.text}
\begin{document}
\begin{tikzpicture}
    \node [circle, draw=red, fill=red!30] (N1) at (0,0) {A};
  \node [circle, draw=red, fill=green!30] (N2) at (5,0) {B};
  \draw [red,->] [postaction={decoration={raise=3pt, text along path, text={|\scshape|Text |\_| |+$\theta$|},text align=center}, decorate}] (N1.north) to [out=45,in=135] (N2.north);
\end{tikzpicture}
\end{document}

I want _ and $\theta$ works.

A: I think you have to use \scshape:
\documentclass[tikz,border=5pt]{standalone}
\usetikzlibrary{decorations.text}

\begin{document}
\begin{tikzpicture}
  \node [circle, draw=red, fill=red!30] (N1) at (0,0) {A};
  \node [circle, draw=red, fill=green!30] (N2) at (5,0) {B};
  \draw [red,->] [postaction={decoration={raise=3pt, text along path, text={|\scshape|text},text align=center}, decorate}] (N1.north) to [out=45,in=135] (N2.north);
\end{tikzpicture}
\end{document}

Edit: answer to the updated version
Put them into {...}:
\documentclass[tikz,border=5pt]{standalone}
\usetikzlibrary{decorations.text}
\begin{document}
\begin{tikzpicture}
\node [circle, draw=red, fill=red!30] (N1) at (0,0) {A};
\node [circle, draw=red, fill=green!30] (N2) at (5,0) {B};
\draw [red,->] [postaction={decoration={raise=3pt, text along path, text={|\scshape|text {\_ $\theta$}},text align=center}, decorate}] (N1.north) to [out=45,in=135] (N2.north); \end{tikzpicture}
\end{document}


Q: Whence this generalization of linear (in)dependence? I recently came across a definition of (in)dependence that is supposed to be a generalization of linear (in)dependence among a set of vectors:

An element $x$ is dependent on a set of elements $\{a_1, \cdots, a_n\}$ iff any two real-valued additive functions that take equal values on each of the elements $a_1, \cdots, a_n$ also agree on $x$.  A set of elements $\{a_1,\cdots,a_n\}$ is independent iff no member of the set is dependent on the rest.

The term "additive function" used in this definition describes a (real-valued) function $f$ such that $f(a + b) = f(a) + f(b)\;\; \forall a, b \in \mathrm{dom}(f)$.  Of course, this presupposes that some form of addition is defined in the domain of such $f$.  It is safe to assume that this domain is an Abelian group, but you may assume additional structure if this is necessary to answer my question.
I find this definition of dependence much harder to think about and work with than the standard definition of linear dependence for vectors, so I wonder what's the justification for such a counterintuitive definition.
Is anyone familiar with this way of defining dependence/independence?  If so, what algebraic structure is it used for?

A: So, I don't know where the definition came from, or whether it is inspired by the following, but it reminds me of the notion of dominion.
The notion was introduced by John Isbell in 1965 as a tool to study epimorphisms. (Epimorphisms and dominions, 1966 Proc. Conf. Categorical Algebra (La Jolla, Calif., 1965). pp. 232-246, Springer-Verlag, NY; MR 0209202).
Definition. Let $\mathcal{C}$ be a category of algebras (in the sense of universal algebra), and let $A\in\mathcal{C}$. Given a subset $S$ of $A$, we say that $S$ dominates $a\in A$ if and only for every object $B\in\mathcal{C}$ and every pair of $\mathcal{C}$-morphisms $f,g\colon A\to B$, if $f(s)=g(s)$ for all $s\in S$, then $f(a)=g(a)$. The collection of all $a\in A$ dominated by $S$ is called the dominion of $S$ in $A$ (relative to $\mathcal{C}$). We denote it by $\mathrm{dom}^{\mathcal{C}}_A(S)$, with $\mathcal{C}$ omitted if it is understood from context.
First, because morphisms respect the structure, it should be clear that the dominion of $S$ always contains the subalgebra generated by $S$. It is not hard to show that the dominion is a subalgebra, and in fact that the dominion construction is a closure operator on the lattice of subalgebras of $A$.
The connection with epimorphisms is the following: an epimorphism is a right-cancellable morphism. That is, $f\colon X\to Y$ is an epimorphism if for every $g,h\colon Y\to Z$, if $gf = hf$, then $g=h$. In the context of categories of algebras, $f$ is an epimorphism if and only if the dominion of $f(X)$ in $Y$ is all of $Y$.
Moreover, if the category $\mathcal{C}$ is closed under subobjects and quotients, then every morphism $f\colon X\to Y$ can be factored into a canonical projection $X\to X/\mathrm{Ker}(f)$ (where $\mathrm{Ker}(f)$ is the congruence of all $(a,b)\in X\times X$ with $f(a)=f(b)$), which is well understood, followed by the immersion $X/\mathrm{Ker}(f)\hookrightarrow f(X)\subseteq Y$, so that we really only need to "understand" dominions of subalgebras in order to understand epimorphisms.
The concept also makes sense in other settings, specifically when the objects in your category are "enriched sets" and the morphisms are set-theoretic maps.
Examples.

*

*In the category of abelian groups, $\mathrm{dom}_A(B)=B$ for all groups $A$ and subgroups $B$. To see this, note that the canonical projection $A\to A/B$ and the zero map $A\to A/B$ agree on $B$ and nowhere else, so no element of $A$ not in $B$ can be in the dominion.

*More generally, in the category of (left) $R$-modules, for all (left) modules $M$ and submodules $N$, $\mathrm{dom}_M(N) = N$. This can again be verified by comparing the canonical projection $M\to M/N$ and the zero map.

*In particular, in the category of $k$-vector spaces, the dominion of a subspace is the subspace itself. Hence, the dominion of a subset $S\subseteq V$ is precisely the span of $V$.
Note that this gives a way to interpret linear dependence and linear independence along the lines of your query, which is precisely what made the connection in my head: say $S=\{s_1,\ldots,s_n\}$ is a subset of the vector space $V$. Then $x$ is dominated by $S$ ("depends on $S$") if and only for any pair of linear transformations $f,g$ with domain $V$ and same codomain, if $f(s_i)=g(s_i)$ for all $i$, then $f(x)=g(x)$. This occurs if and only if $x$ is a linear combination of the $s_i$, if and only if $x$ lies in the span of $S$. We could say a set $S$ is "redundant" of there exists $x\in S$ such that $S\setminus\{x\}$ dominates $x$, so that "non-redundant" sets would correspond to linearly independent sets.

*In the category of all groups, we also have that $\mathrm{dom}_G(H) = H$ for all groups $G$ and subgroups $H$. The simplest way to see this is to use the amalgamated free product $G*_HG$ of $G$ with itself over $H$, and the two canonical embeddings of $G$ into this product; they agree precisely on $H$ and nowhere else.

*On the other hand, in the category of semigroups, we can find semigroups $S$ and subsemigroups $T$ such that $\mathrm{dom}_S(T)\neq T$. For a trivial example, take a group $G$, and a subsemigroup $T$ that is not a group. Since the image of a group under a semigroup homomorphism must be a group, the dominion of $T$ in $G$ relative to the category of semigroups is in fact the subgroup generated by $T$. Thus, for instance, the dominion of $\mathbb{N}$ in $\mathbb{Z}$ is $\mathbb{Z}$. There are plenty of less silly examples, and Isbell gave an intrinsic description of exactly when an element of $S$ is dominated by the subsemigroup $T$, in terms of certain connected factorizations. It's called the Zigzag Lemma for Semigroups. It can be something strictly between $T$ and $S$, all of $S$, just $T$, etc.

*For monoids (semigroups with identity), commutative semigroups, and commutative monoids, the dominion coincides with the dominion when we consider the objects as lying in the larger category of all semigroups. This is not obvious, since enlarging your category will, in general, tend to "shrink" the dominion (there are more pairs of maps to consider). This is a theorem of Isbell and Howie (Isbell, J.R. and Howie, J.M., Epimorphisms and dominions II,  J. Algebra 6 (1967) pp 7-21, MR0209203).

*The category of rings also has nontrivial examples. For instance, any two ring homomorphism with domain $\mathbb{Q}$ that agree on $\mathbb{Z}$ must agree on all of $\mathbb{Q}$ (that is, $\mathbb{Z}\hookrightarrow \mathbb{Q}$ is an epimorphisms). The precise description of the dominion is complicated (Isbell got it wrong in his first paper).

*For a non-algebraic example, in the category of Hausdorff topological spaces, we have that $\mathrm{dom}_X(Y) = \overline{Y}$, the closure of $Y$, since any two continuous maps in a Hausdorff space that agree on a set must agree on its limit points, so the closure of $Y$ is certainly contained in the dominion. For the converse inclusion, consider $X/\sim$, where $\sim$ is the relation that identifies all points of $\overline{Y}$ to a single point, and consider the constant map to the single point and the canonical projection $X\to X/\sim$.
If we take the definition you give and allow additive maps into any semigroup, then it describes precisely when $x$ is in dominion of $\{x_1,\ldots,x_n\}$ in the category of (commutative) semigroups. I don't know off-hand whether restricting the codomain to $\mathbb{R}$ will necessarily "enlarge" the dominion if you start with a semigroup only (I suspect it would).
But if you are starting with a vector space, then: if the ground field is of positive characteristic, then an additive function into $\mathbb{R}$ must be the zero function; so every vector is dominated/depends on any set, and the only independent set is the empty set. If the ground field is characteristic zero, then additive functions into $\mathbb{R}$ must be $\mathbb{Q}$-linear, and the concept you are defining is just $\mathbb{Q}$-linear independence and $\mathbb{Q}$-linear dependence.

A: (Posting as CW because this is actually a reposting of Arturo Magidin's comment to my now deleted answer.)
If your domain is actually a vector space $V$ over some field $K$, let $F\subset K$ be its prime field, then the field extension $K$ is a vector field over $F$, and therefore $V$ is also a vector field over $F$. Consider functions from $V$ to $K$.
Then we have the string of implications that $K$-linearity implies additivity implies $F$-linearity. But if $K$ is a proper extension of $F$, then one can always find a function on $V$ that is $F$-linear but not $K$-linear.
Proof: That $K$-linearity implies additivity is trivial. In the case that the $F$ is a prime finite field $\mathbb{Z}/p\mathbb{Z}$, then multiplication by any element of $F$ is equivalent to the multiplication by a number between $0$ and $p-1$, and hence can be obtained by repeated addition. In the case that $F$ is $\mathbb{Q}$, additivity implies $\mathbb{Z}$-linearity, and then using that $f(v) = nf(v/n)$ you get $\mathbb{Q}$-linearity.
For the second statement, since $K$ is a vector space over $F$ with dimension bigger than 1, we can find a basis $a_i$ of $K$ as vector space over $F$, such that $a_1 = 1$. Let $b_j$ be a basis of $V$ as vector space over $K$. Then the elements $\{a_i b_j\}$ form a basis for $V$ as a vector space over $F$. Consider the function $f$ such that $f(a_ib_j) = 1$ if $i = 1$ and $0$ otherwise, and extend $F$-linearly. This function additive but not $K$ linear.


Q: Php, Symfony 1.4,doctrine I want to convert this mysql syntax into a doctrine 1.2 syntax. I want to show dates with zero values and print some errors on it. Also, is PHP foreach loop relevant for this for the templates/views?
SELECT calendar.datefield AS DATE,
       IFNULL(SUM(orders.quantity),0) AS total_sales
FROM orders RIGHT JOIN calendar ON (DATE(orders.order_date) = calendar.datefield)
WHERE (calendar.datefield BETWEEN (SELECT MIN(DATE(order_date)) FROM orders) AND (SELECT MAX(DATE(order_date)) FROM orders))
GROUP BY DATE..


Q: Getting InvalidOperationException: Incorrect Content-Type: text/plain exception when processing file through Web API Core I am having an API.Net Core Web API app that has a POST method that accepts and processes a PDF file.
However, when I try to test in POSTMAN (Selecting POST, selecting Binary, choosing a file) I get a following error

InvalidOperationException: Incorrect Content-Type: text/plain

At the following line

var file = Request.Form.Files[0];

Please let me know if there is anything I need to fix
Thank you in advance
Here is the entire method
[HttpPost]
[Route("SubmitForm")]
public async Task<IActionResult> SubmitForm()
{

    var file = Request.Form.Files[0];
    HttpClient client = GetClient();
    try
    {

        byte[] docAsBytes;
        using (var ms = new MemoryStream())
        {
            file.CopyTo(ms);
            docAsBytes = ms.ToArray();
            string s = Convert.ToBase64String(docAsBytes);
            // act on the Base64 data
        }

        PdfReader pdfReader = new PdfReader(docAsBytes);
        MemoryStream m = new MemoryStream();
        PdfStamper outStamper = new PdfStamper(pdfReader, m);
        string formName = outStamper.AcroFields.GetField("FormSeqNo");

        string endpointUrl = "https://myproject.sharepoint.com/sites/project" + String.Format(
           "/_api/web/GetFolderByServerRelativeUrl('{0}')/Files/Add(url='{1}', overwrite=true)",
           this.Config["TemplateLibrary"].Replace(" ", "%20"),
           formName + ".pdf");

        ByteArrayContent imageBytes = new ByteArrayContent(docAsBytes);
        var result = await client.PostAsync(endpointUrl, imageBytes);

        //return result.Content.ToString();
    }
    catch (Exception ex)
    {
        //return ex.ToString();
    }

    return Ok();
}


Q: Creating a running total grouped by a statement evaluation Using this article I have implemented a query that determines packing intervals for user events:
http://www.itprotoday.com/microsoft-sql-server/new-solution-packing-intervals-problem
I've ended up with following output:

However, the bit I can't fathom out is how to group the packed intervals by userId for each date.  Basically, I need a group column on the end which increments for each row when isStart is 1, but is output the same as the previous row's when isStart is null.
Thus it should go:
Row 1: 1
Row 2: 2
Row 3: 2
Row 4: 3
Row 5: 4
Row 6: 5
Row 7: 6
Row 8: 7
Row 9: 8
Row 10: 9
Row 11: 9
Row 12: 9
Row 13: 10

... etc
This then allows me to retrieve the min start and max end for each group.  I'm sure this is really obvious but I can't seem to spot it!

A: Just use a cumulative sum:
select t.*,
       sum(isStart) over (order by start) as grp
from t;


Q: iOS - UILocalNotification - can schedule only up to 64 slots at a given time Overview

*

*I have an iOS app which sends local notifications at specific dates.

*I just learned that I can only schedule 64 notifications at a given time.

*There are cases when I can't schedule notifications as the 64 slots are filled.

*So I store them in the database and when the user responds to a notification I check if there are any available slots and schedule the remaining notifications.

Problem

*

*When the user doesn't  respond to a notification my code is not executed so I am not able to schedule the remaining notifications.

Question

*

*Is there a solution for this problem ?

*can I execute a piece of code (house keeping) at certain times ?

*is there any work around for this ?

A: You may not want to signal to the user there is a problem, but rather just do it in the background. If a user has 64 notifications for one app and hasn't opened the app, then they probably aren't using the app. Once a notification has fired it isn't in the array anymore. So you will have room every time a notification is fired off. They do however remain in notification centre, which you have to clear out yourself.
Its usually better to not present possible problems to the user, but rather handle them in a way that makes sense internally if that is an option. Look up the delegate methods for the appDelegate and you will most likely find ways you can handle what you are trying to do.
Thought I would make a post in case you wanted to accept the answer.
Best of luck.


Q: Is an element of a vector a scalar or 1x1 vector or 1x1 matrix? In econometrics, by Hayashi, they defined the error vector of n observations in a $ (n \times K)$ regression funcntion as:
$\epsilon = \begin{bmatrix}\epsilon_{1} \\\epsilon_{2} \\\vdots \\\epsilon_{n}\end{bmatrix}$, where $\epsilon_{i}$ is the ith observation's error term,
and K-dimension x vector of the ith observation as,  $x_{i} = \begin{bmatrix}x_{i1} \\x_{i2} \\\vdots \\x_{ik}\end{bmatrix}$
The book says that the cross moment of two random variables E[xy] is zero means that these two random variables are orthogonal. It's not hard to see the point using [0,1] and [1,0] to check their cross product for orthogonality.
But in the book it has a formula for strict exogeneity assumption:
$E[x_{j}\epsilon_{i}] = \begin{bmatrix}x_{j1}\epsilon_{i} \\x_{j2}\epsilon_{i} \\\vdots \\x_{jk}\epsilon_{i}\end{bmatrix} = 0_{(K\times1)}$
So, here the $\epsilon_{i}$ is an element of the $\epsilon$ vector, and the cross moment for a $(k\times1)$ vector and an element of a vector, which are orthogonal, is a $(k\times1)$ 0 vector. My question is that, what is a cross moment of two random variables, is it the expected value of the inner product? And shall I view the $\epsilon_{i}$ as a scalar, or $(1\times1)$ vector, or $(1\times1)$ matrix?

Thank you very much.

A: Vectors are (in this context) just matrices which have one row or column.
$\def\e{\epsilon}\e_i$ is a scalar, as it is an entry of a  matrix, $\e$.
The cross moment of two random variables $X,Y$ is defined as the expected value of their product, where the product being used depends on context.

*

*If $X$ and $Y$ are scalars, the product is usual multiplication.

*If $X$ is a scalar and $Y$ is a matrix, the product is scalar multiplication.

*If $X$ is and $Y$ are both matrices, then the product is matrix multiplication.

*

*If $X$ is an $1\times n$ vector and $Y$ is an $n\times 1$ vector, then the product is a $1\times 1$ matrix, which can be thought of as a scalar with no loss of generality. If so, this scalar is their inner product.

In answer to your second question, there is one special case where the cross moment is the expected value of the inner product.

A: From what I understand, the n X 1 error vector is a random vector. A random vector of dimension n is a collection of n random variables that are associated to the same event. So in the error vector:
$$\epsilon = \begin{bmatrix}\epsilon_{1} \\\epsilon_{2} \\\vdots \\\epsilon_{n}\end{bmatrix}$$
where $\epsilon_i$ is the error in the $i^{th}$ observation, since the error is random every variable is random.
Now the cross moment expression should be written like :
$$E[x_{j}\epsilon_{i}] = \begin{bmatrix}x_{j1}\epsilon_{i} \\x_{j2}\epsilon_{i} \\\vdots \\x_{jk}\epsilon_{i}\end{bmatrix} = \begin{bmatrix}0 \\0 \\\vdots \\0\end{bmatrix}$$
Now the error $\epsilon_1$ is actually the error observed in the vector $x_1=\begin{bmatrix}x_{11} \\x_{12} \\\vdots \\x_{1k}\end{bmatrix}$ which is again a vector so you are just checking the exogeneity with respect to $\epsilon_1$.
Consider a real number $x$, now this is a scalar because it is plain value. Its physical significance is the magnitude. If we club two such numbers $x$ and $y$ we get a vector$$\left(\begin{array}{c}x\\ y\end{array}\right)$$ Now if we club two such vectors we get a matrix $$\begin{bmatrix}x_1 & x_2 \\y_1 & y_2 \end{bmatrix}$$
The thing is from which space are you viewing the real number. If you are considering only the scalar space then $x$ is a scalar, if you are viewing from a vector space $x$ is a 1X1 vector if you are viewing from matrix space $x$ is a 1X1 matrix. So the hierarchy is like Scalar then Vector then Matrix. Any scalar can be represented as a matrix or a vector but not the other way round.
It is similar to the fact that is $2$ really a complex number. People say it is because in the complex domain it can be represented as $2+0i$,a complex number cant be represented as a real number because it is having real and imaginary parts.
Hope this helps...


Q: Sampling and removing random elements from a list I have written a method which randomly samples a part of a list. The code is as follows:
private List<String> selectImages(List<String> images, Random rand, int num) {
    List<String> copy = new LinkedList<String>(images);
    Collections.shuffle(copy,rand);
    return copy.subList(0, num);
}

The method takes as input the original list, the random number generator and the number of items to sample.
Now I would like to remove the selected elements from the original list (called images). How can this be done?

A: Using removeAll in the old list with the argument being your sub sample.
private List<String> selectImages(List<String> images, Random rand, int num) {
    List<String> copy = new LinkedList<String>(images);
    Collections.shuffle(copy,rand);
    List<String> sample = copy.subList(0, num);
    images.removeAll(sample);
    return sample;
}


Q: to compare two text files and output the difference in other file .txt I want to compare two text files and output the difference in other result.txt.
I use this command in command prompt:
findstr /vixg:Z:\misc\test1.txt Z:\misc\misc\test2.txt > Z:\misc\misc\result.txt

But I have the file result.txt is the same of test2.txt.


Q: db connection deadlock We have a web application that has been running well for several years. The web application was using mysql, spring-1.2.6, and ibatis.
After replacing spring-1.2.6 with spring-3.2.0, we started to notice a problem that multiple concurrent requests to a particular page always hang for some reason.
jConsole shows the following for each concurrent thread:
   java.lang.Thread.State: WAITING on
   org.apache.commons.pool.impl.GenericObjectPool$Latch@b6b09e
   at java.lang.Object.wait(Native Method)
   at java.lang.Object.wait(Object.java:485)
   at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1104)

After investigation, we found that this problem has something to do with a resultMap that looks like the following. With spring-1.2.6, only one connection was needed for each thread regardless of the number of rows in the result set. However, with spring-3.2.0, N+1 connections (depending on the number of rows returned) are needed for each thread. Hence the deadlock. (We are using the default value (8) of maxActive property in our configuration.)
How can I fix it so that connections are reused in this case? Thanks.
<resultMap id="resultBlog" type="Blog">
    <id property="id" column="idBlog" />
    <result property="name" column="blogname" />
    <result property="url" column="blogurl" />
    <result property="author" column="idBlog" select="selectAuthor" />
</resultMap>


Q: How to type cast a literal in C I have a small sample function:
#define VALUE 0

int test(unsigned char x) {
  if (x>=VALUE)
    return 0;
  else
    return 1;
}

My compiler warns me that the comparison (x>=VALUE) is true in all cases, which is right, because x is an unsigned character and VALUE is defined with the value 0. So I changed my code to:
if ( ((signed int) x ) >= ((signed int) VALUE ))

But the warning comes again. I tested it with three GCC versions (all versions > 4.0, sometimes you have to enable -Wextra).
In the changed case, I have this explicit cast and it should be an signed int comparison. Why is it claiming, that the comparison is always true?

A: x is an unsigned char, meaning it is between 0 and 256. Since an int is bigger than a char, casting unsigned char to signed int still retains the chars original value. Since this value is always >= 0, your if is always true.

A: All the values of an unsigned char can fir perfectly in your int, so even with the cast you will never get a negative value. The cast you need is to signed char - however, in that case you should declare x as signed in the function signature. There is no point lying to the clients that you need an unsigned value while in fact you need a signed one.

A: Even with the cast, the comparison is still true in all cases of defined behavior. The compiler still determines that (signed int)0 has the value 0, and still determines that (signed int)x) is non-negative if your program has defined behavior (casting from unsigned to signed is undefined if the value is out of range for the signed type).
So the compiler continues warning because it continues to eliminate the else case altogether.
Edit: To silence the warning, write your code as
#define VALUE 0

int test(unsigned char x) {
#if VALUE==0
  return 1;
#else
  return x>=VALUE;
#endif
}

A: The #define of VALUE to 0 means that your function is reduced to this:
int test(unsigned char x) {
  if (x>=0)
    return 0;
  else
    return 1;
}

Since x is always passed in as an unsigned char, then it will always have a value between 0 and 255 inclusive, regardless of whether you cast x or 0 to a signed int in the if statement.  The compiler therefore warns you that x will always be greater than or equal to 0, and that the else clause can never be reached.