How to setup a failover solution for Windows 2003 SMTP Server?

Question: I'm currently running Windows SMTP Server on a rented Windows 2003 Server VM.  There are times when my hosting company network is down and my clients can't send their emails via the SMTP Server host I provide them with, e.g. smtp.mycompany.com.
I want to provide a failover solution so that if my primary Windows 2003 SMTP Server is down, all SMTP traffic will automatically be diverted to another VM hosted (smtp2.mycompany.com) located in another data center.  Can this be done using Windows?  I know there's HA proxy and Nginx but having to deal with Linux is beyond my capability - which is obvious otherwise I won't be asking such a novice question.:)  However, I'm open to the possibility of renting a service that handles the failover.  Thanks.
Answer: You're over-thinking the problem. DNS already has a solution for you: multiple MX records. Add smtp2.mycompany.com as another MX record for your domain, but give it a higher preference value than your existing MX records. Senders will generally prefer the server with a lower preference.
I say generally because some broken MTA's just pick a random one, and some pick just the first one. A vast majority of those broken MTA's are spammers so there's no real loss there.
But if these are internal email servers for handling outgoing email, then MX records aren't going to help you. Possible options include:

load balancers (but you don't get data center survivability that way, only host survivability)
DNS based fail-over (you'd have to wait for DNS replication and client DNS cache timeouts to occur)
DNS load balancing (your client would have to be smart enough to repeat the DNS query for each SMTP retry)
Comment: I'm filtering those outgoing emails, archiving, some more processing before sending out.
Comment: see my edits above
Comment: thanks for replying. I have to set MX records when I setup my company domain for Google Apps Gmail. From my understanding, MX records are for the "receiving" SMTP Server.  Does it also apply to "sending" SMTP Server. By sending SMTP server, I am referring to the Outgoing Mail Server client that is configured in Outlook mail client, for example, for Gmail, it is smtp.gmail.com, port 578.
Comment: Wait a second, what are you using these SMTP servers for? I assumed they were handling your inbound email. Are you just using them for sending mail? What can't you use Gmail's servers?
Comment: Thanks for the update.  I'm also looking at a service based solution since I'd probably use a hosting company/cloud.  Did some more research and discovered that Azure supports some sort of load balancing and failover.


To express quantification of propositional function using $\land , \lor , \lnot$

Question: $\forall x((x \neq 3) \rightarrow P(x))\equiv  \forall x((x=3) \lor P(x))) $
,where domain of P(x) consists of intergers 1,2,3,4,and 5.
The given answer is:$(P(1)\land P(2)\land P(4)\land P(5))$,
Since $\forall x((x \neq 3) \rightarrow P(x))\equiv  \forall x((x=3) \lor P(x)) $,
I'm confused why not the answer be:
$((x=3 \lor P(1)) \land ... \land (x=3 \lor P(5))$
Comment: I am confused by lack of parenthesis.  Do you mean (p implies q) equivalent r OR p implies (q equivalent r)?
Comment: My fault,have edited.
Comment: P(x) is a statement and statements do not consist of integers.
Answer: When we instantiate $\forall x ((x=3) \lor P(x))$ we get:

$((1 =3) \lor P(1)) \land ((2=3) \lor P(2)) \land ((3=3) \lor P(3)) \land ((4=3) \lor P(4)) \land ((5=3) \lor P(5))$.

But $(1=3) \equiv \text F$ and $(F \lor P(1)) \equiv P(1)$. The same for $2,4,5$.
We have also $(3=3) \equiv \text T$ and $(T \lor P(3)) \equiv T$.
In conclusion, we get:

$P(1) \land P(2) \land T \land P(4) \land P(5)$

i.e. $P(1) \land P(2) \land P(4) \land P(5)$, as expected.


Committee forming: bad intuition, but where?

Question: Consider the following problem:

How many different mixed gender committees of 3 people can be chosen
  from a group of 5 men and 5 women?

Wrong approach: These are committees of the form $M_1M_2W_1$ or $W_1W_2M_1$ (the ordering does not matter).
There are $5\choose 2$$5\choose 1$ of the former and  $5\choose 2$$5\choose 1$ of the latter for a total of $2{5\choose 2}{5\choose 1}=100$ possible committee.
Correct approach: Take the total number of committees of 3 possible and subtract from the number of non-mixed ones. There are ${10\choose 3}$ possible committees and ${3\choose 5}$ all men (and as many all women) ones. Therefore, one gets ${10\choose 3}-2{5\choose 3}=80$ possible committees.
Here is my question: The first approach over-counts 20 committees. I wonder of what form are these over counted committees. More generally, I fail to understand why the first approach gives an incorrect answer.
Answer: Both approaches are correct, but you have evaluated the result of the second approach incorrectly. It should be
\begin{equation}
\binom{10}{3} - 2\,\binom{5}{3} = 120 - 2\times 10 = 100,
\end{equation}
which agrees with the result of the first approach. So, this was just a calculation error.
Comment: Argh: sorry, the correct approach was from a book and of course, I didn't check their calculations (they put the expression in terms of combinatorial and the final answer only)!


What are some strategies one could use to put as many suspensions as possible in a chord progression?

Question: I ask this question in the context of strict (florid) tonal counterpoint as taught, for example, by Albrechtsberger and many later writers.
Fux in his Gradus ad Parnassum recommends putting many suspensions in one's compositions, and letting the suspensions occur in alternating voices. While I agree that this often enlivens the impression of contrapuntal independence, it is easier said than done. For example, I often find that with a falling bass, the natural tendency of good part-writing is to let the other voices rise; but then no (dissonant) suspensions can occur, because these should resolve by stepwise descent.
Or did Fux perhaps mean to include consonant suspensions in his advice? If so, how would one include this kind of suspension in a tonal chord progression without undermining the sense of tonal harmony too much?
Comment: I realize that I really ought to know my Fux by heart, but could you include the quote?
Answer: This isn't really a strategy for florid counterpoint, but just a way to emphatically make the point that suspensions won't undermine the sense of tonality provided the suspensions are resolved. You can have a suspension on each and every chord except for cadences where you would want a complete resolution of dissonance. The following is one of my favorite sequential progressions...

...only the first and last chords are plain triads, all other chords are seventh chords and each chord involves a suspension. The suspensions are formed by holding chordal thirds so they become dissonant seventh, when resolved by downward step the lines moves to the next chordal third.
Using that progression of seventh chords as a gauge, you could use a suspension on every other chord without undermining the tonality, provided they were resolved properly. With each suspension followed by a resolution, you would have a lot of freedom to place the various suspension in whichever voice you like.
I think the thing to do to study putting the suspensions into counterpoint is remember that the suspensions are decorations of otherwise consonant writing. So could write a study of consonant parts then write several revisions that place suspensions wherever the music allows. Or, you could start with a series of suspension figures your want to use then move your parts so that you get the particular suspensions. Some things may work better than others. I would treat the endeavor as studies and sketches. It's process to work through to see what works and what doesn't.

I often find that with a falling bass, the natural tendency of good part-writing is to let the other voices rise; but then no (dissonant) suspensions can occur, because these should resolve by stepwise descent.

I think you can do this. If the bass descent is harmonized in thirds then you have an opportunity for a 4-3 suspension. If you start with a perfect chord (root position) then you could suspend the bass before the descent for a 2-3 suspension...
Comment: Thanks for your answer, which is excellent as always!
Comment: I have seen this called a "chain suspension." It can also be used against a pedal point.
Answer: Although the dissonant suspensions are preferred, there is no reason why you couldn't include consonant suspensions to achieve this goal.  They also help correct a natural consequence of a chain of suspensions, which is that your suspension voice falls and falls and falls and in a few bars you're an octave below where you started.  The Fux examples are full of consonant suspensions,  too.
A longer answer,  and certainly one that requires more work on your part, is to learn which CF motions allow which suspensions so you are faster at finding them.  In doing so you will develop a sixth sense about a CF and where suspensions will be tricky.  Write these spots first, then fill in the easy parts later.


Recursive Feature Elimination returns suspect results regarding accuracy

Question: I am doing RFE with 18 features. My understanding of RFE is, it starts by trying N - 1 models, and then removing the feature that causes the N - 1 models to perform worst. Then it tries N - 2 models, and so on. I've also read elsewhere that RFE does some sort of weighting. Which one is it? Weighting to me indicates a more math-y approach that requires more interpretation of the "optimal" features, whereas doing the N - 1, N - 2 indicates to me more of a brute force approach that requires less interpretation of the "optimal" features.
My model specifically said the highest accuracy was with 18 features. However, the suspect aspect was how the accuracy stayed the same when RFE was run with 0 through 15 features (see picture).

Does this indicate that something might be wrong with my RFE model? If so, what could be wrong?
Answer: That's not how RFE should work. Backwards RFE would build a model with all the variables and then iteratively remove 1 variable with the lowest effect. The plot is a little weird, however keep in mind that the difference between 25 and 18 features in the plot is only 0.003, easily just a random effect.
Comment: That's seems to be exactly what he is concerned about.


How to display all checked values first

Question: My Datatable contains a list of values, of which certain are checked. How can I display all the checked values first followed by the unchecked ones
Comment: `ORDER BY column_name DESC` in the end of your SQL statement
Comment: which database you are using.. and which is datatype of column?
Comment: The database is MySQL, and the datatype is a Boolean
Comment: @devdRew
Can you please post it as an answer, so that I can upvote it
Answer: Write your query with an order by statement (isChecked is your boolean)
<code>select * from table1 order by isChecked desc
</code>

How to display all checked values first


How to configure REST server to create new node from URL parameters?

Question: Drupal   7.23
Services 7.x-3.5
I've followed the instructions for setting up Services module, including https://drupal.org/node/1699354. I got the endpoint setup successfully. I am able to retrieve index of nodes using ...endpoint/node and specific nodes using .../endpoint/node/#.
Now how can I create new nodes via Service through an URL? The Services manual gets really confusing at this point, is outdated and full of errors. The sample code they provide here https://drupal.org/node/1334758 ... am i supposed to put this in a custom module in order to be able to POST? If so, it turns my whole site blank right after adding this line:
// cURL
$curl = curl_init($request_url);

Also, there's an issue with CSRF validation, as showing in the Firefox Poster tool. The Services forum is a madhouse so I come here in hopes that someone can guide me in the right direction. What other modules do I need to get this to work? Why does my site go blank after adding the code above?
A simple solution would be the following:
domain/endpoint?title=test&url=http%253A%252F%252Fwww.example.com
and produce a new node of nodetype with a title and URL.
Answer: In order to create the node you must use the POST HTTP request so you can't do something like domain/endpoint?title=test&url=http%253A%252F%252Fwww.example.com(it's GET HTTP request). You can do the following to solve your problems:

First you need to make the Services 3.0 work with Firefox Poster tool. You can go Testing with REST Server for checking all the basic function in case you forgot to set the permissions or forgot to enable resources.
After you find out how to communicate with Services 3.0. You can use drupal_http_request to build your own POST/GET HTTP request. An example will be here Making authenticated requests to REST Server.
Comment: Thanks. I had to learn how to use the Poster tool, fill in User Auth info, fill in the appropriate parameters, and finally click 'body from parameters'... then POST. I was able to create a post at the URL: http://my-domain/endpoint/node. No headers were required. I did not require any authentication like oAuth, however a username and password was required to post. As for the $curl issue, i will revisit that in another post. Thanks!
Comment: When we use Poster plugin of firefox actually we are using Session Authentication method. If we want to use OAuth authentication it will be a little complicate from we must generate token_request and token_access not just username/password
Answer: Sample code provided there is flawed as there is no need to get CSRF token two times. One time is enough after user login. Also, CSRF token needs to be obtained in the same curl session as login, as Drupal Services returns empty otherwise, try the following code once:
<?php

        // LOGIN AND GET CSRF TOKEN

        /*
            * Server REST - user.login
        */

        // REST Server URL
        $request_url = 'http://mysite....com/server/user/login.json';

        // User data
        $user_data = array(
        'username' => 'xxxx',
        'password' => 'xxxx',
        );
        $user_data = http_build_query($user_data);

        // cURL
        $curl = curl_init($request_url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); // Accept JSON response
        curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
        curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
        curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

        $response = curl_exec($curl);
        //print_r($response);
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        //print "
".$http_code."
";
        // Check if login was successful
        if ($http_code == 200) {
            // Convert json response as array
            $logged_user = json_decode($response);
            //print_r($logged_user);

        }
        else {
            // Get error msg
            $http_message = curl_error($curl);
            die($http_message);
        }

        // Define cookie session
        $cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;

        //GET CSRF TOKEN
        curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://mysite....com/services/session/token',
        ));
        curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session");
        // $csrf_token = curl_exec($curl);
        //print_r($csrf_token);

        $ret = new stdClass;

        $ret->response = curl_exec($curl);
        $ret->error    = curl_error($curl);
        $ret->info     = curl_getinfo($curl);

        //print_r($ret->response);
        $csrf_token = json_decode($ret->response)->token;

        /*
            * Server REST - node.create
        */

        // REST Server URL
        $request_url = 'http://mysite....com/server/node';

        // Node data
        $node_data = array(
        'title' => 'A node created with services 3.x and REST server',
        'type' => 'page',
        'body[und][0][value]' => '
Body
',
        );
        $node_data = http_build_query($node_data);

        // cURL
        $curl = curl_init($request_url);
        // Accept JSON response
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', 'X-CSRF-Token: ' .$csrf_token));
        curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
        curl_setopt($curl, CURLOPT_POSTFIELDS, $node_data); // Set POST data

        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        // use the previously saved session
        curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

        $response = curl_exec($curl);
        print "

";
        print_r($response);
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        // Check if login was successful
        if ($http_code == 200) {
            // Convert json response as array
            $node = json_decode($response);
        }
        else {
            // Get error msg
            $http_message = curl_error($curl);
            die($http_message);
        }

        print_r($node);

    ?>

Comment: thanks for providing this code, although I was able to get the POST functioning without any additional modules. I did install some extra curl libraries in Apache server which i was missing, and could be the reason why my site went blank after any $curl statements. What is the reason for this code if HTTP Post is available without it? Thanks!
Answer: For some reason, the CRUD operation 'index - List all nodes' has to be checked in addition to 'Create a node' within the Resources menu, otherwise the CSRF validation issue remains.


Angular JS: Increment a Counter in a Service From Controller

Question: I'm trying to fetch a value from an API inside my service for a counter, and then increment on that counter inside my controller:
service
angular.module('app')
.factory('MyService', MyService)

function MyService($http) {
  var url = 'URL;

  return {
    fetchTotal: function(p) {
      return $http.get(url, { params: p })
        .then(function(response) {
          var total = response.data.meta.total;
          return total;
        }, function(error) {
          console.log("error occured");
        })
    },
    incrementCounter: function(){
      total++;
    }
  }
}

controller
app.controller('Controller1', function ($scope, MyService) {
    var params = {
       ...
    }

    MyService.fetchTotal(params).then(function(response) {
      $scope.counter = response;
    });

    $scope.incrementCounter = function(){
        MyService.incrementCounter();
    }
});

view

    {{ counter }}
    increment

I can't work out how increment on that total I get back from the API with an ng-click. Is this possible?
Any help is appreciated. Thanks in advance!
Comment: `$scope.counter += response` or `$scope.counter++` without using the response may work
Comment: I need the counter to update in the service, because that `total` is used by two different controllers, and I use the service to keep them in sync.
Comment: move `var total = 0` to below `var url =`
Comment: That doesn't work. It just increments the total upwards from 0.
Comment: See if this related post helps you: http://stackoverflow.com/questions/16023451/binding-variables-from-service-factory-to-controllers
Answer: Angularjs services are singletons, so you can create variables and share it among controllers.
Notice below how variable total is initialized in the service. Same variable is used for interaction with the controllers by using the getCounter() method.
Also notice the init() method. Your controller can call MyService.init first thing to initialize the total variable.
angular.module('app')
.factory('MyService', MyService)

function MyService($http) {
  var url = 'URL';
  var total = 0; /* or some other initial value*/

  return {

    init: function(){
      $http.get(url, { params: p })
        .then(function(response) {
          total = response.data.meta.total;

        }, function(error) {
          console.log("error occured");
        });
    },
    incrementCounter: function(){
      total++;
    },
    getCounter: function(){
     return total;
    }
  }
}

See plunker for demo: http://plnkr.co/edit/idSxgm0axk43ydThTbJF?p=preview
Comment: This is what my controller looks like. `MyService.fetchTotal(params).then(function(response) {
  $scope.counter = MyService.getCounter();
});`. If I put a `console.log()` on the `incrementCounter()` function, I can see the total going up in the console. However, the {{ counter }} on the view doesn't increment.
Comment: The view is looking at `$scope.counter`, not the variable `total` in `MyService`. `$scope.counter` and `total` are detached. Change in one will not effect the other. You'll have to use a controller function in your view that returns you the latest value of `total`
Answer: Looks like you are doing everything right, except the variable total.
You should initialize it in an upper level so that it is also visible from incrementCounter function:
function MyService($http) {
  var url = 'URL;
  var total = 0;

  return {
    fetchTotal: function(p) {
      return $http.get(url, { params: p })
        .then(function(response) {
          total = response.data.meta.total;
          return total;
        }, function(error) {
          console.log("error occured");
        })
     },
     incrementCounter: function(){
       total++;
     }
  }
}

Hope it helps


Neural networks, batch vs sequential learning

Question: I've currently implemented a neural network and I want to know which works better, the sequential learning or the batch learning. As far as I understand, the batch learning is more efficient than the sequential learning, but according to the tests I've made, there is barely any difference between the accuracy of the two learning styles. Worth to notice is that I have a binary classification problem. My question is therefore, is there anything I can do to really showcase the difference between them, is one better for smaller type of training, more complex decision boundaries etc? Thanks in advance!
Comment: When you say "sequential learning" do you mean submitting your entire dataset as one single large batch, rather than splitting into smaller batches?
Comment: I mean that if I have a large data-set with 50 patterns, I submit 1 pattern at a time
Comment: Batch method is good and gives some accurate results when compared to training set to the testing set.
Comment: I'm more interested in a comparison, as far as i understand batch is more efficient in most cases cause of the efficient matrix calculations, but when would you in that case use sequential?
Comment: I don't think it's ever recommended to do *truly* sequential, i,e, batch size = 1, because it's just so stochastic and noisy; you'd be doing weight updates based on just one example of data.
Answer: Andrew Ng gives a good explanation here on how batch sizes affect the training of a network:
https://www.youtube.com/watch?v=2GGKR-vOlgo
Essentially, if you set your mini batch size to 1 (sequential as you refer to it) then it can cause the learning to behave very stochastically (noisy), and if you set it too small (or to 1) then it's unlikely to converge on the minima.
Comment: Thank you for this, the video was actually really helpful, got an idea of where to go from here
Comment: No problem.  All of Andrew Ng's video are certainly worth a watch.
Answer: Batch learning is preferred to Sequential learning as its more time consuming and your R2 might prune to over-saturation. Try both if you are doing it for the first time and share the feedback.


PHP Regex for highlight string

Question: I need a script to highlight occurrences of one or more keywords in a text. I have a script in French and I want my script to look for occurrences with special characters and uppercase letters.
My URL is (example): .../?q=être
And I wish the keywords "être", "Être", "etre" and "Etre" to be highlighted.
Is it possible ? (with ...)
Example :
Bonjour ceci est un texte avec le verbe être, avec la majuscule ça aurait
été Être, et sans accent etre, puis Etre.

So:

Ignore specials characters
Ignore uppercase
Comment: Your description and examples don't match up. `Ignore specials characters - Ignore uppercase`...`I wish the keywords "être", "Être", "etre" and "Etre" to be highlighted`. Those have special characters and uppercase letters. You also should provide an example of what you've tried.
Comment: Yep, i want to on my URL i have "être", "Être", "etre" and "Etre", and i want to on my string target, the word(s) "être", "Être", "etre" and "Etre" to be highlight.
So i want to ignore specials chars and uppercase on all request :)
Comment: `ê` is a special character, `Ê` is special and uppercase... or do you mean any form of `etre`?
Comment: And if the search word is `"etre"` *(without accent)*, do you want also words with accent to be highlighted?
Comment: @CasimiretHippolyte Looks like it should be a dup of http://stackoverflow.com/questions/14114411/remove-all-special-characters-from-a-string.
Comment: @chris85: I don't think, the goal isn't to sanitize the string but to find (and highlight) a word with or without accent, and this without to change the accents of the original string.
Answer: This sample will match with the required words in your sentence:
And I wish the keywords "être", "Être", "etre" and "Etre" to be highlighted.
/[êÊeE]tre/

Comment: Thanks, but i want ALL specials characters, and ALL uppercase. Not just for "être". Thanks you :)
Comment: Could you write me here the ALL special characters what you would like? :)
Answer: I, i think :
$utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[''‹›']/u'    =>   ' ', // Literally a single quote
        '/[""«»"]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );

Thx :)
I have found that here : Remove all special characters from a string
Comment: Instead of writing and accepting whatever, you should take the time to find a real solution. Keep in mind that your question and the accepted answer have for vocation to help eventual future users.

PHP Regex for highlight string


Adding fields to custom content entity

Question: I'm creating a new content entity called Points. My code already creates the table and its fields, but i cant see the fields in the entity form. I thought that fields in baseFieldDefinitions() should to be shown in the form . What i'm doing wrong? it only shows a pair of these fields:
<code>public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('User ID'))
    ->setDescription(t('The user ID of the operation author.'))
    ->setSettings(array(
      'target_type' => 'user',
      'default_value' => 0,
    ))
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

    $fields['target_type'] = BaseFieldDefinition::create('text')
    ->setLabel(t('Target Type'))
    ->setDescription(t('Tipo de entidad sobre la que se realiza la operación'))
    ->setDefaultValue(0)
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);

    $fields['target_entity'] = BaseFieldDefinition::create('integer')
    ->setLabel(t('Target Entity'))
    ->setDescription(t('ID de la entidad sobre la que se realiza la operación'))
    ->setDefaultValue(0)
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);

    $fields['operacion'] = BaseFieldDefinition::create('list_string')
    ->setLabel(t('Operación Realizada'))
    ->setDescription(t('Operación realizada (create, update, delete)'))
    ->setSettings([
      'allowed_values' => [
        'create' => 'create',
        'update' => 'update',
        'delete' => 'delete',
      ],
    ])
    ->setDisplayOptions('view', [
      'label' => 'visible',
      'type' => 'list_default',
      'weight' => 6,
    ])
    ->setDisplayOptions('form', [
      'type' => 'options_select',
      'weight' => 6,
    ])
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);

    $fields['timestamp'] = BaseFieldDefinition::create('changed')
    ->setLabel(t('Changed'))
    ->setTranslatable(TRUE)
    ->setDescription(t('The time that the points was last edited.'))
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);

    $fields['points'] = BaseFieldDefinition::create('integer')
    ->setLabel(t('Points'))
    ->setDescription(t('Points to grant'))
    ->setDefaultValue(0)
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);

    $fields['langcode'] = BaseFieldDefinition::create('language')
    ->setLabel(t('Language code'))
    ->setDescription(t('The points language code.'))
    ->setDisplayConfigurable('view', TRUE)
    ->setDisplayConfigurable('form', TRUE);

    return $fields;
  }
</code>
Answer: In order to add new fields to already existing entity you need to write update hook.
Refer https://git.drupalcode.org/sandbox/Bhanu951-3103712/-/blob/8.x-dev/omdb_api/omdb_api.install#L178 for sample code
Relevant Change Record #2554097

Adding fields to custom content entity


Leaflet on click event returns undefined value from a geojson

Question: Trying to create a map using leaflet and geojson file which will return the country name as its value when i click it. however all im currently getting is undefined.
var popup = L.popup();
function onMapClick(e) {
    popup
        .setLatLng(e.latlng)
        .setContent("click" + MYGEOJSON.features[0].properties.name ) // Have to add
        .openOn(map);
}

name_of_countries = []
eu['features'].forEach(feature => name_of_countries.push(feature['properties']['NAME'].value))

console.log(name_of_countries)
var myStyle = {
    "color": "grey",
    "weight": 2.5,
    "opacity": 1
};
L.geoJSON(MYGEOJSON,{
  style:myStyle
}).addTo(map)
map.on('click', onMapClick);
var options = {
  maxZoom: 16,
  tolerance: 3,
  debug: 0,
  style: {
    fillColor: "#1EB300",
    color: "#F2FF00",
  },
};

console.log(MYGEOJSON.features[0].properties.name)`

I have a geojson file with all european countries mapped as polygons.
Im trying to solve it doing two things. one is to log it into console to see if it works an other is as a click event when i click on the map. However both return undefined.
Answer: Add to the polygons directly a popup while creating:
L.geoJSON(MYGEOJSON,{
  style:myStyle,
  onEachFeature: function(feature, layer){
    layer.bindPopup(feature.properties.name)
  }
}).addTo(map)

Comment: When i click on the polygons on the map the popup is empty.
Comment: Look what properties your feature has `console.log(feature.properties)` after `layer.bindPopup`
Comment: My apologies it was case sensitive.


JobScheduler onStartJob gets delayed once application gets killed

Question: I am not getting why service onStartJob not calling with given time which mentioned in setOverrideDeadline(2000).
I am scheduling job like:
private void scheduleJob() {
    JobInfo myJob = new JobInfo.Builder(0, new ComponentName(this, NetworkSchedulerService.class))
            .setRequiresCharging(true)
            .setMinimumLatency(1000)
            .setOverrideDeadline(2000)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setPersisted(true)
            .build();

    JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.schedule(myJob);
}

JobService snippet:
public class NetworkSchedulerService extends JobService implements
        ConnectivityReceiver.ConnectivityReceiverListener {

    private static final String TAG = NetworkSchedulerService.class.getSimpleName();

    private ConnectivityReceiver mConnectivityReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "Service created");
        mConnectivityReceiver = new ConnectivityReceiver(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "Service destroyed");
    }

    /**
     * When the app's MainActivity is created, it starts this service. This is so that the
     * activity and this service can communicate back and forth. See "setUiCallback()"
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        return START_NOT_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.i(TAG, "onStartJob" + mConnectivityReceiver);
        registerReceiver(mConnectivityReceiver, new IntentFilter(Constants.CONNECTIVITY_ACTION));
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.i(TAG, "onStopJob");
        unregisterReceiver(mConnectivityReceiver);
        return true;
    }
}

Manifest:
 <service
            android:name=".NetworkSchedulerService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE"/>

Can somebody please help me to resolve this issue? If possible please provide detail explanation about this delay.
Comment: could you please add your manifest? have you added the job service declaration into your manifest?
Comment: @AnisBENNSIR: Please have a look at manifest.
Comment: from your implementation, i can see any issue. Is your job not running at all or it run after 1s or you are expecting that it run after  2s? Could you please detail the expected behaviour and what your are exactly facing... From your implementation your receiver will be unregistred as soon as it's registred...
Comment: @AnisBENNSIR: I am expecting call after 2000 milliseconds but getting it almost 1 minute. Even my device is charged. Not getting why call gets delayed.
Answer:  @Override
    public boolean onStartJob(JobParameters params) {
        Log.i(TAG, "onStartJob" + mConnectivityReceiver);
        return true;
    }

The above method call gets delayed due to system resource unavailability. It is not necessary that JobSceduler will start the job within given deadline which I mentioned in the above code.
eg: setOverrideDeadline(2000)
Some of JobInfo methods like setRequiresCharging() and setRequiresBatteryNotLow() can decrease the delay.
Note: This delay varies in both Nougat and Oreo devices. So It's necessary to look at their delay.
Answer: Try adding enabled attribute to NetworkSchedulerService in Manifest:
android:enabled="true"


Sum of column returning all null values in PySpark SQL

Question: I am new to Spark and this might be a straightforward problem.
I've a SQL with name sql_left which is in the format:
Here is a sample data generated using sql_left.take(1):
[Row(REPORT_ID='2016-30-15/08/2019', Stats Area='2 Metropolitan', Suburb='GREENACRES', Postcode=5086, LGA Name='CITY OF PORT ADELAIDE ENFIELD', Total Units=3, Total Cas=0, Total Fats=0, Total SI=0, Total MI=0, Year=2016, Month='November', Day='Wednesday', Time='01:20 am', Area Speed=50, Position Type='Not Divided', Horizontal Align='Straight road', Vertical Align='Level', Other Feat='Not Applicable', Road Surface='Sealed', Moisture Cond='Dry', Weather Cond='Not Raining', DayNight='Night', Crash Type='Hit Parked Vehicle', Unit Resp=1, Entity Code='Driver Rider', CSEF Severity='1: PDO', Traffic Ctrls='No Control', DUI Involved=None, Drugs Involved=None, ACCLOC_X=1331135.04, ACCLOC_Y=1677256.22, UNIQUE_LOC=13311351677256, REPORT_ID='2016-30-15/08/2019', Unit No=2, No Of Cas=0, Veh Reg State='UNKNOWN', Unit Type='Motor Vehicle - Type Unknown', Veh Year='XXXX', Direction Of Travel='East', Sex=None, Age=None, Lic State=None, Licence Class=None, Licence Type=None, Towing='Unknown', Unit Movement='Parked', Number Occupants='000', Postcode=None, Rollover=None, Fire=None)]

Note: Age column has 'XXX','NUll' and other integer values as 023,034 etc.
The printSchema shows Age,Total Cas as integers.
I've tried the below code to first join two tables:
sql_left = spark.sql('''
SELECT *
FROM sql_crash c Left JOIN sql_units u ON c.REPORT_ID=u.REPORT_ID''')
sql_left.createOrReplaceTempView("mytable")

And below code to generate Total Cas:
sql_result = spark.sql('''select concat_ws(' ', Day, Month,Year,Time) as Date_Time,Age,"Licence Type","Unit Type",Sex,COALESCE(sum("Total Cas"),0) as Total_casualities from mytable where Suburb in ('ADELAIDE','ADELAIDE AIRPORT','NORTH ADELAIDE','PORT ADELAIDE') Group by Date_Time, Age,"Licence Type","Unit Type",Sex order by Total_casualities desc''')
sql_result.show(20,truncate=False)

The output I'm getting is below with sum as 0.
+--------------------------------+---+------------+---------+-------+-----------------+
|Date_Time                       |Age|Licence Type|Unit Type|Sex    |Total_casualities|
+--------------------------------+---+------------+---------+-------+-----------------+
|Friday December 2016 02:45 pm   |XXX|Licence Type|Unit Type|Unknown|0.0              |
|Saturday September 2017 06:35 pm|023|Licence Type|Unit Type|Male   |0.0              |
+--------------------------------+---+------------+---------+-------+-----------------+

I've tried multiple options, however nothing worked out.
My main problem here is Total_casualities is returning 0.0 for all rows if I use COALESCE(sum("Total Cas"),0). If I don't use COALESCE, it is displaying values as NULL.
Help is much appreciated.
Comment: Sum of column returning all 0.0 in pyspark sql. My problem here is Total_casualities is returning 0.0 for all rows
Answer: Instead of specifying Total Cas in double-quotes("Total Cas"), mention it in backticks.
i.e. `Total Cas`

Note: The column name with space in between needs to be specified with backticks. As you are mentioning under quotations, it considers it as a string, that's why you are not getting sum. Also, for other columns(like Licence Type,Unit Type), it's displaying the same as a string instead of its value. Hope you got it.
sql_result = spark.sql('''select concat_ws(' ', Day, Month,Year,Time) as Date_Time,Age,`Licence Type`,`Unit Type`,Sex,**sum(`Total Cas`)** as Total_casualities from mytable where Suburb in ('ADELAIDE','ADELAIDE AIRPORT','NORTH ADELAIDE','PORT ADELAIDE') Group by Date_Time, Age,`Licence Type`,`Unit Type`,Sex order by Total_casualities desc''')


Copy Button using jquery

Question: please help me...I just want to create a copy button using jquery or javascript that will copy all signature on the white box.

if i clicked the copy signature.. the whole signature on the white box(signature_gen) will copy and if i used ctrl+v it will paste on the outlook..
here's my html code:

              <?php echo $fname; ?>

              <?php echo $position; ?>

              WeChat: <?php echo $wechatid; ?> | Skype: <?php echo $skypeid; ?>

              Mobile No.: +<?php echo $mobileid; ?> <?php echo $mobileid2; ?> <?php echo $mobileid3; ?>

<div2>51Talk,an NYSE listed company, is a leading  online English teaching platform in the world.</div2>

    <input type="submit" name="submit" class="btn-copy" value="Copy Signature" />

and my js code:

but when i try to paste the code it goes like this:

i want to make it like this:

hope you can help me...
Comment: going to need to see some html for the page, essentially you need to select the p? tag get the text value and add it to the person's clipboard using that button
Comment: yes your right...
Answer:

$(document).ready(function () {
        $("#SignatureHtml").attr('data-clipboard-text', $("#Box").html());

        var clipboard = new Clipboard('.Btn');

        clipboard.on('success', function (e) {
            $("#Box").css("border-color", "blue");
            $("#PastSection").focus();

        });

    });
.element {
        float: left;
    }

    #Box {
        width: 200px;
        height: 85px;
        border: 1px solid #ccc;
        text-align: center;
        padding: 5px;
        margin: 0px 5px 5px 5px;
    }

            Test Text1

            Test Text2

            <textarea rows="6" cols="40" id="PastSection" placeholder="Ctrl+V"></textarea>

        <button id="SignatureHtml" class="Btn" type="button" data-clipboard-text="">copy</button>

Answer: I'd recommend adding an ID to :

    <?php echo $fname; ?>

    <?php echo $position; ?>

    WeChat: <?php echo $wechatid; ?> | Skype: <?php echo $skypeid; ?>

    Mobile No.: +<?php echo $mobileid; ?> <?php echo $mobileid2; ?>
    <?php echo $mobileid3; ?>

You'll need to select the text using jQuery/Javascript then make the button trigger this:
function copyText(){
    var aux = document.createElement("input");
    aux.setAttribute("value", $("#message").text);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand("copy");
}

Something like that should work
and then on your button add onclick="copyText()"
Comment: put the id on the div that surrounds the text, or change the text to a P tag and put the id on that, then you'll only be selecting the text
Comment: Already did that.. when I used ctrl+v the code table are still pasting...
Comment: it doesn't reflect that in your code above however make sure you're selecting the right id, this should work.

Copy Button using jquery


Criar campo unique Android Studio

Question: Sou iniciante no desenvolvimento android e estou tentando criar uma tabela no sqlite onde o valor do email será único. Só que o aplicativo está permitindo cadastrar emails iguais.
<code>@Override
    public void onCreate(SQLiteDatabase db) {
        try {
            String sql = "CREATE TABLE usuario (" +
                "id INTEGER PRIMARY KEY NOT NULL," +
                "email TEXT NOT NULL UNIQUE," +
                "senha TEXT NOT NULL);";
            db.execSQL(sql);
            Toast.makeText(UsuarioRepository.this.contexto, "Tabela criada com sucesso", Toast.LENGTH_LONG).show();
        }catch (SQLException ex){
            Toast.makeText(UsuarioRepository.this.contexto, "Erro ao criar tabela: "+ex, Toast.LENGTH_LONG).show();
        }
    }
</code>
Comment: Se sua aplicação permite cadastrar e-mails iguais mas sua tabela não permite então o erro deve estar em sua aplicação. Outra coisa que pode estar ocorrendo é que alguma caractere espaço no início ou fim do e-mail pode estar diferenciando e-mails aparentemente iguais. Remova eventuais espaços desnecessários.
Answer: Tem um exemplo bacana neste Link: Diferença na utilização Indice Unique e Unique Constraint no MySQL?
No seu create table siga este exemplo:
<code>CREATE TABLE `phone` (
    `id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
    `country` DECIMAL(5,0) UNSIGNED NOT NULL,
    `area` DECIMAL(5,0) UNSIGNED NOT NULL,
    `number` DECIMAL(8,0) UNSIGNED NOT NULL,
    `extension` DECIMAL(5,0) UNSIGNED DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `ix_phone` (`country`, `area`, `number`, `extension`),
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
</code>

Criar campo unique Android Studio


Como acessar atributo de uma classe dentro de outra classe no Django?

Question: Estou tentando simular um sistema de locação de veículos usando Django e me deparei com a seguinte dúvida:
como implementar a fatura? da forma como estou tentando fazer precisaria ter acesso aos atributos das classes Vehicle e Rental dentro da classe de Invoice, isso é possível?
segue o código
class Vehicle(models.Model):
    model = models.CharField(max_length=15)
    category = models.CharField(max_length=15)
    price_per_day = models.FloatField()

class Rental(models.Model):
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT)
    start = models.DateTimeField()
    end = models.DateTimeField()

    @property
    def time_diff(self):
        delta = self.end - self.start
        return delta.total_seconds() / 3600 // 24 # calculando a quantidade de dias da locação

class Invoice(models.Model):
    rental = models.ForeignKey(Rental, on_delete=models.PROTECT)
    # agora não sei como acessar o valor da diária do veículo e a quantidade de diárias da locação

Answer: Para ter acesso aos atributos das classes Vehicle e Rental na classe Invoice, você pode usar o relacionamento de chave estrangeira que você criou entre as classes.
Por exemplo, se você quer acessar o atributo price_per_day do veículo, basta fazer:
vehicle_price_per_day = self.rental.vehicle.price_per_day

E para acessar o atributo time_diff da classe Rental, basta fazer:
rental_time_diff = self.rental.time_diff

Você também pode usar o método related_name na definição da chave estrangeira para dar um nome mais amigável ao atributo que você usará para acessar o objeto relacionado. Por exemplo:
class Rental(models.Model):
    vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT, related_name='vehicle')
    start = models.DateTimeField()
    end = models.DateTimeField()

    @property
    def time_diff(self):
        delta = self.end - self.start
        return delta.total_seconds() / 3600 // 24 # calculando a quantidade de dias da locação

class Invoice(models.Model):
    rental = models.ForeignKey(Rental, on_delete=models.PROTECT, related_name='rental')
    vehicle_price_per_day = self.rental.vehicle.price_per_day
    rental_time_diff = self.rental.time_diff

Assim, você pode acessar os atributos de Vehicle e Rental de forma mais clara e direta.
Comment: Eu consegui fazendo da seguinte forma:
vehicle_price_per_day = rental.vehicle.price_per_day
rental_time_diff = rental.time_diff


How can i block a picturebox from moving further when it collides with another object?

Question: I have made something like a game in C# where the character is a picture box and it is being moved using the arrow keys. I want him to stop when he meets a solid object (I use invisible square panels to define the banned areas) but the code I use makes him move in opposite directions when he is in touch with the panel and I press a different key.
 if (e.KeyCode == Keys.Right)
        {
            j_figure = 2;
            x += velocity;

            if ((playerBox.Bounds.IntersectsWith(panel1.Bounds) || playerBox.Bounds.IntersectsWith(panel2.Bounds)))
            x -= velocity - 10;
            playerBox.Location = new Point(x, y);
        }
        else if (e.KeyCode == Keys.Left)
        {
            j_figure = 1;
            x -= velocity;

            if ((playerBox.Bounds.IntersectsWith(panel1.Bounds) || playerBox.Bounds.IntersectsWith(panel2.Bounds)))
                x += velocity + 10;
            playerBox.Location = new Point(x, y);
        }
        else if (e.KeyCode == Keys.Up)
        {
            j_figure = 3;
            y -= velocity;

            if ((playerBox.Bounds.IntersectsWith(panel1.Bounds) || playerBox.Bounds.IntersectsWith(panel2.Bounds)))
                y += velocity + 10;
            playerBox.Location = new Point(x, y);
        }
        else if (e.KeyCode == Keys.Down)
        {
            j_figure = 0;
            y += velocity;

            if ((playerBox.Bounds.IntersectsWith(panel1.Bounds) || playerBox.Bounds.IntersectsWith(panel2.Bounds)))
                y -= velocity - 10;
            playerBox.Location = new Point(x, y);
        }

Comment: sounds like you need to understand the code that you have written and learn to use the debugger.. it the results effects are not what you expect perhaps you need to change something in the direction that your objects are moving sounds like an `XY` issue to me
Answer: I finally did it. The problem was solved by adding
playerBox.Location = new Point(x, y);
inside every movement key action. More specifically:
    if (e.KeyCode == Keys.Right)
        {
            j_figure = 2;

            x += velocity;
            playerBox.Location = new Point(x, y);

            if (playerBox.Bounds.IntersectsWith(panel1.Bounds))
            {
                x = panel1.Left - playerBox.Width;
            }
            else if (playerBox.Bounds.IntersectsWith(panel2.Bounds))
            {
                x = panel2.Left - playerBox.Width;
            }
         }
...

// code for other directions
...
// again but this time outside the KeyCode if statements
playerBox.Location = new Point(x, y);
}

Answer: In order to make stop the object exactly at banned areas, you must set its location according to the areas bounds and its own size. For the left and right keys this would be:
if (e.KeyCode == Keys.Right) {
    j_figure = 2;
    x += velocity;
    if (playerBox.Bounds.IntersectsWith(panel1.Bounds)) {
        x = panel1.Left - playerBox.Width - 1;
    } else if (playerBox.Bounds.IntersectsWith(panel2.Bounds)) {
        x = panel2.Left - playerBox.Width - 1;
    }
} else if (e.KeyCode == Keys.Left) {
    j_figure = 1;
    x -= velocity;
    if (playerBox.Bounds.IntersectsWith(panel1.Bounds)) {
        x = panel1.Right + 1;
    } else if (playerBox.Bounds.IntersectsWith(panel2.Bounds)) {
        x = panel2.Right + 1;
    }
} ...
playerBox.Location = new Point(x, y);

This logic has to be applied to the vertical directions accordingly.
Make the invisible areas visible for testing.
Comment: It works but not completely. When it happens for the character for example: to stop exactly on the object when he moves left and then I press let's say the key to move up, he reappears in the bottom of the object. The opposite happens when he stops exactly on the right side of the panel and I press the down key, he reappears on top of the panel.
Comment: There might be a overlap of one pixel, so add one pixel when on the right side and subtract one when on the left side.


Gauss-Legendre weights convertion from [-1,1] to [a,b]

Question: Ok so we know for integration with the Gauss-Legendre method :
$\int_1^1f(x)dx = \sum_{i=0}^nc_i^nf(x_i)$
that both $x_i,c_i$ are fixed,depending on $n$ , when we work at the [-1,1] space. I know that for converting $x_i$ from [-1,1]->[a,b] I have to do the following:
$y_i=\frac{(b+a)}{2}+ \frac{(b-a)}{2}x_i$
But what about the weights for the G-L. How do I convert the $c_i$ weights from [-1,1] to [a,b]???
Answer: Given a function $g \colon [a, b] \to \mathbb{R},$ define the transformed function:
$$
f \colon [-1, 1] \to \mathbb{R}, \ x \mapsto g\left(\frac{b+a}2 + \frac{b-a}2x\right).
$$
The standard formula you have quoted, when applied to $f,$ gives:
\begin{align*}
\int_a^b g(y)\,dy & = \frac{b-a}2\int_{-1}^1f(x)\,dx \\
& \bumpeq \frac{b-a}2\sum_{i=0}^nc_i^nf(x_i) \\
& = \frac{b-a}2\sum_{i=0}^nc_i^ng(y_i),
\end{align*}
so the effect is that the weights $c_i^n$ are multiplied by $\frac{b-a}2.$
Comment: Mercifully, Wikipedia agrees: [Gaussian quadrature - Wikipedia](https://en.wikipedia.org/wiki/Gaussian_quadrature#Change_of_interval) ("Change of interval").


can't access to Youtube using the API using Php

Question: so i'm making a site where to upload video.
I tried to implement the access to Youtube and to upload videos on YT from the site and is half working the videos get uploaded on phpmyadmin the table create the row but after that i just get an blank page instead of the authentification page of google for the access to YT.
Here is the code:
<?php

 require_once "Database_connection.php";
 require_once "Database_config.php";
 require_once "Database_class.php";
 require_once "Session.php";

 db = new DB;

 if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {

$title = $_POST['Title'];
$description = $_POST['Description'];
$corso = trim($_POST['SceltaCorso']);
$tags = $_POST['tags'];
$privacy = !empty($_POST['privacy'])?$_POST['privacy']:'public';
/* al momento la variabile è disattivata perchè tutti i video verranno caricati su youtube però alcuni visibili altri privati
$youtube = trim($_POST['SceltaYoutube']);
*/
/*limite modificato dalla configurazione vai su XAMPP riga APACHE tasto CONFIG e poi modifica
  post_max_size = 40M; upload_max_filesize = 40M; (valori originali per ora sostituiti con 5G)*/
$maxsize = 42949672960;  //al momento la dimensione massima e di 5GB

//if di controllo che sia stato inserito un file image con peso sotto i 5GB e gli si da le coordinate fino alla cartella di destinazione
if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {

    $name_img = $_FILES['image']['name'];
    $target_dir_img = "../img/Thumbnail_Video/";
    $target_file_img = $target_dir_img.$name_img;

    if ($_FILES['image']['size'] >= $maxsize) {
        echo "Il file è troppo grande";
    }else{

        move_uploaded_file($_FILES['image']['tmp_name'], $target_file_img);
    }

}elseif (isset($_FILES['image']['name']) == "false" ) {
    $target_file_img = "../img/Thumbnail_Video/logo_STM.png";
 }
/*12/08/21 Provare a creare una tabella del database che raccolga dati solo temporaneamente per creare una anteprima del file da caricare (ES. tabella Video_Temp) */
//12/08/2021 Aggiungere la data di inserimento del file
if($_FILES["file"]["name"] != ''){
    // File upload path
    $fileName = basename($_FILES["file"]["name"]);
    $filePath = "../Video/".$fileName;

    // Check the file type
    $allowedTypeArr = array("video/mp4", "video/avi", "video/mpeg", "video/mpg", "video/mov", "video/wmv", "video/rm");
    if(in_array($_FILES['file']['type'], $allowedTypeArr)){
        // Upload file to local server
        if(move_uploaded_file($_FILES['file']['tmp_name'], $filePath)){
            // Insert video data in the database
            $vdata = array(
                'Title' => $title,
                'Description' => $description,
                'Tags' => $tags,
                'Privacy' => $privacy,
                'File_name' => $fileName
            );
            $insert = $db->insert($vdata);

            // Store db row id in the session
            $_SESSION['uploadedFileId'] = $insert;
        }else{
            header("Location:".BASE_URL."Video.php?err=ue");
            exit;
        }
    }else{
        header("Location:".BASE_URL."Video.php?err=fe");
        exit;
    }
}else{
    header('Location:'.BASE_URL.'Video.php?err=bf');
    exit;
}
}

 // Get uploaded video data from database
 $videoData = $db->getRow($_SESSION['uploadedFileId']);

 // Check if an auth token exists for the required scopes
  $tokenSessionKey = 'token-' . $client->prepareScopes();
   if (isset($_GET['code'])) {
 if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}

 $client->authenticate($_GET['code']);
 $_SESSION[$tokenSessionKey] = $client->getAccessToken();
 header('Location: ' . REDIRECT_URL);
   }

 if (isset($_SESSION[$tokenSessionKey])) {
 $client->setAccessToken($_SESSION[$tokenSessionKey]);
}

  // Check to ensure that the access token was successfully acquired.
 if ($client->getAccessToken()) {

   try{
// REPLACE this value with the path to the file you are uploading.
$videoPath = 'videos/'.$videoData['File_name'];

if(!empty($videoData['Youtube_video_id'])){
    // Uploaded video data
    $videoTitle = $videoData['Title'];
    $videoDesc = $videoData['Description'];
    $videoTags = $videoData['Tags'];
    $videoId = $videoData['Youtube_video_id'];
}else{
    // Create a snippet with title, description, tags and category ID
    // Create an asset resource and set its snippet metadata and type.
    // This example sets the video's title, description, keyword tags, and
    // video category.
    $snippet = new Google_Service_YouTube_VideoSnippet();
    $snippet->setTitle($videoData['Title']);
    $snippet->setDescription($videoData['Description']);
    $snippet->setTags(explode(",", $videoData['Tags']));

    // Numeric video category. See
    // https://developers.google.com/youtube/v3/docs/videoCategories/list
    $snippet->setCategoryId("22");

    // Set the video's status to "public". Valid statuses are "public",
    // "private" and "unlisted".
    $status = new Google_Service_YouTube_VideoStatus();
    $status->privacyStatus = $videoData['Privacy'];

    // Associate the snippet and status objects with a new video resource.
    $video = new Google_Service_YouTube_Video();
    $video->setSnippet($snippet);
    $video->setStatus($status);

    // Specify the size of each chunk of data, in bytes. Set a higher value for
    // reliable connection as fewer chunks lead to faster uploads. Set a lower
    // value for better recovery on less reliable connections.
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Setting the defer flag to true tells the client to return a request which can be called
    // with ->execute(); instead of making the API call immediately.
    $client->setDefer(true);

    // Create a request for the API's videos.insert method to create and upload the video.
    $insertRequest = $youtube->videos->insert("status,snippet", $video);

    // Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(
        $client,
        $insertRequest,
        'video/*',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($videoPath));

    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($videoPath, "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);
    }
    fclose($handle);

    // If you want to make other calls after the file upload, set setDefer back to false
    $client->setDefer(false);

    // Update youtube video id to database
    $db->update($videoData['Video_id'], $status['Video_id']);

    // Delete video file from local server
    @unlink("../Video/".$videoData['File_name']);

    // uploaded video data
    $videoTitle = $status['snippet']['Title'];
    $videoDesc = $status['snippet']['Description'];
    $videoTags = implode(",",$status['snippet']['Tags']);
    $videoId = $status['Video_id'];
}

// uploaded video embed html

$youtubeURL = 'https://youtu.be/'.$videoId;
$htmlBody .= "
Video Uploaded to YouTube
";
$htmlBody .= '<embed width="400" height="315"
 src="https://www.youtube.com/embed/'.$videoId.'"></embed>';
$htmlBody .= '

YouTube URL: '.$youtubeURL.'
';
$htmlBody .= '
Title: '.$videoTitle.'
';
$htmlBody .= '
Description: '.$videoDesc.'
';
$htmlBody .= '
Tags: '.$videoTags.'

';
$htmlBody .= 'Logout';

  } catch (Google_Service_Exception $e) {
   $htmlBody .= sprintf('
A service error occurred: %s
',
    htmlspecialchars($e->getMessage()));
 } catch (Google_Exception $e) {
   $htmlBody .= sprintf('
An client error occurred: %s
',
    htmlspecialchars($e->getMessage()));
  $htmlBody .= 'Please reset session Logout';
 }

  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
 } elseif (OAUTH_CLIENT_ID == '') {
  $htmlBody = <<<END

Client Credentials Required

   You need to set \$oauthClientID and
   \$oauthClientSecret before proceeding.

    END;
  } else {
    // If the user hasn't authorized the app, initiate the OAuth flow
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END

Authorization Required

You need to authorize access before proceeding.

  END;
  }
   ?>

i Think the problem is after this row:$insert = $db->insert($vdata); but i can't find it. Advice and suggestions are welcome, thanks.
Answer: I think there is a lot going on in your code and you should split it up in order to be able to debug your issue better.
This is the code i use for authorization.  Have a look at it.
oauth2callback.php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';

// Start a session to persist credentials.
session_start();

// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

?>

require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    $client = getOauth2Client();

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
return $client;
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function buildClient(){

    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());
    return $client;
}

/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri(){

    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}

Oauth2Authentication.php
    /**
     * Authenticating to Google using Oauth2
     * Documentation:  https://developers.google.com/identity/protocols/OAuth2
     * Returns a Google client with refresh token and access tokens set.
     *  If not authencated then we will redirect to request authencation.
     * @return A google client object.
     */
    function getOauth2Client() {
        try {

            $client = buildClient();

            // Set the refresh token on the client.
            if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
                $client->refreshToken($_SESSION['refresh_token']);
            }

            // If the user has already authorized this app then get an access token
            // else redirect to ask the user to authorize access to Google Analytics.
            if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

                // Set the access token on the client.
                $client->setAccessToken($_SESSION['access_token']);

                // Refresh the access token if it's expired.
                if ($client->isAccessTokenExpired()) {
                    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                    $client->setAccessToken($client->getAccessToken());
                    $_SESSION['access_token'] = $client->getAccessToken();
                }
                return $client;
            } else {
                // We do not have access request access.
                header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
            }
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
    ?>

Note: Your videos will all be private until your application has been thought the verification process.  So setting it public is over kill at this point.


Description field for file field

Question: I have a file field in a content type. I have enabled the description field for this field. How can I print this description field in twig???
I have a situation here I need to print description field only for one content in views page instead of all the contents on the same page.
For example:
First content has Download
Second content has Download
Third content has field description
Can I put some condition in twig or views field?
Comment: If you enable description field then the file(sample.txt) will be renamed with the description. My question is why do you need it to render in twig or view?
Comment: We are doing things via custom HTML in Twig, we need things to be done as per the client's requirements. He needs Download to be displayed on Anchor tags of PDF files but needs fields description for one PDF
Answer: To use the description field directly in twig I found an easier way. Simply add the file field in Views, then rewrite the results and add the token for description and file. Now you can use the field directly into twig file.
Otherwise You might have to do good use of Kint or DSM to find out where does description field come up.

Description field for file field


retornar variável de função python django

Question: Tenho uma função que retorna vários valores, e queria passar dois deles pra fora da função, mas quando tento ele retorna que a variável fora da função não foi declarada.
Para exemplificar no código abaixo, gostaria que as listas teste3 e teste4 da função gerar_gráfico, fossem usadas na função index fora da função gerar_graficos, lembrando que é uma views do django.
Código da função:
class StorageData:
    list_shared = [] #lista compartilhada
    def __init__(self, *dados):
         self.list_shared.extend(dados) #inclui dados na lista

    def extend(self, *args):
         self.list_shared.extend(args)

    def reset(self):
        self.list_shared = [] #reseta lista caso queira zerar ela

def gerar_graficos(request):
    descricao = '01/02/2019 08:00'
    descricao2 = '01/02/2019 09:00'

    if request.method=='POST':
        descricao = request.POST['descricao']
        descricao2 = request.POST['descricao2']
    conn = cx_Oracle.connect('banco')
    cur = conn.cursor()

    cur.execute(consulta do banco)
    teste = []
    teste2 = []
    teste3 = []
    teste4 = []

    d = 0
    for line in cur:
        teste.extend(line)
    for indice, c in enumerate(teste):
        #if c + 0 == c:
            teste3.extend([c - 10000])
        #else:
            d = 0

    cur.execute(consulta do banco)
    for coluna in cur:
        teste2.extend(coluna)
    for indice2, c in enumerate(teste2):
        if indice2 >= d:
            teste4.extend([c])

    transfer = StorageData()
    transfer.reset()
    transfer.extend(teste3,teste4)

    width_n = 0.001
    bar_color = 'yellow'

    cur.close()
    conn.close()

    context = { 'descricao': descricao, 'descricao2': descricao2 }
    return render(request, 'core/graficos_list.html', context)

Código fora da função:
def index(request):
   trans = StorageData()
   my_list = trans.list_shared[0]
   my_list2 = trans.list_shared[1]
   fig = Figure()
   ax = fig.add_subplot(1,1,1)
   ax.plot(my_list, my_list2)
   #ax.bar(x_axis, y_axis, width=width_n, color=bar_color, align='center')
   ax.grid()
   buf = io.BytesIO()
   canvas = FigureCanvas(fig)
   canvas.print_png(buf)
   response=HttpResponse(buf.getvalue(), content_type='image/png')
   return (response)

Answer: Não é possível acessar desta forma pois descricao e descricao2 são variáveis validas apenas para o escopo da função gerar_graficos().
Uma solução seria chamar essas funções calcular_medida() e calcular_data() dentro da gerar_graficos() isso se o x_axis e o y_axis forem utilizados no template.
def gerar_graficos(request):
    descricao = '01/02/2019 08:00'
    descricao2 = '01/02/2019 09:00'

    if request.method=='POST':
        descricao = request.POST['descricao']
        descricao2 = request.POST['descricao2']

    y_axis = calcular_medida(descricao,descricao2)
    x_axis = calcular_data(descricao, descricao2)
    context = { 'descricao': descricao, 'descricao2': descricao2, 'x_axis' : x_axis, 'y_axis': y_axis }
    return render(request, 'core/graficos_list.html', context)

Outro método seria chamar uma função em gerar_gráficos() que execute o que quer fazer.
def gerar_graficos(request):
    descricao = '01/02/2019 08:00'
    descricao2 = '01/02/2019 09:00'

    if request.method=='POST':
        descricao = request.POST['descricao']
        descricao2 = request.POST['descricao2']

    calculaXY(descricao,descricao2)
    context = { 'descricao': descricao, 'descricao2': descricao2 }
    return render(request, 'core/graficos_list.html', context)

def calculaXY(descricao,descricao2):
    y_axis =  []
    x_axis = []
    y_axis = calcular_medida(gerar_graficos.descricao,gerar_graficos.descricao2)
    x_axis = calcular_data(gerar_graficos.descricao, gerar_graficos.descricao2)

Recomendo dar uma lida sobre Class Based Views que pode facilitar toda essa questão de atributos e funções.
Comment: as duas soluções dão certo para a minha pergunta, então vou aceitar sua resposta, mas oq eu preciso não ta na pergunta, ai infelizmente não da certo, obrigado pela ajuda, e caso consiga ajudar mais, eu preciso fazer com que duas listas sejam lidas por duas views diferentes
Comment: @Guilherme Use a View sendo uma [classe](https://docs.djangoproject.com/en/2.1/topics/class-based-views/), você pode ter um atributo de classe que seriam as duas listas, e pode usá-las de maneira independente nas duas funções.
Comment: Ai posso ter duas funções na classe que geram dois templates diferentes?
Comment: @Guilherme assim você consegue que as duas listas sejam atributos da classe e compartilhadas entre as duas funções, mas se o gráfico ter alguma relação com os dados o que você pode fazer é usar um front-end para gerar os graficos, colocando essas funções que calculam a medida no javascript do template, assim fica mais fácil dependendo da aplicação.
Comment: o gráfico é gerado a partir dos dados das listas, mas vou tentar fazer uma classe com as duas funções, sendo lidas cada uma por uma template, se nao der certo, vou pra sua dica do front end, valeu irmão
Answer: @Guilherme,
Cara pelo que li nos comentários, você precisa fazer com que duas views diferentes acessem os mesmos dados.
Você pode tentar armazenar elas na session, como:
 request.session['descricoes'] = [descrição, descricao2]

Porém esta forma não tenho certeza 100% que vai funcionar, mais não custa tentar.
Agora você pode criar uma classe para fazer essa operação de armazenar dados compartilhados.
class StorageData:
    list_shared = [] #lista compartilhada
    def __init__(self, *dados):
         self.list_shared.extend(dados) #inclui dados na lista

    def reset(self):
        self.list_shared = [] #reseta lista caso queira zerar ela

Pronto agora para usar ela, basta instanciar a class é passar suas listas para dentro do construtor dela
StorageData (descrição, descricao2)

E quando você quiser usar esses dados em outra view basta instanciar a classe novamente sem parâmetros e acessar a propriedade list_shared.
#outra view para acessar os dados da descricao e descricao2
def sua_view(request):
    storage = StorageData()
    my_list = storage.list_shared # Aqui a propriedade irá retornar os mesmos dados que foi executado por outra instância passando os dados pelo construtor.

Tente fazer essas maneiras e se não funcionar poste aí pra ver se tem outras formas também.
Usando:
Aqui são duas views distintas que vão utilizar a classe
def transfer(request):

    transfer = Storage()
    transfer.reset() # Coloquei apenas para resetar a lista para cadastrar novamente os mesmos dados, para não ficar adicionando um monte de vez a cada requisição

    descricao = ["Esta lista é a decricao"]
    descricao2 = ["Esta lista é a decricao2"]
    transfer.extend(descricao,descricao2) # Aqui adiciona os dados na classe

    return render(request,'core/transfer.html',context{'descricao':descricao,'descricao2':descricao2})

def Transfer_get(request):
    trans = Storage()
    descricao = trans.list_shared[0]  # Aqui recupera os valores adicionados na classe
    descricao2 = trans.list_shared[1]

    return render(request, 'core/transfer2.html', context={'descricao':descricao,'descricao2':descricao2})

No template apenas mostrei os dados
{{ descricao }}
{{ descricao2 }}

Caso você prefira pode passar a lista completa para os templates e la fazer a interação na lista e exibir os dados dela.
def Transfer_get(request):
    trans = Storage()
    lista = trans.list_shared  # Aqui recupera os valores adicionados na classe

    return render(request, 'core/transfer2.html', context={'lista':lista})

E no template interar essa lista.
Tambem criei as rotas para essas views. Fiz uma mudança simples na classe adicionando o método extend().
class Storage:

    list_shared = []

    def __init__(self, *args):
        self.list_shared.extend(args)

    def extend(self, *args):
        self.list_shared.extend(args)

    def reset(self):
        self.list_shared.clear()

Bom testei aqui é os valores passam normalmente para as duas views, e se eu adicionar mais algum valor na list_shared quando for consultar a lista os novos valores aparecem também sem problema.
Caso você tenha feito certinho e ver que não tem erro nenhum e mesmo assim não funciona, poste o código aqui do jeito que ficou para ver se podemos fazer alguma mudança ou algo do tipo.
Comment: editei o código da pergunta e fiz as alterações que voce me passou, não apresenta mais nenhum erro, mas gera um grafico sem dados nenhum, nao sei o pq, se puder ajudar, mas sua solução ta me dando uma luz no fim do túnel
Comment: editei a resposta da uma olhada la e vê se o sua implementação ficou parecida com essa.
Comment: implementação ta identica, mas agora ele apresenta o seguinte erro: "list index out of range" e esse erro:  "my_list = trans.list_shared[0] "
Comment: Posta ai o seu código das views onde você esta criando a lista e acessando ela, e também a classe transfer. Porque vai fica difícil desobrir onde esta o erro. Este erro gerado é porque você esta tentando acessar um indíce de uma lista que não existe.
Comment: editei a pergunta ai com o código atualizado
Comment: fiz varios testes, inclusive com duas listas que criei com valores de 0 a 5, e sempre da o mesmo erro
Comment: Bom cara me parece estar tudo certo e não era para aparecer esse erro de acesso a lista na posição 0. Tente depurar o código para ver o que esta sendo passado para a list_shared, assim você consegue ver melhor os possíveis erros.
Comment: agora só segunda, codigo ficou no pc da empresa, vou tentar e te retorno
Comment: Beleza segunda agente tenta achar esse erro. Falou bom FDS
Comment: Valeu irmao, então nada no debug retorna sem erros
Comment: Na sua view, quando vc debuga a list_shared fica preenchida? Porque se a list_shared não estiver sendo preenchida na view vai dá erro de acesso mesmo, tenta ver se o que você está passando pra list_shared está do jeito que você imagina mesmo. Pq agora fica mais difícil ajudar descobrir o erro. O mais provável está na hora de vc preencher a lista na view. Dá uma olhada e faça um debug detalhado e estiver conforme o esperado.
Comment: Retorna a list_shared como vazia, preciso ver o pq
Comment: tem alguma luz ai?
Comment: Eae Guilherme, então cara, fica difícil saber o porquê não está preenchendo sua lista, provavelmente alguma coisa na logíca da sua viu. E fica difícil saber sem debugar o código. O que poso tentar é pegar sei código e fazer um teste aqui, mais preciso de um modelo de resultados que a sua consulta retorna, e qual o resultado final esperado para mandar para as outras views.


#ajax form_set_error

Question: I'm using the below code to query a webform field's value against database, and if the value exists, I want to use form_set_error, however I can't, since it requires rewriting the page. I have found this post but it doesn't have an answer, hence my question.
function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['submitted']['kullanici_adi']['#ajax'] = array(
        'event' => 'blur',
        'callback' => '_tubitekuz_check_username',
      );
      break;
    case 'contact_site_form':
      $form['#submit'] = array('_tubitekuz_show_message');
      break;
    default:
      break;
  }
}

function _tubitekuz_check_username($form, &$form_state) {
  $username= $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    $commands = array();
    $commands[] = drupal_set_message('Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
    return array('#type' => 'ajax', '#commands' => $commands);
  }
}

How do I go about that?
PS: drupal_set_message does its thing only when I refresh the page, whereas form_set_error doesn't do at all.
EDIT: I tried to replace the above with the below code:
function _tubitekuz_check_username($form, &$form_state) {
  $username= $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    drupal_add_js(drupal_get_path('module', 'tubitekuz') . '/js/tubitekuz.js');
    drupal_add_css(drupal_get_path('module', 'tubitekuz') . '/css/tubitekuz.css');
  }
}

and in tubitekuz.js I am doing
$(document).ready(function() {
    var username=jQuery('#edit-submitted-kullanici-adi');
    username.addClass('err');
    setTimeout(function() {
      username.removeClass('err');
      }, 3000);
});

and in tubitekuz.css I have the below:
.err {
  border-color:red;
  border-width:2px;
}

however, CSS rules are not applied even though class is added. What is the cause of this? All I'm trying to do is use form_set_error with #ajax
Comment: what you're doing is calling some function while using ajax. And not rebuilding the form/wrapper. You need to use a wrapper in your ajax array or rebuild the form so drupal can display the error messages.
Comment: it would be something like this: $form['submitted']['kullanici_adi']['#ajax'] = array(
        'callback' => '_tubitekuz_check_username',
        'wrapper' => 'form_id'
      );
$commands[] = ajax_command_replace('#form_id', drupal_render($form));
Comment: Why do you want to use ajax in this case? validate seems adapted
Comment: Because ajax seems the only option for real-time check
Comment: validate actually can do it and without submiting the form. Or maybe you want to check something/data from the form you just sent?
Comment: I had no idea validate can do a real-time check (as in check as soon as the user blurs the field)
Comment: Actually validate will be faster, because you don't need to use ajax. See my answers with the code, it should do the trick.
Comment: Doesn't validation work only when I submit the form?
Comment: I may not have understood what you wanted to do, when exactly do you want to do that ajax call?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/25108/discussion-between-kartagis-and-namari).
Answer: Your code needs to be adjusted to something like:
function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['submitted']['kullanici_adi'] += array(
        '#prefix' => '
',
        '#ajax' => array(
          'callback' => 'kullanici_adi_form_login',
          'wrapper' => 'kullanici-adi-container',
        ),
        '#suffix' => '
',
      );

      // Check the form state to see if an e-mail address has been specified.
      if (!empty($form_state['values']['kullanici_adi'])) {
        $mail = trim($form_state['values']['kullanici_adi']);

        if ($account = user_load_by_mail($mail)) {
          form_set_error('submitted][kullanici_adi', 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
        }
      }
      break;
  }
}

function kullanici_adi_form_login($form, $form_state) {
  return $form['submitted']['kullanici_adi'];
}

You will probably have to play around with some of the arrays, etc. to get the correct values, etc.
Comment: I appreciate all this, but this doesn't seem to resolve my main issue of returning a `form_set_error`
Comment: It should, to use an Ajax callback your callback function should return part of the form. Then in your regular form_alter function you need to check for the presence of the data in `$form_state['values']`
Comment: I've edited my answer so it's roughly the complete code required. The part which will need checking/editing are `$form_state['values']` & `$form['submitted']`
Answer: it would be something like this:
$form['submitted']['kullanici_adi']['#ajax'] = array(
        'callback' => '_tubitekuz_check_username',
        'wrapper' => 'the_form_id'
      );

and this one in your ajax callback _tubitekuz_check_username, you can put your form_set_error before. be carefull you might need
form_set_error('kullanici_adi', t('your error'));

or this one if the first doesn't work (I don't remember for this case)
form_set_error('submitted']['kullanici_adi', t('your error'));

then this code to rebuild a part/entire of the form
$commands[] = ajax_command_replace('#the_form_id', drupal_render($form));

This should do it.
That's pretty much what I told you 2 days ago.
EDIT:
function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      global $user;
      if ($user->uid > 0) {
        $form['submitted']['kullanici_adi']['#access'] = FALSE;
      }
      $form['#validate'][] = 'webform_client_form_97_form_validate';
      break;
    case 'contact_site_form':
      $form['#submit'] = array('_tubitekuz_show_message');
      break;
    default:
      break;
  }
}
function webform_client_form_97_form_validate($form, &$form_state){
  $username = $form_state['values']['submitted']['kullanici_adi'];
  $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  if ($exists) {
    form_set_error('submitted][kullanici_adi', 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
  }
}

Comment: I can't believe I still can't do it. I did add a wrapper, and I did both the former form and latter form of form_set_error (I put it before `$commands = array();`) and it still fires only when I refresh the page manually :S The code is at http://paste.fedoraproject.org/232924/45254221/ so you can see.
Comment: wrong wrapper, to get the good wrapper go to the html of your form and take the id of your form, it should be somehting like this: webform-client-form-97 (css id and class don't have underscore)
Comment: I can still have it displayed only when I manually refresh the page. Please see http://ur1.ca/mv1oc. There also is no change regardless of whether I place `form_set_error` before or after lines 26-27 :S
Comment: You can't actually do a form_set_error when it has been submited, you need to do it in the validation function.
Comment: You mean callback, right? Hi
Comment: I've edited my original answer, try it and let me know
Comment: I've just checked, I am doing it in callback.
Comment: No I mean you can't do it after a submit, you have to do it while the form is being validated
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/24958/discussion-between-namari-and-kartagis).
Answer: You can try this one:
//playground.module

function playground_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_1':
      global $user;
      if ($user->uid < 0) {
        $form['submitted']['username']['#access'] = FALSE;
      }
      $form['submitted']['username']['#ajax'] = array(
        'wrapper' => 'webform-client-form',
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'blur',
        'callback' => '_playground_check_username',
      );
      break;
  }
}

function _playground_check_username($form, &$form_state) {
  $exists = FALSE;
  $commands = array();
  $username= $form_state['values']['submitted']['username'];

  $parents = $form_state['triggering_element']['#array_parents'];
  array_pop($parents);
  $element = &drupal_array_get_nested_value($form, $parents);

  if (!empty($username)) {
    $exists = db_query('SELECT name FROM {users} WHERE name = :entered', array(':entered' => $username))->fetchField();
  }

  if ($exists) {
  form_error($element, 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
  $error_selector = '.form-item.webform-component--username';
  $commands[] = ajax_command_replace($error_selector, theme('status_messages'). drupal_render($element) );
  // Use below commands if you want to display in message region.
  // $commands[] = ajax_command_replace($error_selector, drupal_render($element) );
  // $commands[] = ajax_command_remove('#messages');
  // $commands[] = ajax_command_before('#main-wrapper', '

' . theme('status_messages') . '

');

  return array('#type' => 'ajax', '#commands' => $commands);
  }
}

Comment: @vijayc85 while I appreciate this (it actually works), it does the check only the first time. Could it be a jquery version difference? Does #ajax call use jquery anyway?
Comment: I'm running it in standard Drupal 7 installation and it's working all the time. Might be something to do with form cache setup?
Comment: Maybe I need to clear caches afterwards?
Comment: not sure. can you try to check with minimum change and see if it works (i.e. if the form is attached to another page, try to load the form directly and see if it works?)
Comment: I did, it's not doing it there either. I'll try lowering the jquery version tomorrow (to check if there is a conflict) and ping you on IRC.
Comment: @vijayc85, as I told you on IRC, it's definitely a javascript file issue because in the console I'm getting `Unexpected end of input` and the problem goes away when I change the theme to the default, so it's theme stuff. I'll ask our designer to look into this.

#ajax form_set_error


Run/execute concatenated variable as command

Question: word2018 FILE_2018 > FILE_2018.out &
this works OK for me in bin/bash, terminal, konsole, BASH
I have an text-file script in #!/bin/bash, where I run this variable CMD and it works in CSH, but not in BASH.
CMD="word${year} ${FILE_version.txt} > ${FILE_version.out} &"

word2018 - system alias defined/sourced from other location
word - static name
2018 - variable (can be any number 2015, 2022,....)
FILE_version - variable (can be - FILE_2015, FILE_2022,...)

csh -c "$CMD" ...works OK
bash -c "$CMD" ...NOT working, command word2018 not found

any advice, help? I would appreciate very well
Comment: Trying to store commands in variables tends not to work very well (see [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) and many previous questions here). Variables are really for storing data, not executable code. As for the example code in this question, it has so many problems it's hard to tell what're the real problems and what's just sloppy summarization.
Comment: `alias_name = test` tries to run `alias_name` with `=` and `test` etc. as arguments, probably not what you want.
Answer: Just call $CMD
testABC(){
   echo "arg: $1"
}
alias_name=test
#....system alias
var1=ABC
var2=123

CMD="${alias_name}${var1} ${var2}"
echo CMD: $CMD

$CMD

result:
CMD: testABC 123
arg: 123

Comment: it doesnt work........
Comment: Works fine on Mint 20.3


In views, add class depending on the user input in a checkbox.

Question: I need to add a class to a field of views depending if the user wants to have an overlay on the image or no. We need to use a checkbox for the user to input if it needs the class or no.
Answer:
Create your boolean field (my case the name is field_no_overlay),  The checkbox should have the values for the classes you want to use and apply to your field.

In the views, rewrite your value .
Create the style for each class.


for-loop interruption slows down OpenCL kernel

Question: Learning OpenCL implementing program which finds 8 most similar pixels within 10 pixels radius for every pixel:
//-DBEST=8

__kernel void best_pixel_matches(
    __global const uint * image,
    const ushort width,
    const ushort height,
    // [ width ] [ height ] [ BEST ] [ 2 ]
    __global short * best,
    __global int * errors
)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    const uint pixel = image[ y * width + x ];

    const short SURROUND = 10;

    //local best pixels coordinates:
    short s[ BEST ][ 2 ];
    //... corresponding local best pixels computed deltas (storage instead of recompute speeds program about twice):
    uint d[ BEST ];
    //... init with none:
    for ( short i = 0; i < BEST; ++ i ) d[ i ] = -1;

    for ( short sw = - SURROUND; sw < SURROUND; ++ sw ) {
    for ( short sh = - SURROUND; sh < SURROUND; ++ sh ) {
        //avoid inexistent pixels:
        const short tw = x + sw; if ( tw < 0 || tw >= width  ) continue;
        const short th = y + sh; if ( th < 0 || th >= height ) continue;
        //not with itself:
        if ( tw == x && th == y ) continue;
        const uint diff = (uint) abs( (long)pixel - (long)image[ th * width + tw ] );

        for ( short si = 0; si < BEST; ++ si ) {
            if ( d[si] == -1 || diff < d[si] ) {
                d[si] = diff;
                s[si][0] = tw;
                s[si][1] = th;
                break;//<-- this line causes 4 (!) times slow down
            }
        }
    } }

    //copy results from private memory to global:
    const long p = ( x * height + y ) * BEST;
    for ( short b = 0; b < BEST; ++ b ) {
        const long pb = ( p + b ) * 2;
        best[ pb     ] = s[b][0];
        best[ pb + 1 ] = s[b][1];
    }
}

The problem was that it took GPU 3593ms for 2560*1440 image which is almost exactly the same time as plain C++ CPU code I had before (~8500ms). Then I tried to tune it here and there and occasionally removed break; line and execution time -> 900ms!
What's the reason behind such surprising speed up? That break; line just tells program it's not needed to check any other pixels further so supposed to decrease execution time - not slow it down? Maybe there are some other ways to speed up this program too? :)
Answer: You don't say what kind of device are you running this on, but:

On the CPU, optimisation includes autovectorising, which typically is very sensitive to branches. So a factor of 4 isn't surprising there; your loop iteration counts are known at build time, so they can be completely unrolled and vectorised if there's no early-out. With the early-out, the code likely needs to be serialised, so you lose the 4x, 8x, or 16x speedup from vectorisation (depending on CPU type) and only make some of that back from the early-out.
GPU work-items typically run in lock-step threads, but a factor 4 change seems unlikely if that's happening here; it's typically more the case that the break; won't yield any improvement unless there's a high chance of an entire wavefront taking the shortcut. Some GPU models however prefer SIMD code, so you could be running into a similar situation as described for the CPU.

Note that removing the break will presumably fill all BEST items in d & s with the same value (if I'm reading your code correctly) so it won't produce the same output as with the break;.
Comment: Thank you for your answer! **3593ms** duration is on GPU (*AMD Radeon RX 5700 XT*) against single-threaded C++ CPU's *Ryzen 3600x* **8500ms** duration - which is pretty disappointing for OpenCL ... `break;` presence produces different results indeed, but it only decreases the amount of work needed, so why it slows things down? I guess I miss some performance potential? Can't see yet why GPU just won't crunch this problem with 2560*1440 work-items ...
Comment: Another weird thing is that when I decrease *kernel_nd_range* from `0->2560` to `SURROUND->(2560-(SURROUND*2))` (for second 1440 range respectively) and remove `if ( tw < 0 || tw >= width  )` surrounding pixels existence checks from OpenCL kernel - I get **exactly the same durations up to a single millisecond** (measuring first ~10 frames) - which is very strange because it decreases the global work for 1% which is **40ms**.
Answer: Try to maintain memory access order, just before global writing
 // here
 barrier(CLK_GLOBAL_MEM_FENCE);

 //copy results from private memory to global:
 const long p = ( x * height + y ) * BEST;

if your performance problem is originating from memory access pattern, this should ease it.
If problem comes from just branching between threads, then you can also try maintaining order within the second loop after innermost loop:
for ( short si = 0; si < BEST; ++ si ) {
            if ( d[si] == -1 || diff < d[si] ) {
                d[si] = diff;
                s[si][0] = tw;
                s[si][1] = th;
                break;
            }
        }
barrier(CLK_LOCAL_MEM_FENCE); // local => should be faster for many devices

so that in every iteration, all neighboring threads rejoin together and continue executing same instructions until a new break breaks the order.
Lastly, algorithm seems like sorting pixel value differences between SURROUND pixels, by decreasing values. So, the innermost loop could actually be moved to outermost and have all the branching be minimized, just after innermost two new loops(which were outermost before). But this increases image[ th * width + tw ] reading by BEST times so it can be slower too(maybe not when data moved to local memory before this). But, d does not need to be an array now so BEST number of private registers are saved and could give it some performance boost by decreasing register pressure.