text:
Q: force SSL+WWW in CakePHP .htaccess I know the topic "How to force HTTPS + WWW" is often discussed and solved, and in general it works for me.
But as I now got a specific predefined .htaccess from CakePHP I do not know how to include it.
.htaccess for CakePHP:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

If I put the normal code for HTTPS/WWW Forcing in front or backwards to that code, it does not work properly because all requests are set to root directory and not to e.g. /contact.
Normally I am using:
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.mydomain\.com$ [NC]
RewriteRule ^ https://www.mydomain.com%{REQUEST_URI} [R=301]

But you can not just include that above...
Could anybody please help me including HTTPS/WWW Forcing in the above .htaccess?

A: The generic way is:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTPS} !on
    RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

No need to hard-code domain name. Also request will not redirect to root when switching from http to https

A: Thanks LazyOne, this maybe working, but for me it often ended up in "mydomain.com/redirect:/app/webroot/index.php" which was really strange. But maybe this is due to the "{REQUEST_URI}" because I had to change my
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

to
RewriteRule ^(.*)$ index.php [QSA,L]

due to strange problems with redirect (no idea what happend, CakePHP suddenly requestet a "Redirect:Controller" as also described here http://groups.google.com/group/croogo/browse_thread/thread/55539dabfd0191fd?pli=1 - any idea about this?).
It is now working with this code:
RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteRule (.*) https://www.mydomain.com/$1 [R=301,L]

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://www.mydomain.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

A: This is how it should be:
RewriteEngine On

# force https and www.
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.mydomain\.com$ [NC]
RewriteRule ^ https://www.mydomain.com%{REQUEST_URI} [R=301,L]

# route all requests for non-existing resources to CakePHP
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

A: another way might be to force SSL using a component ? http://bakery.cakephp.org/articles/lemon/2008/07/07/component-for-forcing-a-secure-connection


text:
Q: How to determine when rectangle and rotated rectangle intersect using JavaScript? For my application, I have a SVG-drawn rectangle that I am using as a hitbox and I'm looking to make a JavaScript function that returns a boolean of true whenever the hitbox touches another rectangle that has been rotated about its centre by some angle using CSS transformations. I have discovered this code from http://www.inkfood.com/collision-detection-with-svg/:
function intersectRect(r1, r2) {
var r1 = r1.getBoundingClientRect();    //BOUNDING BOX OF THE FIRST OBJECT
var r2 = r2.getBoundingClientRect();    //BOUNDING BOX OF THE SECOND OBJECT

//CHECK IF THE TWO BOUNDING BOXES OVERLAP
 return !(r2.left > r1.right ||
       r2.right < r1.left ||
       r2.top > r1.bottom ||
       r2.bottom < r1.top);
}

This works great for regular rectangles, but I am unsure how to build upon this to work with my rotated rectangle. When I inspect the rotated rectangle using developer tools in my web browser, I can see that it highlights the rectangle correctly. That being said, when I try to extract the bounding client rectangle using JavaScript, it returns the dimensions of the rectangle in its unrotated form. My question is how do I receive the correct dimensions for my rotated rectangle so I can detect when it collides with my hitbox rectangle? Is there another method for me to detect when my hitbox touches my rotated rectangle? Any help would be much appreciated.

A: Alright so this is going to take a lot of optimization before it's practical for your use case, but it does serve as a proof of concept that isPointInPath will work with a rotation, as long as you draw the rectangle by points (you can also use fillRect and rotate to draw it, and just trace the outline with lineTo but no stroke to create your bounding box to check against).
To test out the isPointInPath, edit the values of checkX and checkY

var ctx = document.querySelector('canvas').getContext('2d')

function rotate(x, y, a, b, degrees){
 let angle = degrees * (Math.PI / 180),
   sinA = Math.sin(angle),
   cosA = Math.cos(angle)

  return [
   cosA * (a - x) - sinA * (b - y) + x,
    sinA * (a - x) + cosA * (b - y) + y
  ]
}

function drawRect(x, y, w, h, rotation){
 var manipFn = rotation ? rotate : function(a,b){ return [a,b]; }

  var coords = {
   bottomLeft: manipFn(x,y,x,y,rotation),
    bottomRight: manipFn(x,y,x+w,y,rotation),
    topRight: manipFn(x,y,x+w,y+h,rotation),
    topLeft: manipFn(x,y,x,y+h,rotation)
  }

  var checkX = 106,
    checkY = 18

  ctx.moveTo(...coords.bottomLeft)
  ctx.strokeStyle = "#3a1"
  ctx.lineWidth = 1
  ctx.lineTo(...coords.bottomRight)
  ctx.lineTo(...coords.topRight)
  ctx.lineTo(...coords.topLeft)
  ctx.lineTo(...coords.bottomLeft)
  console.log(ctx.isPointInPath(checkX,checkY))
  ctx.stroke()
  ctx.closePath()

  ctx.fillStyle = "#000"
  ctx.fillRect(checkX, checkY, 2, 2)
}

//drawRect(10, 10, 20, 30)

drawRect(100, 10, 20, 30, 45)
canvas {
  width: 500px;
  height: 500px;
  border: 1px solid black;
}
<canvas></canvas>

A: There is a lot of ick in the SVG spec, but here is a working example of what you requested. Be warned, this is gotcha central!!
https://codepen.io/josephscottstevens/pen/XEgbrP
window.onmousemove = function(e) {
  var c = document.getElementById("circle");
  var l = document.getElementById("line");
  var displayDiv = document.getElementById("isColiding");
  var circle = { radius : c.r, center : { x:c.cx, y:c.cy } };
  var line =   { p1 : { x:l.x1, y:l.y1 }, p2 : { x:l.x2, y:l.y2 } };
  displayDiv.textContent = circle.radius; //(distance == 0) ? "coliding" : "not coliding";
  moveSection("circle", e.clientX - 20, e.clientY - 20);
  var distance = circleDistFromLineSeg(circle, line);

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What happens to other threads when resource is locked in C#? I wonder what does other threads do when one thread locked a resource.
Can other threads do new tasks while they are waiting the lock to be released (like async programming) or they just doing nothing ?
C# code example:
lock (referenceType)
{
    // executing code
}

A: The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.
This link is useful lock statement


text:
Q: How to create a box and whisker plot tracking orders by day of the week in Tableau I have already searched throuoghly both on google and stackoverflow, but cannot find an answer to this question:
My question is very similar to this but for Tableau: Boxpplot on multiple columns - PythonBox and whisker plot on multiple columns
What I'd like to do is this: I have the amount of 3 different products that were sold on different dates. I'd like to do a boxplot to see the avg, max, and min, etc of the three products being sold. Below is a crude drawing of what I want to do:

Here is sample data in CSV format:
Date,A Orders,B Orders,C Orders
"Wednesday, March 30, 2016",28,44,73
"Monday, September 5, 2016",37,36,55
"Friday, March 25, 2016",35,54,67
"Friday, September 16, 2016",32,58,58
"Tuesday, March 1, 2016",30,43,80
"Saturday, November 26, 2016",36,59,71
"Monday, November 21, 2016",28,44,72
"Sunday, March 13, 2016",27,47,67
"Thursday, February 4, 2016",32,51,54
"Tuesday, February 16, 2016",44,46,71
"Thursday, February 4, 2016",47,50,64
"Monday, September 19, 2016",36,41,77
"Friday, December 9, 2016",36,53,87
"Monday, March 28, 2016",32,64,71
"Sunday, October 16, 2016",30,58,59
"Friday, July 22, 2016",31,35,70
"Sunday, October 9, 2016",40,56,67
"Thursday, June 9, 2016",29,49,77
"Tuesday, November 29, 2016",16,44,59
"Thursday, January 28, 2016",38,64,81
"Sunday, January 24, 2016",30,48,81
"Monday, July 4, 2016",27,46,82
"Friday, August 26, 2016",32,47,68
"Monday, December 26, 2016",23,63,83
"Wednesday, February 17, 2016",15,40,67
"Monday, May 16, 2016",34,49,76
"Monday, July 4, 2016",35,46,63
"Monday, January 18, 2016",32,56,76
"Saturday, November 5, 2016",36,44,66
"Sunday, July 24, 2016",39,50,75
"Saturday, July 30, 2016",36,32,64
"Saturday, January 9, 2016",33,56,56
"Saturday, January 9, 2016",37,46,81
"Monday, July 18, 2016",25,55,68
"Wednesday, March 16, 2016",28,41,60
"Tuesday, February 9, 2016",16,40,63
"Friday, September 16, 2016",33,46,76
"Tuesday, January 5, 2016",36,62,86
"Monday, July 25, 2016",23,55,65
"Monday, June 6, 2016",22,46,76
"Saturday, December 17, 2016",38,44,74
"Tuesday, September 6, 2016",30,41,61
"Saturday, April 2, 2016",46,44,67
"Wednesday, February 3, 2016",35,52,69
"Monday, February 8, 2016",33,47,80
"Thursday, December 15, 2016",34,55,67
"Tuesday, December 13, 2016",34,65,83
"Friday, July 8, 2016",19,49,79
"Tuesday, February 9, 2016",24,48,68
"Tuesday, May 24, 2016",22,50,68
"Friday, March 4, 2016",33,57,61
"Friday, May 13, 2016",25,50,83
"Sunday, February 21, 2016",40,46,75
"Monday, October 10, 2016",23,68,53
"Saturday, June 18, 2016",35,51,59
"Tuesday, November 29, 2016",35,59,72
"Saturday, June 25, 2016",27,45,75
"Thursday, March 17, 2016",24,46,55
"Sunday, September 25, 2016",26,38,83
"Monday, May 9, 2016",24,44,58
"Saturday, May 21, 2016",30,58,57
"Monday, February 8, 2016",27,63,82
"Wednesday, January 20, 2016",37,49,85
"Friday, April 22, 2016",34,66,62
"Thursday, October 6, 2016",27,58,84
"Wednesday, August 31, 2016",19,46,68
"Thursday, July 7, 2016",31,60,78
"Sunday, October 23, 2016",29,43,77
"Thursday, October 13, 2016",42,52,84
"Thursday, May 12, 2016",42,51,63
"Saturday, September 24, 2016",23,45,85
"Monday, May 9, 2016",28,53,63
"Saturday, November 19, 2016",31,55,62
"Wednesday, February 17, 2016",30,39,62
"Sunday, February 28, 2016",33,52,73
"Saturday, May 28, 2016",28,49,58
"Monday, January 4, 2016",38,56,70
"Friday, January 29, 2016",37,64,74
"Friday, April 22, 2016",40,47,59
"Thursday, March 3, 2016",27,59,73
"Saturday, December 17, 2016",20,64,68
"Thursday, January 21, 2016",19,40,69
"Tuesday, December 13, 2016",33,45,67
"Thursday, January 7, 2016",31,53,64
"Wednesday, January 6, 2016",23,54,74
"Sunday, November 6, 2016",27,39,72
"Wednesday, September 14, 2016",18,46,81
"Thursday, March 31, 2016",45,37,77
"Wednesday, August 10, 2016",54,61,79
"Saturday, May 7, 2016",24,40,80
"Wednesday, February 10, 2016",32,50,63
"Wednesday, April 27, 2016",37,49,83
"Monday, April 18, 2016",36,46,68
"Sunday, August 7, 2016",28,39,82
"Tuesday, September 6, 2016",16,54,63
"Tuesday, September 13, 2016",26,52,70
"Monday, April 18, 2016",35,49,83
"Monday, December 26, 2016",27,52,70
"Thursday, March 24, 2016",23,49,63

A: Your sample data did not work for me. I built the following example using the Sample Superstore dataset:
image

A: Use box and whisker plot under 'Show Me' in upper-right corner. Suggests you may need to turn off aggregation.
https://help.tableau.com/current/pro/desktop/en-us/buildexamples_boxplot.htm


text:
Q: .each function when try to load content using jquery I have this to add colors to spans:

$('span').each(function() {
  var color = $(this).data('c');
  $(this).css('background', color);
});

It works well if the content is loading direct. But if I load the content using jQuery it will not run. any ideas?

A: Try like this:
$(document).ready(function(){
   $('span.cor').each(function() {
   var color = $(this).data('c');
   $(this).css('background', color);
  });
});


text:
Q: Esconder div para versão mobile com css Eu estava pesquisando aqui as soluções, mas não funcionou no meu código, deixo aqui ele:
CSS:
    @media screen and (max-width:768px)
{
   #img{
            display: none !important;
        }
}

    #img{
       background-color: none;
    }

HTML:

Mas não está funcionando. O que estou fazendo de errado? Aperto F12 para simular um celular, mas não rola.

A: @media only screen and (max-width: 480px) {
        #img{
            display: none !important;
        }
    }
    #img{
        background-color: blue;
        width: 150px;
        height: 150px;
    }

Sua referência de ID não está correta. Tente dessa maneira, e lembre-se de referenciar os ID's de forma correta.

A: Cara! Vi que vc está usando Bootstrap, usa uma coisa massa do bootstrap 4. vc faz o seguinte:

O d-sm-none quer dizer que quando o tamanho da tela for considerado sm (small) essa div n será exibida, precisa nem "cutucar" no css lkkkkkkk


text:
Q: get user location lat long on cordova without enable their location I am making mobile (Android, iPhone and WP8) app in cordova with angular. I need to take users lat, long. I used http://ngcordova.com/docs/plugins/geolocation/ and HTML 5 geolocation API and angular geolocation Js to get users location. When I turn on Mobiles -> Settins -> Locations -> On I am getting users location, When users turned off their location I couldn't take their location.
Is it possible to get users locations if user turned off their locations at mobile settings.

A: No, if the user disables their location you're not allowed to get it. Not only by software, but also in the Terms of Use of the SDKs you're using (Android and iOS stores will ban your apps).
As jcesarmobile commented, you can get it with some accuracy the user location based on their IP. For example, it's good enough for getting the user country to set the app language, works like a charm.


text:
Q: Tensors with low spectral norm Consider a tensor $T$ with six indices, $T_{(ii')(jj')(kk')}$, where each index goes from $1$ to $n$. We can think of $T$ as a linear map from $\mathbb{R}^n \otimes \mathbb{R}^n \otimes \mathbb{R}^n$ to itself and consider its spectral norm:
$
\Vert T \Vert_{\infty} = \sup \vert \sum T_{(ii')(jj')(kk')} x_{ijk}y_{i'j'k'}\vert
$
where the supremum is taken over all unit vectors $x,y \in \mathbb{R}^n \otimes \mathbb{R}^n \otimes \mathbb{R}^n$.
On the other hand $T$ can also be viewed as trilinear form on $n$-dimensional matrices, so we can define a norm:
$
\Vert T \Vert_{2,2,2} = \sup \vert \sum T_{(ii')(jj')(kk')} X_{ii'} Y_{jj'}Z_{kk'}\vert
$
where the supremum is over all matrices $X,Y,Z$ of Frobenius norm $1$.
What are the examples of tensors which have high (as $n \to \infty$) spectral norm as linear maps, but low norm as trilinear forms?
Since the question is admittedly rather general, let's specialize to tensors of a more special form, namely $T_{(ii')(jj')(kk')} = g_{ijk}h_{i'j'k'}$, where $g,h \in \mathbb{R}^n \otimes \mathbb{R}^n \otimes \mathbb{R}^n$, so that $T = gh^{T}$ as a linear map. Then its spectral norm is simply $\Vert g\Vert \cdot \Vert h\Vert$. Taking $g$ and $h$, say, to be unit vectors, how should we choose them to get a low trilinear norm:
$\Vert T \Vert_{2,2,2} = \sup \vert \sum g_{ijk}h_{i'j'k'} X_{ii'} Y_{jj'}Z_{kk'}\vert $
?
It can be shown that randomly chosen $g, h$ will have the desired property, but I'm interested in more explicit examples. Because there is no direct analog of the spectral decomposition for tensors, the intuition that the "mass" of $T$ should be "spread out" roughly in all directions (as in the case of matrices with low spectral norm, but high Frobenius norm) on the $\mathbb{R}^{n^2}$ components of the tensor product is not easy to formalize.


text:
Q: Redirecting a page if user not logged in I'm building a web app that allows users to login with Facebook using OpenFB for Cordova.  I want only certain features viewable if they are logged in.  I am trying to run a check for login status and re-directing if not logged in.  This is what I have so far:
<head>
  <script>
    if(openFB.getLoginStatus.loginStatus = 'unknown'){
                    window.location ="#/app/home";
    }
  </script>
</head>

The getLoginStats function is as such:
function getLoginStatus(callback) {
    var token = tokenStore.fbAccessToken,
        loginStatus = {};
    if (token) {
        loginStatus.status = 'connected';
        loginStatus.authResponse = {accessToken: token};
    } else {
        loginStatus.status = 'unknown';
    }
    if (callback) callback(loginStatus);
}

When I console.log the value I am getting undefined. Even when logged in with facebook.  Am I missing something obvious?
Logout code requested:
//logout function
$scope.fbLogout = function(){
 openFB.logout(); //logouts after revoking permissions.
 alert('Logged out');
}

A: openFB.getLoginStatus is an asynchronous function that takes a callback as parameter. You have to use it like this:
openFB.getLoginStatus((loginStatus) => {
    console.log(loginStatus);
});


text:
Q: Simple NN in python not working, problem with backpropagation algorithm perhaps? I tried to code classic XOR problem using NN with 2 inputs, 2 hidden neurons, 1 output neuron (using stochastic gradient descent). But whatever i do my NN doesn't work correctly, still getting wrong output and i really don't know where is the problem, i think in backpropagation, maybe i multiplied it in wrong order, i really don't know. The formula i used for updating the outputs weights is LEARING_RATE * ERROR * (OUTPUT * (1 - OUTPUT) * HIDDEN_OUTPUT.T
and the formula for hidden weights is LEARING_RATE * HIDDEN_ERROR * (HIDDEN_OUTPUT * (1 - HIDDEN_OUTPUT) * INPUT.
I would like to know where is the problem in my code, I will be grateful for any help you can provide :)
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoid_derivative(y):
    return np.exp(y) * (1 - np.exp(y))

inp = np.array([ [[0, 0]],
                 [[0, 1]],
                 [[1, 0]],
                 [[1, 1]] ])

w_ih = np.random.uniform(size=(2, len(inp[0][0])))  # weights from input to hidden

bias_hidden = np.random.uniform(size=(1, len(w_ih)))

w_ho = np.random.uniform(size=(1, len(w_ih)))       # weights from hidden to output

bias_output = np.random.uniform(size=(1, len(w_ho)))

des_output = [[0, 1, 1, 0]]

r = 0.1 # learning rate

for i in range(10000):
    index_sample = random.randint(0, len(inp) - 1)

    # Forward propagation
    hidden = sigmoid(np.dot(w_ih, inp[index_sample].T) + bias_hidden.T)
    output = sigmoid(np.dot(w_ho, hidden) + bias_output)
    # Calculating error
    output_error = output - np.array(des_output).T[index_sample]
    hidden_error = np.dot(w_ho.T, output_error)

    # Back propagation
    output_gradient = output_error * sigmoid_derivative(output)
    w_ho += np.dot(output_gradient, hidden.T) * r

    bias_output += np.sum(output_gradient, axis=0, keepdims=True) * r

    hidden_gradient = hidden_error * sigmoid_derivative(hidden)
    w_ih += np.dot(hidden_gradient, inp[index_sample]) * r

    bias_hidden += np.sum(np.array(hidden_gradient), axis=0, keepdims=True) * r

test = np.array([ [[0, 0]],
                  [[0, 1]],
                  [[1, 0]],
                  [[1, 1]] ])
for i in test:
    h1_test = sigmoid(np.dot(w_ih, np.array(i).T) + bias_hidden.T)      # testing neural newtwork
    output_test = sigmoid(np.dot(w_ho, h1_test) + bias_output)

    print(output_test, i)


text:
Q: How i can build start button to load counter? I created a counter and I want it to start only when I press button start (not on page load). How I can do that?

$('.counter').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');

  $({
    countNum: $this.text()
  }).animate({
      countNum: countTo
    },

    {

      duration: 6000,
      easing: 'linear',
      step: function() {
        $this.text(Math.floor(this.countNum));
      },
      complete: function() {
        $this.text(this.countNum);
        //alert('finished');
      }

    });

});
body {
  max-width: 800px;
  margin: 100px auto 0;
  text-align: center;
  display: table;
}

.counter {
  font-size: 16px;
  width: 200px;
  border-radius: 50%;
  height: 200px;
  display: inline;
}

.startbtn {
  margin-bottom: 40px;
  border: 1px solid red;
}

Start

0
 km

0
 km

0
 minut

A: Add a click event to your element startbtn.
Look at this code snippet
Click on start.

var start = function() {
  $('.counter').each(function() {
    var $this = $(this), countTo = $this.attr('data-count');

    $({
      countNum: $this.text()
    }).animate({
        countNum: countTo
      }, {
        duration: 6000,
        easing: 'linear',
        step: function() {
          $this.text(Math.floor(this.countNum));
        },
        complete: function() {
          $this.text(this.countNum);
          //alert('finished');
        }
      });
  });
};

$('#startbtn').click(start);
body {
  max-width: 800px;
  margin: 100px auto 0;
  text-align: center;
  display: table;
}

.counter {
  font-size: 16px;
  width: 200px;
  border-radius: 50%;
  height: 200px;
  display: inline;
}

.startbtn {
  margin-bottom: 40px;
  border: 1px solid red;
}

Start

0
 km

0
 km

0
 minut

See? the counter wasn't executed until you clicked on element start.


text:
Q: At what point do I need to add the X-UA Compatible meta tags? I'm trying to add X-UA Compatible meta tags to my .net project by overriding a page method but I'm not exactly sure at what stage I need to add the tags. At the moment I have:
    protected override void OnInit(EventArgs e)
    {
        HtmlMeta meta = new HtmlMeta();
        meta.HttpEquiv = "X-UA-Compatible";
        meta.Content = "IE=EmulateIE7";
        Page.Header.Controls.Add(meta);
        base.OnInit(e);
    }

but this doesn't appear to be working. Do I have to add the tags before the page has initialized? On load? Any help would be appreciated.

A: I would do this via the web.config:
<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <add name="X-UA-Compatible" value="IE=EmulateIE7" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>

Will work and requires no changes to your code.
More information: http://www.iis.net/configreference/system.webserver/httpprotocol/customheaders

A: Generally speaking, you should not add it.
Please check the relevant MSDN article about specifying document models.


text:
Q: DateDifference on VSTO C# differencedate = mspApp.DateDifference(task.BaselineStart, tsv.StartDate, mspApp.ActiveProject.Calendar);
System.Windows.Forms.MessageBox.Show(differencedate.ToString());

no result is shown, the messagebox did not display. I have tried different solutions like converting the parameters to DateTime. Weird part is, the IDE shows the syntax and parameters needed to run this function.

A: The DateDifference method returns an integer which is the duration in minutes between the dates, for an automatically scheduled task.
To get a difference between two dates for a manually scheduled task, which uses an effective calendar that can include non-working time, use the EffectiveDateDifference property.


text:
Q: Passing a parameter recursively in Racket I am having trouble writing a function in racket that is supposed to take another function as it's first parameter and a list as its second.
All seems to go well on the initial call to the function but when I try to recursively call it with the function as a parameter it is wanting parameters to the function.  I want this parameter function to be passed as a function upon the recursion but used for evaluation other places in the definition.  Any help would be greatly appreciated.
(define apply-to-pairs
  (lambda (arg1 arg2)
    (if (or (equal? (length arg2) 0)
            (equal? (length arg2) 1))
        '()
        (cons (arg1 (car arg2) (car (cdr arg2)))
              (apply-to-pairs (arg1 (cdr (cdr arg2))))))))

This is my code and it compiles fine but when the recursive call to apply-to-pairs is performed the program wants parameters for arg1 while I just want it to be passed as the function definition it comes in as.  I get there error 'expected 2 parameters but only found 1' because it is looking at (cdr (cdr arg2)) as an argument to it while i mean that to be the second parameter to the recursive call.

A: In your recursive call to apply-to-pairs you are calling arg1 instead of simply passing it as a value. That is, you have an extra set of parens around (arg1 (cdr (cdr arg2))). In full, what you want is
(define apply-to-pairs
  (lambda (arg1 arg2)
    (if (or (equal? (length arg2) 0) (equal? (length arg2) 1))
        '()
        (cons (arg1 (car arg2) (car (cdr arg2)))
              (apply-to-pairs arg1 (cdr (cdr arg2)))))))

Consider formatting your code across more lines so that it's easier to spot these bugs.


text:
Q: ERROR TypeError: Cannot read property 'items' of null. for displaying total quantity of items in my Shopping Cart I am having problems in displaying total number of items in my shopping-cart.I am getting data from firebase as an object and use one of its properties to get i.e 'quanity' to get total quanity of items and then displaing it on the ShoppingCart badge on my top navbar.
shopping-cart.service.ts
import { map, take } from 'rxjs/operators';
import { AdminProducts } from './models/admin-products';
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { ShoppingCart } from './models/shopping-cart';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {

  constructor(private db:AngularFireDatabase)  {
  }

  private create(){
    return this.db.list('/shopping-cart').push({
      dateCreated: new Date().getTime()
    });
  }

  async getCart(): Promise<Observable<ShoppingCart>> {
    let cartId = await this.getOrCreateCartId();
    return this.db
        .object('/shopping-carts/' + cartId).valueChanges()
          .pipe(map((x:any) => new ShoppingCart(x.items))); // Error: Cannot read property 'items' of null.
  }

  private getItem(cartId: string, productId: string){
    return this.db.object('/shopping-cart/' + cartId + '/items/' + productId);
  }

  private async getOrCreateCartId(): Promise<string> {
    let cartId = localStorage.getItem('cartId');
    if (cartId) return cartId;

    let result = await this.create();
    localStorage.setItem('cartId', result.key);
    return result.key;

  }

   addToCart(product: AdminProducts){
    this.updateQuantity(product, 1);
  }

  removeFromCart(product: AdminProducts){
    this.updateQuantity(product, -1);
  }

  async updateQuantity(product: AdminProducts, change: number){
    let cartId = await this.getOrCreateCartId();
    let item$ = this.getItem(cartId, product.key);
    item$.valueChanges().pipe(take(1)).subscribe((item) => {
      if (item) {
        item$.update({quantity: item['quantity'] + change});
      } else {
        item$.set({ product, quantity: 1 });
      }
    });
  }
}

shopping-cart.ts
import { ShoppingCartItem } from './shopping-cart-item';

export class ShoppingCart {
  items :ShoppingCartItem[];

 constructor(public itemsMap: { [productId:string]: ShoppingCartItem }) {
  this.itemsMap = itemsMap || {};
   for (let productId in itemsMap)
   this.items.push(itemsMap[productId]);
 }

  get totalItemCount(){
   let count = 0;
   for (let productId in this.itemsMap)
      count += this.itemsMap[productId].quantity;
    return count;
  }
}

shopping-cart-item.ts
import { AdminProducts } from "./admin-products";

export interface ShoppingCartItem {
  products: AdminProducts;
  quantity: number;
}

top-navbar.component
import { ShoppingCartService } from './../shopping-cart.service';
import { AutheService } from './../services/authe.service';
import { Component, OnInit } from '@angular/core';
import { ShoppingCart } from '../models/shopping-cart';
import { Observable } from 'rxjs';

@Component({
  selector: 'top-navbar',
  templateUrl: './top-navbar.component.html',
  styleUrls: ['./top-navbar.component.css']
})
export class TopNavbarComponent implements OnInit {
  cart$: Observable<ShoppingCart>;

  constructor(public authe: AutheService, private cartService: ShoppingCartService) {
  }

  async ngOnInit(){
    this.cart$ = await this.cartService.getCart();
  }
  logout(){
  this.authe.logout();
  }
}

top-navbar.component.html

    TheStore
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

    </button>

        <ng-template #anonymousUser>

            login

        </ng-template>

            Shopping Cart

              {{ cart.totalItemCount}}

            {{user.displayName}}

            My Orders
            Manage Orders
            Manage Products
            Log Out

      <form class="d-flex">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>


text:
Q: Ads with AdMob and Google Play Services Library doesnt show on device I have a problem with AdMob and Google Play Services that is driving me crazy for days. It feels like it's practically impossible to make this work. What is wrong with this implementation?
layout.xml (the code below goes in the bottom of the layout):
xmlns:ads="http://schemas.android.com/apk/res-auto"
...
    <LinearLayout
        android:id="@+id/layoutAd"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_marginTop="5dp"
        android:layout_weight="3"
        android:orientation="vertical" >

        <com.google.android.gms.ads.AdView
            android:id="@+id/adView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            ads:adSize="BANNER"
            ads:adUnitId="@string/ad_unit_id" />

    </LinearLayout>

MainActivity.java:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.AdSize;

...
adView = (AdView)this.findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR).
        addTestDevice("9234EBAE83E894E6271DEBE7B380782E").build();
adView.loadAd(request);

AndroidManifest.xml:
<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    ...
            <activity android:name="com.google.android.gms.ads.AdActivity"
                android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

LogCat:
Use AdRequest.Builder.addTestDevice("9234EBAE83E894E6271DEBE7B380782E") to get test ads on this device.

GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.

SQLiteLog: (14) cannot open file at line 30241 of [00bb9c9ce4]

SQLiteLog: (14) os_unix.c:30241: (2) open(/NotificationPermissions.db) -

The Ad never shows up but if I run it on the emulator, it does.
What am I dong wrong?

A: Try reading this and this... ;)

A: My suggestion Comment the code
addTestDevice("9234EBAE83E894E6271DEBE7B380782E").build();
and connect your mobile , make sure computer detects your phone
and run the project, your device should appears on the select device to run
Click ok
Hope this helpe
Final suggestion, if you using Eclipse, goto Project in top menu click on
many time this cleans junk data in workspace

A: Try using:
import com.google.android.gms.ads.*;

Instead of:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.AdSize;

This fixed some issues for me.


text:
Q: Should bounty be returned if there is NO answer at all? Should bounty be returned if there is NO answer at all? Or your contribution (to the bounty) only?
This is similar to many questions like this one (which was a duplicate itself), but I am referring to only when there is no answer at all. Not no upvotes - no answer.

A: As a compromise, what about refunding 50% of the bounty? The user did get increased exposure on the featured tab, but did not get a much-longed for answer. Refunding 50% sounds like a reasonable compromise.

A: Yes.  The bounty should be returned if no answers appear, I would also argue that this should be the case if no answers receive upvotes.  Not returning the bounty is intended to prevent gaming the system, however, if you don't get an answer that anyone thinks is any good, I think the bounty contributed by the asker should be returned to the asker when the bounty period expires.  Note that this wouldn't apply if there was an upvoted answer that also received downvotes to prevent the OP from gaming the system by downvoting an answer that would otherwise receive the bounty.
One argument against my position -- no answers or no answers with upvotes -- is that it encourages the OP to not vote for any answer that is helpful.  That only applies as long as no answer receives any votes, however, so I don't think that is a realistic objection.  If no one else votes for an answer, there is little reason to suspect that the OP should.

A: No.
Bounties are meant to generate interest in your question. If your question is low in the ranks, and you feel that you have already expressed yourself, then you add a bounty on it to encourage interest and people to answer.
Once you add the bounty, the rep is gone. If you are worried about getting no answers, you could increase the bounty to an even higher number, and at that point you can almost guarantee that someone will answer the question. But the bounties are meant to generate interest and answers. If there are still no answers after offering the bounty, it might be time to consider whether or not the question is too obscure to be answered.
Consider bounties to be paying for advertising. Once you've purchased an ad spot, you can't get your money back just because no one bought your product.
Obviously, we might want to consider changing the name since it doesn't act 'bounty-ish'.

A: I think a simpler solution would be to not let bounties expire if there is no answer (or maybe even no answer with an upvote).
This way, by creating a bounty question, you are going to lose points.   But you also have some sort of "guarantee" that you will eventually get a response for your "investment".

A: Yes, I think if you don't get any answers, you absolutely should get your rep back; you've paid for a service that wasn't delivered - that's a refund in anybody's book.
I asked a question (and I don't think it was a crap one - quite clear, but it perhaps is a bit tricky) that had very low views for a few days and so I've whacked a bounty on it.
Still, as yet, no answers, and the number of views hasn't gone up.
If after the 7 days I still get no answers, then I'm going to end up paying with rep because the community could not help.  So the SO message is "If your question is really difficult, and you incentivise the community to answer, but they can't, then you'll be penalised".
That roughly equates to "please ask only questions that somebody here knows the answers to".
If this Q of mine ends up getting a good answer now, then of course my comments here will be less relevant I suppose; however for those people that do ask good, bountied, questions but which nobody knows the answer to are being treated unfairly I think.

A: Adding this as an answer rather than a comment because I believe it should be part of the solution whatever the outcome:
The user interface for issuing a bounty should make it more clear exactly what the contract is.
Some may think, but it already says that!  I ask that we consider a tenant of UX design, which is that when a significant number users do not "get it" as they go through a scenario, the design should change. It could be better emphasized, positioned, worded, whatever.
The content of the many questions, comments, and responses on this topic suggest that lots of people don't pick up on this until after the fact, yet it would probably be a pretty cheap design change to really boost the success rate.
Then we get the payoff: If going forward almost everyone is clear on bounty rules, we will find that the average points allocated for bounties either drops or doesn't change much.  If drops, we can use this data to make a more intelligent decision on whether any of the bounty rules should change.

A: While it might sound superficially reasonable, I don't think it's likely to happen.  Most bounties acquire at least one answer before they expire, as bounty hunters hope that even a mediocre answer will get the 2 upvotes needed for an auto-accept.  Even if they don't, the question will then have answers.
Do you have examples of bounties that expired with no answer at all?

A: Yes they should, and since they aren't (and I wasn't aware of that), I don't think I'll ever place another bounty. I had a question with no activity whatsoever since placing a bounty, so the rep was a complete waste. Because of this, I think the bounty implementation is flawed.


text:
Q: What does "make us dream" mean? I am trying to understand what "make us dream" exactly means because a friend of mine asked me what it means in our language. Actually I know what it means but I just couldn't make a good translation for him.
It is a banner of Liverpool FC and the title of a book written by a fan as well.
How would you explain or paraphrase "make us dream" in English?
Thanks.

A: The meaning of "dream" is the second in Cambridge to imagine something that you would like to happen:
The banner is saying, from the point of view of the fans, "(By playing very good football) make us dream (that we might be able to win the championship)"
The "make us" is used instead of "let us" as it is more forceful and more hopeful.


text:
Q: How to prevent XmlSerializer from escaping < and > characters I use an XlmSerializer to serialize a dotnet object.
One property of the dotnet object is a string with this value:
"<![CDATA[
No Comments
]]>"
Once serialized to a StringWriter, all the < and > characters are converted to < and > including the CDATA's.
How could I stop that from happening ?

A: Don't put the CDATA in - that's the serializer's job. You've just told the serializer to make a valid XML out of the CDATA string. It does exactly that - after deserialization, you're still left with <![CDATA[
No Comments
]]>. That's exactly what you asked for! And more importantly, it's exactly what you want the serializer to do with the data - otherwise you'd be opening yourself to a world of hurt, because you'd need to ensure that the data is actually secure. In essence, you're performing double encoding.
Instead, just put
No Comments
 there - and the serializer will handle the escaping for you, to make sure it's valid XML that actually deserializes to
No Comments
.


text:
Q: Fanfic where Hermione leaves the Wizarding World, pregnant with Harry's baby, and comes back when their son starts his first year I think it's about 18 chapters long. I could be wrong, but the gist was that Hermione got pregnant during the war and was waiting to tell Harry after they'd defeated Voldemort, because she didn't want to pressure him.
Anyways, fast forward to after the war, she was coming around to tell him when she saw Harry and Ginny lip-locking on the school field; needless to say, she left that night and never looked back.
The Wizarding World never stopped looking for her, spearheaded by Harry, who kept looking for her even after everyone else gave up. Eleven years later, Hermione came back with a son and she uses her mother's maiden name and goes by Hermione Watson instead of Hermione Granger.
Harry runs a top-secret wizarding operation and was given the opportunity to work for the school. He took it and unknowingly becomes close with his son. Hermione was kidnapped, then Harry rescued her and was furious that she kept his son away from him.

A: As per this Reddit post, found via a search for fanfic hermione "harry's son", might this be "Sempre Fidelis" by Untold Harmony?

She left years ago after he saved the wizarding world from the hands of Voldemort. She never thought she would be back again... until her son got his letter to Hogwarts.

She's hiding under the name of Jane Watson. Her son is named James. And your memory is correct about the Quidditch pitch.

Hermione told herself she would tell Harry of their baby the day after The Defeat. But then she found him at the ruined Quidditch pitch with his lips locked with Ginny Weasley and their arms wrapped tight around one other.

It looks like it ceased updating in 2020 with 17 chapters.


text:
Q: Google Analytics Tracking on button click (in-page search) How can I incorporate Google Analytics In-Page search tracking via my following search code (which is set to google search "KEYWORDS site:MYDOMAIN.com"?
The issue I face is that hitting Enter causes the user to immediately jump to google for the search query. I've seen some bits and pieces of using hitCallback but I'm unsure of how to implement this on a page of this setup.
<form action="http://www.google.com/search" name="searchbox";
method="get" id="searchform" class="form-search">;
<input type="hidden" name="hl" value="en" />;
<input type="hidden" name="ie" value="ISO-8859-1" />;
<input type="hidden" name="sitesearch" id="s" value="MYDOMAIN.com" />;
<input maxlength="256" size="40" name="q" class="search" value="" />;
</form>

I'm aware I can't use the traditional in-page search offered by the new Universal Analytics but I don't see why there shouldn't be a way to, on submit, submit to GA prior to leaving my domain for the google search page. And in thinking through things I believe one could redirect to another page, submit the GA, then redirect to google but I'd certainly like to minimize my requests and come up with a straightforward solution.

A: You could remove the action from the form and set it with jQuery after putting a timeout on it to let the GATC fire. Something like this:
$('#searchform').on('submit', function(e){
    e.preventDefault();
    window.setTimeout(function(){
        if (typeof _gaq != 'undefined') {
            _gaq.push(['_trackEvent', 'Search', 'value', 'paramX', 'valueY', false]);
        }

        $('#searchform').attr('action', 'http://www.google.com/search');

    },1000);

});

A:     <script>

    $("#searchform").submit(function (event) {

        event.preventDefault(); // cancel default behavior

        var searchTerms = $('input[name=q]').val();
        searchTerms = searchTerms.replace(" ", "+");
        console.debug(searchTerms);
        ga('send', {
            'hitType': 'pageview',
            'page': "http://MYDOMAIN.com/search?hl=en&ie=ISO-8859-1&sitesearch=MYDOMAIN.com&q=" + searchTerms,
            'title': 'Google Search'
        });
        setTimeout(function () {
            window.location.href = "http://google.com/search?hl=en&ie=ISO-8859-1&sitesearch=MYDOMAIN.com&q=" + searchTerms;
        }, 500);

    });

     </script>

The best method I found to achieving a pseudo in-site-search (delivered via google search) despite visiting an external domain was to cause a fake page view prior to redirecting to the correct search page. I inserted a half-second delay to ensure the page view was sent prior to redirect.


text:
Q: Jquery changing table th tag is not working properly I have tried to implement resizable table columns as follow
function mousemove(event) {
            var parent = $element.parent();
            var next = parent.next();
            var th = parent.parent();

            var oldParentWidth = $(parent).width();
            var oldNextWidth = $(next).width();
            var totalWidth = oldParentWidth + oldNextWidth;
            var newParentWidth = event.pageX -$(parent).offset().left;
            if( newParentWidth > totalWidth )
                return;
            if(  newParentWidth >= oldParentWidth ) {
               $(next).css({
                    width: (totalWidth - newParentWidth) + "px"
                });

                $(parent).css({
                     width: totalWidth - $(next).width() + "px"
                 });
            } else {
                $(parent).css({
                    width: newParentWidth + "px"
                });
                $(next).css({
                    width: (totalWidth - $(parent).width()) + "px"
                });

            }

        }

The working demo is here: http://jsfiddle.net/4kc873ec/3/
When I am trying to resize the width of th its not working properly first time. Then after it is working correctly. After that it is working properly. What am I doing wrong?
Thanks in advance.

A: Try changing bind with on
$('.resizeBar').on('mousedown', function(event) {
               event.preventDefault();
            $element = $(this);
            $(document).on('mousemove', mousemove);
            $(document).on('mouseup', mouseup);
        });


text:
Q: Appending .aac files in Java/Android I'm fairly new to working with audio files in Java and fairly new to Android (I know some basics).
I have two .aac files recorded using MediaRecorder and I needed to merge the two after a recording has taken place. I figured I'd attempt it in Java first and then move it over to Android since a lot looks pretty similar?
I was wondering what is the best way to achieve this? So far I've converted the .aac files to byte arrays and merging these however this only produces the first file (from the first byte array) with a bigger file size and no extra audio.
I thought perhaps this is due to audio headers? Should I find a way to target these bytes and remove them from the second (if so is there a documentation explaining where the header is?)
Alternatively I've also read about using .wavs and instead of using MediaRecorder use AudioRecord, create two PCM's, concatenate and then convert to .wav? Would I be able to then convert that .wav to .aac?
What is the fastest way of implementing this? Does anyone have any extra documentation that could help?

A: Thanks to Gabe, sending me down the right course.
In the end I ditched working with .aac's and attempting to remove headers. I used AudioRecord to record .pcm files, then concatenated these and saved as a .wav.
I did struggle with the sound sounding fast forwarded and distorted and initially thought it was down to the sample rate, it turns out I was converting between short to byte which was losing information, thus speeding up and the reason for the distortion.
Hope this helps someone, I might end up adding some .aac encoding library to reduce the size.
Some links I found helpful on my journey.
https://github.com/newventuresoftware/WaveformControl
Android AudioRecord example
How to convert .pcm file to .wav or .mp3?
http://www.topherlee.com/software/pcm-tut-wavformat.html


text:
Q: GWT RequestFactory: how to handle entities with composite primary keys Can RequestFactory handle composite primary keys?
The documentation mentions that entities must implement getId(); how should this be implemented in the case where entities do not have a single "id" field, but rather have multiple foreign key fields that together constitute a composite primary key?

A: In GWT 2.1.1, the Id and Version properties may be of any type that RequestFactory knows how to transport.  Basically, any primitive type (int), boxed type (Integer), or any object that has an associated Proxy type.  You don't have to reduce a composite id to a String yourself; the RF plumbing can take care of composite keys automatically by using the persistent id of an entity-type key or the serialized state of a value-type key.
Using the previously-posted example:
interface Location {
  public String getDepartment();
  public String getDesk();
}

interface Employee {
  public Location getId();
  public int getVersion();
}

@ProxyFor(Location.class)
interface LocationProxy extends ValueProxy {
  // ValueProxy means no requirement for getId() / getVersion()
  String getDepartment();
  String getDesk();
}
@ProxyFor(Employee.class)
interface EmployeeProxy extends EntityProxy {
  // Use a composite type as an id key
  LocationProxy getId();
  // Version could also be a complex type
  int getVersion();
}

If you can't reduce the identity to a single getId() property on the domain type, you can use a Locator to provide an externally-defined id and version property. For example:
@ProxyFor(value = Employee.class, locator = EmployeeLocator.class)
interface EmployeeProxy {.....}

class EmployeeLocator extends Locator<Employee, String> {
  // There are several other methods to implement, too
  String getId(Employee domainObject) { return domainObject.getDepartment() + " " + domainObject.getDesk(); }
}

The DevGuide linked from the question is a bit out of date with respect to
RequestFactory changes in 2.1.1


text:
Q: Posix Semaphore compilation error using the -lrt
Possible Duplicate:
sem_open() error: "undefined reference to sem_open()" on linux (Ubuntu 10.10)

Having issues with compilation of posix semaphores. My goal is to create a shared memory segment and protect it by semaphores. shared memory works fine but semaphores code gives me compilation errors even though I included semaphore.h and added -lrt to compilation flags
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <time.h>

int main (int argc, char** argv) {
    FILE *configFile;
    int i,j;

    int CashDesksNo=0;
    int maxCashDesksNo;
    int n,m;
    int TmaxServe;
    int custPerc; //customer ratio policy
    int maxCapacity;

    char * nlptr=NULL;
    char * pch=NULL;
    char line[125];

    char termInput[30];
    char tmpString[40];

    int flg1,flg2;
    int flag;

    int execResult=0;
    int fd;
    int rc;

    int randNum;

    int status;
    pid_t ch_pid;

    int a,b,c;
    int shmid=0;
    int *shm_ptr;
    int * err;

    int retval;
    sem_t *sp;
    char semName[10];

    strcpy(semName,"mutex");
    //---------- Davasma kai elegxos in line parameters-----------------
        //    read inline params and config file
                              .
                              .
                              .

    //------------ Print Configuration Data ----------------------------
    if(CashDesksNo>maxCashDesksNo || CashDesksNo<1)
    {
        printf("\n# of Cash Desks should be between 1 and %d",maxCashDesksNo);
        printf("\nsupermarket will now exit...\n");
        exit(1);
    }

    printf("\n//-----------------------------------------------");
    printf("\nSupermarket initialization");
    printf("\n# of Cash Desks: %d",CashDesksNo);
    printf("\n# of max products: %d",n);
    printf("\nMax price: %d",m);
    printf("\nMaximum serving time(secs): %d",TmaxServe);
    printf("\n%% Customer/Cashier Percentage: %d/%d",custPerc,100-custPerc);
    printf("\nMax Supermarket capacity: %d",maxCapacity);
    printf("\n//-----------------------------------------------\n");

    printf("\nAbout to create customer and cashier processes");

// ----------- Shared Memory Attachment --------------------------------
shmid=shmget(IPC_PRIVATE,sizeof(int*),0666);

if (shmid < 0)
{
    perror("shmget");
    exit(1);
}

shm_ptr=(int*)shmat(shmid,(void *)0,0);

if (shm_ptr == (int *)(-1))
{
    perror("shmat");
    exit(1);
}

a=0;    //shm
shm_ptr=(int*)a;
printf("shmPtr:%d",(int)shm_ptr);

// ----- create & initialize semaphore ---------------------------------

  sp = sem_open(semName,O_CREAT,0644,1);
  if(sp == SEM_FAILED)
    {
      perror("unable to create semaphore");
      exit(-1);
    }

    while(1)
    {
        printf("\nPress enter to start a new day at the supermarket(type exit to quit)\n");
        fgets(termInput,sizeof(termInput),stdin);

        nlptr = strchr(termInput, '\n');// termatismos string
        if (nlptr) *nlptr = '\0';

        if(strcmp(termInput,"exit")==0)//exit apo tin efarmogi
        {
            printf("\nExiting Supermarket..\n");
            exit(0);
        }

        i=0;
        while(i<maxCapacity)
        {

            //-Fork new process for the simulation --------------------

            ch_pid = fork();

            if (ch_pid == -1) {
            perror("\nFailed to fork initial spliter/merger process  \n");
            exit(1);
            }

            if ( ch_pid == 0 ) //this is the child process
            {
            srand (getpid());//pid based seed

            // "itoa" - Metatropi ari8mou se string
            sprintf( tmpString, "%d", shmid );

            randNum=rand() % 100 + 1;
            if(randNum<custPerc)// customer : cashier ratio
            {
                execResult=execl("customer","customer","0",tmpString,NULL);
                //printf("\nCreated a customer,randNum %d",randNum);
            }else
            {
                execResult=execl("cashier","cashier","0",tmpString,NULL);
                //printf("\nCreated a cashier,randNum %d",randNum);

            }

                if(execResult==-1)
                {
                    perror("Could not perform exec to create cashier/customer process");
                }

            }
        i++;
        }

        //Root process
        //wait for childs to terminate
                for (i = 0; i < maxCapacity; ++i)
                {
                    waitpid(-1,&status,0);
                }
        printf("supermarket shared memory content: %d",(int)shm_ptr);
        sem_close(sp);
        sem_unlink(semName);

        err = (int*)shmctl(shmid, IPC_RMID, 0);
        if (err == -1)
            perror ("Shared Memory Removal.");
        else
            printf("Shared Memory Removed. %d\n", (int)(err));

    }

}

this is the makefile:
OBJS    = supermarket.o cashier.o customer.o
SOURCE  = supermarket.c cashier.c customer.c
HEADER  = struct.h
OUT     = supermarket cashier customer
CC  = gcc
FLAGS   = -lrt -g -c
LIBS    = -lm
# -g option enables debugging mode
# -c flag generates object code for separate files
# -lm math library

all: supermarket cashier customer

supermarket: supermarket.c
    $(CC) supermarket.c -o supermarket

cashier: cashier.c
    $(CC) cashier.c -o cashier

customer: customer.c
    $(CC) customer.c -o customer

# clean house
clean:
    rm -f $(OBJS) $(OUT)

# do a bit of accounting
count:
    wc $(SOURCE) $(HEADER)

I keep getting this error:
george@george-System-Product-Name:~/Desktop/prj3$ make
gcc supermarket.c -o supermarket
supermarket.c: In function 'main':
supermarket.c:310:11: warning: comparison between pointer and integer [enabled by default]
/tmp/ccYxA2Wi.o: In function `main':
supermarket.c:(.text+0x75c): undefined reference to `sem_open'
supermarket.c:(.text+0x9b0): undefined reference to `sem_close'
supermarket.c:(.text+0x9bf): undefined reference to `sem_unlink'
collect2: ld returned 1 exit status
make: *** [supermarket] Error 1

what can i do?
this is a project for operating systems class, my system is linux Ubuntu

A: I think you should link against pthread as well:
-lpthread

Example makefile from an old project of mine (see comments):
CC=gcc
CFLAGS=-c -Wall -O3 -g
LDFLAGS=-pthread
SOURCES=chatzor.c clientlist.c messagequeue.c
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=chatzor_server

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

.cpp.o:
        $(CC) $(CFLAGS) $< -o $@

clean:
    rm -rf *.o ${EXECUTABLE}

A: You're going to have sore shins once you're done with this.
The compilation trace says:
$ make
gcc supermarket.c -o supermarket
supermarket.c: In function 'main':
...

Your makefile says:
supermarket: supermarket.c
    $(CC) supermarket.c -o supermarket

It should say (at minimum):
supermarket: supermarket.c
    $(CC) supermarket.c -o supermarket $(LIBS)

Indeed, it should probably be saying:
supermarket: supermarket.c
    $(CC) $(CFLAGS) supermarket.c -o supermarket $(LDFLAGS) $(LIBS)


text:
Q: NoSuchElementException when using Scanner This code is calculator for prifix.
first input means number of line to calculate,
and then input expression.
e.g)
2\n
12+3*\n
31/2-4*2+\n
And It works well in eclipse but did not work in scoring site.
Scoring site said that

Exception: java.util.NoSuchElementException Maybe at: at
  Calculation.main(Calculation.java:16)
line 16 is 'String string=scan2.nextLine();'

But I cannot find out where is wrong.
    import java.util.*;
    public class Calculation{

        public static void main(String[] args){

            System.out.print("Enter a number: ");
            Scanner scan1=new Scanner(System.in);
            int n=scan1.nextInt();

            ArrayList<String> input=new ArrayList<String>();

            for(int i=0;i<n;i++){

                System.out.print("Enter a expression in postfix: ");
                Scanner scan2=new Scanner(System.in);
                String string=scan2.nextLine();
                input.add(i,string);

            }

            Stack<Integer> stack=new Stack<Integer>();

            for(int i=0;i<=input.size()-1;i++){
                for(int j=0;j<=input.get(i).length()-1;j++){
                    if(input.get(i).charAt(j)>=48&&input.get(i).charAt(j)<=57)
                        stack.push(Integer.parseInt(input.get(i).valueOf(input.get(i).charAt(j))));
                    else{
                        int n2=stack.pop();
                        int n1=stack.pop();

                        if(input.get(i).charAt(j)=='+')
                            stack.push(n1+n2);
                        if(input.get(i).charAt(j)=='-')
                            stack.push(n1-n2);
                        if(input.get(i).charAt(j)=='/')
                            stack.push(n1/n2);
                        if(input.get(i).charAt(j)=='*')
                            stack.push(n1*n2);
                    }

                }

                int output=stack.pop();
                System.out.println(output);
            }

        }

    }

A: the thing is when you use
String str=scan1.nextLine();

it will only read your input until space after that it won't so to read a string input just use
String str=scan1.next();

A: Read a full line to stay in sync with line endings. Don't use another scanner.
  int n=scan1.nextInt();
  scan1.nextLine();
  ArrayList<String> input=new ArrayList<String>();
  for(int i=0;i<n;i++){
       System.out.print("Enter a expression in postfix: ");
       String string=scan1.nextLine();
       input.add(i,string);
  }

A: When you're doing scan2.nextLine(); previous line break after nextInt() was not processed that's why that newline character still in buffer got read through your scan2.nextLine() instead of your new input.
You can handle it two ways -

*

*Do an empty scan1.nextLine() immediately after that first nextInt() call.

*or Instead of using nextInt(), use nextLine() and using Integer.parseInt() convert that string to integer.


text:
Q: How to call a local variable into another function using PHP I am in PHP,
I have 3 Functions in PHP.
Function No 1:
    function get_main_sector($segment_id)
        {
            $dbCon = new dbCon();
            $connect = $dbCon->connect();

            $result = mysql_query($qry);
            while($row = mysql_fetch_object($result))
            {
                $sourcem[] = $row;
            }
            mysql_free_result($result);
            $disconnect = $dbCon->disconnect();
            if(isset($sourcem))
                return $sourcem;
            else
                return ;
        }

Function No 2:
function getSector($sector_id)
        {
            $dbCon = new dbCon();
            $connect = $dbCon->connect();

            $result = mysql_query($qry);
            while($row = mysql_fetch_object($result))
            {
                $sourcem[] = $row;
            }
            mysql_free_result($result);
            $disconnect = $dbCon->disconnect();
            if(isset($sourcem))
                return $sourcem;
            else
                return ;
        }

Function No 3:
function getopinions($opinions)
        {
            $dbCon = new dbCon();
            $connect = $dbCon->connect();

            $result = mysql_query($qry);
            while($row = mysql_fetch_object($result))
            {
                $sourcem[] = $row;
            }
            mysql_free_result($result);
            $disconnect = $dbCon->disconnect();
            if(isset($sourcem))
                return $sourcem;
            else
                return ;
        }

My Problem is that i want to use the variable of Function 1 and Function 3 in my Function 3 as i use in a query of Function 3. But Variables of Function 2 and Function 3 is local.
Can i call these variables in Function 3 or not? If yes then can you please tell me how i can do it?
UPDATE:
I call my first Function as:
if(isset( $_REQUEST['segmentID']))
{$segment_id = $_REQUEST['segmentID'];}
else {$segment_id=0;}

if(isset($segment_id) && $segment_id!=0)
{
    $main_sectors = $cont->get_main_sector($segment_id);
    echo '<select name="main_sector_id" id="main_sector_id" STYLE="width: 300px" onchange="get_sector(this.value);">';

echo '<option value="">[--Select Team----]</option>';

    if(is_array($main_sectors ) && !empty($main_sectors ))
    {
        foreach($main_sectors  as $main_sector)
        {
            echo '<option value="'.$main_sector->ID.'">';

            echo $main_sector->title;

            echo '</option>';
        }
    }

echo '</select>';

    die;
}

A: You have to declare your variables outside from your functions, and then use these variables inside your functions as a global variables. See here how to do it:
http://php.net/manual/language.variables.scope.php


text:
Q: Let $f$ be continuous such that $\lim_{x\to \infty}f(x)/x<1$ Prove that there exists $c$ satisfying $f(c)=c$ Let $f$ be a continuous and nonenegative function on $I=[0,\infty)$ such that $$\lim_{x\to \infty}\frac{f(x)}{x}<1$$
Prove that $\exists c\ge 0$ s.t. $f(c)=c$
Let $g(x)=f(x)-x$, note that $g$ is continuous on $I$ and $g(0)\ge 0$. Now we need $b$ such that $g(b)\le 0$ to apply the intermediate value theorem.
Let $$\ell =\lim_{x\to \infty}\frac{f(x)}{x}<1$$
This means $\forall \epsilon>0, \exists N>0$ such that $$x>N \implies \left| \frac{f(x)}
{x}-\ell \right|<\epsilon$$
Thus
$$x\ell -x(\epsilon +1)<g(x)<x\epsilon +x(\ell -1)$$
Here we have two methods. The first one is from my teacher which says, set $\epsilon =1-\ell $, $$2x(\ell-1)<g(x)<0\quad \forall x>N$$
Now just take $b=N+1$ and we're done by the intermediate value theorem. But here's my method ,
Assume $\forall x>0\quad g(x)>0$. Therefore $0<g(x)<x\epsilon +x(\ell -1)$ meaning $$1<\frac{f(x)}{x}<\epsilon +\ell \quad \forall x>N$$
Hence $$\lim_{x\to 0}\frac{f(x)}{x}\ge 1 $$
Contradiction. Am I right?

A: You could also note that $$\lim_{x\to\infty}\frac{g(x)}{x}=\lim_{x\to\infty}\frac{f(x)}{x}-1<0$$ and use $g(0)\geq0$ to complete the IVT argument. (NOTE: We separated the limits only because of prior information that the limit $\displaystyle\lim_{x\to\infty}\frac{f(x)}{x}$ exists).


text:
Q: Adding and removing elements from useState hook with React I'm trying to implement an add/remove fields from an array. I have my state hook setup, and should be able to click the add button to add a number to the emails array. It should then loop through the array of emails, and render an input for every value in the array. Each button looped over should have a remove button that removes it's specific value from the array.
I'm not able to add or remove elements:
const [emails, setEmails] = useState([]);

function RemoveEmail(i){
  const index = emails.indexOf(i);
  emails.splice(index, 1)
}

{emails.length > 0 && emails.map((email, i) => <p>{email}<button onClick={() => RemoveEmail(i)}>Remove</button></p>)}
<Button variant="outlined" size="small" onClick={() => setEmails(emails + 1)}>+ Add another</Button>

Update
Modified the add button so I can add values, but can't get the slice to remove a given element from the array:
<Button variant="outlined" size="small" onClick={() => setEmails([...emails, 1])}>+ Add another</Button>

A: There are a couple of things which are incorrect in your code.

*

*Setting state directly using the old emails state.

setEmails(emails + 1) this is not the correct way to update the state for the new emails.

*Also removal of the emails is something I believe is incorrect as well.

For such a case when you need to implement adding a new value to the array and deleting it as well while managing the state, try to use a unique identifier.
I have created a working sandbox for you to refer here. Please tweak it as per your convenience.
On how to set state using the previous state value as well, refer to this link.


text:
Q: google.cloud.bigquery error in app engine On local development app-engine server(and on production app engine), I want to run a script which has big-query related code, but I am getting an error. I have already visited all the answers related to this error in stackoverflow but did not find anything workable. following is the code and error that occurred. Thanks in advance for your precious time.
Code
#!/usr/bin/python
from google.cloud import bigquery
client = bigquery.Client('myproject')
query = '(SELECT *FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY tb1.user_id ORDER BY tb1.timestamp DESC) AS RowNo FROM `mytable` tb1) x WHERE x.RowNo = 1)'
job_config = bigquery.QueryJobConfig()
job_config.allow_large_results = True
job_config.destination = dest_table_ref
job_config.write_disposition = 'WRITE_TRUNCATE'
query_job = client.query(query, job_config=job_config)

When I hit the url (http://myproject:8080/cronscript) I get following errors
Error

File "/home/username/src/project-name/python_reporting-2017-12-15-10-37/cronscript.py", line 3, in
      from google.cloud import bigquery
    File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime/sandbox.py", line 1132, in load_module
      raise ImportError('No module named %s' % fullname)
  ImportError: No module named google.cloud.bigquery

However, when I open python shell by typing python
and then if I type

from google.cloud import bigquery
it works fine.
      If I run python cronscript.py it also gets executed properly
          $ python cronscript.py
          Done
          $

Only when I execute this from a local app server after performing dev_appserver.py app.yaml
I receive above error.
What all I have already tried
1) sudo pip install --upgrade google-cloud-bigquery
2) my requirements.txt look like
    google-api-python-client
    google-cloud
3) pip install -t lib/ requirements.txt
4) from google.appengine.ext import vendor
   vendor.add('lib')
5) from __future__ import absolute_import

Still unresolved.

A: It looks like you don't have this module. So, did you try to install/upgrade your google cloud?
sudo pip install --upgrade google-cloud-bigquery


text:
Q: Delete leading characters from multiple lines with Notepad++ I have txt-file with 299516 lines - don't ask why!
I need to remove all 110 leading characters from each line, save the next 5 characters and delete the rest of line.
I can do it in EXCEL with "MID()" in the English version.
Unfortunately, Notepad++ does not support repetition counts like ^.{27}
Hints:
http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Regular_Expressions
http://blog.creativeitp.com/posts-and-articles/editors/understanding-regex-with-notepad/

A: Actually, it does as of version 6 (the old regex library that was previously used was replaced with PCRE). Those articles are now out of date.
Using the latest version of Notepad++, find:
^.{110}(.{5}).*$

Replace with:
\1


text:
Q: Arithmetic with void pointers in C++ I need to access an object in a buffer, pointed by a void pointer. The object is located at a certain offset but since arithmetic on a void pointer is prohibited how can I access the object?

A: You can cast the pointer to char* (+1 on such pointer is offset by one byte) or any other pointer type if that suits your needs better.
However, this approach is grossly error prone! You better check your design, something smells here! void* are in 99% of cases unnecessary in C++, designs that use them are usually more "C" than "C++". Remember, templates and inheritance should be the way to do these things.


text:
Q: Owl Carousel Transitions Effect Not Working After Chrome Latest Update (V36) i'm using the OWl carousel for a while everything were perfect but recently i faced a issue after my chrome browser update. The css transition effects are not working anymore on chrome.
But all effects working fine on firefox.
Anyone can help me..

A: In version 1.3.3 replace this:
support3d = (asSupport !== null && asSupport.length === 1);

in line 804 with this:
support3d = (asSupport !== null && asSupport.length >= 1 && asSupport.length <= 2);

Then it should work out just fine!

A: I have found the Solution friends.
Here is that..
Replacing the below line of code
support3d = (asSupport !== null && asSupport.length >= 1 && asSupport.length <= 2);
instead of
support3d = (asSupport !== null && asSupport.length === 1);
This Solved My Problem. Now CSS Transitions Working Fine on All Browsers.

A: For the convenient, I've created a branch for it, easy to merge, easy to download:
https://github.com/lib-issue/OwlCarousel/tree/stackoverflow_25153801
It's possible to use:
support3d = (asSupport !== null && asSupport.length !== 0);

as well.

A: I was an issue in the Owl.Carousel 2 version. The carousel does't work in Chrome. Then I added this line in my script. The slider is now working fine in all browsers on my end.
Please add var $ = jQuery.noConflict(); in your script file.
ex.
var $ = jQuery.noConflict();
$(document).ready(funnction() {

//your script goes to here

});


text:
Q: Mysql update shift column values Yo guys. I have got 3 rows in my table news (image_1, image_2, image_3). Can I swap them like that? Because this part of code doesn't work.
mysql_query("update news
             set image_1=image_2,
                 image_2=image_3,
                 image_3=''
             where image_1=$_GET[deletephoto]");


text:
Q: Referring to Environment Variables in Swift Does anybody know how I can grab an environment variable in Swift?

A: Along with the NSProcessInfo-based method mentioned by Oleg, you can access environment variables using the the standard C getenv function, like so:
Swift 2.x:
func getEnvironmentVar(name: String) -> String? {
    let rawValue = getenv(name)
    guard rawValue != nil else { return nil }
    return String(UTF8String: rawValue)
}

Swift 3.0:
func getEnvironmentVar(_ name: String) -> String? {
    guard let rawValue = getenv(name) else { return nil }
    return String(utf8String: rawValue)
}

It's also possible to set environment variables using the setenv function:
func setEnvironmentVar(name: String, value: String, overwrite: Bool) {
    setenv(name, value, overwrite ? 1 : 0)
}

The reason I mention the ability to set variables is because it's the only way I know of to set variables when working in an Xcode Playground.
I recently wanted to see a backtrace for a strange CGContext error I was getting when working with a "live" view in a playground. By default, the backtrace isn't shown in the console, so I had to set the CG_CONTEXT_SHOW_BACKTRACE environment variable to see what was up:
setenv("CG_CONTEXT_SHOW_BACKTRACE", "1", 1)

After that, it was smooth sailing. Well, other than the CGContext error I was getting, but that's a topic for another day.
Hope this helps!
P.S. The above functions require the Darwin module to be imported. Foundation automatically imports Darwin, but I thought I should mention it nonetheless.

A: Yes it is possible. Use ProcessInfo for that.
Simple example :
let dic = ProcessInfo.processInfo.environment
if dic["VAR"] != nil {

}

A: Since Swift 3 NSProcessInfo has been renamed to ProcessInfo.
And method processInfo() has been replaced with property processInfo.
import Foundation

for (key, value) in ProcessInfo.processInfo.environment {
    print("\(key): \(value)")
}

A: Swift 3 and up:
import Foundation

if let value = ProcessInfo.processInfo.environment["KEY"] {
    ...
}

A: A Vapor specific solution:
From the code which Vapor automatically A Vgenerates as a project template:
let variable = Environment.get("VARIABLE") ?? "or-the-dafault"


text:
Q: How to display Django friendly forms.ValidationError/message.error before form.save? I would like to know how to display Django message.error before form.save(if user get that error message, the form won't be saved, user have to fill value in form again).
I don't know whether I put them at wrong place or anything else reason, I can definitely get the right value about for loop and if else, but if a user's work_times >= 8 hours, page didn't display that error message, and project can save like before, but I did add for loop and if else!! The partial code of views.py is like this:
class ProjectCreateView(CreateView):
    model = Project
    form_class = ProjectForm

    def form_valid(self, form):
        request = self.request
        for u in user_project:
            user_times = int(sum(t['learn_times'] for t in times))
            if user_times >= 8 or int(request.POST.get('learn_times')) + user_times >= 8:
                messages.error(self.request, u.username + "'s learn_times is more than 8 hours, please check!")
            else:
                pass
        project = form.save(commit=False)
        project.save()
        form.save_m2m()

        messages.success(self.request, 'Project created successfully!')
        return super(CoursePermitCreateView, self).form_valid(form)

    def get_success_url(self):
        return reverse('project_change', kwargs={'pk': self.object.pk})

Thanks so much for any advice.

A: You don't do this in form_valid - as the name implies, by that point the form is already considered to be valid. In fact you don't do it in the view at all. This sort of thing belongs in the form, specifically in the clean() method of ProjectForm. There you can raise forms.ValidationError with your message; the view will then do the right thing and redisplay the invalid form.

A: The general approach to make a form submit invalid, is to render the given form with errors.
You can either send some necessary data to the form and customise the form's clean method...
import forms

class Projectform(forms.ModelForm):
    def __init__(user_project, request, *args, **kwargs):
        self.user_project = user_project
        self.request = request
        super().__init__(*args, **kwargs)

    def clean(self, *args, **kwargs)
        for u in self.user_project:
            user_times = int(sum(t['learn_times'] for t in times))
            if user_times >= 8 or int(self.request.POST.get('learn_times')) + user_times >= 8:
            raise forms.ValidationError(u.username + "'s learn_times is more than 8 hours, please check!")
        return super().clean(*args, **kwargs)

... or you can customize the form_valid method of the view and re-render the form with the new error message.
class ProjectCreateView(CreateView):
    model = Project
    form_class = ProjectForm

    def form_valid(self, form):
        request = self.request
        for u in user_project:
            user_times = int(sum(t['learn_times'] for t in times))
            if user_times >= 8 or int(request.POST.get('learn_times')) + user_times >= 8:
                form.add_error('__all__', self.request, u.username + "'s learn_times is more than 8 hours, please check!")
                return super().form_invalid(form)

    messages.success(self.request, 'Project created successfully!')
    return super().form_valid(form)

The errors will appear {{ form.non_field_errors }} in the template.

A: While using the answer above by Tobias and pass pk as a variable in method
test=Test.objects.get(pk=self.pk)


text:
Q: Prior pdf decay in Recursive Bayesian Estimation I'm doing Recursive Bayesian Estimation numerically. I have a state vector, x, that I'm trying to estimate by regularly taking noisy measurements, z.
I use Posterior = Likelihood x Prior / Normalization, or:
$$P(x_n|z_{1:n}) = \frac{P(z_n|x_n)P(x_n|z_{1:n-1})}{P(z_n|z_{1:n-1})}$$
I can also use the Chapman-Kolmogorov equation to get
$$P(x_n|z_{1:n-1})=\int{P(x_n|x_{n-1})P(x_{n-1}|z_{1:n-1})dx_{n-1}}$$
Together these 2 equations give me a way of recursively calculating the posterior at the current step, n, given all the information preceding step n.
However, it seems that every time step is given equal weight because if you unroll all the recursive equations, you just get a huge chain of products of various probabilities all multiplied together and not weighted in any way at all. Physically, this is silly because more current information should be weighted more heavily.
So my question is, on every time step, can I raise the prior pdf to an arbitrary fractional power, k, between 0 and 1 to weight it differently? As follows:
$$P(x_n|z_{1:n}) = \frac{P(z_n|x_n)P(x_n|z_{1:n-1})^k}{Normalization}$$
I think that doing this on every time step will mean that the older prior distributions are sequentially raised to the k for as many timesteps as they have been used. In other words, with 0 < k < 1, there will be some exponential decay of the prior pdf so that the estimator places more emphasis on recent probabilities.
For example, if I use k= 0, the posterior is identical to the likelihood, i.e. my recursive Bayesian filter has no memory at all and completely ignores the prior distribution (I realize this would be dumb to do, but this is just the limit that k goes to 0). On the other hand, k=1 gives the usual equations without any modification. The interesting region is with k a little less than 1, so that the prior pdf experiences slight exponential decay.
I realize that you cannot just take a pdf and raise it to a power and expect that it is still a probability distribution. However, numerically, my likelihood and prior are just 2D matrices that are multiplied elementwise, and there is a normalization factor that is calculated at each time step that takes care to make it a pdf again.
My question is if raising to the kth power will have the desired effect of placing more emphasis on the recent pdfs and less on older ones. Also, if there is a better way of incorporating memory into the recursive Bayesian estimation equations please let me know. Thanks.


text:
Q: Trying to convert input string to integer in Swift I am trying to write a program that takes a number input from user and stores it into a string, then i am trying to convert that string to integer for further use. Whenever i convert it, it displays nil for the integer value but will print the input when kept as a string. Here is my code so far. This is my first time trying to write in swift.
import Foundation

func input() -> String{
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding:NSUTF8StringEncoding) as! String
}

print("What is a number: ")

let user: String? = input()
print("You typed: " + user!)

var num = Int(user!)
print("Your number was" ,(num))

A: The Int function returns an optional integer, so if your string can't be converted it will return nil. If you assign it a value that it can convert, you'll get the result you're looking for:
let user: String = "5"
var num = Int(user)

if let num = num {
    print("Your number was \(num)")
} else {
    print("Your number is nil")
}

Also, your input function is returning a String, but you're defining the user variable as an optional String?

A: After searching around and trying different things, I was able to do exactly what I wanted after doing...
var user = input()
var newString = user.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())


text:
Q: timer pause button reseting when press start again So I have a program which is a stopwatch and I have the stopwatch is working but when I press the pause button the thing pauses but when I press the start button again to start the stopwatch from where it left off it resets instead I have tried multiple thing but nothing seems to work can you help me.
below is my code that I have for my reset, start and pause function they are all IBactions and Outlets.
I think the problem is with the start or pause buttons
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var pauseButton: UIButton!

@IBAction func startTimer(_ sender: AnyObject) {
    if(isPlaying) {
        return
    }
    startButton.isEnabled = false
    pauseButton.isEnabled = true
    isPlaying = true

    let aSelector : Selector = #selector(ViewController.updateTime)
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)

    counter = NSDate.timeIntervalSinceReferenceDate

}

@IBAction func pauseTimer(_ sender: AnyObject) {
    startButton.isEnabled = true
    pauseButton.isEnabled = false

    timer.invalidate()
    isPlaying = false

}

@IBAction func resetTimer(_ sender: AnyObject) {
    startButton.isEnabled = true
    pauseButton.isEnabled = false

    timer.invalidate()
    isPlaying = false
    counter = 0.0
    timeLabel.text = String("00:00:00:00")

}

then I also have my Updatetimer part which I'm sure works fine but f you need it just ask!!
If you need more info or specifications just ask or leave a comment.
here is my update timer
@objc func updateTime() {
        let currentTime = NSDate.timeIntervalSinceReferenceDate
    //Find the difference between current time and start time.
    var elapsedTime: TimeInterval = currentTime - counter

    //calculates the hour in elapsed time
    let hours = UInt8(elapsedTime / 3600.0)
    elapsedTime -= (TimeInterval(hours) * 3600.0)
    //calculate the minutes in elapsed time.
    let minutes = UInt8(elapsedTime / 60.0)
    elapsedTime -= (TimeInterval(minutes) * 60)

    //calculate the seconds in elapsed time.
    let seconds = UInt8(elapsedTime)
    elapsedTime -= TimeInterval(seconds)

    //find out the fraction of milliseconds to be displayed.
    let fraction = UInt8(elapsedTime * 100)

    //add the leading zero for minutes, seconds and millseconds and store them as string constants
    let strHours = String(format: "%02d", hours)
    let strMinutes = String(format: "%02d", minutes)
    let strSeconds = String(format: "%02d", seconds)
    let strFraction = String(format: "%02d", fraction)

    //concatenate minuets, seconds and milliseconds as assign it to the UILabel
    timeLabel.text = "\(strHours):\(strMinutes):\(strSeconds):\(strFraction)"
}

A: The problem is in this line counter = NSDate.timeIntervalSinceReferenceDate in your startTimer() function. You should only set the counter if the counter == 0.0. So change your code such as following:
     if counter == 0.0{
          counter = NSDate.timeIntervalSinceReferenceDate

        }else{
          counter = previousDate.timeIntervalSinceReferenceDate

        }

also add the following line to your pause function, so it saves the date that counter was paused, so the next time the counter will start from that point:
var previousDate = NSDate()
@IBAction func pauseTimer(_ sender: AnyObject){
//...Your other code...
previousDate = NSDate()
}

Also your update function should use the saved date previousDate for updating the counter.
That should fix the problem.


text:
Q: open PDF file in the browser window using angularjs I have PDF file located in the local file system,
local file path:
C:\pdf\sample.pdf

How do i open the pdf file in the browser using angularjs.

A: I hope it may help just follow the instructions and there is an example in the zip file try it.
http://ngmodules.org/modules/ng-pdfviewer


text:
Q: Why is npm install downloading other useless plugins into my node_modules folder? I just started getting into node.js and terminal. My issue is that, whenever I am doing an npm install of a plugin, i.e lets say 'sudo npm install browser-sync', it downloads a bunch of useless plugins into my node_modules folder. I didn't have this issue before reformating my Mac.
I want it to behave like it used to before, which in this case, download only the browser-sync plugin into my node_modules folder. Right now I've got 223 folders including browser-sync inside my node_modules. Is there a way to fix this?


text:
Q: Image won't display in  in Xamarin Forms I am trying to load a png image into an Image control in Xamarin Forms. I have added the image to both the drawable and the drawable-hdpi folder, set the BuildAction = AndroidResource and the Custom Tool = MSBuild:UpdateGeneratedFiles. One of the png images I try to use, monkeyface.png, copied from a sample project, loads just fine. The other png image will not display at all. Here are the relevant details:
CODE
            <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                <Image  Source="monkeyface.png" Aspect="AspectFill" HorizontalOptions="CenterAndExpand" VerticalOptions="Start"/>
                <Image  Source="homepage.png" Aspect="AspectFill" HorizontalOptions="Fill" VerticalOptions="End"/>
                <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="Center">
                    <Button Text="Click" TextColor="Black" HorizontalOptions="FillAndExpand"/>
                </StackLayout>
            </Grid>

OUTPUT

IMAGE INFO FOR IMAGE 1

IMAGE INFO FOR IMAGE 2

I am going crazy trying to figure this out. Any help would be greatly appreciated!
UPDATE
I also tried, with no success, the following code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="NGIC_XAML.Views.Login.Login">
    <ContentPage.Content>
        <StackLayout>
            <Image  Source="homepage.png" Aspect="AspectFit"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

But this works:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="NGIC_XAML.Views.Login.Login">
    <ContentPage.Content>
        <StackLayout>
            <Image  Source="monkeyface.png" Aspect="AspectFit"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

UPDATE 2
    <AndroidResource Include="Resources\drawable\homepage.png">
      <Generator>MSBuild:UpdateGeneratedFiles</Generator>
    </AndroidResource>
  <ItemGroup>
    <AndroidResource Include="Resources\drawable-hdpi\homepage.png">
      <Generator>MSBuild:UpdateGeneratedFiles</Generator>
    </AndroidResource>
  </ItemGroup>

And in case someone points out that the image that won't load has the Generator specified, I removed that also and it STILL doesn't load.
  <ItemGroup>
    <AndroidResource Include="Resources\drawable\monkeyface.png" />
  </ItemGroup>
  <ItemGroup>
    <AndroidResource Include="Resources\drawable-hdpi\monkeyface.png" />
  </ItemGroup>

the png file in question

The location of the images in the Android Resources folder

After removing bin and obj folders and rebuilding, I get the following errors:
System.NullReferenceException: Object reference not set to an instance of an object.
   at Xamarin.AndroidDesigner.DesignerProject.set_PreferredTheme(Theme value) in E:\A_work\711\s\Xamarin.Designer.Android\Xamarin.AndroidDesigner\DesignerProject.cs:line 901
   at Xamarin.AndroidDesigner.AndroidDesignerSession.SetTheme(Theme theme, Boolean triggerChange) in E:\A_work\711\s\Xamarin.Designer.Android\Xamarin.AndroidDesigner\AndroidDesignerSession.cs:line 376
   at Xamarin.Designer.Forms.Preview.AndroidXamlRenderer.GetRenderSessionForFormFactor(XamlRenderContext context, XamlFormFactor formFactor) in E:\A_work\711\s\Xamarin.Designer.Forms\Xamarin.Designer.Forms.Preview\Android\AndroidXamlRenderer.cs:line 236
   at Xamarin.Designer.Forms.Preview.AndroidXamlRenderer.d__25.MoveNext() in E:\A_work\711\s\Xamarin.Designer.Forms\Xamarin.Designer.Forms.Preview\Android\AndroidXamlRenderer.cs:line 136
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Xamarin.Designer.Forms.Preview.AndroidXamlRenderer.d__27.MoveNext() in E:\A_work\711\s\Xamarin.Designer.Forms\Xamarin.Designer.Forms.Preview\Android\AndroidXamlRenderer.cs:line 307
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)

A: You need to set Grid number of rows and columns,
then specify in each child which row and column it should be on. As this example has only one column, it does not need to be specified as good code practice in XAML.
<Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

    <Grid.RowDefinitions>
        <RowDefinition Height="49*" />
        <RowDefinition Height="49*" />
        <RowDefinition Height="2*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Image Source="monkeyface.png" Aspect="AspectFill" HorizontalOptions="CenterAndExpand" />
    <Image Grid.Row="1" Source="homepage.png" Aspect="AspectFill" HorizontalOptions="Fill" />
    <Button Grid.Row="2" Text="Click" TextColor="Black" HorizontalOptions="FillAndExpand"/>

</Grid>

A: So, after 2 days of frustration in trying to get the png file to display in an Image, and after following all of the great suggestions posted in response to my question, I decided to perform the Visual Studio update from the version I was using, Version 16.6.0, to Version 16.6.1. After the update  finished, I loaded the solution again and LO AND BEHOLD! the image displays perfectly. I still have no definitive reason why it was failing to load before I did the update, but WHO CARES! It loads now and that's all that matters.
Thanks to everyone who tried to help!

A: The issue is not with your image, but with your incorrect use of a layout for what you are trying to achieve. If you want the items to be one below the other, then the best layout will be a StackLayout.
Currently, you are using a Grid layout and you have added all of its items without even specifying the row definitions. This way you are just trying to "align" them by their HorizontalOptions & VerticalOptions, which is not the best approach, since the grid is trying to guess what you want your end result to look like.
If you still want to use a Grid for your layout, then I strongly suggest you read thoroughly grid's Rows & columns guide.

A: Seeming as this issue comes up for quite a few searches on google for 'missing image issues on iOS Xamarin', another possible solution when you've exhausted all potential layout issues is to clean the solution and rebuild.
In Visual Studio, Right click the project and click Clean.


text:
Q: Creating a TCP Socket connection and keep the connection open across several views I have successfully made a connection from an iPhone to a Server (which is a Windows machine) using TCP sockets.  Currently, I'm using a button to execute the following code:
while(1)
{
    Socket *socket;
    int port = 11005;
    NSString *host = @"9.5.3.63";

    socket = [Socket socket];

    @try
    {
        NSMutableData *data;
        [socket connectToHostName:host port:port];
        [socket readData:data];
        //  [socket writeString:@"Hello World!"];

        //** Connection was successful **//
        [socket retain]; // Must retain if want to use out of this action block.
    }
    @catch (NSException* exception)
    {
        NSString *errMsg = [NSString stringWithFormat:@"%@",[exception reason]];
        NSLog(errMsg);
        socket = nil;
    }
}

That was the easy part... I'm trying to establish the sockets connection as soon as the app loads.  I tried putting this code in my viewDidLoad, but the loop is infinite and the view never loads.  I have several views in my project, and I'd like to open the connection keep the connection open at all times, across all views.
Objective:

*

*Open TCP Sockets connection when app first loads

*Maintain connection infinitely, no matter what view I am in (Multiple Views in Project)

I'm still rather new to iOS development, so I appreciate as much clarity as possible.  It should be noted that I am using the SmallSockets library to open my Sockets connection.  Thanks for the help!
* EDIT *
Based off the answer below, this is what I've got going so far:
SocketConnection.h
#import <Foundation/Foundation.h>

@interface SocketConnection : NSObject
{

}

+ (SocketConnection *)getInstance;

@end

SocketConnection.m
static SocketConnection *sharedInstance = nil;
@implementation SocketConnection

- (id)init
{
    self = [super init];

    if (self)
    {
        while(1)
        {
            Socket *socket;
            int port = 11005;
            NSString *host = @"9.5.3.63";

            socket = [Socket socket];

            @try
            {
                NSMutableData *data;
                [socket connectToHostName:host port:port];
                [socket readData:data];
                //  [socket writeString:@"Hello World!"];

                //** Connection was successful **//
                [socket retain]; // Must retain if want to use out of this action block.
            }
            @catch (NSException* exception)
            {
                NSString *errMsg = [NSString stringWithFormat:@"%@",[exception reason]];
                NSLog(errMsg);
                socket = nil;
            }
        }
    }
    return self;
}

+ (SocketConnection *)getInstance
{
    @synchronized(self)
    {
        if (sharedInstance == nil)
        {
            sharedInstance = [[SocketConnection alloc] init];
        }
    }
    return sharedInstance;
}

@end

I still have not figured out how the singleton class gets invoked.  I fired up my app with the code from above and it's not connecting to the server.  Any ideas?
Thanks!

A: You should create a singleton classes to keep your connection like below code:
h file:
#import <Foundation/Foundation.h>
    @interface SocketConnection : NSObject
    {
    }

     + (SocketConnection *)getInstance;

    @end;

m file:
#import "SocketConnection.h"

static SocketConnection *sharedInstance = nil;

@implementation SocketConnection

- (id)init
{
    self = [super init];

    if (self) {
    }
    return self;
}

+ (SocketConnection *)getInstance
{
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [[SocketConnection alloc] init];
        }
    }
    return sharedInstance;
}

@end;


text:
Q: How to make in matlab three vectors with probabilities with a sum of one for each set? i have to make three vectors with probabilities p1, p2 and p3= (1-p1-p2) in order to plot the entropy of a signal source without memory that produces three symbols. I have tried many things with rand() and vectors like [1: .001:1] but none worked as it supposed to, the main problem is that i can't maintain a constant sum of one for every set of probabilities. Is there any way or funtion to do this? Any piece of advice would be appreciated.

A: You can generate a vector p of 3 real numbers between zero and one
p = rand(1,3);

then normalize p
p = p / sum(p);

Then p(1) + p(2) + p(3) is  1.
EDIT:
to respond to OP's comment
N = 100;

p = rand(N, 3);
for k = 1: N
    p(k,:) = p(k,:)/sum(p(k,:));
end;

Now you have an N x 3 matrix with rows summing up to one. I'm pretty sure that there is a more "pure" MATLAB way of writing the loop using some vectorization tricks, however my MATLAB is kind of rusty now, and this will do. Please next time be more precise when asking a question.


text:
Q: Streaming live wih Raspberry PI Camera on a C# Application I'm trying to use a raspberry pi to guide a car from a C# Application from a computer. The raspberry and computer are booth connected to a router. What I want is to receive live streaming from raspberry camera to computer so I can control the car. I've seen how to broadcast on browser, but I want to receive the live streaming directly into my C# Application. Is there any way to do this?

A: I'm making some assumptions here since there's not much detail in the question, but, if you want to stream from Raspberry Pi, it's as easy as using ffmpeg. There's a thousand command line parameters, but something like this will do the trick;
ffmpeg -y -loglevel warning -f dshow -i video="screen-capture-recorder" -vf crop=690:388:136:0 -r 30 -s 962x388 -threads 2 -vcodec libx264 -vpre baseline -vpre my_ffpreset -f flv rtmp:///live/myStream.sdp

See here for more docs: https://trac.ffmpeg.org/wiki/StreamingGuide
On the C# side, you just need to receive the video stream. There's quite a few options for RTMP and/or RTSP, here's one: https://code.google.com/p/rtmp-mediaplayer/ but there are many others.
Depending on what exactly you're doing with the video (overlays? vision?) you'll want to pick the right format, bitrate, and container to make processing simpler.


text:
Q: Excel Power Query Filtering by Cell Reference I have a table named "TicketData" and it has many columns.  What I want to do is show a filtered view of this table in another table. I opened query editor and filtered everything down, except I have one additional filter needed and that is a date reference in a cell on another tab.  The other tab is named "ABN Chart".  I want that cell to filter the column named "Created Date".
Example
G5 in "ABN Chart" sets the filter of column 'TicketData'[Created Date] of the power query. I believe this can be done in the advanced query editor, but I don't know how. *I can change G5 to named reference if needed.

A: I created another column in the original table called "InRange" and just pointed it to match the cell. This is the desired behavior.