Add dict into Item dynamodb python

Question: I have an item register on dynamodb with the next structure:
{
"OwnerID":"12312wqeq",
"license":"23423werwegdf",
"MaintenanceList":{
        "10-11-2018":{
                      "garage" : "lopcars",
                      "city" : "NY",
                      "country" "USA",
                      "location" : "1929-1927 Fulton St Brooklyn"
              }
       }
}

I need to add a new Maintenance to the list, and I tried this:
response=table.update_item(
    Key={
        "OwnerID":"12312wqeq",
        "license":"23423werwegdf",'
    }
    ,UpdateExpression = "SET #d1=:dt",
    ExpressionAttributeValues = {
            ':dt' : "12-11-2019":{
                       "garage" : "Crazycars",
                       "city" : "NY",
                       "country" "USA",
                       "location" : "120 E Suffolk Ave Central Islip"
               }
        }
                },
    ExpressionAttributeNames={
            '#d1' : 'MaintenanceList'
                },
    ReturnValues="UPDATED_NEW"
)

but overwrite the attribute MaintenanceList and I need it to look like this after update:
{
"OwnerID":"12312wqeq",
"license":"23423werwegdf",
"MaintenanceList":{
        "10-11-2018":{
                      "garage" : "lopcars",
                      "city" : "NY",
                      "country" "USA",
                      "location" : "1929-1927 Fulton St Brooklyn"
              },
        "12-11-2019":{
                       "garage" : "Crazycars",
                       "city" : "NY",
                       "country" "USA",
                       "location" : "120 E Suffolk Ave Central Islip"
               }
       }
}

Answer: The SET MaintenanceList=:dt expression indeed replaces the value of the the attributed called MaintenanceList. If you wanted the content of this attribute to be a hash table, and add to it, you need to update it using a nested atribute path as explained in this DynamoDB documentation. For example do something like SET #d1.#date=:dt.
However, note that keeping a hash table inside a single attribute's value is problematic - its total size is strictly limited (to 400KB) and you'll also pay for the entire item size every time you read or write a small part of it.

Add dict into Item dynamodb python


need to have image dragging option to position images in Gallery

Question: I have created a image content type and upload few images. And then I created another content type for Gallery and using node reference field, I added several images under a  gallery. I followed the tutorial in youtube https://www.youtube.com/watch?v=MUSpTSTVL0Q
Now I wish I could have dragable like feature, so that I can adjust the serial order of each image in a gallery. Image in 1st order should be cover of the gallery. Please suggest.
Comment: Did you tried [Draggable Views](https://www.drupal.org/project/draggableviews)?
Comment: thanks, I'nt use it but I'll give a try. Thanks again
Answer: This is solved by module called "Draggable Views"


starting a web server for angular nodejs app

Question: I am taking baby steps into the MEAN stack but can't figure out step 1, how to run my app. What do I use for a development web server and how do I start it in my directory?
If I just launch index.html as a file it will not work.
Here is my code
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>My Site</title>

    <link rel="stylesheet" href="style.css">

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/3.2.1/css/bootstrap-combined.min.css"
rel="stylesheet">

    Show the Form

I used to be hidden!

app.js
var app = angular.module( 'myApp', [] );

app.controller( 'MainCtrl', function( $scope ) {
  $scope.visible = false;
});

Comment: Look [HERE](http://stackoverflow.com/questions/16333790/node-js-quick-file-server-static-files-over-http) for simple node http server.
Answer: If you simply want to explore AngularJS functionality(or any other front end library for that matter), you don't need a Node.js app.
Assuming you already have npm installed just follow these simple steps:

npm install http-server -g
go from your console to the folder containing your html files
enter http-server -c-1 -p 9000

That would start a simple web server on port 9000 with no caching on your specified directory.
Then simply go to http://0.0.0.0:9000/your_page.html from a browser and voila.
If you want to explore more options on http-server
Answer: This code can run without a http server, just in the browser. Note that you are using a really outdated version of Angular (1.0.3), they just released version 1.3.0.
If you want to run your stuff on a local development server, you could use something like yeoman, which generates the app boilerplate for you and comes with a local node server and a build job (check for example https://github.com/yeoman/generator-webapp or https://github.com/yeoman/generator-gulp-webapp)
If you just want a super easy hhtp server and have python installed you can also use python -m SimpleHTTPServer to start up an http server in the current folder.
Here is your code in plunker and it works: http://plnkr.co/edit/j2SqmrP1yWqR68Gm3UCn?p=preview
Answer: As you are using the MEAN stack, you should probably check node.js to implement your web server. Check http://www.nodebeginner.org/, it should allow you to code a very simple one.


Split a string and keep delimiter

Question: Lets say I have a string:
StringA/StringB/StringC

Is there any way I can split this string by the / symbol, but keep it in the returned values:
StringA
/StringB
/StringC

Answer: Yes, with a look-ahead: (?=/)
library(stringr)
str_split(str, "(?=/)")

#[[1]]
#[1] "StringA"  "/StringB" "/StringC"

Works equally well with tidyr separating function:
tidyr::separate_rows(data.frame(str), str, sep = "(?=/)")

#  str
#1 StringA
#2 /StringB
#3 /StringC

With base R's strsplit, look-aheads are less straightforwards, but this works well:
unlist(strsplit(str, "(?<=.)(?=[/])", perl = TRUE))
#[1] "StringA"  "/StringB" "/StringC"

And reversely:
unlist(strsplit(str, "(?<=/)", perl = TRUE))
#[1] "StringA/" "StringB/" "StringC"

Comment: With a look-behind: `str_split(str, "(?<=/)")`.
Comment: Thanks! Likewise, how would it work if I wanted it to end with the / instead?
Answer: You can try scan + gsub like below
> scan(text = gsub("/", " /", "StringA/StringB/StringC"), what = "")
Read 3 items
[1] "StringA"  "/StringB" "/StringC"

Answer: With str_extract
library(stringr)
str_extract_all(str1, "/?[^/]+")[[1]]
[1] "StringA"  "/StringB" "/StringC"

Split a string and keep delimiter


phusion passenger processes dying and new ones starting up mysteriously

Question: as you can see, passenger processes are dying and new ones booting up, even though we're not explicitly restarting passenger ourselves. we can't pinpoint what's causing this. what are some common places we should look to find out what's triggering these restarts?
the passenger-status commands were issued about 30 min apart. passenger_pool_idle_time is set to 0 in our conf file, which you can see here: https://gist.github.com/panabee/8ddf95a72d6a07e29c7f
we're on passenger 4.0.5, rails 3.2.12, and nginx 1.4.1.
[root@mongo ~]# passenger-status
----------- General information -----------
Max pool size : 20
Processes     : 3
Requests in top-level queue : 0

----------- Application groups -----------
/home/p/p#default:
  App root: /home/p/p
  Requests in queue: 0
  * PID: 17171   Sessions: 0       Processed: 536     Uptime: 27m 56s
    CPU: 0%      Memory  : 62M     Last used: 20s ago
  * PID: 18087   Sessions: 0       Processed: 363     Uptime: 17m 31s
    CPU: 0%      Memory  : 36M     Last used: 39s ago
  * PID: 19382   Sessions: 0       Processed: 51      Uptime: 2m 55s
    CPU: 0%      Memory  : 34M     Last used: 5s ago

[root@mongo ~]# passenger-status
----------- General information -----------
Max pool size : 20
Processes     : 2
Requests in top-level queue : 0

----------- Application groups -----------
/home/p/p#default:
  App root: /home/p/p
  Requests in queue: 0
  * PID: 25266   Sessions: 0       Processed: 73      Uptime: 2m 56s
    CPU: 0%      Memory  : 32M     Last used: 34s ago
  * PID: 25462   Sessions: 1       Processed: 18      Uptime: 51s
    CPU: 0%      Memory  : 28M     Last used: 0s ago

[root@mongo ~]#

config.ru:
[root@newvps Tekiki]# cat config.ru
# This file is used by Rack-based servers to start the application.

require ::File.expand_path('../config/environment',  __FILE__)
run Tekiki::Application

Comment: Could you please post your application's config.ru file?
Comment: done, @fsoppelsa. any insights?
Answer: It's a bug in 4.0.5, will get fixed in 4.0.6. In the meantime, set pool_idle_time to a large value.
Comment: we emailed the makers of passenger, not sure if they posted publicly.
Comment: Is this bug documented? Could you please provide a URL?


Solr search, number of results

Question: I'm trying to find a way to display the number of resuts in a solr search.
I need to display it in search-results template.
Thanks for any hint
Comment: Theres a good article on Lullabot about this http://www.lullabot.com/blog/article/display-count-search-results-drupal-7
Answer: The link given is a nice one to deal with the default search result number count. In Apache Solr you can use the following code to get the total number of documents returned in the search result.
<code>if (apachesolr_has_searched() && ($response = apachesolr_static_response_cache())) {
  $returned_doc_num = $response->response->numFound;
}
</code>
Comment: Actually I only used $GLOBALS['pager_total_items'][0] as I have a pagination system.
Comment: That is fine I hope, but never used it. But you can use the numFound in templates as well.
Check https://www.drupal.org/node/1516462 comment #4, #6 & #8

Solr search, number of results


String format or REGEX

Question: I need an simple way to check whether a string that is sent to my function is of the form:
<code>(x + n)(x + m)
//the +'s can be minus'
//n and m represent a double
//x represents the char 'x'
</code>
Is there a simple string format that I can use to check that this is the form. As opposed to checking each character singularly.
The whitespace will be removed to save any confusion.
Regards
Lloyd
Comment: I'll bet his professor wouldn't accept regex as a solution, unless the lesson included regex.
Comment: Why do people just jump on the cocky remarks when certain questions are asked? I wanted to know for my own justification. Regex is the weakest of my programming tools and want to develop that area of my programming. Obviously asking here whilst you were about wasn't the best idea!
Comment: Regex was initially what I was looking at. But I was wondering if there was an easy way to check for '(' 'x' operator value')' consecutively.
Answer: Here's a stab at a RegEx example...
<code>var pattern = @"^(\(x[+-]\d+(\.\d+)?\)){2}$";
var input = "(x-0.123)(x+5)";
var result = System.Text.RegularExpressions.Regex.IsMatch(input, pattern);

if (result) {
  Console.Write("YAY IT MATCHES");
}
</code>
Comment: Thank you. I just can't seem to get my head around regex! Appreciated.
Comment: Regex is super confusing. I use http://regexpal.com/ to play around with them until something works. They have a handy quick reference on the page.
Comment: Regular expressions are one of the more powerful items in your developer toolbox, but they can be a pain to learn using a compiled language.  They really clicked for me in python because I could do things from the python interpreter and quickly try things out.
Answer: You can use regular expressions to check this.
Answer: !Regex

Use this and you won't have 2 problems ;)

<code> class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(IsGood1("+x(3)-)x-5+"));
            Console.WriteLine(IsGood1("(x * n)(x + m)"));
            Console.WriteLine(IsGood1(" ( x + 12.9) (x+33.9)"));
        }

        private static bool IsOrdered(string s) // bad idea
        {
            var ind = new List<int>();
            ind.Add(s.IndexOf('('));
            ind.Add(s.IndexOfAny(new char[] { '+', '-' }));
            ind.Add(s.IndexOf(')'));
            ind.Add(s.LastIndexOf('('));
            ind.Add(s.LastIndexOfAny(new char[] { '+', '-' }));
            ind.Add(s.LastIndexOf(')'));

            bool order = true;

            for (int i = 0; i < ind.Count - 1; i++)
            {
                order = order && (ind[i] < ind[i + 1]);
            }
            return order;
        }

        public static bool IsGood1(string s)
        {
            if (!IsOrdered(s)) return false;

            double m = 0;
            int c = 0;

            foreach (var item in s.Split(new char[] { '+', '-', '(', ')' }))
            {
                var xx = item.Trim();

                if (xx != "")
                    switch (c)
                    {
                        case 0:
                        case 2:
                            if (xx == "x") c++;
                            break;
                        case 1:
                        case 3:
                            if (double.TryParse(xx, out m)) c++;
                            break;
                    }
            }

            return c == 4;
        }

    }
</code>
Comment: won't that accept `+x(3)-)x-5+` , and all other combination of `[-+()]`?
Comment: +1 Kobi Thanks! Took care of it but it looks dirty now! you know of some better way? Feel free to edit my answer :)
Answer: This is a case where I think Regular Expressions make a lot of sense.  Unlike C++, C# does not have a way (that I know of) to use string formatting as part of parsing a string.
Quoting Eric Lippert:

Is this clever? No. Beautiful? No.
  Short? No. Correct according to the
  specification?

I hope so, but I have not fully tested it. It looks pretty good though.
<code>    static bool testJoin(string x)
    {
        string[] s = x.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (s.Length != 3) return false;
        if (s[1] != "+" && s[1] != "-") return false;
        if (s[0] != "x") return false;
        double tmp;
        return Double.TryParse(s[2], out tmp);
    }
    static bool testString(string x)
    {
        if (x.Length < 2) return false;
        if (x[0] != '(' || x[x.Length-1]!=')') return false;
        string[] y = x.Substring(1,x.Length-2).Split(new string[] { ")(" }, StringSplitOptions.None);
        if (y.Length != 2) return false;
        return testJoin(y[0]) && testJoin(y[1]);
    }
</code>
Comment: Note that our specifications might not agree.  For example, I require there to be one or more spaces before and after the +/-.
Comment: For those who didn't get it, my reference to Eric Lippert was a joke, since his context was, "let's do it right, even if it isn't pretty" and my context is, "this isn't pretty."

String format or REGEX


301 redirect for OpenCart (old url to new)

Question: I am looking for a 301 redirect. I have a OC 188.8.131.52 (abc.com) and have a new store now on OC 220.127.116.11 (xyz.com ). I have migrated my data from abc.com to xyz.com and since all the product / pages urls are the same except the domain change, i am looking for a simple code which i can add to htaccess to make this happen.
Since my old website urls are listed on Google, i would like to redirect the traffic coming to a particular url to the same page on the new website. It would be a permanent redirect.
Answer: I paid a freelancer to get this done.. was in a hurry. Anyways, i have posted the answer below for the benefit of all.
Upload this to .htaccess on your old domain abc.com, replace example.com with your new domain name.
<code>RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !example.com/$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
</code>


Ubuntu PHP-FPM not starting

Question: I recently installed PHP 5.3.8 from source distribution on Ubuntu 11.04.
Here's the first parts of my configure directive:
./configure --enable-fpm --with-fpm-user=php-fpm
--with-fpm-group=php-fpm --prefix=/usr/local/php-5.3.8
--exec-prefix=/usr/local/php-5.3.8
--with-config-file-path=/usr/local/php-5.3.8/etc
--with-config-file-scan-dir=/usr/local/php-5.3.8/etc

Afterwards, I downloaded a sample for the shell script file that I used for /etc/init.d/php-fpm. I got the script from here: http://svn.php.net/repository/php/php-src/branches/PHP_5_3/sapi/fpm/init.d.php-fpm.in. I edited the file and added the paths to relevant locations and then I copied the contents to /etc/init.d/php-fpm.
I chmod +x php-fpm and then attempt to start it with ./php-fpm start and I get the following error:
Starting php-fpm [07-Sep-2011 02:55:34] ERROR: bind() for address '127.0.0.1:9000' failed: Address already in use (98)

I changed the listening port number in php-fpm.conf and I still get the same error.
One thing I noticed is that there doesn't seem to have been a php.ini file created. I've looked everywhere for it under my prefix php directory and other places. I'm not sure if this is what is causing the problem.
I'd appreciate any guidance on how I can get PHP working.
Thanks.
EDIT:
This is what I get when I use the command: lsof -i -P
sshd     2267    root    3u  IPv4   3188      0t0  TCP *:22 (LISTEN)
sshd     2267    root    4u  IPv6   3190      0t0  TCP *:22 (LISTEN)
sshd    12342    root    3r  IPv4 408697      0t0  TCP WorbServer1:22->184.108.40.206.vgccl.net:30961 (ESTABLISHED)
php-fpm 12485    root    6u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12486 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12487 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12488 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12489 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12490 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12491 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12492 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12493 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12494 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12495 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12496 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12497 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12498 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12499 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12500 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12501 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12502 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12503 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12504 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)
php-fpm 12505 php-fpm    0u  IPv4 409587      0t0  TCP localhost:9000 (LISTEN)

I'm not sure why they are so many though, I'll have to look at the php-fpm.conf.
Answer: You can also use
fuser 9000/tcp

That will list all the pids running on that port.. easy way to kill them all
fuser -k 9000/tcp

Comment: fuser doesn't seem to be on my system for some reason (I'm using a Rackspace Cloud Server with Ubuntu 11.04). I intuitively tried `apt-get install fuser` but that didn't work.
Comment: +100 Works like a charm
Answer: Well, the simplest explanation to the port being in use would be that the port is, in fact, in use.
What do you get from lsof -i -P?
Comment: Lol, I figured that much but I had no idea what to do about it. Here's the last few results from lsof: `php-fpm 11859 php-fpm    0u  IPv4 398087      0t0  TCP localhost:9500 (LISTEN)
php-fpm 11860 php-fpm    0u  IPv4 398087      0t0  TCP localhost:9500 (LISTEN)
php-fpm 11861 php-fpm    0u  IPv4 398087      0t0  TCP localhost:9500 (LISTEN)
sshd    12342    root    3r  IPv4 408697      0t0  TCP WorbServer1:22->184.108.40.206.vgccl.net:30961 (ESTABLISHED)`
Comment: so why is this the correct answer?
Comment: why is this the correct answer?

Ubuntu PHP-FPM not starting


How to access element id from another page using JavaScript?

Question: I am trying to access an element id of an HTML page from another page. I have seen other solutions but none have worked so far.
For example, if this is One.html
<input id="a" type="text"></input>

I am trying to access the element id 'a' from Two.html to get the value that has been inputted using `
var thing = document.getElementById('a').value;
document.getElementById('demo').innerHTML = "the value is" + " " + thing;

Comment: only under very limited conditions can pages talk to each other so we need more details before we can help you
Comment: Is two.html ever loaded into your browser?
Comment: not from your current web page?
Answer: you can use localStorage
for example in firstpage.html you save data with
var thing = document.getElementById('a').value;
localStorage.something = thing ;
then in your seconpage.html you can use it by
document.getElementById("demo").innerHTML=localStorage.something;

Comment: Do I add this in the first or second HTML page? And if it is the first page then how do I access localstorage from the second page?
Answer: sorry I don't have enough reputation to leave this as a comment but just a heads up, input tags are standalone tags.
Example:

    <input type="text" id="a" />

Comment: Thanks! I did not know that!


Facebook iOs Leaderboards

Question: I would like to use the Facebook Scores API to make a social leaderboard for my iOS game.
From the documentation, I saw that it would require to request a publish permission so that I could post scores. The thing is that I don't want to publish to the player's wall (I simply think it's invasive), I just want to use the API backend to store the score, but everything I saw involved posting to the user's wall in order to write the score on the backend.
How should I proceed to only write the score without posting it into facebook?
If this thing exists, can I avoid requiring the publish permission?
Thanks
Comment: Welcome to Stack Overflow. Please include the work you have done so far. Otherwise this looks like you are asking for code.
Answer: If you simply use the Score API as intended, the user will have the option of choosing whether to give your app the visibility permissions like "private, friends, public, etc".  That lets the user decide what is invasive rather than you deciding for them.
Here is a related stackoverflow question with the opposite question, showing how users have control over what is shared with the API:
Facebook scores blocked by "only me" visibility
Comment: Thks Henry, the thing is that when prompting for the publish permission it is done in a different dialog popup than the public profile and friends persmission. This double popup wouldn't be sthg I am looking foward to, nor posting to the user's wall when I simply want to store his score. Anyway I think the best solution would be to have a login in facebook and a custom backend for storing the scores. Thks for your response.
Comment: Well if you don't want social leaderboards, then the facebook score api is the wrong thing to be using.  If you really wanted to use facebook as a personal data store you can use User Owned Objects: https://developers.facebook.com/docs/opengraph/using-objects#objectapi-appanduserobjects.  However, since you simply want to store data, I would use Parse.com.  It's easier to use and you'll get Facebook and Twitter sign in for free.
Comment: thks Henry, I'l try that out and see what happens!

Facebook iOs Leaderboards


Input um abaixo do outro

Question: Estou fazendo um código HTML.
Tenho alguns inputs criados porém eles estão ficando um do lado do outro como se tivesse um float neles, só que eu não quero assim.
Quero que fique um abaixo do outro, tem uma função no CSS que faz isso?
Eu sei que com o
 eu consigo fazer, porém queria saber como faz no CSS.
Answer: Existem várias maneiras de fazer isso pelo CSS, mas o importante é vc saber que o input é um elemento do tipo inline, na verdade inline-block, ou seja, ele fica em linha, pois só ocupa o espaço dele mesmo, assim como labels, spans, etc.

Mas como resolver isso só com CSS?
Uma das formas de colocar um input por linha é dando a ele o display:block, assim ele ocupa 100% da largura da tela, e o próximo input só viria a baixo dele, na "linha de baixo".

input {
 display: block;
}
<input type="text">
<input type="text">
<input type="text">
Comment: Muito obrigado ;)
Comment: Hugo eu tentei fazer isso só que os inputs saem do alinhamento. Estou utilizando `text-align: center;` no ``, mas ao colocar `block` nos inputs eles não ficam mais centralizados.
Comment: @JeanExtreme002 fala Jean, cada depois que vc muda ele para display: block ele passa a aceitar alguns atributos do `box model block`, então com um simples `margin: 0 auto;` vc consegue alinha-los no centro novamente olha aqui https://prnt.sc/t6vk02 Qq dúvida comenta ai que te ajudo
Comment: Funcionou, você pode me falar apenas como dar uma margem entre os inputs?
Comment: @JeanExtreme002 olha ai https://prnt.sc/t72ffn
Comment: @JeanExtreme002 de nada jovem!
Answer: Poderia ser resolvido assim também.
Dependendo do que esta fazendo. Provavelmente precisará colocar um label.
Pra adicionar um label, ficaria mais ou menos assim:

  <input type="checkbox" name="checkBox[]" class="checkbox-block" id="checkbox-id-1">
  Checkbox 1

  <input type="checkbox" name="checkBox[]" class="checkbox-block" id="checkbox-id-2">
  Checkbox 2

  <input type="checkbox" name="checkBox[]" class="checkbox-block" id="checkbox-id-3">
  Checkbox 3

Answer: Pode utilizar uma div flexbox em forma de coluna e definir um width para os inputs (de forma geral ou individual). No exemplo abaixo defini um width 200px para a div onde estão os inputs. Como a div é um flexbox, os inputs terão 100% de largura da div:

div.col{
   display: flex;
   flex-direction: column;
   width: 200px;
}

div.col input:not(:last-child){
   margin-bottom: 10px;
}

   Exemplo de inputs em coluna:

   <input type="text">
   <input type="text">
   <input type="text">
   <input type="text">

Defini também um espaçamento de 10px de um input ao outro abaixo, exceto no último com :not(:last-child).
Answer: Você pode fazer de várias maneiras como já falado, você só deve decidir se o CSS será colocado no input (ou seja todos os input terão esse efeito) ou em alguma .classeDefinida (então vc especifica quando quer usar) no caso abaixo criei uma .class chamada .limitar

.limitar{
     inline-size: 20px;
}

<input type="text">
<input type="text">
<input type="text">

Answer: tenta colocar no CSS, cada input, como Display: block; Ou então no container em que eles estão.
Answer:

    *{
        padding: 0px;
        margin: 0;
        box-sizing: border-box;
    }
    body{
        width: 100vw;
        height: 100vh;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: #6A6F69;
    }
    .btn1{
        text-decoration: none;
        margin: 3px;
        width: 170px;
        text-align: center;
        padding: 10px;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
        font-size: 23px;
        border-radius: 20px;
        display: flex;
        background-color: #4DDB34;
        color: white;
        box-shadow: 2px 2px 2px 2px #4D4C4C;
    }
    .btn1:hover{
        box-shadow: 2px 2px 2px 2px #1F1F1F;
    }
Media Creation
Midia De instalção
Iso Windows MultiSelect
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Input um abaixo do outro


Taxonomy Term Reference Fields Don't Get Created on Nodes During Migration

Question: I have followed the steps shown here to create/run the migration.  Everything seems to migrate correctly except the Taxonomy Term Reference fields never get added to the nodes.  The taxonomies and vocabularies do get created.
I'm thinking that those fields should have been created in d6_field_instance so here is my migrate_plus.migration.upgrade_d6_field_instance.yml.
uuid: 6e1fd6ac-1ec4-4631-93d1-753068fdc667
langcode: en
status: true
dependencies: {  }
id: upgrade_d6_field_instance
migration_tags:
  - 'Drupal 6'
migration_group: migrate_drupal_6
label: 'Field instance configuration'
source:
  plugin: d6_field_instance
  constants:
    entity_type: node
process:
  field_type_exists:
    -
      plugin: migration
      migration: upgrade_d6_field
      source:
        - field_name
    -
      plugin: extract
      index:
        - 1
    -
      plugin: skip_on_empty
      method: row
  entity_type: constants/entity_type
  field_name: field_name
  bundle:
    -
      plugin: migration
      migration: upgrade_d6_node_type
      source: type_name
    -
      plugin: skip_on_empty
      method: row
  label: label
  description: description
  required: required
  status: active
  settings:
    plugin: d6_field_field_settings
    source:
      - widget_type
      - widget_settings
      - global_settings
  default_value_callback: ''
  default_value:
    plugin: d6_field_instance_defaults
    source:
      - widget_type
      - widget_settings
destination:
  plugin: 'entity:field_config'
migration_dependencies:
  required:
    - upgrade_d6_node_type
    - upgrade_d6_field
  optional:
    - upgrade_d6_field
    - upgrade_d6_node_type

Any idea what it can point me where in code to look.
Answer: The problem wasn't in migrate_plus.migration.upgrade_d6_field_instance.yml but instead the problems were in  migrate_plus.migration.upgrade_d6_field.ym and migrate_plus.migration.upgrade_d6_field_instance_widget_settings.yml.  Also in the term yml files I had to update the field name to include field_ in the file name.
I documented how I was debugging and what I was changing here.


AWS IAM policy, user should see only s3 public buckets

Question: i have tried several methods, couldn't succeed. I need to have policy that attach to users, so that they could see only public buckets not all the buckets in their aws console
Comment: See where? In AWS console? can you be more specific? What did you try?
Comment: sry, to specify that, yes in the user aws console
Answer: The ability to view a list of buckets is granted via the s3:ListAllMyBuckets permission, which is defined as:

Grants permission to list all buckets owned by the authenticated sender of the request

Thus, the user either has permission to list the names of all buckets, or none of the buckets. It is not possible to filter which buckets are returned in the listing.


Resume a WHILE loop from where it stopped SQL

Question: I have a while loop query that I only want to run until 11PM everyday - I'm aware this can be achieved with a WAITFOR statement, and then just END the query.
However, on the following day, once I re-run my query, I want it to continue from where it stopped on the last run. So I'm thinking of creating a log table that will contain the last processed ID.
How can I achieve this?
<code>DECLARE @MAX_Value BIGINT  = ( SELECT MAX(ID) FROM dbo.TableA )

DECLARE @MIN_Value BIGINT = ( SELECT MIN(ID) FROM dbo.TableA )

            WHILE (@MIN_Value < @MAX_Value )
            BEGIN

                INSERT INTO dbo.MyResults
                /* Do some processing*/
                ….
                ….
                ….

                SET @MIN_Value = MIN_Value + 1

            /*I only want the above processing to run until 11PM*/

            /* Once it's 11PM, I want to save the last used @MIN_Value
            into my LoggingTable (dbo.Logging) and kill the above processing.*/

        /* Once I re-run the query I want my processing to restart from the
 above @MIN_Value which is recorded in dbo.Logging */

            END
</code>
Comment: What is the actual problem your loop is supposed to solve? What is the use case (business scenario)? Are you processing something/calculating stuff?

Ok, got it, will answer with SQL.
Comment: Before answering this question... It appears to me that you are trying to use a wrong kind of solution for your actual problem. What is the problem are you trying to solve by implementing this WHILE loop? Are you running SQL Server?
Comment: Yes, I'm using SQL Server. I'm aware I could just create a job to do this. But I want to solve it using T-SQL.
Answer: Disclaimer: I do not recommend using WHILE loops in SQL Server but considering the comment that you want a solution in SQL, here you go:
<code>-- First of all, I strongly recommend using a different way of assigning variable values to avoid scenarios with the variable being NULL when the table is empty, also you can do it in a single select.

-- Also, if something started running at 10:59:59 it will let the processing for the value finish and will not simply rollback at 11.

CREATE TABLE dbo.ProcessingValueLog (
    LogEntryId BIGINT IDENTITY(1,1) NOT NULL,
    LastUsedValue BIGINT NOT NULL,
    LastUsedDateTime DATETIME NOT NULL DEFAULT(GETDATE()),
    CompletedProcessing BIT NOT NULL DEFAULT(0)
)

DECLARE @MAX_Value BIGINT = 0;
DECLARE @MIN_Value BIGINT = 0;

SELECT
    @MIN_Value = MIN(ID),
    @MAX_Value = MAX(ID)
FROM
    dbo.TableA

SELECT TOP 1
    @MIN_Value = LastUsedValue
FROM
    dbo.ProcessingValueLog
WHERE
    CompletedProcessing = 1
ORDER BY
    LastUsedDateTime DESC

DECLARE @CurrentHour TINYINT = HOUR(GETDATE());
DECLARE @LogEntryID BIGINT;

WHILE (@MIN_Value < @MAX_Value AND @CurrentHour < 23)
BEGIN

    INSERT INTO dbo.ProcessingValueLog (LastUsedValue)
    VALUE(@MIN_Value)

    SELECT @LogEntryID = SCOPE_IDENTITY()

    // Do some processing...

    SET @MIN_Value = @MIN_Value + 1;

    UPDATE dbo.ProcessingValueLog
    SET CompletedProcessing = 1
    WHERE LogEntryId = @LogEntryID

    SET @CurrentHour = HOUR(GETDATE())
END
</code>
Comment: What is `CURRENT_IDENTITY()`? Did you mean `IDENT_CURRENT()`? As a rule, [`Scope_Identity()`](https://msdn.microsoft.com/en-us/library/ms190315.aspx) is a much better choice as it is limited to the current session and scope. An alternative (that is overkill in this instance) is an [`OUTPUT`](https://msdn.microsoft.com/en-us/library/ms177564.aspx) clause.
Comment: @HABO Oops, I meant SCOPE_IDENTITY()... Was typing in the SO editor, did not even check the syntax. Fixed, thanks for pointing out.


java.lang.NullPointerException (Unknown Source)

Question: I can not figure out this problem , I have no info what happens ! I get this error from my google apps panel.Do not be referred to this.
This is the error in google publish:
 java.lang.RuntimeException: Unable to start activity
     ComponentInfo{es.project/es.project.activity.ChatActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
    at android.app.ActivityThread.access$600(ActivityThread.java:123)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4424)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.NullPointerException
    at es.project.activity.ChatActivity.onCreate(Unknown Source)
    at android.app.Activity.performCreate(Activity.java:4470)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
    ... 11 more

In my emulator this code works , but I think some people have errors in. This is my OnCreate:
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    serverId = getIntent().getExtras().getInt("serverId");
    server = Chatsi.getInstance().getServerById(serverId);
    Settings settings = new Settings(this);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(false);
    setTitle("");
    setContentView(R.layout.chat);
    EditText input = (EditText) findViewById(R.id.input);
    input.setOnKeyListener(inputKeyListener);
    //INDICATOR
    pager = (ViewPager) findViewById(R.id.pager);
    pagerAdapter = new ConversationPagerAdapter(this, server);
    pager.setAdapter(pagerAdapter);
    final float density = getResources().getDisplayMetrics().density;
    indicator = (ConversationIndicator) findViewById(R.id.titleIndicator);
    indicator.setServer(server);
    indicator.setTypeface(Typeface.DEFAULT);
    indicator.setViewPager(pager);
    indicator.setFooterColor(0xFFFF8800);
    indicator.setFooterLineHeight(2 * density);
    indicator.setFooterIndicatorHeight(4 * density);
    indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);
    indicator.setSelectedColor(0xFF000000);
    indicator.setSelectedBold(true);
    indicator.setBackgroundColor(0xFFF2F2F2);
    indicator.setTextColor(0xFF222222);
    //Botones
    Button boton1 = (Button) this.findViewById(R.id.enviar);
    boton1.setOnClickListener(mandartexto);
    Button boton2 = (Button) this.findViewById(R.id.emoticonos);
    boton2.setOnClickListener(mandaremoticon);
    Button boton3 = (Button) this.findViewById(R.id.lupa);
    boton3.setOnClickListener(mandarlupa);
    //MENUS
    menuview = (ListView) findViewById(R.id.menuview);
    MenuAdapter menuAdapter = new MenuAdapter(this, BOTONES);
    menuview.setAdapter(menuAdapter);

    historySize = settings.getHistorySize();

    if (server.getStatus() == Status.PRE_CONNECTING) {
        server.clearConversations();
        pagerAdapter.clearConversations();
        server.getConversation(ServerInfo.DEFAULT_NAME).setHistorySize(historySize);
    }

    float fontSize = settings.getFontSize();
    indicator.setTextSize(fontSize * density);

    input.setTextSize(settings.getFontSize());
    input.setTypeface(Typeface.DEFAULT);

    // Optimization : cache field lookups
    Collection<Conversation> mConversations = server.getConversations();

    for (Conversation conversation : mConversations) {
        // Only scroll to new conversation if it was selected before
        if (conversation.getStatus() == Conversation.STATUS_SELECTED) {
            onNewConversation(conversation.getName());
        } else {
            createNewConversation(conversation.getName());
        }
    }

    scrollback = new Scrollback();
    this.overridePendingTransition(R.anim.appear,R.anim.disappear);

}

Comment: On what line? Help us out here
Comment: It might be possible that your onCreate is taking too much time to execute, I had a similar issue on low end devices. have you tried moving some of the code to onResume() where possible?
Comment: Remyoman@ tell me I should move, my OnResume is very extensive Tim Castelijns@ I dont  know  the line, the debug not inform me
Comment: @Remyoman - no, this is clearly a null pointer exception not a timeout error.
Answer: server = Chatsi.getInstance().getServerById(serverId);

and then
if (server.getStatus() == Status.PRE_CONNECTING) {

Form one of potentially many examples of places where a trivial failure to obtain an object (due to anything from temporarily poor signal strength on up) has the potential to result in an uncaught Null Pointer Exception.
Whenever you obtain an object form a mechanism that could fail, you should either check that the object is non-null before you utilize it, or protect your attempt to utilize it with a try/catch block or higher level handler which can recover from the exception.
The problem is not necessarily with your server object - it could be your view or anything else which is obtained by a mechanism which can fail, or used in a code pathway which may not have yet initialized it.
Comment: what you say  can not help my


Calling an inner class in a main method in java

Question: So I've already tried looking up what's causing this and comparing my code for any possible errors to others and I have yet to find anything else that would lead to this issue.
I'm trying to call the inner class Pair in order to store data.
Quick info about my project.
Take voting data and determine someone's political stance on it.
Right now I'm just trying to parse the data.
Example data
Rep1[tab]D[tab]-+-+-++---

I'm storing it as...
ArrayList<Pair<String,String>>

So rep1 is the place in the ArrayList and then D and -+-+-++--- are the pair.
But I'm having an issue with trying to instantiate the Pair class " non-static variable this cannot be referenced from a static context"
specifically
C:\Users\Stephanie\Desktop>javac DecisionTree.java
DecisionTree.java:26: error: non-static variable this cannot be referenced from a static context
                        Pair pair = new Pair();
                                    ^
1 error

Code:
public class DecisionTree{
public static void main(String[] args)
{
    ArrayList<Pair> data = new ArrayList<Pair>();
    FileReader input = new FileReader ("voting-data.tsv");
    BufferedReader buff = new BufferedReader(input);
    String line = null;

    while((line=buff.readLine())!=null)
    {
        Pair pair = new Pair();
        String[] array = line.split("\\t");
        pair.setLabel(array[1]);
        pair.setRecord(array[2]);
        data.add(pair);
    }
}

/**
* Private class to handle my inner data
*/
public class Pair
{
    private String label;
    private String record;
    /**
    * contructor
    *@param String label, the label of the person's party
    *@param String record, their voting record
    */
    private Pair(String label, String record)
    {
        this.label = label;
        this.record = record;
    }
    /**
    * empty contructor
    */
    private Pair()
    {

    }
    /**
    * get the label
    *@return String label, the label of the person's party
    */
    private String getLabel()
    {
        return label;
    }
    /**
    * get the record
    *@return String record, their voting record
    */
    private String getRecord()
    {
        return record;
    }
    /**
    * set the label
    *@param String label, the label of the person's party
    */
    private void setLabel(String label)
    {
        this.label=label;
    }
    /**
    * set the record
    *@param String record, their voting record
    */
    private void setRecord(String record)
    {
        this.record=record;
    }
}

}
Thanks! I feel like I'm missing something really basic, it's just been a long time since I've used Java
Comment: Possible duplicate of [Java inner class and static nested class](http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class)
Answer: Make your Pair static, i.e.:
public static class Pair

Otherwise you cannot construct a Pair object in main(), because it is a static method.  Inner classes (as opposed to static nested classes) require a surrounding instance.
Also your comment says Pair is private, but the class is marked public.  Make it private if that is your intent.
Answer: Non-static inner classes are associated with an instance of the enclosing class in Java. This means that an instance of class Pair in your example belongs to a specific instance of DecisionTree. You can only create it in the context of an instance of DecisionTree. You can't directly create a Pair using new Pair() in the main() method, because that method is static (so, it's not associated with an instance of DecisionTree).
If you don't want this, make the inner class static:
public class DecisionTree {
    // ...

    public static class Pair {
        // ...
    }
}

Answer: Pair is an inner class. Instances of an inner class are associated with instances of the class they are a member of, and can only be created in the context of a parent instance.
If you declare Pair static it will become a nested class, which is more like a regular class. The enclosing class only contributes its name.


Prism shared region

Question: I have a question. I created a region with view and model for a "pdf reader". Then I add this "pdf reader region" to two content controls in two usercontrols. I want to recycle this region with the view and model
The pdf reader is only a view to display a pdf file.
Bootstrapper register:
regionManager.RegisterViewWithRegion(BaseNames.PDF_VIEW_REGION, typeof(
                    Infrastructure.Base.Views.PdfView));

BaseNames class
public static class BaseNames
{
    public const string PDF_VIEW_REGION = "PdfViewBaseRegion";
}

View 1
<ContentControl Grid.Column="1" prism:RegionManager.RegionName="{x:Static contract:BaseNames.PDF_VIEW_REGION }"/>

View 2
<ContentControl Grid.Column="1" prism:RegionManager.RegionName="{x:Static contract:BaseNames.PDF_VIEW_REGION }"/>

Exception:

Prism.Regions.Behaviors.RegionCreationException: "An exception occurred while creating a region with name 'PdfViewBaseRegion'. The exception was: System.ArgumentException: Region with the given name is already registered: PdfViewBaseRegion
     bei Prism.Regions.RegionManager.RegionCollection.Add(IRegion region)
     bei Prism.Regions.Behaviors.RegionManagerRegistrationBehavior.TryRegisterRegion()
     bei Prism.Regions.Behaviors.RegionManagerRegistrationBehavior.StartMonitoringRegionManager()
     bei Prism.Regions.Behaviors.RegionManagerRegistrationBehavior.OnAttach()
     bei Prism.Regions.RegionBehavior.Attach()
     bei Prism.Regions.RegionBehaviorCollection.Add(String key, IRegionBehavior regionBehavior)
     bei Prism.Regions.RegionAdapterBase1.AttachDefaultBehaviors(IRegion region, T regionTarget)
     bei Prism.Regions.RegionAdapterBase1.Initialize(T regionTarget, String regionName)
     bei Prism.Regions.RegionAdapterBase`1.Prism.Regions.IRegionAdapter.Initialize(Object regionTarget, String regionName)
     bei Prism.Regions.Behaviors.DelayedRegionCreationBehavior.CreateRegion(DependencyObject targetElement, String regionName). "
Comment: What exactly is your question? You create two regions with the same name and the exception is telling you you're not allowed to do that.
Answer: If you navigate to View that uses RegionManager, you should remove your Region from RegionCollection in RegionManager.
    public void OnNavigatedFrom(NavigationContext navigationContext)
    {
    navigationContext.NavigationService.Region.RegionManager.Regions.Remove(BaseNames.PDF_VIEW_REGION);
    }

Prism shared region


How often do tires need to be changed in Kart Racing?

Question: We are new to karting and are renting a Kart for Racing. Our fee does not include new tires this is something we must pay for if we want to provide new tires.
The existing rear/front tires we use a device to heat scrape off any debris before
the next race.
The person we are renting from says we should replace the front tires in a few more weekends. (each weekend has 4 races) The tires on the Kart now are not new.
We know that tires are expensive 200.00 a pair but want our child to be safe.
How do we know when to replace?
So we want to know when is the right time to replace. Can we tell by looking? or is it more something our son can tell while racing.
The track is a track that is set up in a parking lot so it has a lot of bumps and is not a normal smooth maintained race track. (although they do blow debris off
before the racing begins)
Answer: New tyres simply make the kart go quicker by providing more grip. Even if a tyre fails, you are highly, highly unlikely to be in any danger as a result. You might spin if a rear tyre fails partway through a quick corner, but your son will spend more time spinning off at the start of his karting career as a result of driving incorrectly than he will through tyre failures. Don't fret over tyre failures.
In my opinion, if your son is starting out, he may arguably benefit from running on well-used tyres for a while as it will help him hone his kart control skills. The bottom line though is that if we had a choice, we'd all slap new tyres on for every race. They will always be quicker. You change tyres when a) you can afford it, or b) you are sacrificing too much time per lap because your old tyres are past their "best" (grippiest) (or if you get a puncture!).
In terms of "how long" - it will depend on all sorts of things, not least the brand of rubber, the abrasiveness of the circuit, your son's driving style, the characteristics of the kart he is driving etc. Someone else in the same class and at the same circuit may have a good idea as a guess, but really it will ultimately down to your son exerting enough pressure on you to dip into your wallet again ;)
Answer: Bottom line: it all depends on how serious you are taking your racing. If your in it to just race and enjoy the time with your kids then 3-4 race weekends on a set of tires is reasonable.   If your in it to win a lot and be very competitive, change them every race day.   Racing was never meant to be or intended to be a cheap sport and certainly isn't for everyone or family.   If money is of ANY concern, racing may not be the right sport for your family.   That's just a reality.  We race the SKUSA series and last season spent $12k and already owned our equipment. That was just on normal expenses to be semi competitive. I know people in karting that spend $25-30k per season.


CSS: element that only visible above certain elements

Question: Is it possibe by any way to make element that only can be visible above certain other elements?
For example, in this code, I would like the .reflection element to be visible only above the .reflective elements (which are at the top and bottom) and not visible on the .non-reflective element (which is in the center):

  .bg
  {
      position: relative;
      width: 300px;
      height: 150px;
      background-color: green;
  }
  .reflective
  {
      width: 100%;
      background-image: url(https://sample.wdd.co.il/wp-content/uploads/sites/6/2024/01/mahogany-4.jpg);
      height: 45px;
      margin: 2.5px 0;
      border: 1px solid gray;
      border-radius: 15px;
      box-shadow: inset 0 0 10px black;
  }
  .non-reflective
  {
      width: 100%;
      background-color: transparent;
      height: 50px;
      border: 1px solid brown;
      border-radius: 15px;
  }
  .reflection
  {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      width: 250px;
      height: 150px;
      border-radius: 100%;
      background: linear-gradient(to bottom right, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 100%);
  }

Answer: You can achieve this using z-index property combined with the position property.
Also you have to add another non-reflective-inner to solve the reflection don't show on outside or the border

.bg {
  position: relative;
  width: 300px;
  height: 150px;
  background-color: green;
}

.reflective {
  width: 100%;
  background-image: url(https://sample.wdd.co.il/wp-content/uploads/sites/6/2024/01/mahogany-4.jpg);
  height: 45px;
  border: 1px solid gray;
  border-radius: 15px;
  box-shadow: inset 0 0 10px black;
}

.non-reflective {
  width: 100%;
  z-index: 2;
  position: relative;
  background-color: inherit;
  padding: 2.5px 0;
}

.non-reflective-inner {
  height: 50px;
  border: 1px solid brown;
  border-radius: 15px;
}

.reflection {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 250px;
  height: 150px;
  border-radius: 100%;
  background: linear-gradient(to bottom right, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 100%);
  z-index: 1;
}

Comment: This does the reverse of what is required - ie the reflection is seen only through non-reflective (and that is because the non-reflective element is transparent).
Comment: @sevi I edited the answer, Please check it and let me know if this works.
This fix will solve the issue you have in @A Haworth's answer
Comment: @Jai248 part of the trick that you remved margin from the .reflective, thus it seems like the reflection is not visible above the background.
Comment: @Sevi this is what you wanted right ?
Comment: @Jai248 no. its not "only" can be visible above certain other elements.
Answer: Maybe this will help, portio of image. background-position

 .bg {
        position: relative;
        width: 300px;
        height: 150px;
        background-color: green;
        margin: 50px 0;
      }
      .bg2 {
        position: relative;
        background-image: url(https://sample.wdd.co.il/wp-content/uploads/sites/6/2024/01/mahogany-4.jpg);
        background-size: 300px 150px;
        width: 300px;
        height: 150px;
        margin: 50px 0;
      }
      .reflective {
        width: 100%;
        background-image: url(https://sample.wdd.co.il/wp-content/uploads/sites/6/2024/01/mahogany-4.jpg);
        background-size: 300px 150px;
        height: 45px;
        margin: 2.5px 0;
        border: 1px solid gray;
        border-radius: 15px;
        box-shadow: inset 0 0 10px black;
        background-position: 0 0;
        overflow: hidden;
      }
      .reflective div {
        background: linear-gradient(to bottom right, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 100%);
        border-radius: 100%;
        overflow: hidden;
        width: 100%;
        height: 150px;
      }
      .reflective2 {
        background-position: 0 200px;
        overflow: hidden;
      }
      .reflective2 div{
        background: linear-gradient(to bottom right, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 100%);
        margin-top: -100px;
        border-radius: 100%;
        width: 100%;
        height: 150px;
      }
      .non-reflective {
        width: 100%;
        background-color: transparent;
        height: 50px;
        border: 1px solid brown;
        border-radius: 15px;
        z-index: 10;
        position: relative;
      }
      .reflection {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
        width: 250px;
        height: 150px;
      }

portion of picture

the whole picture

Comment: this is an example of an idea if you thought like this https://stackoverflow.com/questions/73693721/have-image-only-show-in-certain-boxes-of-container


Linux, some packets are not being NAT

Question: I'm trying to NAT HTTP traffic, I'm new to this and facing some issues. What I'm trying to do is NAT client HTTP requests to a webserver.
CLIENT -> NAT BOX -> WEBSERVER
When the client open the IP of the NAT BOX, the request should be pass to the web server. But I'm getting "HTTP request sent, awaiting response..." and then wait several minutes before the request is done.
Looking at the tcpdump output, it looks like the first Syn packet on (10:48:54) is being NAT but not the second, third, fourth... ACK or PSH packets, and wait until (10:52:04) it starts NAT again on the ACK packet.
The iptables command I'm using is:
iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 80 \
 -j DNAT --to-destination WEBSERVER

I'm wondering what could have caused this behavior?
10:48:54.907861 IP (tos 0x0, ttl  49, id 16395, offset 0, flags [DF],
 proto: TCP (6), length: 48) CLIENT.61736 > NATBOX.http: S,
 cksum 0x6019 (correct), 1589600740:1589600740(0) win 5840 <mss 1460,nop,wscale 8>

10:48:54.907874 IP (tos 0x0, ttl  48, id 16395, offset 0, flags [DF],
 proto: TCP (6), length: 48) CLIENT.61736 > WEBSERVER.http: S,
 cksum 0xb5d7 (correct), 1589600740:1589600740(0) win 5840 <mss 1460,nop,wscale 8>

10:48:55.102696 IP (tos 0x0, ttl  49, id 16397, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x2727 (correct), ack 2950613896 win 23

10:48:55.102963 IP (tos 0x0, ttl  49, id 16399, offset 0, flags [DF],
 proto: TCP (6), length: 160) CLIENT.61736 > NATBOX.http: P 0:120(120)
 ack 1 win 23

10:48:58.103078 IP (tos 0x0, ttl  49, id 16401, offset 0, flags [DF],
 proto: TCP (6), length: 160) CLIENT.61736 > NATBOX.http: P 0:120(120)
 ack 1 win 23

10:48:58.366344 IP (tos 0x0, ttl  49, id 16403, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x26af (correct), ack 1 win 23

10:49:04.103204 IP (tos 0x0, ttl  49, id 16405, offset 0, flags [DF],
 proto: TCP (6), length: 160) CLIENT.61736 > NATBOX.http: P 0:120(120)
 ack 1 win 23

10:49:04.363943 IP (tos 0x0, ttl  49, id 16407, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x26af (correct), ack 1 win 23

10:49:16.101583 IP (tos 0x0, ttl  49, id 16409, offset 0, flags [DF],
 proto: TCP (6), length: 160) CLIENT.61736 > NATBOX.http: P 0:120(120)
 ack 1 win 23

10:49:16.363475 IP (tos 0x0, ttl  49, id 16411, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x26af (correct), ack 1 win 23

10:49:40.100796 IP (tos 0x0, ttl  49, id 16413, offset 0, flags [DF],
 proto: TCP (6), length: 160) CLIENT.61736 > NATBOX.http: P 0:120(120)
 ack 1 win 23

10:49:40.563898 IP (tos 0x0, ttl  49, id 16415, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x26af (correct), ack 1 win 23

10:50:28.099396 IP (tos 0x0, ttl  49, id 16417, offset 0, flags [DF],
 proto: TCP (6), length: 160) CLIENT.61736 > NATBOX.http: P 0:120(120)
 ack 1 win 23

10:50:28.761678 IP (tos 0x0, ttl  49, id 16419, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x26af (correct), ack 1 win 23

10:52:04.093668 IP (tos 0x0, ttl  49, id 16421, offset 0, flags [DF],
 proto: TCP (6), length: 160) CLIENT.61736 > NATBOX.http: P 0:120(120)
 ack 1 win 23

10:52:04.093678 IP (tos 0x0, ttl  48, id 16421, offset 0, flags [DF],
 proto: TCP (6), length: 160) CLIENT.61736 > WEBSERVER.http:
 P 1589600741:1589600861(120) ack 2950613896 win 23

10:52:04.291021 IP (tos 0x0, ttl  49, id 16423, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x25d3 (correct), ack 217 win 27

10:52:04.291028 IP (tos 0x0, ttl  48, id 16423, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > WEBSERVER.http: .,
 cksum 0x7b91 (correct), ack 217 win 27

10:52:04.300708 IP (tos 0x0, ttl  49, id 16425, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x253c (correct), ack 368 win 27

10:52:04.300714 IP (tos 0x0, ttl  48, id 16425, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > WEBSERVER.http: .,
 cksum 0x7afa (correct), ack 368 win 27

10:52:04.301417 IP (tos 0x0, ttl  49, id 16427, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: F,
 cksum 0x253b (correct), 120:120(0) ack 368 win 27

10:52:04.301438 IP (tos 0x0, ttl  48, id 16427, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > WEBSERVER.http: F,
 cksum 0x7af9 (correct), 120:120(0) ack 368 win 27

10:52:04.498875 IP (tos 0x0, ttl  49, id 16429, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > NATBOX.http: .,
 cksum 0x253a (correct), ack 369 win 27

10:52:04.498881 IP (tos 0x0, ttl  48, id 16429, offset 0, flags [DF],
 proto: TCP (6), length: 40) CLIENT.61736 > WEBSERVER.http: .,
 cksum 0x7af8 (correct), ack 369 win 27

Comment: Could you add the output for: 'iptables -vnL FORWARD' and 'iptables -vnL -t nat' ? If you are using 'src host' on tcpdump, that is the problem for which you dont see traffic coming back, just use 'host'
Comment: 'iptables -vnL FORWARD' is empty, nat table only has the one NAT rule in PREROUTING chain.
Comment: iptables -vnL -t nat , should shows how many packet hit the rule .
Comment: Chain PREROUTING (policy ACCEPT 38 packets, 11645 bytes)
 pkts bytes target     prot opt in     out     source               destination
    2   232 DNAT       tcp  --  eth0   *       0.0.0.0/0            0.0.0.0/0           tcp dpt:80 to:WEBSERVER:80
Comment: So 38 packet matching your rule. Is it increasing fastly while accessing through http
Comment: yes, once the connection "established". not sure why it stuck in the middle "HTTP request sent, awaiting response..." for serveral minutes and then turned out ok.
Comment: Did you enable ip forwarding on NAT_BOX ?
Answer: Does WEBSERVER knows that CLIENT ia reachable through NAT BOX? D'u'wanna SNAT CLIENT to look like NAT BOX for WEBSERVER, don't ya?
Comment: I'm doing triangle routing, the WEBSERVER SNAT return packets directly to CLIENT, which seems working fine, just not sure why it needs to wait serveral minutes in the middle.
Comment: I'm not sure you know what you're doing. As it's usual it's better describe what you wan't to achieve, not how you're trying. Why does dump show Client -> Natbox? Isn't it supposed to be transparent? If not, the simplest thing is proxy (even xinetd) @ Natbox.
Comment: Basically what I want to do is CLIENT->NATBOX->WEBSERVER->CLIENT. so NATBOX route HTTP packets to WEBSERVER use DNAT, WEBSERVER return respose to CLIENT use SNAT bypassing the NATBOX. It looks like it's working as expected, the client will eventually get the webpage requested. but the things is I'm not sure why it takes so long to finally process the request, so I tcpdump the NATBOX and see some of the packets doesn't seem to be DNAT/routing to the WEBSERVER. Something I'm missing?
Answer: It seems like the kind of routing you are trying to setup is called Direct Routing. It is usualy used to load-balance traffic between servers (it allows to avoid the router bottleneck from the server to the client as the path is direct in this direction).
You can find a detailed explaination of Direct Routing configuration and theory on LVS site.
Comment: thanks for the info, it seems Direct Routing is a little bit different as the boxes needs to be in a physical segment. The one I'm trying to setup doesn't need to be in a physical segment.

Linux, some packets are not being NAT


Would someone be able to give me a basic understanding of s(x1), s(x2), s(x3), etc. terms work in R Generalized Additive Models (GAM)?

Question: Hi there would someone be able to explain to me how the s(x1) terms work in the GAMS?
For instance in the equation:
gam(response ~ s(x1) + s(x2) + s(x3))

Would each smoother variable be "accounting for the influence on each other and on the response" after than gam was ran? In other words, would the graph produced between the response variable and x1 also account for the influence of x2 and x3 on the response? If not, if there a way to account for this interaction?
In addition to this, I'm wondering if this was a built model for one dataset could it be used on a different dataset to predict and generate values for the response variable of interest if I had data for x1, x2, and x3?
I'm admittedly a beginner to GAMs in R so I'm having a hard time even knowing that vocab to find out how to understand this problem. I really appreciate any advice or insight anyone has.
Comment: These are very basic questions which are answered by basic documentation and tutorials. GAM stands for "generalized additive model", note the "additive" part. That means your example doesn't model interactions. However, mgcv provides interaction smoothers, see `help("te")`. Study `help("predict.gam")` to learn how to predict from the model with new data.
Answer: I provided the following answer to exactly the same questions sent to me directly by email. I hadn't noticed that this had been asked on [so] or here before replying privately.
GAMs work just like other regression models, they just don't enforce a particular parametric relationship between covariates and the response.
The model
gam(y ~ s(x1) + s(x2) + s(x3)

estimates smooth effects of x1 conditional upon the smooth effects of the two other covariates, and vice versa. But then you mention "interaction" so I wonder if you mean is the effect of x1 allowed to vary with either one or both of the other covariates' effects? If so, no; this model is an additive model.
If you want the equivalent of an interaction but for smooths, you would need to fit
gam(y ~ te(x1, x2, x3))

but you'd need a lot of data to estimate a 3D smooth like this because of the curse of dimensionality.
You can use GAM for prediction; mgcv has a predict() method where you can supply new values of the covariates. Just be careful not to predict outside the observed range of your covariates unless you know what you are doing and what the implications are.


Points $S$ and $T$ are on side $\overline{CD}$ of rectangle $ABCD$ such $ \overline{AS}$ and $\overline{AT}$

Question: Points $S$ and $T$ are on side $\overline{CD}$ of rectangle $ABCD$ such $\overline{AS}$ and $\overline{AT}$ trisects $\angle DAB$. If $CT = 3$ and $DS = 6$, then what is the area of $ABCD$?
I have drawn the picture but what can you do next? Are there similar triangles or ratios to do? This question is pretty urgent. It is really hard for me. Thanks for helping!
Answer: Hint: $m\angle DAB=90^\circ$, so $m\angle DAS=30^\circ=m\angle SAT=m\angle BAT$. See that $\tan30^\circ=\dfrac{1}{\sqrt{3}}=\dfrac{6}{DA}$, assuming that $S$ is the point on $CD$ closest to vertex $D$. Thus, $DA={2\sqrt{3}}$.
Comment: Oh thanks, we've found one side but how about the other side. DS=6 and CT=3 When I drew my rectangle, CT looked equal to ST. Is that true?
Comment: @user139617 Not necessarily.
Comment: ok, if that doesn't work how do you fidn the length of the extra side


Extract first character of word to create acronym

Question: How do i use split or stringtokenizer to get only the 1st character of each word to create an acronym? It would also include the '&' symbol. And it isn't case sensitive
exmaple:

Some Kind Of Long String ---> SKOLS
another Kind of Long String ---> AKOLS
string & string ---> s&s

The reason for this is because i have a query that populates a table, and since the column name are 3 or more words each. it stretches the table, even with a scroll bar placed, 100+ columns with long names would make it look really long. So i would like to reduce space by using only acronyms and generating a legend.
Comment: The way this site works is that you post your code and we help you get it right.
Comment: I didn't really know if it mattered since this code isn't related to any important processes. I just wondered if i could shorten out the column names queried from the database since 100 or so column would mean a lot of scrolling
Answer: First you need to split the String at either " " or "&".
You can use the "split" method for String. http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)
The regular expression would be either space or ampersand.
Then you would use the charAt method to get the character at index 0. You would concatenate the characters to get the acronym.
Comment: Yes i was able to breakdown the string using split with " " as the delimiter. I just didnt know how to only get the first character of each string array. thanks for that


What are the charges/action against sledging in cricket?

Question: Sledging is used to diverse a Player's mind from his game and make him difficult to concentrate on his game which affects its performance in the game.
Sledging is used as master weapon by many international cricket teams like Australia,England and West Indies.

What are the charges specified against the sledging?

a specific time of ban,match fees amount or any other charges.

Is there any cricketing rules specified for sledging?

I know an incident between Harbhajan–Symonds incident (Monkey-Gate).In which it was considered an offence of sledging Andrew Symonds by Harbhajan Singh in which a three match ban was proposed and then lifted out because of not having a proof but he was charged under Level 2.8 offence (abuse and insult not amounting to racism) to which he pleaded guilty and was fined 50 per cent of his match fees.

In such a case What if whole team is found guilty ?

will all of them will be considered guilty and banned for playing the considered cricket matches ?

Who takes the amount of fine ?

the money taken as fine belongs to whom the player who was sledged or the team to which the player belongs or the ICC
Comment: I read the [Law 42 (Fair and unfair play)](http://www.lords.org/mcc/laws-of-cricket/laws/law-42-fair-and-unfair-play/). But I could not find anything about it. Really looking for a good answer. +1. However, I am not sure if there are *specified* charges for sledging since the sledging can have different level. It's totally up to match referee IMO.
Answer: Sledging is essentially just trash talk to distract the opposing team/player. It's part of every competitive sport. There are no specific charges or rules for such a thing. That being said, it's commonly mistaken for poor sportsmanship, verbal abuse or personal abuse in which case its taken more seriously. It's then up to the referee to decided how severe it is and what the penalty should be.
Really, it's a hot topic. It's a debate that's been going on for a long time and not just in cricket itself. I think it adds some fun, playful humour and good ol' competition to the game but there is a line, and when it's crossed the ref will make the call.
Comment: banter is part of cricket, seldging isnt going anywhere :o)


ADF Pipeline Expression Builder - Concat Parameters & functions

Question: I need help writing the correct expression for a REST API connection I´ve build in a ADF pipeline.
I need to dynamiclly change the created_since and created_before values in the URL to be active based on todays date. I need to filter by the last 2 weeks.
I´m trying to acheive this by keeping the Base URL the same without these two values and then add a expression into the Relative URL to change these two filters.
the result should be something like this:
API.API.co.uk/api/get-clients/campaigns? limit=100&offset={offset}&created_since=2023-08-18%2007%3A29%3A25&created_before=2023-08-17%2008%3A29%3A25
this works as i´ve tested it outside of ADF however I need the values to change automatically and not be hard coded.
I´m using the Concat funcion to join up the two string parameters and the UTCnow functions available in the expression builder however it doesnt like it.
heres the expression I´ve got:
@concat(dataset().{created_before},formatDateTime(utcnow(),'yyyy-MM-dd HH:mm:ss'),dataset().{created_since},formatDateTime(addDays(utcnow(),-1),'yyyy-MM-dd HH:mm:ss'))

here´s a look at the two parameters I´ve set up.
parameters
I´ve also tried a few different ways by adding variables directly into the base URL and then using query parameters and normal parameters to change the dates however I couldnt get these to work either. is there a better way to do this??
Answer:
API.API.co.uk/api/get-clients/campaigns? limit=100&offset={offset}&created_since=2023-08-18%2007%3A29%3A25&created_before=2023-08-17%2008%3A29%3A25

To get the URL like that, follow the below approach.
First create the dataset parameters for the created_since and created_before.

Now, use these parameters in the URL. Here, for demo I am using your URL and I am using the dataset parameters in the Relative URL.
Change the Base and relative URL as per your requirement but use the parameters at the values of the dates by using string interpolation(@{<dataset parameter>}).
?limit=100&offset={offset}&created_since=@{dataset().created_since}%2007%3A29%3A25&created_before=@{dataset().created_before}%2008%3A29%3A25

Now, in the copy activity, it will ask the values for the dataset parameters. Here, use the utc functions to give the date.
Here, for demo I am giving the yesterday date for created_before
@adddays(utcNow(),-1,'yyyy-MM-dd')

and today date for created_before.
@utcNow('yyyy-MM-dd')

Change the dates as per your requirement.

Here, ignore that my copy activity failed because it's not a valid URL. But you can see in the error that I got the desired URL.
Comment: thanks. follow up question. do I need the "%2007%3A29%3A25" part of the below URL or just the dataset parameters?

?limit=100&offset={offset}&created_since=@{dataset().created_since}%2007%3A29%3A25&created_before=@{dataset().created_before}%2008%3A29%3A25
Comment: If '%2007%3A29%3A25' this is a static part of your URL, then you can use the above approach. If it is a dynamic part, you need to create dataset parameters for it as well.
Comment: okay thanks. It´ll have to be a dynamic part so I´ll remove this and just try with the "&created_since=@{dataset().created_since}" part
Comment: I´ve added it like you said but its saying its in the wrong format? I´ve added a screenshot of the new parameters i´ve set as per your screenshots

Rest call failed with client error, status code 400 BadRequest, please check your activity settings.
Request URL: https://abbotts.fastdox.co.uk/api/get-clients/campaigns?limit=100&offset=0&created_before=%7Bcreated_before%7D&created_since=%7Bcreated_since%7D.
Response: {"created_since":["The created since does not match the format Y-m-d H:i:s."],"created_before":["The created before does not match the format Y-m-d H:i:s."]}


How to create a Privatemsg thread with multiple recipients in a Rules component?

Question: I'd like to send private messages to a selected group of users. For this purpose I use a view with VBO and a Rules component action (utilizing the "Send message" action provided by Privatemsg) - as  described in this question.
However, I still have a minor issue with it: Since I send the messages looping through the list of users, privatemsg module sends individual messages and doesn't create a thread with multiple users. Is it possible to use the whole array of users in a single "Send message" action?
Probably one solution might be to use cutoms PHP code in rules component and create thred with privatemsg_new_thread function. But it's not a very drupalish way, I guess.
Answer: I found a solution using a rule component with custom php code. It needs some changes in privatmsg module, see in this discussion: https://www.drupal.org/node/2725325


Does serial correlation have something to do with endogeneity?

Question: I'm a beginner of econometrics, and I've construed that endogeneity is caused by omitted variable bias, measurement error, and reverse causality, and it makes OLS estimator be biased.
And also I've learned that serial correlation which refers to correlation among the error terms makes variance-covariance matrix not to be identity matrix, which may eventually makes OLS estimator be inefficient.
However, famous free youtube channel 'ben lambert' offers lectures and I've just seen that serial correlation is sometimes caused by omitted variable bias, measurement error etc. If it's the case, then it seems omitted variable bias not just lead to biased estimator but also inefficient estimator at the same time.
How should I understand this lecture?
Answer: I am answering under the supervision of CV's peers. Be critical.
Assume one has the following model specification
$$\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{u}$$
where $\boldsymbol{y}$ is a $n \times 1$ vector, $\boldsymbol{X}$ an $n \times k$ matrix, $\boldsymbol{\beta}$ a $k \times 1$ hyperparameter and $\boldsymbol{u}$ a $n \times 1$ vector of homoscedastic but autocorrelated residuals. At this stage we still do not know how those are autocorrelated.
Assume that one omitted to include another variable, say a $n \times 1$ vector $\boldsymbol{z}$, whose endogeneity consists of its autocorrelation such that
$$\boldsymbol{z} = f(\boldsymbol{z})$$
where $f$ is assumed to be a bijective/invertible vector function which specifies the correlation structure between the $n$ components $z_{i=1,...,n}$ of $\boldsymbol{z}$.
This means that $\boldsymbol{u}$ is hiddenly generated as follows (where $\gamma \neq 0$ is a scalar parameter and $\boldsymbol{v}$ is $n \times 1$ vector of errors assumed to be iid normal.)
$$\boldsymbol{u} = \gamma\boldsymbol{z} + \boldsymbol{v} \iff \frac{1}{\gamma}(\boldsymbol{u}-\boldsymbol{v}) = \boldsymbol{z} \iff f\left(\frac{1}{\gamma}(\boldsymbol{u}-\boldsymbol{v})\right) = f(\boldsymbol{z})$$
But since one has $\boldsymbol{z} = f(\boldsymbol{z})$, the above last equivalence can be turned into an equality. Which leads to
$$\frac{\boldsymbol{u}-\boldsymbol{v}}{\gamma} = f\left(\frac{\boldsymbol{u}-\boldsymbol{v}}{\gamma}\right) \iff u = f\left(\frac{\boldsymbol{u}-\boldsymbol{v}}{\gamma}\right)\gamma+\boldsymbol{v}$$
Which shows that even if the correlation is not the same as the one there is between the components of $\boldsymbol{z}$, it does exist.
Thus yes serial correlation does have something to do with endogeneity when, e.g., this endogeneity consists of an omitted autocorrelated variable whose autocorrelation structure is invertible.

But actually, it is very unlikely that $f$ be invertible. I mean that, if autocorrelation works through time, $f$ is the backshift operator, and it is not invertible.
Comment: Any question or remarks @KevinKang ?
Answer: For OLS, we usually assume that observations are independent each other. If we write this in equation, $y_i = x'_i \beta + \epsilon_i$ and we assume $\epsilon_i$ and $\epsilon_j$ are independent if $i \not= j$.
Serial correlation violates this independence assumption; $\epsilon_i$ and $\epsilon_j$ are not independent.  This can be caused by various reasons, and omitted variables are one possibility.  An easy example where an omitted variable causes serial correlation is a case where $\epsilon_i = u_{i} + u_{i-1}$, where $u_i$ is an unknown random variable and shared across multiple observations.  If $u$ and $x$ are correlated, the OLS estimates are biased due to the endogeneity.  This may also reduce the efficiency due to the smaller variation across observations.
That said, the omitted variables do not always cause serial correlation. Suppose $\epsilon_i = u_{i}$.  This can cause endogeneity if $u$ and $x$ are correlated.  However, serial correlation may not occur if $u_i$ are independent from each other.


Mailgun laravel 4.2 change version "v2" to "v3"

Question: I'm working with Laravel 4.2 and Mailgun.
The base url of the api of mailgun changed, now it's https://api.mailgun.net/v3/..........
When I perform a request with Laravel it looks like : https://api.mailgun.net/v2/.........
I checked the Facade who handle that :
// vendor/laravel/framework/src/Illuminate/Mail/Transport/MailgunTransport.php
/**
 * Set the domain being used by the transport.
 *
 * @param  string  $domain
 * @return void
 */
public function setDomain($domain)
{
    $this->url = 'https://api.mailgun.net/v2/'.$domain.'/messages.mime';

    return $this->domain = $domain;
}

The version is hardcoded ... How I can change that properly ?
Answer: Laravel 4.2 was build with mailgun v2. You could probably change v2 to v3 in the code and it would probably work since v3 of mailgun is backwards compatible. (http://blog.mailgun.com/default-api-version-now-v3/) But its not the nicest solution.
You could use an external dependancy like https://github.com/Bogardo/Mailgun that uses mailgun v3 api.
Answer: I'd suggest making a code change to the code for the class with the problem, and submitting it back to Laravel's Github as a pull request.
I agree with you that it looks totally hard coded and can't be changed other than doing this, so that seems to be your best bet.
One thing to beware of though: I don't know the mailgun API, but if it's gone from v2 to v3, that implies there have been some breaking changes to the API, so don't think you can just change the number '2' into a '3' and expect it to work; you'll probably also need to change the code that makes the relevant API calls.
Comment: Just checked the API of mailgun, they are smart, you can still use the API without problems ;) (Still doesn't work with my mail config, but i will go ahead and see what's happening there)


Remove SKU label from product reference select list

Question: Is there a way to remove/hide the SKU value in the product reference widget (select list)? Because we don't want to show the SKU value to the editors.
Answer: In a custom module (or theme) you could implement hook_field_widget_WIDGET_TYPE_form_alter() and alter the labels of the options (i.e., stored in the $element['#options'] variable). If I'm not mistaken your function would be mymodule_field_widget_options_select_form_alter(&$element, &$form_state, $context), where mymodule is your custom module (theme) name. Don't forget to check for which field you're altering the options, you can find this in $context['field']['field_name'].
If you don't want to write custom code, you could as an alternative use the Entity reference module in combination with Views. Hereby you can use the output generated by a view as an option list for the (entity) reference field (pointing to your product).
Comment: @Nagarjuna, did it solve your problem?
Comment: That worked @watergate. have a look at my answer
Answer: function <mymodule>_field_widget_options_select_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_<fieldname>') {
    foreach ($element['#options'] as $key => $values) {
      $value = explode(':', $values);
      $element['#options'][$key] = trim($value[1]);
    }
  }
}

I hope this helps some one.
Comment: I see in your code that you're using explode() to get the value (i.e., label), but I was wondering if this label isn't available in the $element variable?
Answer: I found Nagarjuna's code useful. I modified it to allow me to accommodate more than one field. In case someone can find it useful, I included the code below:
function <mymodule>_field_widget_options_select_form_alter(&$element, &$form_state, $context) {

  $affected_fields = array('field_<field_1>','field_<field_2>','field_<field_3>','field_<field_4>');

  if(in_array($context['field']['field_name'], $affected_fields)) {

    foreach ($element['#options'] as $key => $values) {
      $value = explode(':', $values);

      if(isset($element['#options'][$key])) {
        if(isset($value[1])) {
          $element['#options'][$key] = trim($value[1]);
}
}

}
  }
  }


Strange Change in ssh behavior + LDAP

Question: We have a cluster with a front node that admits normal users and LDAP users. Two days ago the ssh show a strange behavior:

The LDAP users can't login in the front node using password
but, The LDAP users can login if they setup ssh-key in authorized_keys
normal users (No LDAP, /etc/passwd ones) can login without problems
Other services using the same LDAP server works right

So, I think is a problem located in the front node. The LDAP appears to work, using getent [passwd|shadow] command we are getting all users.
At the same time, the ssh show a warning/error when we login from this node to other nodes. But it allow the ssh anyway:
[root@frontnode ~]# ssh othernode
/etc/ssh/ssh_config line 50: Unsupported option "GSSAPIAuthentication"
[root@othernode ~]#

Also, When I restart the ssh daemon, we have also errors related to GSSAPI:
[root@frontnode ~]# service sshd restart
Stopping sshd:                                             [  OK  ]
Starting sshd: /etc/ssh/sshd_config line 81: Unsupported option GSSAPIAuthentication
/etc/ssh/sshd_config line 83: Unsupported option GSSAPICleanupCredentials
/etc/ssh/sshd_config line 97: Unsupported option UsePAM
                                                           [  OK  ]

No one changed ssh configuration, neither sshd configuration. And was working until now. We don't know what the problem is.
The login node is a Scientific Linux release 6.2 (redhat based)
Comment: Please show us `passwd` and `shadow` entries in `/etc/nsswitch.conf`.
Answer: It looks like sshd or some libraries got changed on the front node.
The UsePAMoption is what would allow you to login with LDAP stored passwords.
Troubleshooting steps

You should check your /var/log/yum.log for any package changes.
Do you have a configuration management system running there? Make sure no one put in a new sshd binary.
Check for rootkits using chrootkit or rkhunter.

Cleanup
Now that you have determined that there is a rootkit, you need to ensure that everyone changes their passwords and recommend that they change their passwords on other sites, too.
The safest option for cleanup is to reinstall and restore from a backup before this started. You can never really know if some seemingly innocuous file got modified and will reinfect after you clean up.
Comment: @Zhen If you're saying that reinstalling yum fixes the binary, but the binary gets overwritten again shortly afterwards, we cannot help you with this problem. Either a user on the system or some sort of automated job (configuration management) is overwriting it.
Comment: Do you have a configuration management system running there? Make sure no one put in a new sshd binary. Also, run a rootkit hunter like chrootkit or rkhunter.
Comment: Yes, sshd binary is change, but is the same yum version that the one in the rpm package. I reinstalled it with yum, and work again. But in no time some process change it again back to wrong binary.
Comment: thank, was a rootkit, we are in process to remove it. I you put as an answer I can accept it.
Comment: So sorry to hear that. I wish you the best in cleaning up.

Strange Change in ssh behavior + LDAP


Expressão Regular que impossibilita SQL Injection

Question: Estou procurando alguma maneira de evitar SQL Injection no sistema que estou desenvolvendo.
Existe alguma expressão regular que percebe a tentativa de uma possível tentativa de SQL Injection?
Vocês sabem alguma outra forma de evitá-la? Às vezes pode até existir melhores formas de prevenção mas ainda desconheço.
Comment: Expressão regular pra tratar SQL Injection? Não é melhor usar algum recurso pronto que trate disso usando parâmetros nas _queries_? Aliás, qual a linguagem?
Answer: As SQL injections em geral possuem =ou ;, elas basicamente são constituidas em 2 grupos, "Always true" ou "Batched SQL Statements".
Sugiro que use uma regex que capture um desses caracteres citados no input e faça um tratamanto ou dê algum erro e não complete a transaction para o BD. Como não foi citado o flavour da regex ou linguagem de desenvolvimento, vou utilizar o flavour mais comum, o utilizado por php.
(.*?[=|;].*)

Explicação:

() delimita o que será capturado
.*? implica que qualquer caractere exceto quebras de linhas serão capturado até chegar a limitação.
[=|;] é a limitação onde o .*?, deve parar, implica uma condição para captura, deve ser capturado todos aqueles caracteres apenas se houver = OU (|) ;
.* implica que após a captura do carácter obrigatório (= ou ;) capturará todos os caracteres até o fim da linha.

Isso deve ajuda-lo, caso o flavour da regex for diferente, edite sua pergunta que eu editarei essa regex para melhor atende-lo.
Você pode testar a regex que te falei aqui
Comment: Muito obrigado! A linguagem é exatamente PHP. vou utilizar dessa forma


How do you simplify an equation for only integer inputs?

Question: I've been trying to simplify an equation for the last few weeks. Below is the initial equation:
$y(n) = -\frac{3+2n}{8}(-1)^{\frac{2n+1-(-1)^n}{4}}+\frac{1}{8}(-1)^{\frac{6n+1-(-1)^n}{4}}+\frac{1}{4}(-1)^{\frac{2n+1-(-1)^n}{2}}$
This equation outputs a result of 0,0,1,1,-1,-1,2,2,-2,-2,3,3,... for integer inputs.
While this equation works fine, it is quite ugly. I have tried simplifying it a few different ways, but ultimately the best form I was able to get is shown below:
$y(n) = \frac{i^n}{8}[(1+n)(1+e^{i\pi n}) +i(2+n)(1-e^{i \pi n})]+\frac{1}{4}$
While this function has different complex components than the original, this does not matter to me. I am interested in preserving the output for given inputs, and do not care what happens to the equation on non-integer inputs.
Does anyone have any clever ideas of how to simplify my equation further while preserving the output for integer inputs?
For those interested, if y(n) is plotted against y(n+1), it forms a square spiral.
Do you know of any similar problems where you simplify an equation based on only certain inputs?
Comment: Well, it looks like $y(2n)=y(2n+1)=(-1)^{n+1}n$ for $n\in \{0,1,2,3,\cdots\}$, assuming your values start at $y(0)$.
Comment: How about $y(n)=\frac{1}{4} \left((n+2) \sin \left(\frac{\pi  n}{2}\right)-(n+1) \cos \left(\frac{\pi
   n}{2}\right)+1\right)$?
Comment: Fabian, I could you briefly describe how you got that?
Answer: The OEIS sequence A242601 "Integers repeated twice in a canonical order" is what you have. The formula given there using the floor function is $\, a_n = \lfloor{(n+2)/4}\rfloor (-1)^{\lfloor{(n+2)/2}\rfloor}.\,$


Load time of Laravel

Question: I'm currently working on Laravel 4 and bootstrap.css. I'm currently designing/implementing the front-end/back-end features, and couldn't help, but notice, that the performance of serving my resources is really slow.
My system config is:
- am developing on localhost.
- have set the database host to 127.0.0.1 (in case it does matter)
- Ubuntu, Mysql, php

and found out that it's not the db which is the one responsible for the performance issue. Most responses are served between 700 and 800ms. But the page render takes around more then 5 seconds which is insanely slow (yet again: I'm on local). This problem is persistence in production environment too.
Comment: I am using apache server. The issue is that the page gets the view but the completes rendering after sometime.
Answer: Simply Use this code
This page took {{ (microtime(true) - LARAVEL_START) }} seconds to render

Output Likes :
This page took 0.1246546165498 seconds to render

Answer: Do you use php artisan serve or apache/nginx? The built in PHP webserver does not cache anything, so it'll have to reload everything on every request. Additionally, you might want to try something that minimizes your CSS/Javascript, like Asset Pipeline, or Laravel Guard.
You could also install the Laravel Debugbar, which shows you which queries are fired, how long a request took, the memory usage, and more. Using the debugbar slows down pageload a bit, but it does give you more insight into why your pages are slow.
Comment: another really great and powerful tool is Clockwork (https://github.com/itsgoingd/clockwork) which profiles your laravel and makes it viewable within chrome dev tools (requests, sql queries, used routes, ...). maybe this points you into the right direction.

Load time of Laravel


I'm having trouble using the Model I wrote

Question: I wrote a model like this:
List<School> schools = [
  School(city: "ISTANBUL", name: "Exam1"),
  School(city: "ISTANBUL", name: "Name2"),
  School(city: "ISTANBUL", name: "Name3")
];

List allSchools() {
  return schools;
}

class School {
  String city;
  String name;
  School({required this.city, required this.name});
}

I want to be able to use city and name values in the list in Flutter.
Flutter codes:
  TextFieldSearch(
    decoration: InputDecoration(
      hintText: "Select School",
      prefixIcon: const Icon(
        Icons.search,
        color: Colors.black45,
      ),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8.0),
        borderSide: BorderSide.none,
      ),
      filled: true,
      fillColor: const Color.fromARGB(255, 229, 229, 229),
    ),
    initialList: allSchools(),
    label: "",
    controller: _schoolController,
  ),

How can I use model and list together? I hope you understand my point. Thanks in advance for your help.

Error
Comment: are you using this [package](https://pub.dev/packages/textfield_search)?
Comment: Yes @eamirho3ein.
Answer: The package you used only support one string, there is a workaround for that which is convert your schools list to a newlist like this:
List<String> newList = schools.map((e) => '${e.city}-${e.name}').toList();

and use this list to build your TextFieldSearch.
For cleaner code you can separate this widget like this:
Widget buildSearchField(List<School> schools) {
    List<String> newList = schools.map((e) => '${e.city}-${e.name}').toList();

    return TextFieldSearch(
      decoration: InputDecoration(
        hintText: "Select School",
        prefixIcon: const Icon(
          Icons.search,
          color: Colors.black45,
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.0),
          borderSide: BorderSide.none,
        ),
        filled: true,
        fillColor: const Color.fromARGB(255, 229, 229, 229),
      ),
      initialList: newList,
      label: "",
      controller: _schoolController,
    );
  }

and use it like this:
buildSearchField(allSchools()),

Comment: Hello, thanks for your reply. I got an error like this => https://imgur.com/a/GJzrY9E
Comment: I can't see your image, could you edit your question and add there?
Comment: I did what you said and edited the question.
Comment: change this: `List allSchools() {` to this: `List allSchools() {`