text:
Q: How can we pass element ID as a variable in an AJAX request? I am trying to write a template that will create a blog feed, like blogging websites with multiple instances of the same kind.
Now, each instance (each blog post) needs its own like button. For implementing this feature, I am using AJAX.
I am able to make changes in the database by clicking the 'follow' button but not able to make changes in the template with the success function.
Here is the template,
    {% for question, count, is_follow in zipp %}

  Tags:
  {% for tag in question.tags.all %}
    {{tag.name}} |
  {% endfor %}

{{ question.question }}

Arguments added: {{ count }}

  {% include 'snippets/follow_question.html' %}

<button type="button" class="btn btn-secondary btn-sm mt-1">Share</button>

{% endfor%}

Script

As far as I understand, the problem is in the success function. I am trying to make the changes in the correct instance. I get the idea for it from this question
Question
follow_question.html

<form action = "{% url 'follow_question' %}" method = "post">{% csrf_token %}
  {% if is_follow %}
    <button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Followed</button>
  {% else %}
    <button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Follow</button>
  {% endif %}
</form>

Views.py
def follow_question(request):
question = get_object_or_404(Question, question_id = request.POST.get("id"))

is_follow = False

if question.follow.filter(username = request.user).exists():
    question.follow.remove(request.user)
    is_follow = False
else:
    question.follow.add(request.user)
    is_follow = True

context = {}
context["question"] = question
context["is_follow"] = is_follow

if request.is_ajax():
    html = render_to_string('snippets/follow_question.html', context, request=request)
    return JsonResponse({'form':html})

A: You can define $(this) as a variable and use it elsewhere, Especially in ajax events functions:

A: If your is_follow is a boolean field you have to do like this
{% if is_follow %}
    <button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Followed</button>
  {% else %}
    <button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Follow</button>
  {% endif %}

you don't have to add this in a form tag if you do this with a GET request do as you like I'm giving example with GET request you can change it with POST
inside your Ajax do like this
$(document).ready(function(){ // you don't need to pass a event on document ready
  $(document).on('click', '#follow', function(event){
    event.preventDefault();
    var pk = $(this).attr('value');
    $.ajax({
      type: 'GET',
      url: '{% url 'follow_question' %}',
      data: {'id': pk},
      datatype: 'json',
      success: function(response){
        // here you have to do nothing or you can just pass a success msg button is automatically changed by Django template
      },
      error: function(rs, e){
        console.log(rs.responseText);
      },
    });
  });
});

and inside you view you can do like this
def my_ajax_call(request):
    if request.method == 'GET' and request.is_ajax():
       id = request.GET.get('id')
       Mymodel.objects.filter(id=id).update(is_follow=True)
       # or you can check the value of is_follow by sending it from ajax call
       to your view and can add toggle condition like this

def my_ajax_call(request):
    if request.method == 'GET' and request.is_ajax():
       follow_status = request.GET.get('is_follow')
       id = request.GET.get('id')
       if follow_status:
         follow_status = False
       else:
         follow_status = True
       Mymodel.objects.filter(id=id).update(is_follow=follow_status)


text:
Q: Speed of convergence of power method for eigenvalues This theorem is in my book. As no proof is given, I looked for some reference online, but I didn't find any real proof...

Let $M \in \mathbb R ^{n \times n}$ a diagonalisable matrix such that its eigenvalues satisfy $|\lambda_1|> |\lambda_2| \ge \dots \ge |\lambda_n|$. Let $v_1,\dots,v_n$ be respective eigenvectors. Let $x_0 = \sum_{i=1}^n c_i v_i$ for some scalars $c_i$, $c_1\neq0$, $x_k = M^k x_0$, for all positive $k \in \mathbb Z$, and $w\in \mathbb R^n \smallsetminus v_1^\perp$. Then
  $$\frac{w^T x_{k}}{w^T x_{k-1}} = \lambda_1 + O\left(\left|\frac{\lambda_2}{\lambda_1}\right|^{k}\right)$$

First of all, is this statement correct? And then, does it mean that there's a constant $C$ such that
$$\left|\frac{w^T x_{k}}{w^T x_{k-1}} - \lambda_1 \right| \le C\left|\frac{\lambda_2}{\lambda_1}\right|^{k}$$
is satisfied for all $k$? I know that $\lim \frac{w^T x_{k}}{w^T x_{k-1}} = \lambda_1$ and that there's a constant $D$ such that $\left\|\frac{1}{\lambda_1^k}x_k-c_1 v_1\right\|_2 \le D\left|\frac{\lambda_2}{\lambda_1}\right|^{k}$ for all $k$, but I not particularly at ease with the big oh notation... Do you know any proof (a reference is fine as well) that doesn't use some "obvious" and "immediate" steps with the big oh?

Since $x_k= \sum_{i=1}^n c_i \lambda_i^kv_i$, then
\begin{align}\left|\frac{w^T x_{k}}{w^T x_{k-1}} - \lambda_1 \right| &= \left| \dfrac{
\sum_{i=1}^n c_i \lambda_i^kw^Tv_i - \lambda_1 \sum_{i=1}^n c_i \lambda_i^{k-1}w^Tv_i
}{\sum_{i=1}^n c_i \lambda_i^{k-1}w^Tv_i} \right|\\
&=\left| \frac{\sum_{i=2}^n  (\lambda_i-\lambda_1) c_i\lambda_i^{k-1}w^Tv_i}
{\sum_{i=1}^n c_i \lambda_i^{k-1}w^Tv_i} \right|\\
&=\left| \frac{\lambda_2}{\lambda_1} \right|^{k-1} \left|  \frac{\sum_{i=2}^n  (\lambda_i-\lambda_1) c_i(\lambda_i/\lambda_2)^{k-1}w^Tv_i}
{\sum_{i=1}^n c_i (\lambda_i/\lambda_1)^{k-1}w^Tv_i} \right| \\
&\le \left| \frac{\lambda_2}{\lambda_1} \right|^{k-1}   \frac{\sum_{i=2}^n  \left|(\lambda_i-\lambda_1) c_i w^Tv_i\right|}
{\left|\left|c_1 w^Tv_1\right|- \sum_{i=2}^n  \left| c_i w^Tv_i\right| \right|} .
\end{align}
Is this correct?

A: Write $w=\sum_i a_i v_i$. Notice that $x_k=\sum_i c_i \lambda_i^k v_i$. Therefore $w^T x_k = \sum_{i,j} a_i c_j \lambda_j^k v_i^T v_j$. The point is that the $\lambda_1^k$ term does not vanish (this is what the technical assumptions are for) and that it is far larger than the others if $k$ is large enough. Precisely speaking, $w^T x_k=C \lambda_1^k + O(\lambda_2^k)$ where $C$ does not depend on $k$. Thus when you take the ratio you are looking at $\frac{C \lambda_1^k+O(\lambda_2^k)}{C \lambda_1^{k-1}+O(\lambda_2^k)}$. Eventually the first term in the denominator is bigger than the second, at which point you may recover the desired estimate by dividing top and bottom by $C \lambda_1^{k-1}$ and then applying the formula for the the geometric series. (There are other ways to do the analysis, of course.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: android after disableKeyguard the inKeyguardRestrictedInputMode() still return true version: android 4.4.2
I use keyguardLock.disableKeyguard() unlock the screen, then use keyguardManager.inKeyguardRestrictedInputMode() print screen lock state, it always return true,but the powerManager.isScreenOn() return true,and i can use my phone normally.
ps: I do lock and unlock in a android service.
Is there any thing wrong when use disableKeyguard()?

A: The keyguardLock is deprecated starting from API 13. Please use the FLAG_DISMISS_KEYGUARD and/or FLAG_SHOW_WHEN_LOCKED. See here


text:
Q: How do detect that transaction has already been started? I am using Zend_Db to insert some data inside a transaction. My function starts a transaction and then calls another method that also attempts to start a transaction and of course fails(I am using MySQL5). So, the question is - how do I detect that transaction has already been  started?
Here is a sample bit of code:
       try {
                    Zend_Registry::get('database')->beginTransaction();

                    $totals = self::calculateTotals($Cart);
                    $PaymentInstrument = new PaymentInstrument;
                    $PaymentInstrument->create();
                    $PaymentInstrument->validate();
                    $PaymentInstrument->save();

                    Zend_Registry::get('database')->commit();
                    return true;

            } catch(Zend_Exception $e) {
                    Bootstrap::$Log->err($e->getMessage());
                    Zend_Registry::get('database')->rollBack();
                    return false;
            }

Inside PaymentInstrument::create there is another beginTransaction statement that produces the exception that says that transaction has already been started.

A: Do a try/catch: if the exception is that a transaction has already started (based on error code or the message of the string, whatever), carry on.  Otherwise, throw the exception again.

A: The framework has no way of knowing if you started a transaction.  You can even use $db->query('START TRANSACTION') which the framework would not know about because it doesn't parse SQL statements you execute.
The point is that it's an application responsibility to track whether you've started a transaction or not.  It's not something the framework can do.
I know some frameworks try to do it, and do cockamamie things like count how many times you've begun a transaction, only resolving it when you've done commit or rollback a matching number of times.  But this is totally bogus because none of your functions can  know if commit or rollback will actually do it, or if they're in another layer of nesting.
(Can you tell I've had this discussion a few times? :-)
Update 1: Propel is a PHP database access library that supports the concept of the "inner transaction" that doesn't commit when you tell it to.  Beginning a transaction only increments a counter, and commit/rollback decrements the counter.  Below is an excerpt from a mailing list thread where I describe a few scenarios where it fails.
Update 2: Doctrine DBAL also has this feature. They call it Transaction Nesting.

Like it or not, transactions are "global" and they do not obey object-oriented encapsulation.
Problem scenario #1
I call commit(), are my changes committed? If I'm running inside an "inner transaction" they are not. The code that manages the outer transaction could choose to roll back, and my changes would be discarded without my knowledge or control.
For example:

*

*Model A: begin transaction

*Model A: execute some changes

*Model B: begin transaction (silent no-op)

*Model B: execute some changes

*Model B: commit (silent no-op)

*Model A: rollback (discards both model A changes and model B changes)

*Model B: WTF!? What happened to my changes?

Problem scenario #2
An inner transaction rolls back, it could discard legitimate changes made by an outer transaction. When control is returned to the outer code, it believes its transaction is still active and available to be committed. With your patch, they could call commit(), and since the transDepth is now 0, it would silently set $transDepth to -1 and return true, after not committing anything.
Problem scenario #3
If I call commit() or rollback() when there is no transaction active, it sets the $transDepth to -1. The next beginTransaction() increments the level to 0, which means the transaction can neither be rolled back nor committed. Subsequent calls to commit() will just decrement the transaction to -1 or further, and you'll never be able to commit until you do another superfluous beginTransaction() to increment the level again.
Basically, trying to manage transactions in application logic without allowing the database to do the bookkeeping is a doomed idea.  If you have a requirement for two models to use explicit transaction control in one application request, then you must open two DB connections, one for each model. Then each model can have its own active transaction, which can be committed or rolled back independently from one another.

A: Store the return value of beginTransaction() in Zend_Registry, and check it later.

A: Looking at the Zend_Db as well as the adapters (both mysqli and PDO versions) I'm not really seeing any nice way to check transaction state.  There appears to be a ZF issue regarding this - fortunately with a patch slated to come out soon.
For the time being, if you'd rather not run unofficial ZF code, the mysqli documentation says you can SELECT @@autocommit to find out if you're currently in a transaction (err... not in autocommit mode).

A: You can also write your code as per following:
try {
    Zend_Registry::get('database')->beginTransaction();
}
catch (Exception $e) { }

try {
    $totals = self::calculateTotals($Cart);

    $PaymentInstrument = new PaymentInstrument;
    $PaymentInstrument->create();
    $PaymentInstrument->validate();
    $PaymentInstrument->save();

    Zend_Registry::get('database')->commit();
    return true;
}
catch (Zend_Exception $e) {
    Bootstrap::$Log->err($e->getMessage());
    Zend_Registry::get('database')->rollBack();
    return false;
}

A: For innoDB you should be able to use
SELECT * FROM INFORMATION_SCHEMA.INNODB_TRX WHERE TRX_MYSQL_THREAD_ID = CONNECTION_ID();

A: This discussion is fairly old. As some have pointed out, you can do it in your application. PHP has a method since version 5 >= 5.3.3 to know if you are in the middle of a transaction. PDP::inTransaction() returns true or false.  Link http://php.net/manual/en/pdo.intransaction.php

A: In web-facing PHP, scripts are almost always invoked during a single web request. What you would really like to do in that case is start a transaction and commit it right before the script ends. If anything goes wrong, throw an exception and roll back the entire thing. Like this:
wrapper.php:

try {
   // start transaction
   include("your_script.php");
   // commit transaction
} catch (RollbackException $e) {
   // roll back transaction
}

The situation gets a little more complex with sharding, where you may be opening several connections. You have to add them to a list of connections where the transactions should be committed or rolled back at the end of the script. However, realize that in the case of sharding, unless you have a global mutex on transactions, you will not be easily able to achieve true isolation or atomicity of concurrent transactions because another script might be committing their transactions to the shards while you're committing yours. However, you might want to check out MySQL's distributed transactions.

A: Use zend profiler to see begin as query text and Zend_Db_Prfiler::TRANSACTION as query type with out commit or rollback as query text afterwards. (By assuming there is no ->query("START TRANSACTION") and zend profiler enabled in your application)

A: I disagree with Bill Karwin's assessment that keeping track of transactions started is cockamamie, although I do like that word.
I have a situation where I have event handler functions that might get called by a module not written by me. My event handlers create a lot of records in the db. I definitely need to roll back if something wasn't passed correctly or is missing or something goes, well, cockamamie. I cannot know whether the outside module's code triggering the event handler is handling db transactions, because the code is written by other people. I have not found a way to query the database to see if a transaction is in progress.
So I DO keep count. I'm using CodeIgniter, which seems to do strange things if I ask it to start using nested db transactions (e.g. calling it's trans_start() method more than once). In other words, I can't just include trans_start() in my event handler, because if an outside function is also using trans_start(), rollbacks and commits don't occur correctly. There is always the possibility that I haven't yet figured out to manage those functions correctly, but I've run many tests.
All my event handlers need to know is, has a db transaction already been initiated by another module calling in? If so, it does not start another new transaction and does not honor any rollbacks or commits either. It does trust that if some outside function has initiated a db transaction then it will also be handling rollbacks/commits.
I have wrapper functions for CodeIgniter's transaction methods and these functions increment/decrement a counter.
function transBegin(){
    //increment our number of levels
    $this->_transBegin += 1;
    //if we are only one level deep, we can create transaction
    if($this->_transBegin ==1) {
        $this->db->trans_begin();
    }
}

function transCommit(){
    if($this->_transBegin == 1) {
        //if we are only one level deep, we can commit transaction
        $this->db->trans_commit();
    }
    //decrement our number of levels
    $this->_transBegin -= 1;

}

function transRollback(){
    if($this->_transBegin == 1) {
        //if we are only one level deep, we can roll back transaction
        $this->db->trans_rollback();
    }
    //decrement our number of levels
    $this->_transBegin -= 1;
}

In my situation, this is the only way to check for an existing db transaction. And it works. I wouldn't say that "The Application is managing db transactions". That's really untrue in this situation. It is simply checking whether some other part of the application has started any db transactions, so that it can avoid creating nested db transactions.

A: Maybe you can try PDO::inTransaction...returns TRUE if a transaction is currently active, and FALSE if not.
I have not tested myself but it seems not bad!


text:
Q: How does implicit/inline/$inject dependency injection work in AngularJS? I'm new to AngularJS and I would like to understand more about the dependencies that are being injected by default. While reading through code I've noticed that sometimes dependencies are explicitly declared beforehand, and sometimes they aren't. For example:
someModule.controller('MyController', ['$scope', 'someService', function($scope, someService) {
  // ...
}]);

Gives the same results as:
someModule.controller('MyController', function($scope, someService) {
  // ...
});

How does this work? Is Angular assuming that the modules being injected are named the same as the variables in the parameters?
Also, strangely enough, if you do specify the dependencies that are going to be injected, you must specify all of them and in the right order, otherwise nothing will work. For example, this is broken code:
someModule.controller('MyController', ['someService', '$scope', function($scope, someService) {
  // Won't give us any errors, but also won't load the dependencies properly
}]);

Can someone clarify to me how is this whole process working? Thank you very much!!

A: Just to provide a different sort of answer, as to the how inline/implicit dependencies work in AngularJS. Angular does a toString on the provided function and parses the parameter names from the string which is produced. Example:
function foo(bar) {}
foo.toString() === "function foo(bar) {}"

References:
source code
AngularJS Dependency Injection - Demystified

A: Yes, dependency injection in Angular works via the names of the components you (and Angular - for the internal ones) registered.
Below is an example showing how a service is registered and injected into a controller using several different annotations. Please note that dependency injection always works the same in Angular, i.e. it doesn't matter if you are injecting something into a controller, a directive or a service.
app.service('myService', function () {
    // registering a component - in this case a service
    // the name is 'myService' and is used to inject this
    // service into other components
});

Two use (inject) this component in other components, there are three different annotations I am aware of:
1. Implicit Annotation
You can either specify a constructor function which takes as parameters all the dependencies. And yes, the names need to be the same as when these components were registered:
app.controller('MyController', function ($http, myService) {
    // ..
});

2. Inline Array Annotation
Or you can use a notation using an array, where the last parameter is the constructor function with all the injectables (variable names do not matter in this case). The other values in the array need to be strings that match the names of the injectables. Angular can this way detect the order of the injectables and do so appropriately.
app.controller('MyController', ['$http', 'myService', function ($h, m) {
    /* Now here you can use all properties of $http by name of $h & myService by m */
    // Example
    $h.x="Putting some value"; // $h will be $http for angular app
}]);

3. $inject Property Annotation
A third option is to specify the $inject-property on the constructor function:
function MyController($http, myService) {
    // ..
}
MyController.$inject = ['$http', 'myService'];
app.controller('MyController', MyController);

The reason why the last two options are available, at least as far as I know, is due to issues which occured when minifying the JavaScript files which led to the names of the parameters being renamed. Angular then wasn't able to detect what to inject anymore. In the second two cases the injectables are defined as strings, which are not touched during minification.
I would recommend to use version 2 or 3, as version 1 won't work with minification/obfuscation. I prefer version 3 as from my point of view it is the most explicit.
You can find some more detailed information in the internet, e.g. on the Angular Developer Guide.


text:
Q: CMake cant find installed Python Interpreter My system is of Ubuntu 20.04 LTS having a python version 3.8.10. but while installing USRP open source tool chain UHD 3.14.0.0. there arises an error regarding python interpreter for cmake as follows
$ cmake ..
-

-- Configuring the python interpreter...
-- Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE) (Required is at least version "2.0")
-- Python interpreter: PYTHON_EXECUTABLE-NOTFOUND
-- Override with: -DPYTHON_EXECUTABLE=<path-to-python>
CMake Error at cmake/Modules/UHDPython.cmake:54 (message):
Error: Python interpreter required by the build system.
Call Stack (most recent call first):
cmake/Modules/UHDVersion.cmake:9 (include)
cmake/Modules/UHDPackage.cmake:9 (include)
CMakeLists.txt:110 (include)

-- Configuring incomplete, errors occurred!
See also "/home/capsys/workarea/uhd/host/build/CMakeFiles/CMakeOutput.log".

all the available python versions in my system as follows
$ python3 --version
Python 3.8.10`

$ ls /usr/bin/python*
/usr/bin/python3    /usr/bin/python3.8-config  /usr/bin/python3.8-dbg         /usr/bin/python3.8d-config  /usr/bin/python3d     /usr/bin/python3-dbg-config  /usr/bin/python3-futurize
/usr/bin/python3.8  /usr/bin/python3.8d        /usr/bin/python3.8-dbg-config  /usr/bin/python3-config     /usr/bin/python3-dbg  /usr/bin/python3d-config     /usr/bin/python3-pasteurize

why cant cmake find the installed libraries? is there any specific cmd to make cmake look for specific python library for build?
Do I need to install any specific version of python for this ?
$ cmake ..
-

-- Configuring the python interpreter...
-- Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE) (Required is at least version "2.0")
-- Python interpreter: PYTHON_EXECUTABLE-NOTFOUND
-- Override with: -DPYTHON_EXECUTABLE=<path-to-python>
CMake Error at cmake/Modules/UHDPython.cmake:54 (message):
Error: Python interpreter required by the build system.
Call Stack (most recent call first):
cmake/Modules/UHDVersion.cmake:9 (include)
cmake/Modules/UHDPackage.cmake:9 (include)
CMakeLists.txt:110 (include)

-- Configuring incomplete, errors occurred!
See also "/home/capsys/workarea/uhd/host/build/CMakeFiles/CMakeOutput.log".


text:
Q: ActiveModel::Serializer sort and serialize for example i have two activeRecord models:
class Article < ActiveRecord::Base
  has_one :article_poster
end

and
class ArticlePoster < ActiveRecord::Base
  belongs_to :article
end

In some controller:
CustomSerializer.new(articles)

CustomSerializer:
class CustomSerializer < ActiveModel::Serializer
end

I have 4 articles, with poster and without it.
For example:
1st article poster present
2nd article poster NOT present
3rd article poster present
4th article poster present
I need articles in order by poster presence: 1,3,4,2.
What is the best way to implement it in CustomSerializer or in Article model?

A: My solution is:
class CustomSerializer < ActiveModel::Serializer

  def initialize(resources, options = {})
    resources = sort(resources)
    super(resources, options)
  end

  def sort(resources)
    top = []
    regular = []
    resources.each do |article|
      if article.poster
        top << article
      else
        regular << article
      end
    end
    resources = top + regular
  end

end

A: Here is a solution using sql
class Article < ActiveRecord::Base
  has_one :article_poster

  scope :join_article_posters, -> {
    joins('LEFT OUTER JOIN article_posters ON article_posters.article_id = article.id') }
  }

  scope :posters_first -> { join_article_posters.order(article_posters: { id: :desc }) }
end

posters_first may be done better differently depending on your database

CustomSerializer.new(articles.posters_first)


text:
Q: Detect winning game in nought and crosses I need to know the best way to detect a winning move in a game of noughts and crosses. Source code doesn't matter, I just need a example or something I can start with.
The only thing I can come up with is to use loops and test every direction for every move a player makes, to search for e.g five in a row. Is there a faster and more efficient way?

A: The real easy solution is to just check from the last move made...obviously, no prior move could have won the game, or you wouldn't be here...so you just need to check to see if there are 5 (or however many) in a row/column/diagonal around the move that was just placed.
For example, if the board looks like this, and X marks the most recent move:
.............
.............
.............
.............
.....X.......
.............
.............
.............
.............
.............

You don't need to check anything outside the range of "C":
.C...C...C...
..C..C..C....
...C.C.C.....
....CCC......
.CCCCXCCCC...
....CCC......
...C.C.C.....
..C..C..C....
.C...C...C...
.............

Does that help?  (It looked like you might be alluding to this in your original question, but I wasn't sure.)
Beyond this, simple loops are going to be your best friend.  You could probably do some micro-optimization, but (depending on what your actual application is doing) it's probably not worth it.
One thing to keep track of is that you can't just jump out 5 in any direction from the most recent move looking for that many in a row, because this move might be in the middle of a streak.  So I'd do something like
From the new move
    left = how many in a row we have to the left of the lastest move
    right = how many in a row we have to the right of the latest move
    if (left + right + 1 >= 5) then you have a winner

    up = how many in a row we have above the latest move
    down = how many in a row we have below the latest move
    if (up + down + 1 >= 5) then you have a winner

    // repeat for both diagonal directions.

A: Noughts and crosses is a neat programming challenge, because there's alot of mathematical tricks you can use to simplify the problem.
Noughts and crosses is typically a 3-by-3 grid. If you assign each position in your grid a number from one to nine (not in numerical order) you can arrange the numbers so that every horizontal, vertical, and diagonal row adds up to 15
+----+----+----+
| 4  | 3  | 8  |
|    |    |    |
+----+----+----+
| 9  | 5  | 1  |
|    |    |    |
+----+----+----+
| 2  | 7  | 6  |
|    |    |    |
+----+----+----+

Why's that useful? If you can pick any three squares belonging to either 'O' or 'X', and those three squares add up to a total sum of 15, you know that player has won the game.

A: Consider the 3X3 board
Let X = 1
Let O = -1
and a space is represented by a zero.
So if the top row looks like this [X][X][X] the sum is 3, hence it is a win
                                  [O][O][O] the sum is -3, hence it is the other win.
[X][X][ ] is 2, hence if it is X turn, he can win by moving to the blank, or O must block.
[X][O][X] is 1, hence no win.
In a 3x3 board there are 8 positions to evaluate.
In NXN the number gets larger but the idea remains the same
if N=8 and a row or column sums to 7, then you know there is a winning move for X on that row/column
That method worked for me in high school.
Best Wishes
Evil

A: I'm not aware of a better method then looping, but the board is so small, it's quite trivial.
A little Python psuedo code:
def get_winner(board):
    if board[0][0] != EMPTY and board[0][0] == board[1][1] == board[2][2]:
        return board[0][0]
    if board[2][0] != EMPTY and board[2][0] == board[1][1] == board[0][2]:
        return board[2][0]
    for i in xrange(3):
        if board[i][0] != EMPTY and board[i][0] == board[i][1] == board[i][2]:
            return board[i][0]
        if board[0][i] != EMPTY and board[0][i] == board[1][i] == board[2][i]:
            return board[0][i]

A: There are more efficient ways, but they really only matter when you extend this game for much, much larger board configurations. For example, if you stored groupings of noughts and crosses in directional objects (store a diagonal configuration, for example), you could sort by those with length winLength-1, and only test the new move against these groupings. You save some iterations, but you have to maintain a lot of extra information in memory.

A: It's a question of representation. How do you store the game board? Now think outside the box; how else could you store it? You might for example represent the board as a pair of bitmaps - one for noughts and one for crosses - then do a numerical pattern match to detect winning conditions.


text:
Q: Uml class diagram alternative of map attribute Through searching I found that in UML, aggregation(assuming that it's used properly) can be used to represent attributes in a class.
For example,

(Assume column can stand alone)
Then, using such example, if I want to replace the attribute: Column[] with map to represent the column's name, would it be correct to use an association class just like below? (In case, I'm not willing to put the column name in Column class as an attribute)

A: Association classes are used with simple associations. They have m-1-1-n multiplicity. The shared aggregation (as you used) has no defined semantics (and I recommend to simply not use it unless you have a domain specific and documented use for it). It's simply better to put the intended multiplicity on either side of an association.
An association class connects two classes, adding attributes and/or operations. Your example is "unconventional" since Table/Column have a simple relation which would not need an association class. A general example is the Student/Lecture relation where you can put an association class in between to record exam results, times etc.

A: Yes, I think that is a valid way of modelling the fact that you have some sort of key string that can be used to identify a Column of this Table.
Using a Map is one if the many possible implementations, so it's not a real equal to.
The advantage of modelling using the Association Class is that your model remains at the more abstract functional level and leaves out implementation details.
BTW. I would use a composition instead of an aggregation for the association between Table and Column, as there is an obvious strong ownership relation and life-cycle dependency between the two.

A: If you want to replace the attribute Column[] with map to represent the column's name and you are not willing to put the column name in Column class as an attribute and assuming that you want to follow UML specification precisely then you'll produce the model shown below:

Map<Key, Value> is usually understood as an associative container that contains key-value pairs Map.Entry<Key, Value> with unique keys. The container is modeled by the directional aggregation from Map<Key, Value> to Map.Entry<Key, Value>.
Map<Key, Value> and Map.Entry<Key, Value> are templates. Clause 7.3.3.1 of UML specification says that:

A template cannot be used in the same manner as a non-template Element of the same kind. The template Element can only be used to generate bound Elements or as part of the specification of another template.

According to clause 7.3.3.3:

A TemplateBinding is a relationship between a TemplateableElement and a template that specifies the substitutions of actual ParameterableElements for the formal TemplateParameters of the template.

Thus we have two bound elements that have TemplateBinding (marked by <> keyword) relationships with their templates:

*

*ColumnNames which essentially is the name for Map<String, Column>

*ColumnName which essentially is the name for Map.Entry<String, Column
According to clause 11.5.1 of the UML specification:

An Association classifies a set of tuples representing links between typed instances. An AssociationClass is both an Association and a Class.

ColumnName is AssociationClass representing the link between instances of String and Column classes. We use notation from clause 11.5.5, figure 11.35 to express that.
Finally, the directional composition association between Table and ColumnNames classes tells us that each instance of Table owns an instance of ColumnNames, i.e. set of column names.
Note that while ColumnNames and ColumName classes are usually hidden from the end-user by an implementation, they nevertheless exist.
I used BoUML to draw the diagram.


text:
Q: wrong type argument: stringp, nil Before now I've just been cutting and pasting code into my .emacs file, but then I decided to add some maven functionality to emacs.  Now, I don't see how I was able to mess this up, but last night I kept getting the error I put in the title when I run M-x jarl-mvn-exec.  I slept on it, and came back the next day but I'm still not getting anywhere.
(defun jarl-get-pom ()
  (concat (locate-dominating-file
       (buffer-file-name
        (current-buffer))
       "pom.xml")
      "pom.xml"))

(defun jarl-visit-pom ()
  (interactive)
  (find-file (jarl-get-pom)))

(defun jarl-mvn-exec ()
  (interactive)
  (switch-to-buffer (get-buffer-create "maven"))
  (start-process-shell-command "mvn-exec" "maven" "mvn" "-f" (jarl-get-pom) "compile")
  (start-process-shell-command "mvn-exec" "maven" "mvn" "-f" (jarl-get-pom) "exec:exec"))

A: You'll need to provide more information to be sure.  Try setting
(setq debug-on-error t)

which will give you a stack trace showing what function is complaining about the string being nil.
My guess is that buffer-file-name is returning nil, and that's where the problem lies (not all buffers have file names).  Check out the debugging section of An Introduction To Programming in Emacs Lisp, or the debugging section of the Emacs Lisp manual.

A: The secret to finding a problem in your init file is not a secret: binary search.
Use comment-region to comment out half your init file, then 3/4, 7/8,... It is very quick to identify the problem. comment-region also uncomments: C-h f comment-region RET.


text:
Q: how to show array of objects in json format I have formatted the output like
{"main" : { "membersdetails": [{result:SMS message(s) sent},
      {result:SMS message(s) sent},{result:SMS message(s) sent}]}}

Error is: {result: SMSmessage(s----------------------^Expecting
  'STRING', }'

What should be done to make it correct.

A: Your best bet is not to produce JSON strings by hand. Instead, let json_encode do it for you:
Example: (live copy)
$data = array(
    main => array(
        membersdetails => array(
            array(
                result => 'SMS message(s) sent'
            ),
            array(
                result => 'SMS message(s) sent'
            ),
            array(
                result => 'SMS message(s) sent'
            )
        )
    )
);
echo json_encode($data);

Output:

{"main":{"membersdetails":[{"result":"SMS message(s) sent"},{"result":"SMS message(s) sent"},{"result":"SMS message(s) sent"}]}}


text:
Q: Revoke Specific Provisioning Profile? I have an iOS enterprise developer account, which only allows me to have one Distribution Certificate. My distribution certificate is used for several adhoc and enterprise provisioning profiles for several app IDs and a wildcard app ID.
I'd like to revoke the profile for a specific app id, so the builds signed with that profile will no longer launch. Is that possible without revoking the entire cert and having to distribute new builds of all apps with new provisioning profiles?

A: You can revoke the profile and/or the certificate but this will not influence the app already installed.
Only development and Ad-Hoc profiles have a limited live span, InHouse profiles do not have this.
Well I was proven wrong, As apple stated if you retract a Distribution Certificate you app will fail to launch. If have test it with a developement certificate and nothing happend. But I can't (read don't want to) test this with the inhouse profile singed with my Distribution Certificate.


text:
Q: Eclipse cannot open android project? Eclipse was working perfectly with my android project and then I received a popup stating that my system is low on disk space on drive C:. I deleted some files from C drive (approx 2 GB) and then restarted my system.
On restarting, eclipse refused to open my android project. I can see the name of my project with a folder icon in Package view window, but i cannot open it either by double clicking it or by selecting the option 'Open Project' by right clicking it. No error messages are displayed.
The contents of the project are intact on the physical device.
I had no joy by trying to import this project into eclipse. It turned down the request by saying that this project already exists.

A: *

*You may delete the project from eclipse by right clicking the project folder icon. (Do not check the Delete project contents from disc checkbox)

*You may delete the .project and .classpath files from the physical location

*Create a new Android project, chose the Create project from existing source option


text:
Q: I need help finding the x intercept of an absolute value equation.
$y= |2x-3| + 2x +6$
Find the $x$ intercept.

(P.S.: In my Algebra teacher's answer document it says that there is no $x$ intercept for this equation. I'm confused as to why that is. I keep getting an $x$ intercept.)

A:
$y= |2x-3| + 2x +6$
Find the $x$ intercept.

To solve this problem, will have  to remind ourselves that the $x$ intercept will have as coordinates $(x_0,0)$. So, to find $x_0$, will have to solve the equation $y=0$: $$y= \color{blue}{|2x-3|} + \color{black}{2x}+ \color{black}{6}=0\Rightarrow \color{blue}{|2x-3|}=-2x-6 \\\,\\ \therefore\,\,2x-3=\begin{cases}-2x-6 & (1) \\ 2x+6 & (2)\end{cases} \\\,\\ 2x-3=-2x-6\Rightarrow x=3/4$$
We check that value by substitution: $$\require{cancel}2\cdot\dfrac34-3=2\cdot\dfrac34-6 \\ \dfrac32-\dfrac62=\dfrac32-\dfrac{12}2 \\ \color{red}{\cancel{\color{black}{\dfrac32}}}-\dfrac62=\color{red}{\cancel{\color{black}{\dfrac32}}}-\dfrac{12}2 \\ -\dfrac62=-\dfrac{12}2 \\ \text{Contradiction!}$$ So $x=3/4$ is not a solution of $\text{(1)}$.
Let's continue with $\text{(2)}$: $$2x-3=2x+6 \\ \color{red}{\cancel{\color{black}{2x}}} -3=\color{red}{\cancel{\color{black}{2x}}}+6 \\ -3=6\quad\, \\ \text{Contradiction!}$$
So equation $\rm (2)$ admits no solution which means that $y=0$ have no solution.
Therefore, $y=|2x-3|+2x+6$ has no $x$ intercept.

Exercise:

*

*Does $y=|2x-3|+2x+6$ have a $y$ intercept?

*Does $y=|2x-3|-2x+3$ have an $x$ intercept?

*Does $y=|2x-3|+2x-3$ have an $x$ intercept?

*Does $y=\left|\dfrac{3x+2}{x-3}\right|-5$ have an $x$ intercept? Does it have a $y$ intercept?

*How many $x$ intercepts does $y=|2x-1|-3|2x+4|+7$ have? Does it have any $y$ intercept?

A: If you substitute $y=0$, you can never have a solution to the equation.
Case 1:
Let's say $y=0$. Assume $x>\frac{3}{2}$. The equation reduces to $4x=-3$ which is contradictory because we just assumed that $x$ is positive.Case 2: Again assume $y=0$. Now take $x<\frac{3}{2}$. The equation reduces to $-2x-3+2x+6=0$ which is even more ridiculous. Hence, $y$ can never be equal to zero; proving that the function cannot have an $x$-intercept.

A: This equation can be thought of as the sum of two functions, if you replace y with f(x). The slope, when x is less than 1.5, is equal to 0, and f(0)=9. For x>1.5, the slope is 2, so f(x)=>9 for all x. I think the book meant "Is there an x-intercept to the function?, If so, find it."


text:
Q: CSS: Scroll container horizontally instead of page? (display: grid break) I'm trying to get the cyan box to scroll horizontally instead of triggering a horizontal scrollbar on the page.
It seems to break when I try using a grid layout; I had to horizontally scrolling before when I didn't use a grid.
How can I fix this? .page-wrap should fill the whole window and add vertical scrollbar as needed. Only the .boxs should scroll horizontally.

html {
  overflow: hidden;
}

.page-wrap {
  display: grid;
  grid-template-areas:
    "sidebar main"
    "footer footer";
  grid-template-columns: 250px 1fr;
  grid-template-rows: auto 60px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
}

.sidebar {
  background-color: green;
  grid-area: sidebar;
}

.footer {
  background-color: red;
  grid-area: footer;
}

.main {
  background-color: yellow;
  grid-area: main;
}

.box {
  background-color: cyan;
  margin: 10px;
  overflow-x: scroll;
}

sidebar

          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veritatis, modi laudantium facilis. Cum quasi dolore quam doloribus reprehenderit illum nostrum id quas ea. Nostrum adipisci dolor nulla veniam exercitationem ipsa.
          Accusamus deserunt voluptatibus rem, aspernatur enim dolores, amet illum accusantium! Tempora, repellendus, fuga. Ex, consectetur mollitia reprehenderit qui, consequuntur ipsam maiores excepturi sapiente tempore odit repudiandae facere incidunt! Vero, beatae.
          Et minus eaque corrupti voluptas, earum ex non similique. Officiis a dignissimos veritatis quas provident sunt? Fuga vel officia qui, numquam eos sint, totam aspernatur, commodi quis, temporibus animi excepturi!
          Natus quaerat, sint nemo quia laudantium dolorem asperiores deserunt neque porro esse iusto reprehenderit et assumenda ipsum saepe consequuntur soluta officiis illum maiores cumque quos voluptate expedita tenetur eum autem!
          Asperiores ducimus accusantium aliquid nemo aliquam fugiat culpa maxime repudiandae pariatur minus. Eum incidunt iste molestias officiis sunt nostrum facilis velit. Reprehenderit quis aut officia quas beatae assumenda esse asperiores.
          Architecto, nam consequuntur odit distinctio! Suscipit fuga nam reprehenderit, nostrum modi provident iusto aperiam alias qui. Optio repudiandae reiciendis, omnis esse maiores! A blanditiis ducimus voluptate nobis exercitationem. Temporibus, vel!
          Similique et est omnis fuga, ad earum sapiente. Nam qui est quidem. Dignissimos amet harum voluptate a, sint culpa autem et neque, natus quod cum eos laudantium molestias, dolorem optio.
          Saepe aspernatur consequuntur sint nisi dolores nihil ab repudiandae, odio dolor, assumenda culpa corporis fugiat ullam officia quibusdam eaque enim, harum voluptatem eveniet reprehenderit natus consectetur deleniti nesciunt et! Omnis!
          Nihil quas quod numquam ut fugiat doloremque repudiandae animi iusto. Ullam quidem ipsa dolorem quos veritatis adipisci quisquam obcaecati culpa et consequatur, aspernatur unde eligendi rerum labore ab odit asperiores.
          Hic, aliquam, harum? Harum tempora accusantium animi ratione id perspiciatis quasi maiores iste odio quisquam, adipisci, laudantium cupiditate voluptatem mollitia soluta sunt eveniet facere quibusdam aspernatur? Suscipit obcaecati dolorum eligendi.
          Possimus natus, dignissimos vero nesciunt cum voluptatibus reiciendis commodi maxime voluptates qui illo quia distinctio tempora perferendis fugit modi itaque, quis recusandae quisquam quos ullam alias! Voluptatum repellat mollitia incidunt.
          Quod in ducimus, saepe obcaecati, eius vero ipsa ea cum reprehenderit velit sunt numquam eaque sapiente dolorem, possimus id nostrum natus eligendi accusamus nulla voluptatibus necessitatibus harum vitae. Dolorum, praesentium.
          Ab iusto, dicta deleniti explicabo perspiciatis pariatur deserunt blanditiis vel accusantium. Tempore architecto fugit cum similique laudantium et veritatis id, quos deleniti eaque voluptatum laboriosam, natus commodi itaque veniam vel.
          Dignissimos, quis excepturi, ratione nemo minima tenetur possimus. Quos eum placeat veniam voluptas, tempora, aliquam? Dolores ipsum obcaecati nisi itaque dolor, officiis quidem minima, nesciunt molestias facilis cupiditate repellat sequi.
          Dolores asperiores quidem totam illo veniam! Natus architecto nulla et asperiores modi quaerat, sed! Quam cum rem voluptatibus, rerum pariatur deserunt fugit odit, totam blanditiis animi nulla nisi facilis saepe.
          Quibusdam dolor explicabo soluta adipisci est quis aliquam tempora non, sint laudantium tempore minima inventore dolorum magni ad a rem magnam dignissimos expedita maxime numquam voluptas facere, quidem harum aliquid.
          Facere dolorem, ullam quasi. Numquam alias maiores harum voluptate delectus quos totam architecto voluptatum, sapiente pariatur modi, autem culpa omnis facere commodi unde assumenda. Quaerat, rem deserunt. Beatae, voluptates, cum.
          Magni pariatur eos quo perspiciatis ipsam a modi accusantium nulla fugiat officiis dolor ducimus hic, provident eius facilis quibusdam molestiae quasi, sunt, quis repellat nesciunt! Enim ipsum ducimus cumque placeat?
          Recusandae porro, consectetur placeat, temporibus delectus nesciunt aliquid nam incidunt at ipsa accusantium hic maxime tempora dolorum! Totam reiciendis, consequatur deserunt eveniet natus, vitae ipsa voluptate repudiandae velit, quia aspernatur!
          Et iusto ab repellat quae? Quas, ratione sapiente a, fuga voluptates, unde ullam dolores, fugit sint magnam perferendis ad quae. Magnam consequatur nisi quisquam, maiores quasi qui provident similique nobis.
          Ab qui hic, incidunt consequuntur officia exercitationem laboriosam suscipit veritatis est deleniti, debitis reiciendis at quidem consequatur iure ut quisquam tempore delectus aut soluta sequi tenetur sed magnam nostrum. Ab?
          Earum quis perspiciatis perferendis, rem, fugit cumque reiciendis! Porro consequatur quam consequuntur quaerat, atque praesentium adipisci fugit, dignissimos, ab labore reprehenderit provident temporibus, totam magnam illum pariatur deserunt alias cum!
          Officiis sit quam vero nobis doloribus necessitatibus possimus. Veniam, totam! Illo magnam, ipsum consequuntur at, ipsam sit fuga rerum architecto eum libero officiis, nobis! Obcaecati incidunt, mollitia placeat eaque atque.
          Nisi nam assumenda laudantium quos non quasi. Fuga enim, voluptatibus possimus tempora numquam dolores maiores, eum quaerat sit odit distinctio saepe optio aut accusamus explicabo, dolorem quidem consequatur. Maxime, similique!
          Autem inventore expedita quibusdam ipsum. Consequuntur nulla in vero blanditiis deleniti dignissimos, earum eligendi voluptatibus, minus illo, perspiciatis doloremque nisi sed maiores tempora. Excepturi minima, officia incidunt vitae pariatur illo!
          Sequi delectus dolorum, ea rem quis voluptatem accusantium quibusdam suscipit corrupti est laborum adipisci tenetur optio expedita inventore quam molestiae cupiditate totam. Rem sed, odit blanditiis eius quia vel eos.
          Vero dolor nam quisquam reiciendis quibusdam id sapiente quia est veritatis facilis, expedita recusandae sequi iste tempora harum illum nihil. Amet laborum, accusamus soluta dolores et iure? Possimus, et? Iusto.
          Ullam ipsum blanditiis obcaecati, rem aliquam voluptates fuga quo praesentium quia cum dignissimos debitis laboriosam itaque? Nostrum explicabo quae, rem praesentium accusantium dicta officia veritatis magni earum officiis. Inventore, ut.
          Quisquam, ex, dolore. Voluptates porro eum, blanditiis ullam non sequi suscipit iste eius! Soluta, nam quia impedit veritatis laudantium id ea iure autem magnam sapiente, a modi omnis. Optio, animi!
          Consequuntur amet, tenetur quidem consequatur doloremque distinctio ipsum minima, incidunt, fuga voluptatibus placeat quae autem recusandae quasi. Nihil, dolorum? Aliquid eligendi hic expedita saepe recusandae suscipit tempora tempore illum tenetur.

footer

A: Figured it out.

html {
  overflow: hidden;
}

.page-wrap {
  display: grid;
  grid-template-areas:
    "sidebar main"
    "footer footer";
  grid-template-columns: 250px 1fr;
  grid-template-rows: auto 60px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow-y: scroll;
  overflow-x: auto;
}

.sidebar {
  background-color: lime;
  grid-area: sidebar;
}

.footer {
  background-color: orange;
  grid-area: footer;
}

.main {
  background-color: yellow;
  grid-area: main;
   min-width: 0;
}

.box {
  background-color: cyan;
  margin: 10px;
  overflow-x: scroll;
  max-width: 100%;

}

sidebar

          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veritatis, modi laudantium facilis. Cum quasi dolore quam doloribus reprehenderit illum nostrum id quas ea. Nostrum adipisci dolor nulla veniam exercitationem ipsa.
          Accusamus deserunt voluptatibus rem, aspernatur enim dolores, amet illum accusantium! Tempora, repellendus, fuga. Ex, consectetur mollitia reprehenderit qui, consequuntur ipsam maiores excepturi sapiente tempore odit repudiandae facere incidunt! Vero, beatae.
          Et minus eaque corrupti voluptas, earum ex non similique. Officiis a dignissimos veritatis quas provident sunt? Fuga vel officia qui, numquam eos sint, totam aspernatur, commodi quis, temporibus animi excepturi!
          Natus quaerat, sint nemo quia laudantium dolorem asperiores deserunt neque porro esse iusto reprehenderit et assumenda ipsum saepe consequuntur soluta officiis illum maiores cumque quos voluptate expedita tenetur eum autem!
          Asperiores ducimus accusantium aliquid nemo aliquam fugiat culpa maxime repudiandae pariatur minus. Eum incidunt iste molestias officiis sunt nostrum facilis velit. Reprehenderit quis aut officia quas beatae assumenda esse asperiores.
          Architecto, nam consequuntur odit distinctio! Suscipit fuga nam reprehenderit, nostrum modi provident iusto aperiam alias qui. Optio repudiandae reiciendis, omnis esse maiores! A blanditiis ducimus voluptate nobis exercitationem. Temporibus, vel!
          Similique et est omnis fuga, ad earum sapiente. Nam qui est quidem. Dignissimos amet harum voluptate a, sint culpa autem et neque, natus quod cum eos laudantium molestias, dolorem optio.
          Saepe aspernatur consequuntur sint nisi dolores nihil ab repudiandae, odio dolor, assumenda culpa corporis fugiat ullam officia quibusdam eaque enim, harum voluptatem eveniet reprehenderit natus consectetur deleniti nesciunt et! Omnis!
          Nihil quas quod numquam ut fugiat doloremque repudiandae animi iusto. Ullam quidem ipsa dolorem quos veritatis adipisci quisquam obcaecati culpa et consequatur, aspernatur unde eligendi rerum labore ab odit asperiores.
          Hic, aliquam, harum? Harum tempora accusantium animi ratione id perspiciatis quasi maiores iste odio quisquam, adipisci, laudantium cupiditate voluptatem mollitia soluta sunt eveniet facere quibusdam aspernatur? Suscipit obcaecati dolorum eligendi.
          Possimus natus, dignissimos vero nesciunt cum voluptatibus reiciendis commodi maxime voluptates qui illo quia distinctio tempora perferendis fugit modi itaque, quis recusandae quisquam quos ullam alias! Voluptatum repellat mollitia incidunt.
          Quod in ducimus, saepe obcaecati, eius vero ipsa ea cum reprehenderit velit sunt numquam eaque sapiente dolorem, possimus id nostrum natus eligendi accusamus nulla voluptatibus necessitatibus harum vitae. Dolorum, praesentium.
          Ab iusto, dicta deleniti explicabo perspiciatis pariatur deserunt blanditiis vel accusantium. Tempore architecto fugit cum similique laudantium et veritatis id, quos deleniti eaque voluptatum laboriosam, natus commodi itaque veniam vel.
          Dignissimos, quis excepturi, ratione nemo minima tenetur possimus. Quos eum placeat veniam voluptas, tempora, aliquam? Dolores ipsum obcaecati nisi itaque dolor, officiis quidem minima, nesciunt molestias facilis cupiditate repellat sequi.
          Dolores asperiores quidem totam illo veniam! Natus architecto nulla et asperiores modi quaerat, sed! Quam cum rem voluptatibus, rerum pariatur deserunt fugit odit, totam blanditiis animi nulla nisi facilis saepe.
          Quibusdam dolor explicabo soluta adipisci est quis aliquam tempora non, sint laudantium tempore minima inventore dolorum magni ad a rem magnam dignissimos expedita maxime numquam voluptas facere, quidem harum aliquid.
          Facere dolorem, ullam quasi. Numquam alias maiores harum voluptate delectus quos totam architecto voluptatum, sapiente pariatur modi, autem culpa omnis facere commodi unde assumenda. Quaerat, rem deserunt. Beatae, voluptates, cum.
          Magni pariatur eos quo perspiciatis ipsam a modi accusantium nulla fugiat officiis dolor ducimus hic, provident eius facilis quibusdam molestiae quasi, sunt, quis repellat nesciunt! Enim ipsum ducimus cumque placeat?
          Recusandae porro, consectetur placeat, temporibus delectus nesciunt aliquid nam incidunt at ipsa accusantium hic maxime tempora dolorum! Totam reiciendis, consequatur deserunt eveniet natus, vitae ipsa voluptate repudiandae velit, quia aspernatur!
          Et iusto ab repellat quae? Quas, ratione sapiente a, fuga voluptates, unde ullam dolores, fugit sint magnam perferendis ad quae. Magnam consequatur nisi quisquam, maiores quasi qui provident similique nobis.
          Ab qui hic, incidunt consequuntur officia exercitationem laboriosam suscipit veritatis est deleniti, debitis reiciendis at quidem consequatur iure ut quisquam tempore delectus aut soluta sequi tenetur sed magnam nostrum. Ab?
          Earum quis perspiciatis perferendis, rem, fugit cumque reiciendis! Porro consequatur quam consequuntur quaerat, atque praesentium adipisci fugit, dignissimos, ab labore reprehenderit provident temporibus, totam magnam illum pariatur deserunt alias cum!
          Officiis sit quam vero nobis doloribus necessitatibus possimus. Veniam, totam! Illo magnam, ipsum consequuntur at, ipsam sit fuga rerum architecto eum libero officiis, nobis! Obcaecati incidunt, mollitia placeat eaque atque.
          Nisi nam assumenda laudantium quos non quasi. Fuga enim, voluptatibus possimus tempora numquam dolores maiores, eum quaerat sit odit distinctio saepe optio aut accusamus explicabo, dolorem quidem consequatur. Maxime, similique!
          Autem inventore expedita quibusdam ipsum. Consequuntur nulla in vero blanditiis deleniti dignissimos, earum eligendi voluptatibus, minus illo, perspiciatis doloremque nisi sed maiores tempora. Excepturi minima, officia incidunt vitae pariatur illo!
          Sequi delectus dolorum, ea rem quis voluptatem accusantium quibusdam suscipit corrupti est laborum adipisci tenetur optio expedita inventore quam molestiae cupiditate totam. Rem sed, odit blanditiis eius quia vel eos.
          Vero dolor nam quisquam reiciendis quibusdam id sapiente quia est veritatis facilis, expedita recusandae sequi iste tempora harum illum nihil. Amet laborum, accusamus soluta dolores et iure? Possimus, et? Iusto.
          Ullam ipsum blanditiis obcaecati, rem aliquam voluptates fuga quo praesentium quia cum dignissimos debitis laboriosam itaque? Nostrum explicabo quae, rem praesentium accusantium dicta officia veritatis magni earum officiis. Inventore, ut.
          Quisquam, ex, dolore. Voluptates porro eum, blanditiis ullam non sequi suscipit iste eius! Soluta, nam quia impedit veritatis laudantium id ea iure autem magnam sapiente, a modi omnis. Optio, animi!
          Consequuntur amet, tenetur quidem consequatur doloremque distinctio ipsum minima, incidunt, fuga voluptatibus placeat quae autem recusandae quasi. Nihil, dolorum? Aliquid eligendi hic expedita saepe recusandae suscipit tempora tempore illum tenetur.

footer

I remembered an annoying quirk with flexbox, thought it might apply to grid too.
The trick is to add min-width: 0 to .main.


text:
Q: Calendly Api integration Hello i have a custom form on my website that users are supposed to use to schedule an event,
Is there a way i could integrate to Calendly where i send this data as a post request to Calendly and a schedule is created with the data provided from the custom form?
I have been doing research from the calendly api docs but i can't find an endpoint where i can send the data to.
In my case i don't think using calendly webhooks is a good choice since i need to capture the schedule event details as they are created from the form,
Please if anyone could assist me on to figure out a way to handle this

A: I just started looking at their API for a project also and I don't see anywhere in the API to create new events. I believe it is only for getting information.
I am guessing that you will need to embed their booking form on your site instead.
https://help.calendly.com/hc/en-us/articles/223147027-Embed-options-overview


text:
Q: Concatenate 2 STL vectors in constant O(1) time I'll give some context as to why I'm trying to do this, but ultimately the context can be ignored as it is largely a classic Computer Science and C++ problem (which must surely have been asked before, but a couple of cursory searches didn't turn up anything...)
I'm working with (large) real time streaming point clouds, and have a case where I need to take 2/3/4 point clouds from multiple sensors and stick them together to create one big point cloud. I am in a situation where I do actually need all the data in one structure, whereas normally when people are just visualising point clouds they can get away with feeding them into the viewer separately.
I'm using Point Cloud Library 1.6, and on closer inspection its PointCloud class (under <pcl/point_cloud.h> if you're interested) stores all data points in an STL vector.
Now we're back in vanilla CS land...
PointCloud has a += operator for adding the contents of one point cloud to another. So far so good. But this method is pretty inefficient - if I understand it correctly, it 1) resizes the target vector, then 2) runs through all Points in the other vector, and copies them over.
This looks to me like a case of O(n) time complexity, which normally might not be too bad, but is bad news when dealing with at least 300K points per cloud in real time.
The vectors don't need to be sorted or analysed, they just need to be 'stuck together' at the memory level, so the program knows that once it hits the end of the first vector it just has to jump to the start location of the second one. In other words, I'm looking for an O(1) vector merging method. Is there any way to do this in the STL? Or is it more the domain of something like std::list#splice?
Note: This class is a pretty fundamental part of PCL, so 'non-invasive surgery' is preferable. If changes need to be made to the class itself (e.g. changing from vector to list, or reserving memory), they have to be considered in terms of the knock on effects on the rest of PCL, which could be far reaching.
Update: I have filed an issue over at PCL's GitHub repo to get a discussion going with the library authors about the suggestions below. Once there's some kind of resolution on which approach to go with, I'll accept the relevant suggestion(s) as answers.

A: A vector is not a list, it represents a sequence, but with the additional requirement that elements must be stored in contiguous memory. You cannot just bundle two vectors (whose buffers won't be contiguous) into a single vector without moving objects around.

A: This problem has been solved many times before such as with String Rope classes.
The basic approach is to make a new container type that stores pointers to point clouds. This is like a std::deque except that yours will have chunks of variable size. Unless your clouds chunk into standard sizes?
With this new container your iterators start in the first chunk, proceed to the end then move into the next chunk. Doing random access in such a container with variable sized chunks requires a binary search. In fact, such a data structure could be written as a distorted form of B+ tree.

A: There is no vector equivalent of splice - there can't be, specifically because of the memory layout requirements, which are probably the reason it was selected in the first place.
There's also no constant-time way to concatenate vectors.
I can think of one (fragile) way to concatenate raw arrays in constant time, but it depends on them being aligned on page boundaries at both the beginning and the end, and then re-mapping them to be adjacent. This is going to be pretty hard to generalise.
There's another way to make something that looks like a concatenated vector, and that's with a wrapper container which works like a deque, and provides a unified iterator and operator[] over them. I don't know if the point cloud library is flexible enough to work with this, though. (Jamin's suggestion is essentially to use something like this instead of the vector, and Zan's is roughly what I had in mind).

A: No, you can't concatenate two vectors by a simple link, you actually have to copy them.
However! If you implement move-semantics in your element type, you'd probably get significant speed gains, depending on what your element contains. This won't help if your elements don't contain any non-trivial types.
Further, if you have your vector reserve way in advance the memory needed, then that'd also help speed things up by not requiring a resize (which would cause an undesired huge new allocation, possibly having to defragment at that memory size, and then a huge memcpy).
Barring that, you might want to create some kind of mix between linked-lists and vectors, with each 'element' of the list being a vector with 10k elements, so you only need to jump list links once every 10k elements, but it allows you to dynamically grow much easier, and make your concatenation breeze.
std::list<std::vector<element>> forIllustrationOnly; //Just roll your own custom type.

index = 52403;

listIndex = index % 1000
vectorIndex = index / 1000

forIllustrationOnly[listIndex][vectorIndex] = still fairly fast lookups
forIllustrationOnly[listIndex].push_back(vector-of-points) = much faster appending and removing of blocks of points.

A: You will not get this scaling behaviour with a vector, because with a vector, you do not get around the copying. And you can not copy an arbitrary amount of data in fixed time.
I do not know PointCloud, but if you can use other list types, e.g. a linked list, this behaviour is well possible. You might find a linked list implementation which works in your environment, and which can simply stick the second list to the end of the first list, as you imagined.

A: Take a look at Boost range joint at http://www.boost.org/doc/libs/1_54_0/libs/range/doc/html/range/reference/utilities/join.html
This will take 2 ranges and join them. Say you have vector1 and vector 2.
You should be able to write
auto combined = join(vector1,vector2).

Then you can use combined with algorithms, etc as needed.

A: No O(1) copy for vector, ever, but, you should check:

*

*Is the element type trivially copyable? (aka memcpy)

*Iff, is my vector implementation leveraging this fact, or is it stupidly looping over all 300k elements executing a trivial assignment (or worse, copy-ctor-call) for each element?

What I have seen is that, while both memcpyas well as an assignment-for-loop have O(n) complexity, a solution leveraging memcpy can be much, much faster.
So, the problem might be that the vector implementation is suboptimal for trivial types.


text:
Q: Keep connection alive with php If i send request to server to - mysql_connect, select_db it replies in 250ms or so, after that everytime i send same request reply averages about 50ms. If i go idle for 10 seconds or more it goes back to 250ms reply
$user="";
$password="";
$database="";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database " . $database);

Is there something i can do that everytime i send this request it doesnt go back to 250ms even if user goes idle for a bit.
I know for some people 200ms difference is silly but i really need this for my case.


text:
Q: how use tar and extract everything except certain files? I want to extract website.tgz but I don't want these to "come out":
app/config.ini
log/

How do I do this?
Or/also how do I overwrite everything except the above?

A: Try using the following command
tar -xvzf /path/to/tarfile --exclude='file dont want to extract'

A: You can use, as commented by Gryphius, the --exclude option to GNU tar.
You could also post-process the tar archive with tardy.
tardy  enables you to do other useful transformations (e.g. prefixing the archived file paths, changing user or group name, etc...).


text:
Q: jquery - how to change the selector keeping the action same Suppose I have an array Boxes={"#box5","#box3",#box1"","#box2","#box4"} and I have a jquery statement
$(Boxes[2]).click(--------some code----------)

my problem is that the statement is always executed as - when box1 is clicked even though I swap the Box array several times in between. So even when Boxes[2] = "box2" the code is still executed when I click box1 and not box2.
Is this some sort of preprocessing?

A: When you call $(Boxes[2]) what matters is the value of Boxes[2] on the time you call it.
So the better is hook the click event to all boxes and inside the code check whether the array value is the box being clicked or not.
Sample:
// bind to all elements that id begin with "box"
$("id^=[box]").click(function() {
    // see if the clicked box is the one we want
    if ($(this).id == Boxes[2]) {
       // some code
    }
})


text:
Q: How to use delegated events? I'm using an event to replace "src" attributes in some layers (
):
$('.playOnAP').on('click',function() {
    $('#mp3-list ul li',this).each( function( index, element ) {
    $('.total-title').eq(index).attr('src', $(this).text() );
});

and it works the first time, but not after an Ajax request, when the $('.playOnAP') elements are replaced. I'm guessing I should use Delegated Events, but don't make myself clear.
I've tried the next:
$('.playOnAP').on('click','#mp3-list ul li',function() {
$('.playOnAP #mp3-list ul li').on('click',function() {
$('.playOnAP #mp3-list ul li').on('click','#mp3-list ul li',function() {

but doesn't work.

A: Try this:
$(document).on('click', '.playOnAP',function() {

When using event delegation, you must bind the event to an element that was originally in the DOM. If something has been dynamically replaced, you cannot bind to that.
As Anup insightfully mentioned, it is not strictly necessary to bind the click event to document -- any parent element will do, as long as it was originally in the DOM.
For example, if .playOnAP is the topmost container element that is being replaced:

        //some stuff here

You could use:
$('#someDiv').on('click', '.playOnAP', function() { //do your stuff });

As a default, though, you can pretty much always use $(document).on() (even if just as a quick check to make sure everything works before narrowing down to the most appropriate element).

A: You need to put the delegate on a parent of .playOnAp if you are replacing .playOnAp.  The event handlers only attach to DOM elements that exist when you add the event handler.


text:
Q: How do I fix Cannot resolve symbol 'activity_main'? Can anyone help me fix this problem? Everything seems fine. My xml and java looks normal but I can't seem to find what is wrong with the error. I already tried invalidating my cache and cleaning the project but the error is still there. Is there anyway I can fix this problem?
My Problem:
Cannot resolve symbol 'activity_main'

MainActivity
package com.example.machineproblem2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;

      public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lbl_msg"
        android:textAppearance="?android:attr/textAppearanceLarge"/>
    <EditText
        android:id="@+id/etMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/lbl_msg">
        <requestFocus/>
    </EditText>
    <Button
        android:id="@+id/btnNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_send"
        android:onClick="doNextActivity"/>

    <TextView
        android:id="@+id/tvContext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/msg"
        android:textAppearance="?android:attr/textAppearanceLarge"
        />
</LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

A: The suggested fixes were not really working so what I did was.

*

*Copied the contents of activity_main

*Delete the activity_main

*Create a new layout of the same name

*Pasted the copied contents of the previous xml file to the new layout.
It is a mystery why it did not detect the previous activity_main but this fix seemed to work

A: 1 - try to Clean then Rebuild project (Build > Clean Project / Rebuild Project)
2 - if (1) not work with you click : File > Invalidate Caches / Restart',
    and then click the 'Invalidate and Restart' button.

A: add
import com.example.machineproblem2.R

I don't see it in your imports, so Activity cannot resolve activity_main.xml because it doesn't understand what is R mean.
Another workaround:
try to rename your package from com.example.machineproblem2 to com.example.machineproblem.
It is possible what you break the rule of individual package naming (see: Package names in Android studio when dev name starts with a number?)

A: Does R.layout have access to the other xml layouts? (activity_second & layout_toast)? That was at least you'll know if its an issue with that layout specifically or with the project in general. If the others work then consider copy-pasting the layout and see if you can reference the new one then.


text:
Q: Pagination not taking effect on webpage I'm applying pagination on my sports.html page. In views.py I'm using ListView and using paginate_by = 2 but issue is pagination is not taking effect on webpage.
Pagination numbers are visible on page and when clicking on those page numbers it's not showing any error but all posts are visible on all pages, posts are not divided by paginate_by value.
Can anyone point out what I'm doing wrong here ?
views.py
class SportsList(ListView):
    model = Sports
    template_name = 'frontend/sports.html'
    paginate_by = 2

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['main'] = Main.objects.all()
        context['sports'] = Sports.objects.all()
        return context

sports.html

                        {% for sport in sports %}

XAR

From: {{ sport.from_date }}

To: {{ sport.to_date }}

{{ sport.category }}

{{ sport.title }}

{{ sport.content|truncatewords:30|safe }}

                                        View More

                        {% endfor %}
                        {% if is_paginated %}

                            {% if page_obj.has_previous %}

                            {% endif %}
                            {% for num in page_obj.paginator.page_range %}
                                {% if page_obj.number == num %}

{{ num }}

                                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}

{{ num }}

                                {% endif %}
                            {% endfor %}
                            {% if page_obj.has_next %}

                            {% endif %}

                            {% endif %}

A: This is because you are creating your queryset on get_context_data. You are not respecting the listview structure. Try something like this on your view:
class SportsList(ListView):
    queryset = Sport.objects.all()
    context_object_name = "sports"
    template_name = 'frontend/sports.html'
    paginate_by = 2

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['main'] = Main.objects.all()
        return context

A: You need to use the following in the views.py.
 context_object_name = 'sports'

By default, While a Django view is executing, self.object_list will contain the list of objects (usually, but not necessarily a queryset) that the view is operating upon. You can see the reference in Django doc here.
generic list view
Of course, you are adding 'sports' in the context of def get_context_data but a Django generic list view need to get operated upon the value mentioned in  context_object_name or the object_list.
Hence in your views.py use:
class SportsList(ListView):
    model = Sports
    template_name = 'frontend/sports.html'
    paginate_by = 2
    context_object_name = 'sports'
    ordering = ["id"]


text:
Q: Drop rows with duplicate column values in a dataframe and create a new column with secondary column data I have a dataframe with the following structure:
id  a   b
1   X   A
2   X   B
3   X   C
3   Y   D
4   Y   E
5   Y   F
5   X   G
6   X   H
7   Y   I

I'd like to remove the duplicate ids (3, 5) but make new columns (c, d) that contain the data in the 'a' and 'b' columns being deleted within the remaining id. e.g.:
id  a   b   c   d
1   X   A
2   X   B
3   X   C   Y   D
4   Y   E
5   Y   F   X   G
6   X   H
7   Y   I

I'm not what you'd call 'good at programming,' and this has gotten above my ability to search for a solution. An important point is that the logic doesn't need to be first/last/max/min for column a or b because these are uncorrelated strings and the sequence of occurrence doesn't matter — the goal is to import the data from rows being removed to the remaining row across the df. Any hints are appreciated!

A: this is the way you can follow:
res = (df.groupby('id').
       apply(lambda x: x[['a','b']].values.ravel()).
       apply(pd.Series))

print(res)
'''
    0  1    2    3
id
1   X  A  NaN  NaN
2   X  B  NaN  NaN
3   X  C    Y    D
4   Y  E  NaN  NaN
5   Y  F    X    G
6   X  H  NaN  NaN
7   Y  I  NaN  NaN


text:
Q: NodeJS - returning undefined issue Trying to create a blog website where users can comment on posts. I was able to create different blog posts so now I am trying to implement the comment feature. In my routes/admin/comments.js file I was able to create a comments array and append each comment into the array. I am using EJS to try to display the comments which should be <%=comments%> but I am getting an error that says 'comments is not defined' even though I have defined it in:
  Comment.find({})
    .then(comments =>{
      console.log(comments)
      res.render('home/post', {comments})
    })
})

What am i doing wrong? I am following the same method I did with creating posts.
models/Post.js Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const PostSchema = new Schema({
  title:{
    type: String,
    required: true
  },
  description:{
    type: String,
    required: true
  },
  body:{
    type: String,
    required: true
  },
  comments:[{
    type: Schema.Types.ObjectId,
    ref: 'comments'
  }]
},{usePushEach:true})

module.exports = mongoose.model('posts', PostSchema);

models/Comment.js Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const CommentSchema = new Schema({
  username:{
    type: String,
    required: true,
  },
  body:{
    type: String,
    required: true
  },
})

module.exports = mongoose.model('comments', CommentSchema)

routes/admin/comments.js file
const express = require('express');
const router = express.Router();
const Post = require('../../models/Post');
const Comment = require('../../models/Comment');

router.get('/', (req,res) =>{
  Comment.find({})
    .then(comments =>{
      console.log(comments)
      res.render('home/post', {comments})
    })
})

//Finds the comments and makes it available as object
router.post('/', (req,res) =>{
  Post.findOne({_id: req.body.id})
    .then(post=>{
      console.log(post)
      const newComment = new Comment({
        username: req.body.username,
        body: req.body.body,
      });
      post.comments.push(newComment);
      post.save()
        .then(savedPost =>{
          newComment.save()
            .then(savedComment =>{
              res.redirect('/')
            })
        })
    })
})

module.exports = router;


text:
Q: Javascript on touchstart event to trigger function The javascript code below works on desktop, but the touch event doesn't trigger on mobile (at least on iPhone). Where is my error on this? Your help is greatly appreciated.
// Virtual Tour
// -----------------------------------

// Toggles Intro to Virtual Tour Sections
function activate(){
    document.getElementById("virtual-tour-intro").className += " hide";
    document.getElementById("virtual-tour").className += " show";
};

// Click and OnTouch Event Trigger
var VirtualTour = document.getElementById("activate-video")
    VirtualTour.addEventListener("mouseup", tapOrClick, false);
    VirtualTour.addEventListener("touchstart", tapOrClick, false);

function tapOrClick(event) {
   //handle tap or click.
    activate();
    event.preventDefault();
    return false;
}

A: The code submitted actually works. It's was WordPress code injections into the HTML that was causing it to fail. Problem resolved.


text:
Q: Best practice for using includes in C I am learning C and I am unsure where to include files. Basically I can do this in .c or in .h files:
Option 1
test.h
int my_func(char **var);

test.c
#include <stdio.h>
#include "test.h"
int my_func(char **var) {printf("%s\n", "foo");}
int main() {...}

Option 2
test.h
#include <stdio.h>
int my_func(char **var);

test.c
#include "test.h"
int my_func(char **var) {printf("%s\n", "foo");}
int main() {...}

With option 2 I would only need to include test.h in whatever .c file I need the library. Most of the examples I see use option 1.
Are there some general rules when to do what or is this a question of personal preferences?

A: Don't use includes, you don't need.
I'd choose something like "Option 1". Why "something like" ? Because I'd create a separate file for the main and I'd keep all declaraions inside the .h and all definitions inside the corresponding .c.
Of course, both options are valid.
If you want to include only one header in your main, you can just create a header file, containing only includes - that's a common practice. This way, you can include only one header, instead of several.

A: I tend to prefer Option 1, as cyclic dependencies will come and bite you very quickly in option 2, and reducing the input size is the best way to guarantee faster compile times.  Option 2 tends towards including everything everywhere, whether you really need it or not.
That said, it might be best to experiment a little with what works for structuring your projects.  Hard and fast rules tend to not apply universally to these kinds of questions.

A: both options are correct. the C standard allows both solutions
All C standard headers must be made such that they can be included several times and in any order:

Standard headers may be included in any order; each may be included
  more than once in a given scope, with no effect different from being
  included only once

(From Preprocessor #ifndef)

A: I don't think that there is a universal rule (from a "grammatical" point of view, both your options are correct and will work). What is often done is to include in the .h file the headers you need for the library (as in your option 1), either because you'll need them when working with the library (thus avoiding always including the same set of header files in your .c files, which is more error prone), or because they are mentioned in the .h file itself (e.g., if you use a int32_t as type in the function prototypes of the .h files, you will of course need to include <stdint.h> in the .h file).

A: I prefer to use includes in c file.
If your program is getting bigger you might forgot to include something in one header file, but it is included in one other you use.
By including them in c-file you won't lose includes, while editing other files.

A: I prefer Option 1.  I want to know what I used in my project, and in much time, Option 1 works more effective than Option 2 in time and efficiency.

A: There is no rule specifying you have following a particular fashion. Even if you include / not include  in test.c file, it is not going to bother much, provided you include it in test.h file and include that test.h file in test.c. Hope you are clear with that.
This is because, you have preprocessor directives like #ifndef, #define, #endif. They are called Include guards. These are used in the inbuild header files. However, when you include a file written by you, either go with your option 2, or use include guards to be safe.
The include guards work as follows.
 #ifndef ANYTHING
 #define ANYTHING
..
..
..
 #endif
So when you include for the first time, ANYTHING is not yet defined. So ifndef returns true, then ANYTHING gets defined, and so...on.. But the next time if you include the same file ( by mistake) ifndef would return a false since ANYTHING is now defined and so the file would not be included at all. This protection is necessary to avoid duplicate declarations of variable present in the header file. That would give you a compilation error.
Hope that helps
Cheers


text:
Q: Sniffing traffic at embedded linux Are there any sniffers out there? I'm looking for something that can be compiled for an embedded device.
Important: I'm not limited in space. Therefore it can be any-size sniffer that can be compiled for armv7 and run at embedded Linux


text:
Q: How to clone a solution in VS2013? I have a solution MySolution.ABC.sln with 2 projects MySolution.ABC.Hello1.csproj and MySolution.ABC.Hello2.csproj in my TFS.
Name spaces are MySolution.ABC.Hello1 and MySolution.ABC.Hello2.
I need to clone this solution with another name like MySolution.XYZ.sln with same 2 projects with names changed to MySolution.XYX.Hello1.csproj and MySolution.XYZ.Hello2.csproj.Name spaces also should change to MySolution.XYX.Hello1 and MySolution.XYZ.Hello2.
Is there any way for this?
Thanks.

A: May be there are some shorter ways to do that, but I usually do it in this way:

*

*In file explorer, make a copy of the solution.

*Rename the copied folder as MySolution.XYZ

*Rename the folders of projects inside the solution folder as MySolution.XYX.Hello1 and MySolution.XYZ.Hello2

*Open the copied solution in Visual Studio

*With the mouse right click, remove references to the projects

*With the mouse right click, rename the solution to MySolution.XYZ (this will rename *.sln file)

*With the mouse right click, add existing projects (MySolution.XYX.Hello1 and MySolution.XYZ.Hello2) to solution

*With the mouse right click on the projects, rename the projects (this will rename *.csproj files)

*With F2 click on namespace, rename it with a new name.

*With the right mouse click on the projects, select properties and set the default namespase