text:
Q: Is functional Clojure or imperative Groovy more readable? OK, no cheating now.
No, really, take a minute or two and try this out.
What does "positions" do?
Edit: simplified according to cgrand's suggestion.
(defn redux [[current next] flag] [(if flag current next) (inc next)])

(defn positions [coll]
  (map first (reductions redux [1 2] (map = coll (rest coll)))))

Now, how about this version?
def positions(coll) {
  def (current, next) = [1, 1]
  def previous = coll[0]
  coll.collect {
    current = (it == previous) ? current : next
    next++
    previous = it
    current
  }
}

I'm learning Clojure and I'm loving it, because I've always enjoyed functional programming. It took me longer to come up with the Clojure solution, but I enjoyed having to think of an elegant solution. The Groovy solution is alright, but I'm at the point where I find this type of imperative programming boring and mechanical. After 12 years of Java, I feel in a rut and functional programming with Clojure is the boost I needed.
Right, get to the point. Well, I have to be honest and say that I wonder if I'll understand the Clojure code when I go back to it months later. Sure I could comment the heck out of it, but I don't need to comment my Java code to understand it.
So my question is: is it a question of getting more used to functional programming patterns? Are functional programming gurus reading this code and finding it a breeze to understand? Which version did you find easier to understand?
Edit: what this code does is calculate the positions of players according to their points, while keep track of those who are tied. For example:

Pos Points
1. 36
1. 36
1. 36
4. 34
5. 32
5. 32
5. 32
8. 30

A: edit: may not be relevant anymore.
The Clojure one is convoluted to me. It contains more abstractions which need to be understood. This is the price of using higher order functions, you have to know what they mean. So in an isolated case, imperative requires less knowledge. But the power of abstractions is in their means of combination. Every imperative loop must be read and understood, whereas sequence abstractions allow you to remove the complexity of a loop and combine powerful opperations.
I would further argue that the Groovy version is at least partially functional as it uses collect, which is really map, a higher order function. It has some state in it also.
Here is how I would write the Clojure version:
(defn positions2 [coll]
  (let [current (atom 1)
        if-same #(if (= %1 %2) @current (reset! current (inc %3)))]
    (map if-same (cons (first coll) coll) coll (range (count coll)))))

This is quite similar to the Groovy version in that it uses a mutable "current", but differs in that it doesn't have a next/prev variable - instead using immutable sequences for those. As Brian elloquently put it, readability is not intrinsic. This version is my preference for this particular case, and seems to sit somewhere in the middle.

A: I agree with Timothy: you introduce too much abstractions. I reworked your code and ended with:
(defn positions [coll]
  (reductions (fn [[_ prev-score :as prev] [_ score :as curr]]
                (if (= prev-score score) prev curr))
    (map vector (iterate inc 1) coll)))

About your code,
(defn use-prev [[a b]] (= a b))
(defn pairs [coll] (partition 2 1 coll))
(map use-prev (pairs coll))

can be simply refactored as:
(map = coll (rest coll))

A: The Clojure one is more convoluted at first glance; though it maybe more elegant.
OO is the result to make language more "relatable" at higher-level.
Functional languages seems to  have a more "algorithimc"(primitive/elementary) feel to it.
That's just what I felt at the moment.
Maybe that will change when I have more experience  working with clojure.
I'm afraid that we are decending into the game of which language can be the most concise or solve a problem in the least line of code.
The issue are 2 folds for me:

*

*How easy at first glance to get a feel of what the code is doing?.
This is important for code maintainers.

*How easy is it to guess at the logic behind the code?.
Too verbose/long-winded?. Too terse?
"Make everything as simple as possible, but not simpler."
Albert Einstein

A: I too am learning Clojure and loving it. But at this stage of my development, the Groovy version was easier to understand. What I like about Clojure though is reading the code and having the "Aha!" experience when you finally "get" what is going on. What I really enjoy is the similar experience that happens a few minutes later when you realize all of the ways the code could be applied to other types of data with no changes to the code. I've lost count of the number of times I've worked through some numerical code in Clojure and then, a little while later, thought of how that same code could be used with strings, symbols, widgets, ...
The analogy I use is about learning colors. Remember when you were introduced to the color red? You understood it pretty quickly -- there's all this red stuff in the world. Then you heard the term magenta and were lost for a while. But again, after a little more exposure, you understood the concept and had a much more specific way to describe a particular color. You have to internalize the concept, hold a bit more information in your head, but you end up with something more powerful and concise.

A: Groovy supports various styles of solving this problem too:
coll.groupBy{it}.inject([]){ c, n -> c + [c.size() + 1] * n.value.size() }

definitely not refactored to be pretty but not too hard to understand.

A: I know this is not an answer to the question, but I will be able "understand" the code much better if there are tests, such as:
assert positions([1]) == [1]
assert positions([2, 1]) == [1, 2]
assert positions([2, 2, 1]) == [1, 1, 3]
assert positions([3, 2, 1]) == [1, 2, 3]
assert positions([2, 2, 2, 1]) == [1, 1, 1, 4]

That will tell me, one year from now, what the code is expected to do. Much better than any excellent version of the code I have seen here.
Am I really off topic?
The other thing is, I think "readability" depends on the context. It depends who will maintain the code. For example, in order to maintain the "functional" version of the Groovy code (however brilliant), it will take not only Groovy programmers, but functional Groovy programmers...
The other, more relevant, example is: if a few lines of code make it easier to understand for "beginner" Clojure programmers, then the code will overall be more readable because it will be understood by a larger community: no need to have studied Clojure for three years to be able to grasp the code and make edits to it.

A: I don't think there's any such thing as intrinsic readability.  There's what you're used to, and what you aren't used to.  I was able to read both versions of your code OK.  I could actually read your Groovy version more easily, even though I don't know Groovy, because I too spent a decade looking at C and Java and only a year looking at Clojure.  That doesn't say anything about the languages, it only says something about me.
Similarly I can read English more easily than Spanish, but that doesn't say anything about the intrinsic readability of those languages either. (Spanish is actually probably the "more readable" language of the two in terms of simplicity and consistency, but I still can't read it).  I'm learning Japanese right now and having a heck of a hard time, but native Japanese speakers say the same about English.
If you spent most of your life reading Java, of course things that look like Java will be easier to read than things that don't.  Until you've spent as much time looking at Lispy languages as looking at C-like languages, this will probably remain true.
To understand a language, among other things you have to be familiar with:

*

*syntax ([vector] vs. (list), hyphens-in-names)

*vocabulary (what does reductions mean?  How/where can you look it up?)

*evaluation rules (does treating functions as objects work?  It's an error in most languages.)

*idioms, like (map first (some set of reductions with extra accumulated values))
All of these take time and practice and repetition to learn and internalize.  But if you spend the next 6 months reading and writing lots of Clojure, not only will you be able to understand that Clojure code 6 months from now, you'll probably understand it better than you do now, and maybe even be able to simplify it.  How about this:
(use 'clojure.contrib.seq-utils)                                        ;;'
(defn positions [coll]
  (mapcat #(repeat (count %) (inc (ffirst %)))
          (partition-by second (indexed coll))))

Looking at Clojure code I wrote a year ago, I'm horrified at how bad it is, but I can read it OK.  (Not saying your Clojure code is horrible; I had no trouble reading it at all, and I'm no guru.)


text:
Q: Creation Variations of Pandas DataFrame with Column Dependencies I want to be able to expand my DataFrame to incorporate other scenarios. For example, for a DataFrame capturing active users per company, I want to add a scenario where active users increase but do not exceed the total user count.
Example input:

Example output:

I tried using a loop but quite inefficiently, yielding odd results:
    while df[df['active_users'] + add_users <= df['total_users']].any():
            df[(df['active_users'] + add_users) <= df["total_users"]]['active_users'] = (df['active_users'] + add_users).astype(int)
            add_users += 1

A: Use Index.repeat with DataFrame.loc and for counters use GroupBy.cumcount:
df1 = df.loc[df.index.repeat(df['inactive_users'] + 1)]

df1['inactive_users'] = df1.groupby(level=0).cumcount(ascending=False)

s = df1.groupby(level=0).cumcount()
df1['active_users'] += s

df1['company'] = (df1['company'] + ' + ' + s.astype(str).replace('0','')).str.strip(' +')
print (df1)
  company  contract  total_users  active_users  inactive_users
0       A     10000           10             7               3
0   A + 1     10000           10             8               2
0   A + 2     10000           10             9               1
0   A + 3     10000           10            10               0
1       B      7500            5             4               1
1   B + 1      7500            5             5               0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как записывать стрим в файл, используя ffmpeg+python? У меня есть простой websocket клиент на python, который получает чанки ogg трека ежесекундно. Мне нужно, чтобы ffmpeg в онлайн режиме записывал эти чанки в файл. Если это важно, я могу менять ogg на любой другой формат.
Моя реализация такая:
async def hello(uri):
    process = subprocess.Popen(['ffmpeg', '-i', '-', 'ffmpeg.ogg'], stdin=subprocess.PIPE) #  или sys.stdout
    async with websockets.connect(uri) as websocket:
        while True:
            r = await websocket.recv()
            process.stdin.write(r)  # или sys.stdout.write()

В результате ffmpeg даже не создает файл, в который должен все это записывать.
Вместо этого через несколько секунд появляется ошибка Broken pipe, а в случае с sys.stdout сам ffmpeg выводит:
pipe:: Bad file descriptor
EDIT:
Код для деления файла на чанки
from pydub import AudioSegment

song = AudioSegment.from_ogg("tst.ogg")
current_offset = 0
offset = 1000
while True:
    chunk = song[current_offset:current_offset+offset]
    current_offset += offset
    websocket.send(chunk.raw_data)

A: Проблема решается добавлением опции -re к запуску ffmpeg:
ffmpeg -re -i - ffmpeg.ogg
И при отправке чанков сначала кодируем каждый чанк в ogg, используя pydub:
data = chunk.export('bin/chunk.ogg', 'ogg').read()
await websocket.send(data)


text:
Q: Azure SQL: Is it possible to use the view from another database? Being new to Azure SQL, I am already successfully JOINing my table with the table from the other database (by defining the CREATE EXTERNAL TABLE and the related things). However, some queries contain views from the other database, not the tables. How can I join my table with that external view? Is it possible at all? Or do I have to copy the code from the remote view and work directly with the external tables?

A: with create external table you can access a table or view :
take a look at
https://medium.com/@fbeltrao/access-another-database-in-azure-sql-1afc526b7ad4


text:
Q: Why am I getting ':' expected"? I'm trying to define a few functions to run some unit tests on for a benchmark I'm trying to get these functions defined to run some synchronous and asynchronous test cases on them with Mocha and Chai in JS, what am I doing wrong? Why is my editor marking certain lines?
module.exports = {

    function myFunctiona ()  {

    }

    function myFunctionb ()  {
        for (let i = 0; i < 10000; i++) {
          new Date();
        }
      }

    function myFunctionc(done)  {
        setTimeout(done, 0);
      }

    function myFunctiond (done) {
        setTimeout(done, Math.round(Math.random() * 10));
      }

    }

A: This is a syntax error because you're defining an object with properties, but you don't have property keys. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_colon_after_property_id for more information.
Typically, you'd define an object like the following
(note the commas after each property too):
var object = {
    property1: 'thing',
    property2: function() {
        return 'thing2';
    }
}

so to change your functions to properties, set the property key as the function name, and then assign a function to it like:
module.exports = {

    myFunctiona: function ()  {
        //nothing
    },

    myFunctionb: function ()  {
        for (let i = 0; i < 10000; i++) {
            new Date();
        }
    },

    myFunctionc: function (done)  {
        setTimeout(done, 0);
    },

    myFunctiond: function (done) {
        setTimeout(done, Math.round(Math.random() * 10));
    }

};


text:
Q: What is the Twilio URL parameter? I am trying to write a Twilio script to make a call in Python. I am trying to follow the documentation, but am baffled by the url parameter.
The example the documentation supplies is as follows:
from twilio.rest import TwilioRestClient

account_sid = "ACXXXXXXXXXXXXXXXXX"
auth_token = "YYYYYYYYYYYYYYYYYY"
client = TwilioRestClient(account_sid, auth_token)

call = client.calls.create(to="+14085551234",  # Any phone number
                           from_="+12125551234", # Must be a valid Twilio number
                           url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient")
print call.sid

What is the url parameter doing here? Should I copy it or supply my own URL? Does that mean I have to write my own endpoint?
The documentation on URL parameter is not much more enlightening: https://www.twilio.com/docs/api/rest/making-calls#url-parameter
Please could someone explain what this is, and whether I need to change it or not?

A: The Url parameter determines what is heard on the call when the phone is answered.  This is customizable using TwiML (Twilio Markup Language) a set of roughly a dozen XML tags, which your application should return at the specified url.  The XML your application returns at the Url decides how to handle the call, for example whether to forward the call to another line, speak some words or send an SMS reply.  You can read a bit more about TwiML here:
https://twilio.radicalskills.com/projects/getting-started-with-twiml/2.html


text:
Q: Acceptance testing for REST API We have a situation to find  System Acceptance testing (SAT) for Webapi.
We are already doing SUT (System Unit Testing), and SIT (Integration Testing). However, I am just wondering is it really a good idea to do SAT against Webapi or it makes more sense to hit SAT from UI level?
For me it does make sense to do SAT for non functional such as Security, logging, exception handling, performance etc..
But for functional level SAT, I believe it is going to be effective if it starts from UI because that is what the end user will see.
How others are handling the same?
If you are doing SAT at API level can you suggest me the tools that you are using ?


text:
Q: Largest sum contiguous subarray (Interview Question)
Possible Duplicate:
Find the maximum interval sum in a list of real numbers.

I was asked the following question today at Adobe interview for the position of software engineer.
Problem  Given a array arr[1..n] of integers. Write an algorithm to find the sum of contiguous subarray within the array which has the largest sum. Return 0 if all the numbers are negative.
Example
Given array arr[1..6] = [ 12, 14, 0, -4, 61, -39 ]
Answer
83 constructed with [ 12, 14, 0, -4, 61 ].
I could come up with a solution running in O(n logn) but I don't think it was very efficient. The interviewer asked to me to write an O(n) algorithm. I couldn't come up with it.
Any idea about how to write an O(n) solution for this problem?
Algorithm to be implemented either in C/C++/Java.
Thanks in advance

A: You can use Kadane's algorithm which runs in O(n).
Here is the algorithm (shamelessly copied from here)
Initialize:
    max_so_far = 0
    max_ending_here = 0

Loop for each element of the array
  (a) max_ending_here = max_ending_here + a[i]
  (b) if(max_ending_here < 0)
            max_ending_here = 0
  (c) if(max_so_far < max_ending_here)
            max_so_far = max_ending_here
return max_so_far


text:
Q: ios6 "translate" method interference? How come the following does not work on ios6, but replacing "translate" with "something_else" makes it work just fine?

A: There's a new translate attribute added in HTML5. You are merely setting it to true, since by definition all objects evaluates to true.


text:
Q: How do I put the dragged item at the screen position where it was left? In this drag and drop, I'd like to put the dragged HTML element exactly where it was left by the mouse but currently it's putting the control in the top most left. I'm putting the element in the drop target div by a appendChild(), I have no code to show yet because  I have no idea how to do that yet, how to get the coordinates in the end of the drag operation and insert the HTML element in this very same coordinates in the final drag div.
Example with images. So let's say I drag the HTML element to this position:

the HTML should stay there rather go to left top most:

my code look like this:

        <input type="button" value="Button 1" id="button1" draggable="true" class="control">

        <input type="text" value="Edit 1" class="edit" draggable="true" class="control">

A: Get the coordinates of the element dropped relative to the parent like so:
var rect = e.target.getBoundingClientRect();
const coordinates = [e.pageX - rect.left, e.pageY - rect.top];

Set the draggable element's position to absolute, and set the corresponding left and top attributes.
Example:

const item = document.querySelector('.control');

item.addEventListener('dragstart', dragStart);

function dragStart(e) {
  e.dataTransfer.setData('text/plain', e.target.id);
  setTimeout(() => {
    e.target.classList.add('hide');
  }, 0);
}

const box = document.querySelector('#panel');
box.addEventListener('dragenter', dragEnter);
box.addEventListener('dragover', dragOver);
box.addEventListener('dragleave', dragLeave);
box.addEventListener('drop', drop);

function dragEnter(e) {
  e.preventDefault();
  e.target.classList.add('drag-over');
}

function dragOver(e) {
  e.preventDefault();
  e.target.classList.add('drag-over');
}

function dragLeave(e) {
  e.target.classList.remove('drag-over');
}

function drop(e) {
  var rect = e.target.getBoundingClientRect();
  const coordinates = [e.pageX - rect.left, e.pageY - rect.top];
  e.target.classList.remove('drag-over');

  const id = e.dataTransfer.getData('text/plain');
  const draggable = document.getElementById(id);

  e.target.appendChild(draggable);
  draggable.style.position = "absolute";
  draggable.style.left = coordinates[0] + "px";
  draggable.style.top = coordinates[1] + "px";
  draggable.classList.remove('hide');
}
#panel {
  position: relative;
}

.toolbox {
  height: 250px;
  width: 150px;
  border: solid 3px #ccc;
  margin: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.edit {
  width: 140px;
}

.form {
  height: 250px;
  width: 150px;
  border: solid 3px red;
}

.drop-targets {
  display: flex;
  flex-direction: row;
  //justify-content: space-around;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
}

.drag-over {
  border: dashed 3px red;
}

    <input type="button" value="Button 1" id="button1" draggable="true" class="control">

    <input type="text" value="Edit 1" class="edit" draggable="true" class="control">


text:
Q: GP Web Service dll I have a project in VS2010 that includes a Service Reference to a GP Web Services. I can access all classes and methods for GP Web services and I have a Class Library project around it to use it. Everything works fine but when I generate a new dll and include this dll on a web folder in order to be used by an aspx web application, when accessing the GP web service I get the following error message:
Could not find default endpoint element that references contract 'GP.DynamicsGP' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
Any thoughts?

A: So you included a seperate assembly as a project in your application, which would allow you to access the classes and whatnot.
The problem is that it needs access to an endpoint address. The app.config file in your referenced DLL would have that information, however, The application configuration file of the current executing program is the one that gets used, so you'll need to copy the xml from the app.config file in your referenced assembly to your current project.
This is the block of code you're looking for.
    <client>
        <endpoint address="WebServiceAddress"
            binding="wsHttpBinding" bindingConfiguration="GPWebService"
            contract="DynamicsGP.DynamicsGP" name="GPWebService">
            <identity>
                <userPrincipalName value="crm@emailaddress" />
            </identity>
        </endpoint>
    </client>


text:
Q: Is it possible to get real-time update on conversations? Is it possible to get notification when a user sends private message to someone or receives it from someone?

A: No this isn't possible without polling the thread id. You can see the list of available connections at https://developers.facebook.com/docs/reference/api/realtime/


text:
Q: Facebook SDK integration with android? I import the Facebook SDK to the eclipse but it show's me the error on following imports. Ii search everywhere for the libraries of these import but failed to find. Kindly suggest me with some solution to resolve these imports errors. ...
android.support.annotation.Nullable;
android.support.v4.content.LocalBroadcastManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;


text:
Q: DataPager ceases to work when PageSize is set in code I have a standard ASP.Net DataPager with a standard ListView (using a DataTable as a data source).
When I set PageSize="24" in the design code:
<asp:DataPager runat="server" ID="DataPager1" PagedControlID="ListView1" QueryStringField="page" PageSize="24" >

the paging works as advertised.
However, when I then change that in code, in the Page_Load, eg:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    DataPager1.PageSize = 48
End Sub

the paging ceases to work completely, while the initial loaded data set is indeed 48 items.
I can't see anything in the code which would affect this, so I'm wondering if I'm missing something - should I be changing something else?
Regards
Moo

A: Protected Sub DataPager1_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataPager1.Init
    DataPager1.PageSize = 48
End Sub

I managed to get this working by setting the page size property in the init event for the datapager.

A: This sort of error I usually find is a data-binding issue... either binding when you shouldn't, or not re-binding when appropriate.  Hard to tell from your little snippet of code.
I am unfamiliar with the DataPager object, but I suspect it must rebind the data when you set the PageSize.  If so, then every time the page loads it is re-binding and you are losing events.  Have you tried this?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack
        DataPager1.PageSize = 48
    End If
End Sub


text:
Q: How to calculate the ratio of field and gropuby the field in Splunk I have this table.
Fruits  Result
--------------
Apple   sold
Apple   sold
Apple   instock
Apple   expired
Banana  sold
Banana  sold
Banana  sold
Orange  instock
Orange  instock

I have to generate report like below in Splunk. I'd like to count by Fruits type and calculate the ratio of results.
Fruits  count  instock_ratio expired_ratio sold_ratio
----------------------------------------------------
Apple   4       0.25         0.25          0.5
Banana  3       0            0             1.0
Orange  2       1.0          0             0

In SQL, I can get this result.
WITH src AS(
    SELECT
       Fruits,
       count(CASE WHEN result="sold" THEN Fruits ELSE null END) AS sold_count,
       count(CASE WHEN result="instock" THEN Fruits ELSE null END) AS instock_count,
       count(CASE WHEN result="expired" THEN Fruits ELSE null END) AS expired_count,
       count(Fruits) AS total_counts
    FROM table
    GROUP BY Fruits
)
SELECT
   Fruits,
   total_counts,
   sold_count/total_counts,
   instock_count/total_counts,
   expired_count/total_counts
FROM src

Can anyone help me with the splunk command?

A: Add the following to your search
| stats count, count(eval(Result="sold")) AS sold_count, count(eval(Result="expired")) AS expired_count, count(eval(Result="instock")) AS instock_count by Fruits
| eval sold_ratio=sold_count/count, expired_ratio=expired_count/count, instock_ratio=instock_count/count | fields - *_count

We just calculate the total count and the count of each Result for each fruit. To work out the ratio, just divide each count by the total.
Here is an example that shows it works. It also uses the foreach command to make things cleaner.
| makeresults count=100 | eval r1=random()%3 | eval Fruits=case(r1=1, "Apple", r1=2, "Banana", true(), "Orange") | eval r2=random()%3 | eval Result=case(r2=1,"instock", r2=2, "sold", true(), "expired")
| stats count, count(eval(Result="sold")) AS sold_count, count(eval(Result="expired")) AS expired_count, count(eval(Result="instock")) AS instock_count by Fruits
| foreach *_count [ eval <<MATCHSTR>>_ratio=<<FIELD>>/count ] | fields - *_count


text:
Q: Json data into javascript array var test=[];
$(document).ready(function(){
            $.getJSON("data.json",function(data){
                $.each(data,function(key,value){
                    test.push(value.topic);
                });
            });
        });

Here is my javacript code. I want to push json object's all values with key as topic. But when I try to access test[i] (i be any integer within array length) I get an error "undefined" . What' am I msissing?
Here is my json object sample-
[
        {
            "topic": "Books",
            "quantity": 3
        },
        {
            "topic": "Grossery",
            "quantity": 3
        },
        {
            "topic": "stationery",
            "quantity": 3
        },
        {
            "topic": "food",
            "quantity": 2
        },
        {
            "topic": "market items",
            "quantity": 3
        }
]

A: See the following working code:

var data = [
        {
            "topic": "Books",
            "quantity": 3
        },
        {
            "topic": "Grossery",
            "quantity": 3
        },
        {
            "topic": "stationery",
            "quantity": 3
        },
        {
            "topic": "food",
            "quantity": 2
        },
        {
            "topic": "market items",
            "quantity": 3
        }
]
var test = [];
$.each(data,(i,v) => test.push(v.topic));
console.log(test);

A: Your code seems to be working fine for me.
Are you accessing the data before the callback that you pass to getJson has been executed?
Here's an example that works if I serve it locally using python3 -m http.server 8080:


text:
Q: Why, for x=0, 'not x' is True and 'x' is False in Python? I am stuck about True/False of x and not x,
for x = 0 where x is int, in Python.
Why does if not x allow execution of the following statement and why not for if x?
Please give explanation.

A: from the python docs:
"By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:

*

*constants defined to be false: None and False.

*zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

*empty sequences and collections: '', (), [], {}, set(), range(0)
https://docs.python.org/3/library/stdtypes.html
that is, zero is integer,
>>> type(0)
<class 'int'>

but has a False logical value, as '', (), []... and so on

A: Because in python 0 is considered false, so when you write (if x) it will execute only when x !=0 (so it will be evaluated as true).

A: If statements don't execute their contents if their condition evaluates to a "false" value, like 0, an empty string, False, or an empty list/tuple.

A: Going to assume you mean
x = True
y = 0

if x:
  print('x is true')
if not y:
  print('your not sure why this prints')

This is because in Python, 0 evaluates to False.

A: 0 is a subclass bool, False, while any number that's not zero evaluates to True.
x = 0
if not x

is like saying
x = 0
if x is False:

which the condition meets.

A: Sounds like you need a bit of Boolean review.
Everything in the world of python (and most of programming) boils down to be either True or False.
Lets take Integers, for example.
In python (and probably most languages) a value of 0 goes to False and everything else is True.
You can get the true/false value of just about anything in python by using the bool function. Try bool(0) or bool(2).
Now, what if does is take an expression (basically just a Boolean value), and if it is True, executes the code block, and if it's False, skips it.
x = 0
if x:
    print("This will never be printed because x is", x, "and it's Boolean value is", bool(x))

Now, what not does is take a Boolean value and make it the opposite. not True is False. not False is True. It does that however many times not is there, so not not True would be True.
x = 0
if not x:
    print("This will print, because x is", 0, "the Boolean value of x is", bool(x), "and the not value of boolean x is", not bool(x))

A: Ultimately: because the language definition says so.
Python has chosen to make almost any expression implicitly convertible to a boolean (True/False) value. The conversion is defined in the language.
For integer types, the conversion is that 0 is False, other values are True.
And, of course, if an expression X is False, then not X is True, by simple definition of the operator not.


text:
Q: How can I reload app.component.ts on event in pages? app.component.ts is not listening to the event when it is firing on a particular page. I want to reload my app.component.ts as I want to show a different side menu when a user is logged in.

A: You can just use the *ngIf directive:
<sidenav-not-logged-in *ngIf="!userIsLoggedIn()"></sidenav-not-logged-in>
<sidenav-logged-in *ngIf="userIsLoggedIn()"></sidenav-logged-in>

If you want to listen to an event (@Output) from a child you have to bind the event to some function in the parent template:
<some-child (someEvent)="someFuntion()"></some-child>

Then just implement someFuntion() in the parent component.
For more documentation on types of data sharing between components and an example project see here:
https://github.com/H3AR7B3A7/EarlyAngularProjects/tree/master/dataSharing
'Child to Parent with EventEmitter & Output' is about the emitting of events.
I'm willing to take a further look into your problem if you link a stackblitz.


text:
Q: $a+b+c=0$. $a,b,c \in \mathbb{R}^{*}$. Prove that $\frac {1}{-a^2+b^2+c^2} + \frac{1}{a^2-b^2+c^2} + \frac{1}{a^2+b^2-c^2} = 0$ The following problem proves how some equations can be solved with very little data.
Let a, b, c be real numbers $a, b, c \in R*$ such that $a+b+c=0$.
Prove that
$\frac {1}{-a^2+b^2+c^2} + \frac{1}{a^2-b^2+c^2} + \frac{1}{a^2+b^2-c^2} = 0$
for any a, b, c real numbers.
Do not use anything beyond 8th grade's curriculum and no geometry to solve this.
I have tried brute-forcing it by bringing it to the common denominator. It doesn't work, however, as the expression gets more and more complicated. Neither does writing a in terms of b and c seem to work, as you get sums at the denominators.
The last attempt was to try and prove that the 2 expressions, the given one and the ugly one are equivalent.

A: Hint: Multiplying to a common denominator in the identity gives
$$
(a + b + c)(a + b - c)(a - b + c)(a - b - c)=0.
$$

A: Hint :$-a^2+b^2+c^2=-2bc$
Now try putting this in the original expression


text:
Q: Force to download file(sound,video) and and file from url use php Hello i need help to Force Download File
i have download link for file like this

https://cf-media.sndcdn.com/WSIkwY864LX0.128.mp3?Policy=eyJTdGF0ZW1lbnQiOlt7IlJlc291cmNlIjoiKjovL2NmLW1lZGlhLnNuZGNkbi5jb20vV1NJa3dZODY0TFgwLjEyOC5tcDMiLCJDb25kaXRpb24iOnsiRGF0ZUxlc3NUaGFuIjp7IkFXUzpFcG9jaFRpbWUiOjE1MTg4Njc5MjF9fX1dfQ__&Signature=D8mLMEF87phwsYauLxjeHVuPhYYyC~rVu901PnMNJzRX1WoYEQz3-t05OVfDJD5KQPN-mt2IXIW9SEjSy8ASWkD3esS4MQ9DoRRzLmlp84Irsj65LeyonJAj-3gvi~XVEoGkcwNQgWKNDlHpT8gJmjGwgiMsRwEfH5uBfLcKd2Vw9l9DlaFEk332reKvoI3lZuNpiNktGfNsxZWDYNzI-aqg4HvB1NHomnNl4XhnoZkXCMXVhT7p4IUM6Lxi8wFjKbrhoNupVqO-BEJfv4Gc7G4VDS5Jzmhzj6o~GZn~HYpa10RB208CCwpcg8gtaouhNhkwArozMWq74PDfz4447w__&Key-Pair-Id=APKAJAGZ7VMH2PFPW6UQ

this link for mp3 file when i click on it i can't download it just play it in browser
if i set like in IDM (internet download manager )
it will download
Click here to show image from idm
i try pass url in post or get but doesn`t work
<?php
    if(isset($_POST['comment']) && !empty($_POST['comment'])){

    $file = $_POST['comment'];
    header ("Content-type: octet/stream");
    header ("Content-disposition: attachment; filename=".$file.";");
    header("Content-Length: ".filesize($file));
    readfile($file);
    exit;
    }
?>

A: this has nothing to do with php rather you need to edit the .htaccess file. and this will force the mp3 files to download rather than playing
<FilesMatch "\.(?i:mp3)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

One more idea, Add it in the .htaccess I got it from here
AddType application/octet-stream .mp3
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

A: Try the below code
if(isset($_POST['comment']) && !empty($_POST['comment'])){
    $fileName = 'test.mp3';
    $file = $_POST['comment'];
    ob_start();
    header('Content-type: audio/mpeg');
    header("Content-Transfer-Encoding: Binary");
    header('Content-Disposition: attachment; filename="'.basename($fileName).'"');
    file_put_contents($fileName, $file);
    readfile($fileName);
    ob_end_flush();
}


text:
Q: What makes quantum-entanglement communication so surprising? I don't understand why quantum entanglement seems so surprising to physicists in the case of communication.
Let us say we take a pair of shoes, and put the two shoes in two separate boxes, and shoot one of the box into a black hole while holding the other box at the other end of the universe. If I were to open the box inside the black hole and find the left shoe in it, it is obvious that the other shoe in the far end of the universe will be a right shoe. The two objects are pre-entangled pairs, there is no need of further communication to maintain their entanglement.

A: I like to teach undergraduates about what new mathematics you can do with entanglement, with a game that I like to call "Betrayal."
Rules of Betrayal
Betrayal is a cooperative game for a team of 3 people. They are playing against and trying to beat the game. The game is usually going to force one member of this team to act at cross-purposes to the other two; I will call this person the "traitor" for short. (Of course since they're cooperating with the others they don't want to betray their friends!)
The whole game consists of some large number $N$ of similar rounds. The team is allowed to prepare however they want between each of these rounds.
In each round, all three teammates are put into boxes through which no known communication can travel.1 They can bring whatever they want to into that box. Each box has a timer, a screen onto which the game will display a message, and two buttons marked $0$ and $1$. After we display the message on the screen, the timer counts 5 minutes which they have to press exactly one button once, locking in their numbers. We then bring everyone back together and sum up these three numbers, and they win based on whether the sum is even or odd. Tampering with the box in any way other than pressing one button once during a round is, of course, against the rules.
Getting more in-depth, 25% of our tests are control rounds. We display on all three of their screens, "Make the sum of your three numbers even." When we get back their chosen numbers and sum them together, the team beats that round only if this sum is even. Simple enough, right?
In 75% of our rounds we randomly choose one of the teammates to be the traitor, and we lie to them by broadcasting that same message onto their screen: "Make the sum of your three numbers even." As for the other two, we broadcast the true objective onto their screen: "Make the sum of your three numbers odd." When we get back their chosen numbers and sum them together, the team beats that round only if this sum is odd. Everybody is, of course, informed in advance about these rules.
Now in this hypothetical future, the team plays this for something like 3-4 weeks straight, doing 300 rounds total, and they win if they beat 270 or more of these rounds. To give some financial incentive, let's say the team gets to split a trillion credits if they win, but they have to pay ten thousand credits if they lose, where a credit in the future is equal to the present value of a dollar.
(Footnote 1. Technically, this is achieved by those boxes being inside of spaceships which fly until they're more than 5 light-minutes apart from each other, but that's not super-important.)
Classical limits
It turns out in classical probability the above game is exactly identical to a slightly revised game: we similarly separate the players and then we ask all of the players "what would you do if you told us to make the sum even?" and they press one button; then we ask all of them "what would you do if you told us to make the sum odd?". Doing so we get 6 total answers, of course. Let's call our players Alice, Bob, and Carol and denote their answers to the question $(A,B,C)_{o,e}$ where $A_e$ is "Alice's answer if we ask her to help make the sum even."
After this process we choose, uniformly at random, to either evaluate $A_e + B_e + C_e$ for evenness, or $A_o + B_o + C_e$ for oddness, or $A_o+B_e+C_o$ for oddness, or $A_e+B_o+C_o$ for oddness. Note that at least one of these cannot hold, because summing all three together we would find that $2(A_e + B_e + C_e + A_o + B_o + C_o)$ is even+odd+odd+odd = odd, but two times anything is even. You can only satisfy at most three of these at once, which means that your best strategy will always fail 25% of the time. Invoking the binomial CDF we find out that your chance of getting 30 or fewer failures on 300 trials with a failure probability of 25% is 0.0000000000412,  or one in 24.3 billion. So at that rate you would have to spend something like 243 trillion before you could expect to win 1 trillion. I was going to say that the administrators of the game would therefore be very happy, but with on average 120 trials before each failure the $10,000 probably does not cover their personnel costs to administer the game for the necessary weeks...
Quantum limits
If these three people share a quantum-entangled state of three qubits, their chance of failure is 0%. To see this, define $|+\rangle = |0\rangle + |1\rangle$ and $|-\rangle = |0\rangle - |1\rangle.$ The state $|+++\rangle + |---\rangle$ only has even sums (in the qubits' computational basis) in it: "make the sum of your numbers even," check. Just don't modify the state, and measure it.
The state $|+++\rangle - |---\rangle$ has only odd terms. Any two people can transform the former into the latter by the unitary mapping $|+\rangle \mapsto |+\rangle,$ and $|-\rangle \mapsto i|-\rangle,$  and then whatever they measure is odd.
However, quantum entanglement, to be preserved, needs to be isolated from the world around it. Basically, if an entangled qubit interacts with its environment in different ways for its $|0\rangle$ and $|1\rangle$ states, then this interaction causes the environment itself to now be entangled with the qubit, and in practice that means that no qubit is 100% faithful. But if each qubit has roughly a 3% error over the course of the experiment and we naïvely sum that to a 9% error for the whole ensemble, we get a 76.4% chance of passing all of the trials, which is pretty darn good; we'll probably get it the first try and we'll almost definitely get it in the first 4.


text:
Q: Clone the HDD of a broken PS3 to a new one My PS3 recently died and I'm planning on getting a new one. Since I won't be able to use the data transfer utility couldn't I clone the HDD to the new PS3 HDD?

A: No not really.  I hate to be the barer of bad news but because of Sony's obsessive security your data is probably lost.  There's no way to clone a PS3 drive or swap it over into another machine and have it work because it's pretty much bonded to the machine it came from.(at least from what I know)


text:
Q: How to import a function from python file by Boost.Python I am totally new to boost.python.
I reviewed a lot of recommending of using boost.python to apply with python, however still not easy to understand and find a solution for me.
What I want is to import a function or class that directly from a python "SourceFile"
Example File:
Main.cpp
MyPythonClass.py
Let's says if there is a "Dog" class in "MyPythonClass.py" with "bark()" function, how do I get callback and send argument in cpp?
I have no idea what I should do!
Please help me!

A: When one needs to call Python from C++, and C++ owns the main function, then one must embed the Python interrupter within the C++ program.  The Boost.Python API is not a complete wrapper around the Python/C API, so one may find the need to directly invoke parts of the Python/C API.  Nevertheless, Boost.Python's API can make interoperability easier.  Consider reading the official Boost.Python embedding tutorial for more information.

Here is a basic skeleton for a C++ program that embeds Python:
int main()
{
  // Initialize Python.
  Py_Initialize();

  namespace python = boost::python;
  try
  {
    ... Boost.Python calls ...
  }
  catch (const python::error_already_set&)
  {
    PyErr_Print();
    return 1;
  }

  // Do not call Py_Finalize() with Boost.Python.
}

When embedding Python, it may be necessary to augment the module search path via PYTHONPATH so that modules can be imported from custom locations.
// Allow Python to load modules from the current directory.
setenv("PYTHONPATH", ".", 1);
// Initialize Python.
Py_Initialize();

Often times, the Boost.Python API provides a way to write C++ code in a Python-ish manner.  The following example demonstrates embedding a Python interpreter in C++, and having C++ import a MyPythonClass Python module from disk, instantiate an instance of MyPythonClass.Dog, and then invoking bark() on the Dog instance:
#include <boost/python.hpp>
#include <cstdlib> // setenv

int main()
{
  // Allow Python to load modules from the current directory.
  setenv("PYTHONPATH", ".", 1);
  // Initialize Python.
  Py_Initialize();

  namespace python = boost::python;
  try
  {
    // >>> import MyPythonClass
    python::object my_python_class_module = python::import("MyPythonClass");

    // >>> dog = MyPythonClass.Dog()
    python::object dog = my_python_class_module.attr("Dog")();

    // >>> dog.bark("woof");
    dog.attr("bark")("woof");
  }
  catch (const python::error_already_set&)
  {
    PyErr_Print();
    return 1;
  }

  // Do not call Py_Finalize() with Boost.Python.
}

Given a MyPythonClass module that contains:
class Dog():
    def bark(self, message):
        print "The dog barks: {}".format(message)

The above program outputs:
The dog barks: woof

A: Boost python is used to call cplusplus functions from a python source. Pretty much like the Perl xs module.
If you have a function say bark() in main.cpp, you can use boost python to convert this main.cpp into a python callable module.
Then from python script(assuming link output file is main.so):
import main
main.bark()


text:
Q: "Bundle "App" does not exist or it is not enabled I'm getting this error when GETing{{url}}/api/user/me:

An exception has been thrown during the rendering of a template ("Bundle >"App" does not exist or it is not enabled. Maybe you forgot to add it in the >registerBundles() method of your App\Kernel.php file? in @App/Controller/UserController (which is being imported from "....\config/routes.yaml"). Make >sure the "App/Controller/UserController" bundle is correctly registered and >loaded in the application kernel class. If the bundle is registered, make >sure the bundle path "@App/Controller/UserController" is not empty.").

I'm using FOSRestBundle and FOSOauthBundle.
routes.yml
app_api:
  resource: "@App/Controller/UserController"
  type:     annotation

bundles.php
<?php

return [
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
    Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle::class => ['all' => true],
    Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
    Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
    Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
    Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle::class => ['all' => true],
    Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
    Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
    Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
    Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true],
    Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
    Symfony\Bundle\WebServerBundle\WebServerBundle::class => ['dev' => true],
    Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
    Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
    Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle::class => ['all' => true],
    FOS\OAuthServerBundle\FOSOAuthServerBundle::class => ['all' => true],
    FOS\RestBundle\FOSRestBundle::class => ['all' => true],
    JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true],
    Nelmio\ApiDocBundle\NelmioApiDocBundle::class => ['all' => true],
    FOS\UserBundle\FOSUserBundle::class => ['all' => true]
];

UserController
<?php

namespace App\Controller;

use App\Entity\User;
use App\Service\UserService;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

/**
 * @RouteResource("User")
 */
class UserController extends AbstractFOSRestController implements ClassResourceInterface
{
    /**
     * @var TokenStorageInterface
     */
    private $tokenStorage;

    /**
     * @param TokenStorageInterface $tokenStorage
     */
    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    /**=
     * @Route("/api/user/me")
     * @Method("GET")
     *
     * @return User|string
     */
    public function getMeAction()
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

        $loggedInUser = $this->tokenStorage->getToken()->getUser();

        return new Response($loggedInUser);
    }

composer.json
...
"autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
...

Directory

A: The @App/... notation with the "at" symbol is used purely to resolve the location of a bundle.
You are trying to resolve the location of your project source files which do not live in a bundle.
In routes.yml try this instead:
app_api:
  resource: "../src/Controller/*"
  type:     annotation


text:
Q: how to send this txtPath to encrpt.addActionListener I am trying to select a .txt file using JFileChooser and store it in a JTextField.  I named the field txtPath  The problem is that it is not reading the txtPath.
txtPath.setText(fileChooser.getSelectedFile().toString());

---

public void actionPerformed(ActionEvent evt)
{
  File f = new File(txtPath);
  int ch;

  StringBuffer strContent = new StringBuffer("");
  FileInputStream fin = null;
  try
  {
    fin = new FileInputStream(f);
    while ((ch = fin.read()) != -1)
      strContent.append((char) ch);
    fin.close();
  }
  catch (Exception e)
  {
    System.out.println(e);
  }
  System.out.println("Original string: " +strContent.toString()+"\n");
}

A: You want:
File f = new File(txtPath.getText());

instead of:
File f = new File(txtPath);

Otherwise you are feeding the File constructor an object reference, not the text contained in the JTextField object.

A: I'd say use method getText() to first extract string from text field


text:
Q: Buffering Micro-SD data for power saving useful? I have a datalogger which has only 4KB of SRAM, and because of that it needs to flush its buffer to MicroSD every second. Would adding external SRAM to create a larger buffer safe any significant power? Because when I look into Sandisk's datasheets it says that their cards go into sleep-mode after 5 ms. So it seems there would be no difference in writing every second vs. writing once in 30 seconds? However everything I've hearded untill now seems to contradict that.

A: There are 4 numbers you need:
A. Power when writing. Assumed 200 mA.
B. Power when not in sleep mode, but not writing.
C. Power when in sleep mode. Assumed 300 uA.
D. Time to perform a write
Power = Voltage * (A*D + (5 ms-D) * B + 995 mS * C).
If D ~ 5 ms; A is dominant.


text:
Q: Sum of complex number I tried to solve the following Sum of complex number:

$\sum_{k=0}^{32} (\frac{1}{2}+i\frac{\sqrt{3}}{2})^k$

I proceeded like this  :

$\sum_{k=0}^{32} (\frac{1}{2}+i\frac{\sqrt{3}}{2})^k$= $\sum_{k=0}^{32}e^{i\frac{2k\pi}{3}}$=$\frac{1-e^{i\frac{2*33\pi}{3}}}{1-e^{i\frac{2\pi}{3}}}$= $\frac{1-e^{{10i\pi}}}{1-e^{i\frac{2\pi}{3}}}$=$0$

The only problem is that $|e^{i\frac{2k\pi}{3}}|$=1. and not less then 1.

A: What's the problem? The equality$$\sum_{k=0}^Nz^k=\frac{1-z^{N+1}}{1-z}$$holds whenever $z\neq1$. So, your approach is correct. But note that$$\frac12+\frac{\sqrt3}2i=\exp\left(\frac{\pi i}3\right).$$Therefore, the answer is$$\frac{1-\exp\left(11\pi i\right)}{1-\exp\left(\frac{\pi i}3\right)}=\frac2{1-\exp\left(\frac{\pi i}3\right)}=1+\sqrt3\,i.$$


text:
Q: Android Httppost strange behaviour I have an Android App example I am trying to include into my App. This example shows how to connect to a MySql database and read the information stored into it (through a php file). If I use the example everything works, but if I include the Java files into my App it does not connect to the DB (I always got "Connection fail"). This is the piece of code:
public class DbselectActivity extends Activity {
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        String result = null;
        InputStream is = null;
        try {
          HttpClient httpclient = new DefaultHttpClient();
          HttpPost httppost = new HttpPost("http://www.volantinoweb.it/prova/selectall.php");
          HttpResponse response = httpclient.execute(httppost);
          HttpEntity entity = response.getEntity();
          is = entity.getContent();
        }
            catch(Exception e) {
          Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
        }
            //convert response to string
            try {
          BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
          StringBuilder sb = new StringBuilder();
          String line = null;
          while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
          }
          is.close();
          result=sb.toString();
        }
            catch(Exception e) {
              Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
            }

...
...
...


text:
Q: How to rotate the hands of clock for the 24 hour clock? I am working on a clock project, i know how to implement hands (Hour, Minute, Seconds) rotation of 12 hour clock. The code i have used is follows
CGFloat secAngle,minAngle,hourAngle;

NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
NSInteger seconds = [dateComponents second];
NSInteger minutes = [dateComponents minute];
NSInteger hours = [dateComponents hour];

if (timeFormat == 12)//12 hour clock
{

    if (hours > 12) hours -=12; //PM

     secAngle = Degrees2Radians(seconds/60.0*360);
     minAngle = Degrees2Radians(minutes/60.0*360);

     hourAngle = Degrees2Radians(hours/12.0*360) + minAngle/12.0;

    //secHand.transform = CATransform3DMakeRotation (secAngle+M_PI, 0, 0, 1);
    minHand.transform = CATransform3DMakeRotation (minAngle+M_PI, 0, 0, 1);
    hourHand.transform = CATransform3DMakeRotation (hourAngle+M_PI, 0, 0, 1);
}
else //24 hour clock
{

    secAngle = Degrees2Radians(seconds/60.0*360);
    minAngle = Degrees2Radians(minutes/60.0*360);
    hourAngle = (30 * hours + minutes / 2) /2;

    //secHand.transform = CATransform3DMakeRotation(secAngle * M_PI / 180,0,0,1);
    minHand.transform = CATransform3DMakeRotation(minAngle * M_PI ,0,0,1);
    hourHand.transform = CATransform3DMakeRotation(hourAngle * M_PI,0,0,1);

}

But when i try to implement the 24 hour clock. It is not working. Each time when i run this project the clock shows wrong timings.
Can anyone tell me what wrong do i did. Many thanks in advance

A: Here's how I do it - I use the face center and the angle to compute the x,y position of the endpoints of the hands, drawing is simple from there.  Here's a complete clock face class.  It's a subclass of UIView.  Set it's time property every second and it works like a charm...
//
//  ClockFace.h
//

#import <UIKit/UIKit.h>

@interface ClockFace : UIView

@property (strong,nonatomic) NSDate *time;

@end

//  ClockFace.m

#import "ClockFace.h"

@interface ClockFace ()

@property(assign,nonatomic) CGPoint boundsCenter;
@property(assign,nonatomic) NSInteger seconds;
@property(assign,nonatomic) NSInteger minutes;
@property(assign,nonatomic) NSInteger hours;

@end

@implementation ClockFace

@synthesize time=_time;
@synthesize boundsCenter=_boundsCenter;

- (id)initWithCoder:(NSCoder *)aDecoder {

    self = [super initWithCoder:aDecoder];
    if (self) {
        _boundsCenter = CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _boundsCenter = CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
    }
    return self;
}

- (CGPoint)secondsHandPosition {

    float secondsAsRadians = (float)self.seconds / 60.0 * 2.0 * M_PI - M_PI_2;
    float handRadius = self.frame.size.width / 2.4;
    return CGPointMake(handRadius*cosf(secondsAsRadians)+self.boundsCenter.x, handRadius*sinf(secondsAsRadians)+self.boundsCenter.y);
}

- (CGPoint)minutesHandPosition {

    float minutesAsRadians = (float)self.minutes / 60.0 * 2.0 * M_PI - M_PI_2;
    float handRadius = self.frame.size.width / 2.2;
    return CGPointMake(handRadius*cosf(minutesAsRadians)+self.boundsCenter.x, handRadius*sinf(minutesAsRadians)+self.boundsCenter.y);
}

- (CGPoint)hoursHandPosition {

    float hoursAsRadians = (float)self.hours / 12.0 * 2.0 * M_PI - M_PI_2;
    float handRadius = self.frame.size.width / 3.8;
    return CGPointMake(handRadius*cosf(hoursAsRadians)+self.boundsCenter.x, handRadius*sinf(hoursAsRadians)+self.boundsCenter.y);
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGFloat zClear[4] = {1.0,1.0,1.0,0.0};
    CGContextSetFillColor(context, zClear);
    CGContextFillRect(context, rect);

    CGRect face = CGRectInset(rect, 1.0, 1.0);
    CGContextSetLineWidth(context, 1.0);
    CGContextAddEllipseInRect(context, face);
    CGContextStrokePath(context);

    CGRect center = CGRectMake(self.boundsCenter.x-2.0, self.boundsCenter.y-2.0, 4.0, 4.0);
    CGContextAddEllipseInRect(context, center);
    CGContextStrokePath(context);

    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGPoint secondsHandPosition = [self secondsHandPosition];

    CGContextSetStrokeColor(context, red);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, self.boundsCenter.x, self.boundsCenter.y);
    CGContextAddLineToPoint(context, secondsHandPosition.x, secondsHandPosition.y);
    CGContextStrokePath(context);

    CGFloat black[4] = {0.0f, 0.0f, 0.0f, 1.0f};
    CGPoint minutesHandPosition = [self minutesHandPosition];

    CGContextSetStrokeColor(context, black);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, self.boundsCenter.x, self.boundsCenter.y);
    CGContextAddLineToPoint(context, minutesHandPosition.x, minutesHandPosition.y);
    CGContextStrokePath(context);

    CGPoint hoursHandPosition = [self hoursHandPosition];

    CGContextSetStrokeColor(context, black);
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, self.boundsCenter.x, self.boundsCenter.y);
    CGContextAddLineToPoint(context, hoursHandPosition.x, hoursHandPosition.y);
    CGContextStrokePath(context);
}

- (void)setTime:(NSDate *)time {

    _time = time;

    static NSCalendar *gregorian;

    if (!gregorian) gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *weekdayComponents =
    [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:time];

    self.hours = [weekdayComponents hour];
    if (self.hours > 12) self.hours -= 12;
    self.minutes = [weekdayComponents minute];
    self.seconds = [weekdayComponents second];

    [self setNeedsDisplay];
}

@end

To use this in a view controller, create a property:
#import "ClockFace.h"

// ...

@property(strong, non atomic) ClockFace *clockFace;

In view did load (or in storyboard if you know how to add custom views):
self.clockFace = [[ClockFace alloc] initWithFrame:CGRectMake(10, 10, 300, 300)];

Whenever you want the clock to run, setup a timer:
[NSTimer scheduledTimerWithTimeInterval:1.0
    target:self
    selector:@selector(timerFired:)
    userInfo:nil
    repeats:NO];

When the timer fires, tell the clock what time it is:
- (void)timerFired:(NSTimer *)timer {

    self.clockFace.time = [NSDate date];
}

A: @danh answer updated for Swift.
ClockFace:
class ClockFace: UIView {

    var calendar: NSCalendar!
    var time: Date!
    private var figureCenter: CGPoint = .zero
    private var faceRadius: CGFloat = 0
    private var seconds: Int = 0
    private var minutes: Int = 0
    private var hours: Int = 0
    private let angleOffset: CGFloat = -.pi / 2 // an offset to make 0 at "12:00" instead of "3:00"

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        figureCenter = CGPoint(x: bounds.midX, y: bounds.midY)
        faceRadius = frame.size.width / 2.0
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        // Initialization code
        figureCenter = CGPoint(x: bounds.midX, y: bounds.midY)
        faceRadius = frame.size.width / 2.0
    }

    func secondsHandPosition() -> CGPoint {
        let radiansPerSecond = (CGFloat.pi * 2) / 60
        let secondsAsRadians: CGFloat = angleOffset + (CGFloat(seconds) * radiansPerSecond )
        let handRadius: CGFloat = faceRadius / 1.1
        return CGPoint(x: CGFloat(handRadius * cos(secondsAsRadians) + figureCenter.x), y: CGFloat(handRadius * sin(secondsAsRadians) + figureCenter.y))
    }

    func minutesHandPosition() -> CGPoint {
        let radiansPerMinute = (CGFloat.pi * 2) / 60
        let minutesAsRadians: CGFloat = angleOffset + (CGFloat(minutes) * radiansPerMinute)
        let handRadius: CGFloat = faceRadius / 1.25
        return CGPoint(x: CGFloat(handRadius * cos(minutesAsRadians) + figureCenter.x), y: CGFloat(handRadius * sin(minutesAsRadians) + figureCenter.y))
    }

    func hoursHandPosition() -> CGPoint {
        let radiansPerHour = (CGFloat.pi * 2) / 12
        let hoursAsRadians: CGFloat = angleOffset + (CGFloat(hours) * radiansPerHour)
        let handRadius: CGFloat = faceRadius / 1.8
        return CGPoint(x: CGFloat(handRadius * cos(hoursAsRadians) + figureCenter.x), y: CGFloat(handRadius * sin(hoursAsRadians) + figureCenter.y))
    }

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()!
        context.setFillColor(UIColor.white.cgColor)
        context.fill(rect)

        for count in 0...60 {
            let tickRadius = faceRadius / ((count % 5 == 0) ? 1.20 : 1.15)
            let lineWidth = (count % 5) == 0 ? 3 : 2
            let tickAngle = CGFloat(count) * ((CGFloat.pi * 2) / 60)
            context.beginPath()
            context.move(to: CGPoint(x: CGFloat(faceRadius * cos(tickAngle) + figureCenter.x), y: CGFloat(faceRadius * sin(tickAngle) + figureCenter.y)))
            context.addLine(to: CGPoint(x: CGFloat(tickRadius * cos(tickAngle) + figureCenter.x), y: CGFloat(tickRadius * sin(tickAngle) + figureCenter.y)))

            context.setStrokeColor(UIColor.black.cgColor)
            context.setLineWidth(CGFloat(lineWidth))
            context.strokePath()
        }

        let lineWidth: CGFloat = 5.0
        let face = rect.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)
        context.setLineWidth(lineWidth)
        context.addEllipse(in: face)
        context.strokePath()

        let secondsHandPosition = self.secondsHandPosition()

        context.beginPath()
        context.move(to: figureCenter)
        context.addLine(to: secondsHandPosition)
        context.setLineWidth(1)
        context.setStrokeColor(UIColor.red.cgColor)
        context.strokePath()

        let minutesHandPosition = self.minutesHandPosition()

        context.beginPath()
        context.move(to: figureCenter)
        context.addLine(to: minutesHandPosition)
        context.setLineWidth(3)
        context.setStrokeColor(UIColor.black.cgColor)
        context.strokePath()

        let hoursHandPosition = self.hoursHandPosition()

        context.beginPath()
        context.move(to: figureCenter)
        context.addLine(to: hoursHandPosition)
        context.setLineWidth(5)
        context.setStrokeColor(UIColor.black.cgColor)
        context.strokePath()

        let center = CGRect(x: figureCenter.x - 5.0, y: figureCenter.y - 5.0, width: 10.0, height: 10.0)
        context.addEllipse(in: center)
        context.setFillColor(UIColor.black.cgColor)
        context.fillPath()
        context.strokePath()
    }

    func setTime(_ time: Date?) {

        self.time = time
        var weekdayComponents: DateComponents!

        if calendar == nil {
            calendar = NSCalendar(identifier: NSCalendar.Identifier.gregorian)
        }

        if let time = time {
            weekdayComponents = calendar.components([.day, .weekday, .hour, .minute, .second], from: time)
        }

        if weekdayComponents != nil {
            hours = weekdayComponents.hour!
            minutes = weekdayComponents.minute!
            seconds = weekdayComponents.second!

            hours = (hours + (12 - 1)) % 12 + 1;
        }

        self.setNeedsDisplay()
    }
}

View Controller:
class ViewController: UIViewController {

    @IBOutlet weak var clockView: ClockFace!

    override func viewDidLoad() {
        super.viewDidLoad()

        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerFired(_:)), userInfo: nil, repeats: true)
    }

    @objc func timerFired(_ timer: Timer?) {
        clockView.setTime(Date())
    }
}


text:
Q: Tracking click on dynamic button via php I need to track a dynamic button that sends the user to another url, depending on the product he is. Something like pinterest. The website is in PHP.
I'm having problems tracking how many user clicked on the button. Tried Piwik, Google, Clicky, Mixpanel and Kissmetrics. Everyone gives different data. For what I've been searching some users say it's a javascript problem because outbound timing. Also tried with a sendmail function, but it sent an email everytime the user visited the product, not everytime he clicked on the button
Is there an easy way to track those clicks inside my site without using any of those metrics services? I just need to track 2 things:

*

*url (where is sending the user)

*clicks (number of clicks)

A: This sounds like you sould just have to send an ajax request to the server (assuming you defined the global variable clicks
var url = 'yourUrl';

clicks++;

$('#yourBtn').click(function() {
$.ajax({
   data: {url: url, clicks: clicks},
   url: 'ajax/test.html',
   success: function(data) {
     alert('Load was performed.');
   }
 });
});


text:
Q: Creating an array from other arrays I'm pulling data from a table in two different queries, and I am trying to compare the date field from both results. When the date is equal I want to add the two ending balances from each query together and put the results into a new array. The problem I am having is on line 59, The error I get is
 Notice: Undefined offset.
This is what I have:
 include "../sqlConnect.php";

 mysqli_set_charset($dbScrap, 'utf8');
 $dataArray[] = array();
$dateArray[] = array();
$balanceArray[] = array();

//Smaller
$query = "SELECT Account, Date ,SUM(EndingBalance) AS 'Month_Total' FROM gl_period_posting_history
    INNER JOIN gl_account
      ON gl_period_posting_history.AccountKey = gl_account.AccountKey
  Where gl_account.Account= '5010-15-0000' AND  FiscalYear > 2012
  GROUP BY Account, Date";

$result = mysqli_query( $dbScrap, $query) or die("SQL Error 1: " .
mysqli_error($dbScrap));
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){

$EndingBalance15 = $row['Month_Total'];
$Date15 = $row['Date'];

$dateArray[] = array(
    'Date' => $Date15
);

$balanceArray[] = array(
    'EndingBalance' => $EndingBalance15
);

}

\\Bigger
    $query1 = "SELECT Account, Date ,SUM(EndingBalance) AS 'Month_Total' FROM gl_period_posting_history
    INNER JOIN gl_account
      ON gl_period_posting_history.AccountKey = gl_account.AccountKey
  Where gl_account.Account ='5010-08-0000' AND  FiscalYear > 2012
  GROUP BY Account, Date";

 $result = mysqli_query( $dbScrap,$query1) or die("SQL Error 1: " . mysqli_error($dbScrap));
 while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)){

$Date08 = $row['Date'];
$EndingBalance08 = $row['Month_Total'];

for($i = 0; $i < $dateArray; $i++){
        if($Date08 == $dateArray[$i]) {
            $message = "Date Equal";
            $EndingBalance = $EndingBalance08 + $balanceArray[$i];
            $Date = $Date08;
        }else{
            $message = "Date Not Equal";
            $Date = $Date08;
            $EndingBalance = $EndingBalance08;
        }
    }
    $dataArray[] = array(

        'EndingBalance' => $EndingBalance,
        'Date' => $Date,
        'Message' => $message
    );
 }
 echo "<pre>";
 print_r($dataArray);
 //echo json_encode($dataArray);
 echo "</pre>";

 $result->close();
 /* close connection */
 $dbScrap->close();

Thank you for your help.

A: The problem is in for loop, correction:
for ($i = 0; $i < count($dateArray); $i++){

A: In the loop where you fetch results from your first query, use the date from each row as the key in  $balanceArray, like this:
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
    $EndingBalance15 = $row['Month_Total'];
    $Date15 = $row['Date'];

    $balanceArray[$Date15] = $EndingBalance15;
}

Then in the loop where you fetch results from your second query, you can use isset to check if that date exists in the results from the first query, like this.
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {

    $Date08 = $row['Date'];
    $EndingBalance08 = $row['Month_Total'];

    if (isset($balanceArray[$Date08])) {
        $message = "Date Equal";
        $EndingBalance = $EndingBalance08 + $balanceArray[$Date08];
    } else {
        $message = "Date Not Equal";
        $EndingBalance = $EndingBalance08;
    }
    $dataArray[] = array(
        'EndingBalance' => $EndingBalance,
        'Date' => $Date08,
        'Message' => $message
    );
}


text:
Q: JavaScript not loading into HTML file I looked for a slider online and I got here (https://codepen.io/doodlemarks/pen/aFcly), so I copied the code into their respective html, css and js files (which contains more code), but the JS code ain't working. I linked it with a  tag, but still doesn't work. (The provided code is a fragment of the HTML file; The css and js code is copied into their files just as the page shows).

Galería

                >
                <

SLIDE 1

SLIDE 2

SLIDE 3

SLIDE 4

A: The src is supposed to provide a path to your JS file. If you have a file structure like:
>index.html
>main.js

( both being on the same level )
the src should be src="./main.js".


text:
Q: What does "type name{}" mean in C++? I found the following construction in the source code:
variable_type variable_name{func(arg1, arg2, arg3)};

In the next version of the code this construction has been replaced by the following one:
variable_type variable_name = func(arg1, arg2, arg3);

So, my question is what the first line mean and how is it different from the second line? I also would like to know why it might be better or worse to use the first line instead of the second one?

A: It is an example for a C++11 brace initialization.
See for example the following article:
https://www.informit.com/articles/article.aspx?p=1852519

A: The first line is a new feature from C++11 known as uniform initialization. This style of initialization can also be used on classes which define a constructor that takes an std::initializer_list, in which case such a constructor takes priority.


text:
Q: Grid search on epochs in neural network: each parameter being run 3 times My sequential dense DNN seems to run through each parameter in my parameter grid three times while doing Grid Search. I expect it to run once per specified epcohs in the grid: 10, 50 and 100. Why does this happen?
model architecture:
def build_model():
    print('building DNN architecture')
    model = Sequential()
    model.add(Dropout(0.02, input_shape = (150,)))
    model.add(Dense(8, init = 'normal', activation = 'relu'))
    model.add(Dropout(0.02))
    model.add(Dense(16, init = 'normal', activation = 'relu'))
    model.add(Dense(1, init = 'normal'))
    model.compile(loss = 'mean_squared_error', optimizer = 'adam')
    print('model succesfully compiled')
    return model

Grid search on epochs:
from sklearn.model_selection import GridSearchCV
epochs = [10,50,100]
param_grid = dict(epochs = epochs)
grid = GridSearchCV(estimator = KerasRegressor(build_fn = build_model), param_grid = param_grid)
grid_result = grid.fit(x_train, y_train)
grid_result.best_params_

A: Because GridSearchCV does both grid search and cross-validation. For each parameter combination, three (by default) splits are used for cross-validation, and this is why you see the model being trained three times for each parameter set.
You can change the number of folds (splits) with the "cv" parameter. Check it out in the documentation.


text:
Q: Using a calculated value in two places in a postgresql query I want to calculate the distance between two lat-longs, and display that value.
I also want to use that value (rounded to the nearest KM)
NOTE: Contrived example
Here's what I have
SELECT
ST_Distance(
   ST_GeogFromText(
     'SRID=4326;POINT(' || longitude || ' ' || latitude || ')'
   ),
   ST_GeogFromText('SRID=4326;POINT(1 1)')
 ) AS distance, id from locations limit 10

Now this works perfectly well..  I get distance in meters
But I want to get the distance in both meters and km  (for this question that is simple enough)
Here's what I thought would work
SELECT
ST_Distance(
   ST_GeogFromText(
     'SRID=4326;POINT(' || longitude || ' ' || latitude || ')'
   ),
   ST_GeogFromText('SRID=4326;POINT(1 1)')
 ) AS distance, distance/1000 as distance_in_km, id from locations limit 10

This returns an error..
column "distance" does not exist
It has the arrow pointing at the second "distance" in the query.
What I'd really like to avoid is having the calculation in both the full value and the rounded to KM
Please note: This is not the actual query, but one that was contrived to present the issue.

A: try this out :-
SELECT distance, distance/1000 as distance_in_km from
(
    SELECT
        ST_Distance(
            ST_GeogFromText(
            'SRID=4326;POINT(' || longitude || ' ' || latitude || ')'
        ),
        ST_GeogFromText('SRID=4326;POINT(1 1)')
    ) AS distance, id from locations limit 10
) t;


text:
Q: Assigning a Value from an MS Access Table to a Variable I'm attempting something that I believe should be very simple but it does not work.  I've got a repeater macro in MS Access that I want to use to output a set of data to a series of files.  I'm pulling the current record from my Table CurrentSt, field StCurr.  There is only 1 record in this table
In order to include StCurr in the name of the output, I'm doing the following:
 Dim VarOutPut As String
 VarOutPut = CurrentSt.StCurr

I'm then calling VarOutPut in my export command.  This works when I set VarOutPut to a fixed number (e.g. VarOutPut = "1000") but when I try to call the value from the CurrentSt table I get an "Object Required" error.
Any guidance would be greatly appreciated.

A: There are probably dozens of options for what you're asking. Without knowing more about the structure of your data, this is one possibility:
VarOutPut = DLookup("StCurr", "CurrentSt")

This assumes there is only one value / row in your table.
Otherwise, you will need another method.

A: CurrentSt has to have a reference to a specific table.   you can lookup values using the DLookup function
varoutput=DLookup("StCurr","CurrentSt",[Any criteria]) as [Type]

it would really be helpful to see all of your code.


text:
Q: What vector does the electrostatic field assign to a point? I know that the electrostatic field is a vector field. The definition of a vector field is that it is a function which assigns a vector to each point in space. So my question is: what vector does the electric field assign to each point? Sorry if the question sounds stupid, but the book I am using has been extremely unclear about this.

A: The electric field can be used like a sensor. Usually we have to ask the electric field function for an answer, say what is the electric field at this particular point [3,1]?
Then it will give us an answer as an arrow vector of some length. This arrow is the direction that a positive charge will follow if we let it go at this particular point. The length is how fast this positive charge will start to move move once we let it go.
Whether the field is "real" or not permeating all space is of some debate, I think, usually we can just think of the electric field as an arrow sign symbolizing what a positive charge will do if we release it at that particular place...
Hope it helps.

A: It assigns the electric field $\mathbf{E}$ in $\text{V}\,\text{m}^{-1}$. It is the force field of a test charge.

A: Field is an imaginary region in space in which evry point is affected by force. This applies to all field forces like gravity, eletrical, magnetic etc. It is a vector quantity
Coming to your eletrostatic field, its a type of field present which affects only particles having property of electrical charge. That is, that any partcile which possess such property of electrical charge, when placed in an electric field, experiences force. Thus, we write:
$$\vec F_{\text{electric}}=q\vec E$$
Electric field can also be written in electric potential terms:
$$\vec E=-\frac{dV}{d\vec r}$$
Now electric field is generated by particles possessing charge. Note that in reality, there is no significance of 'electric field lines' as depicted. They are imaginary.


text:
Q: nginx rewrite does not forward $arg_page to upstream I have
rewrite (?i)^/museums/Andorra /search-results?country=ad&page=$arg_page break;
// 246 more similar rewrites for other country codes.
proxy_pass http://127.0.0.1:7001;

and yet, when I go to /museums/Andorra&page=1 in the browser, the REQUEST_URI in the proxied app is set to /search-results?country=ad&page=
nginx is a bit old: 1.14.2 if that matters. This answer from 2013 however https://stackoverflow.com/a/17739990/308851 seems to suggests an $arg variable in the replacement part of rewrite should work.

A: You are correct that rewrite can use $arg_ parameters in the rewritten URI, although you do not necessarily need to.
There are two problems:
You do not need to add &page=$arg_page to the end of the rewritten URI, as rewrite will automatically append the original query string unless the rewritten URI ends with a ?. So your existing rewrite statement will generate /search-results?country=ad&page=1&page=1 (assuming that the $arg_page variable is set).
Use either:
rewrite (?i)^/museums/Andorra /search-results?country=ad break;

Or:
rewrite (?i)^/museums/Andorra /search-results?country=ad&page=$arg_page? break;

See this document for details.

Your test URL does not contain a query string.
Use:
/museums/Andorra?page=1


text:
Q: How to update MySql timestamp column to current timestamp on PHP? I want to update the columns of data type timestamp manually through my PHP code.
Can you please tell me how to do that?

A: Use this query:
UPDATE `table` SET date_date=now();

Sample code can be:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE `table` SET date_date=now()");

mysql_close($con);
?>

A: Another option:
UPDATE `table` SET the_col = current_timestamp

Looks odd, but works as expected.  If I had to guess, I'd wager this is slightly faster than calling now().


text:
Q: Sequence ALTER RESTART does not affect on the current value of a sequence Why the next ALTER does not define currval of the sequence comments_comment_id_seq?
db=# alter sequence comments_comment_id_seq restart with 65545;
ALTER SEQUENCE
db=# SELECT currval('comments_comment_id_seq');
ERROR:  currval of sequence "comments_comment_id_seq" is not yet defined in this session
db=#

Additional detail
The table which owns the sequence is a child of another table:
   Column   |            Type             |                             Modifiers
------------+-----------------------------+--------------------------------------------------------------------
 comment_id | bigint                      | not null default nextval('comments_base_comment_id_seq'::regclass)
 auser_id   | bigint                      | not null
 dt         | timestamp without time zone | not null
 text       | text                        | not null
 is_deleted | smallint                    | default 0
 parent     | bigint                      | default 0
 post_id    | bigint                      | not null
Indexes:
    "comments_pkey" PRIMARY KEY, btree (comment_id)
Inherits: comments_base

A: When you restart the sequence you set it into a state like it was just created. And in this case you don't have a currval before you first selected a nextval.


text:
Q: Disqus get comments count I know this seems like a simple question, but I have discovered there is no simple way of getting comment count for a given disqus identifier in an ajax page.
I have looked at their API, and this is an option, but we are building an ajax cms-based website for end-users, and it would seem a bit tedious to force each user to have to create their own disqus application API and fill in public and secret keys just to get comments count. Besides, it seems overkill to load a separate remote JS, returning an entire JSON object, just to get the current page comments count.
There is a count.js script here, but there is no information about how to update count dynamically for ajax pages. Well almost ... after a lot of searching, I found some undocumented method DISQUSWIDGETS.getCount(). However, this stops working after one call for each identifier. Besides, this method also requires loading an external JS just to get comments count ...
Seems strange #comments amount cannot be extracted easier. The amount of comments is after all available after comments are displaying on the page, but we can't access that iframe with JS of course. Any enlightenments are appreciated ...

A:  This is the html file which will help you to count the number of comments in a particular node in for any site which has disqus comment.

  <!DOCTYPE html>

      <title>Disqus Comment Counts Example</title>

Comment Counts Example

Fullscreen BEAM: The first YouTube app for Google Glass comes with    public or private sharing

       <button type="button" id="get-counts-button">Get Comment Counts</button>


text:
Q: perl script to convert the string EXP501.1-01.0 to EXP501_01 I want to convert the string

EXP501.1-01.0

to

EXP501_01

That means -01, -02, -03... are incremental and I want to append that same number which is in first string next to the _ of the second string (which will be parsed on the basis of the first string).

A:     my $string = "EXP501.1-01.0";
    $short = substr($string, 0, -7);
    $new = substr($string,8,-2);
    my $str = $short . $new;
    $str =~ s/ - /_/g; # Replace all " - " with "_"
    $str =~ s/[^A-Za-z0-9]/_/g; # Replace all non-alphanumericals with "_"

    print $str . "\n";


text:
Q: Cutting down calculations Okay so I was solving some questions on vectors but then I came across a question which I could not  solve quickly enough . The method I used is basically super lengthy and prone to errors . I had to find the values of $\lambda$ and $\mu$ using the two relations (comparing them).
Basically I found the coordinates of the same point once in terms of $\lambda$ and then in terms of $\mu$ .
$$\left (\frac{16\lambda + 6}{\lambda +1}\right),\left (\frac{-19\lambda - 7}{\lambda +1}\right),\left (\frac{-4\lambda}{\lambda +1}\right) \cdots (1)$$
$$\left (\frac{2\mu}{\mu +1}\right),\left (\frac{-5\mu+3}{\mu +1}\right),\left (\frac{10\mu-6}{\mu +1}\right) \cdots  (2)$$
On comparing I eventually get $\lambda=\frac{-1}{3}$ and $\mu=1$.
The thing is this takes too much time ? Is there a better way to do this ?
P.S. - I made $3$ equations and solved them and basically made more equations and solved them to get these values.

A: You said in the comments that the problem has originated as a question to find the intersection of two lines $AB$ and $CD$, where the co-ordinates of the points $A,B,C,D$ are given.
Solution: Express $X$ via those points as follows:
$$\vec{AX}=\alpha\vec{AB}\text{, i.e. }X=A+\alpha(B-A)$$
$$\vec{CX}=\beta\vec{CD}\text{, i.e. }X=C+\beta(D-C)$$
This gives us the vector equation:
$$\alpha(B-A)-\beta(D-C)=C-A$$
which, when written in co-ordinates, gives you a system of linear equations with unknowns $\alpha$ and $\beta$. Solving this system provides you with $\alpha$ and $\beta$, and therefore with $X$. Beware: this system may have zero, one or multiple solutions in ($\alpha, \beta$).
Example: With $A(6,-7,0)$, $B(16,-19,-4)$,$C(0,3,-6)$,$D(2,-5,10)$, the calculation goes as follows:
$$X=(6,-7,0)+\alpha((16,-19,-4)-(6,-7,0))=(6+10\alpha, -7-12\alpha, -4\alpha)$$
$$X=(0,3,-6)+\beta((2,-5,10)-(0,3,-6))=(2\beta, 3-8\beta, -6+16\beta)$$
which gives us the system:
$$\begin{array}{rcl}6+10\alpha&=&2\beta\\-7-12\alpha&=&3-8\beta\\-4\alpha&=&-6+16\beta\end{array}$$
or:
$$\begin{array}{lll} 10\alpha&-2\beta&=-6\\-12\alpha&+8\beta&=10\\-4\alpha&-16\beta&=-6\end{array}$$
Solving this gives a unique solution $\alpha=-\frac{1}{2}, \beta=\frac{1}{2}$, which then in turn gives $X=(1, -1, 2)$.

A: If $a_1, a_2, a_3$ are the values in (1), and $b_1, b_2, b_3$ those in (2), we see immediately $b_3=-2\,b_2$, and $a_3=-2\,a_2$ means $38\lambda+14=-4\,\lambda$, i.e. $\lambda=-1/3$. $a_1=b_1$ now gives $\mu=1$.

A: I hope this could be a shortcut. We solve for the two equations $$\frac{16\lambda+6}{\lambda+1}=\frac{2\mu}{\mu+1}\implies 7\mu\lambda+8\lambda+2\mu+3=0\\\frac{-4\lambda}{\lambda+1}=\frac{10\mu-6}{\mu+1}\implies7\mu\lambda-\lambda+5\mu-3=0$$ Subtracting gives $$9\lambda-3\mu+6=0\implies\mu=3\lambda+2$$ Plugging this into the first equation, $$7(3\lambda+2)\lambda+8\lambda+2(3\lambda+2)+3=21\lambda^2+28\lambda+7=0\implies 3\lambda^2+4\lambda+1=0$$ giving $\lambda=-\dfrac13,-1$, but $\lambda\neq-1$ due to the denominator so we have $\boxed{\lambda=-\frac13\implies\mu=-1}$


text:
Q: Absolute value and limit reasoning. I am trying to develop my reasoning ability with absolute value. So, I wanted to know if the following reasoning is correct:
Find $\lim_{x \to -6}\dfrac{2x+12}{|x+6|}$
By definition of absolute value we have $|x| = x$ when $x > 0$ and $|x| = -x$ when $x<0$
So for the above limit we can consider the limit from the left and the limit from the right: $(x+6)<0$ and $(x+6)>0$:
Case $(x+6)<0$:
$\dfrac{2x+12}{-(x+6)} = \dfrac{2(x+6)}{-(x+6)} = -2$
Case $(x+6) > 0$:
$\dfrac{2x+12}{(x+6)} = \dfrac{2(x+6)}{(x+6)} = 2$
Hence, the limits from the left and right are not and equal and we conclude that the limit does not exist.

*

*If we were not considering the limit at $-6$ we could just evaluate the function at any point since the function is continuous everywhere else

*I graphed this function and I see that I have a vertical asymptote at $x=-6$. What do these left and right limits evaluating to $-2$ and $2$ mean then?

A: Yes, your reasoning is correct.

A: As echoed by others, your reasoning is correct.
Your graph should consist of 2 horizontal lines:
$y=2$ if $x>6$
$y=-2$ if $x<6$
The function is undefined at $x=6$.
Approaching $x=-6$ from the left, you will approach -2, even though the function is undefined at $x=6$. Likewise, approaching $x=-6$ from the right, you will approach 2.
The meaning of "approaching" in this case is pretty intuitive, as the function doesn't change value on each side of $x=6$. For a more rigorous definition of what "approaching" means in the general case, read about the epsilon-delta definition of limit.


text:
Q: What does $f:[0, 1] \rightarrow [0,1]\times[0, 1]$ mean? I'm not sure what the right hand side of the function definition stands for? Does that mean that the output is a matrix?

A: The output lives in the set $\{(x,y) | x \in [0,1], y\in [0,1] \}$.
In LaTeX you should use "\times" rather than a capital X to represent this - it's called a Cartesian product of two sets.

A: To elaborate in more layman terms, the function maps any number between 0 and 1 inclusive to a point in the unit square.


text:
Q: MimeDecode koi8r charset I've a problem with koi8r charset with mimeDecode,
As an example:
Subject: =?KOI8-R?B?8NLJ18XUIQ==?=
   From: =?KOI8-R?B?4czFy9PBzsTSIPfPzMvP1w==?=
Becomes:
Subject: п÷я─п╦п╡п╣я┌!
   From: Александр Волков
It should be as follows,
Subject: Привет!
   From: Александр Волков
So the exact problem is
        if (is_string($this->_decode_headers)) {
            $conv = @iconv($charset, $this->_decode_headers, $text);
            $text = ($conv === false) ? $text : $conv;
        }

Thank you.
UPDATE
Solved, the problem was email headers were saved to db in other charset.

A: Don't you want to use mb_decode_mimeheader ?
iconv translates encoded strings, here your string is only ascii.
mb_internal_encoding("UTF-8");
$string = "=?KOI8-R?B?8NLJ18XUIQ==?=";
$conv = mb_decode_mimeheader($string);

This will work provided that you're sending utf-8 encoded string of course, otherwise you have to adapt the first command


text:
Q: How to insert character in between a string in SQL Server 2008? I need help in inserting a character inside a string, e.g.:
031613 05:39 AM
The output should be:
03/16/13 05:39 AM

A: You can use STUFF
DECLARE @String NVARCHAR(20) = '031613 05:39 AM'

SELECT STUFF(STUFF(@String,3,0,'/'),6,0,'/')

Fiddle

A: How about using SUBSTRING?
DECLARE @String VARCHAR(50) = '031613 05:39 AM'

SELECT  @String,
        SUBSTRING(@String,1,2) + '/' + SUBSTRING(@String,3,2) + '/' + SUBSTRING(@String,3,2) + SUBSTRING(@String,7,LEN(@String)-6)

SQLFiddle DEMO

A: use can also do like this.. but quite big solution.
declare @T varchar(100)= '031613 05:39 AM'
declare @result varchar(100) =''

;with CTE
as
(
Select 0 as startIndex, 2 as endIndex
union all
select convert(int, endIndex) as startIndex , endIndex+2 as endIndex from CTe where endIndex < charindex(' ',@T)
)
select top 3 @result += substring(@T,startIndex+1, endIndex-startIndex)+'/' from CTe
select substring( @result,0,len(@result))


text:
Q: Converting an Actionscript 2 Script to an AS3 Equivalent I have the following code to open a document through a separate window (through a button action) in AS2:
mapSym_btn.onRelease = function() {
getURL ("https://myPortal.html", "_blank")}

Can anyone show me how to get the same results in AS3? I'd appreciate any assistance.

A: (untested code)
mapSym_btn.addEventListener(MouseEvent.CLICK, goSomewhere);
function goSomewhere(evt:MouseEvent):void {
   var request:URLRequest = new URLRequest("https://myPortal.html");
   try{
      navigateToURL(request, "_blank")
   } catch(e:Error){
      trace("Ah snap, there was a problem!");
   }
}


text:
Q: HTML Landing Page Override for Magento Store is there a way to override a Magento store (a store within a magento install, that isnt the primary one)?
I have a html landing page I want to put in place of the store while Im developing it.
Is this possible? What is the best way?

A: You could use a simple rewrite rule in your .htaccess
Eg.
# replace to suit the domain
RewriteCond %{HTTP_HOST} www.example.com
# change to suit your own IP
RewriteCond %{REMOTE_ADDR} !^x\.x\.x\.x
RewriteCond %{REQUEST_URI} !^/maintenance\.htm$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/maintenance.htm [R=307,L]


text:
Q: Как в Objective-J отправить запрос на получение RSS ленты? Всем привет! Недавно начал знакомится с web фреймверком Cappuccino. Подскажите пожалуйста как отправить запрос на получение RSS ленты?
Пробовал делать вот таким способом:
var request = [CPURLRequest requestWithURL:"http://www.domain.ru/rss.xml"];
var connection = [CPURLConnection connectionWithRequest:request delegate:self];
...

- (void)connection:(CPURLConnection)aConnection didReceiveData:(CPString)data
{
CPLog.debug(data);
}

Но CPLog.debug(data); выводить в FireBug пустую строку.
A: Посмотрите здесь: cappuccino-rss-reader-tutorial.
var request = [CPURLRequest requestWithURL:"https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=" + encodeURIComponent([aFeed url])];
[request setValue:@"http://gregbell.ca" forHTTPHeaderField:@"Referer"];

[CPJSONPConnection sendRequest:request callback:"callback" delegate:self];


text:
Q: How Do I Recover Formatted Mac hfs+ Partition? I was installing Win8 on a Mac where I got the error that I can because of GPT disk I dont know what MAC I have but the Mainboard is number is Apple Mac 942859f58194171B. I tried formatting the specific partition not the disk but unfortunately, I formatted the disk which contained my MAC OS together with the Recovery. I am now stuck in windows and I don't have the MAC Recovery Disk. What can I do to recover my MAC OS and potentially recovery in Windows?

A: The easiest way (depending on your model) is to do an Internet Recovery. You can do this by holding Command+Option+R while your computer boots. You will get a globe and will either ask you to connect to Wifi or if you are connected to ethernet you will just see a progress bar. After it downloads it will bring you to the recovery partition and you can re-partition your HDD and such.


text: Q: allow multi value in managed metadata I have managed metadata field for which allow multi value is checked, I can select multiple value in edit form or new form but could not select multiple value in search form (custom form created)


text:
Q: MuleSoft: After converting from byte array to string, payload not printing more that 50lines. and ends with [..] I got a payload more than 50 lines and it was in byte array.
So after converting from byte array to string, payload not printing more that 50lines.
and ends with [..]
Help me to print complete payload without ending with dots.

A: That's seems to be a known limitation of logging long strings in Mule. Try writing the string to a file to see if it is correct. I would not recommend to create big log entries anyway.

A: Actually I resolved my problem by using a groovy, as Byte Array To String is not helpful in these kind of scenarios.
Below is the script I used to resolve.
<scripting:transformer doc:name="Groovy to Transform Byte Array To String">
<scripting:script engine="Groovy"><![CDATA[return payload.join(", ")]]></scripting:script>
</scripting:transformer>

A: I use <logger message="#[message.payloadAs(java.lang.String)]" level="INFO" doc:name="Logger"/> all the time -- for developing, not in Production -- haven't had a problem. Removing Groovy is a plus.


text:
Q: MYSQL sync data overwriting I'm in trouble. I make a system where a Master DB and three child DB in remote Location.
Child DB's are on offline mode. When internet come, it sends data to Master DB.
But Issue is:
IN Master DB , Student Table Last inserted ID is 12 (primary key with auto increment)
Child A have Same data and Child B have also Same data.
Now Child a insert new Data into student table and sync with Master DB.
So, Master DB ID=13 and One Student is "John".
Now Child B also insert one data and its local table ID is 13 and Student is "Maria".
When Child B Sync with Master, I lost "JOHN" , its overwrites with "Maria".
How Can I solve this issue?


text:
Q: What are these scripts that are loading in Chrome when I press F12? (ophan, jquery) When I press F12 in Chrome on my own web site, I see these scripts in the network tab. I don't include them, they are not in the HTML source, and I don't know where they come from.

The URLs are
http://j.ophan.co.uk/ophan.r2.js.map
https://d1e1g6hlwfi0h5.cloudfront.net/wp-includes/js/jquery/jquery-2.0.3.min.map

I can't find anything in Google about 'ophan'.
I do use Google Analytics and New Relic. I also use AdBlock Plus, Awesome Screenshot Capture, and Google Voice extensions.
When I reload the page, they are gone. They only show up when I open F12, and only for my site, https://tyger.ac/users/48. I disabled all my extensions, and it still happens. It does NOT happen in a private browser session.

A: They are source map files and they are only loaded when the dev console is open. Basically the file maps minified names like function a() {} to function realFunctionName() {} so that debugging minified code is easier.

A: It's just script related with Adblock Plus. Example Script


text:
Q: How to access a file in the dll's folder instead of the executable? I have an executable that's using a dll (they're in 2 different folders).
When I do System.IO.Directory.GetCurrentDirectory() in one of the methods in the dll, I'm getting the executable folder. Is there anyway to get the dll folder?

A: Use Assembly.GetExecutingAssembly().Location to get the full path to the DLL.


text:
Q: How can I construct D-modules over projective space using explicit differential equations? Over $\mathbb{A}^n$, it is easy to construct D-modules by writing down an explicit linear system of PDE's and then writing a presentation of the associated D-module
$$
\mathcal{D}^n \xrightarrow{} \mathcal{D}^m \to \mathcal{M} \to 0
$$
Is there an analogous process for constructing D-modules over projective space as an explicit system of differential equations?

A: You can construct $\mathcal{D}$ modules on projective space (or actually any space) by precisely the same process: write down a system of PDE's (using differential operators on the whole of $\mathbb{P}^n$) and consider the corresponding quotient.  The key caveat is that on a general space, not every $\mathcal{D}$-module will be of this form: some of them can be defined using systems on different coordinate patches which are consistent, but not globally (I think a degree 0 line bundle on an elliptic curve should give a counterexample). However, $\mathbb{P}^n$ is special, and every $\mathcal{D}$-module can be defined this way (by the Beilinson-Bernstein theorem).