text:
Q: C# WinForms ListView Item Count Change Event Is there an event in Win Forms that can fire when the count of items in ListView change?  I tried Size and Text - oddly enough they "sorta" worked but not always...
Im trying to trigger a label to update with the count of the listview items as it changes without manually doing that in a hundred methods.

A: If you are not using a bound datasource you can create a wrapper around the ListView Control and add a Method and an Event to fire off an event on adding an item to your ListView Collection.
Custom ListView
public class customListView : ListView
{
    public event EventHandler<CustomEventArgs> UpdateListViewCounts;
    public void UpdateList(string data)
    {
        // You may have to modify this depending on the
        // Complexity of your Items
        this.Items.Add(new ListViewItem(data));
        CustomEventArgs e = new CustomEventArgs(Items.Count);
        UpdateListViewCounts(this, e);
    }
}
public class CustomEventArgs : EventArgs
{
    private int _count;
    public CustomEventArgs(int count)
    {
        _count = count;
    }
    public int Count
    {
        get { return _count; }
    }
}

Example Usuage
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();

        customListView1.UpdateListViewCounts+=customListView1_UpdateListViewCounts;
    }

    private void customListView1_UpdateListViewCounts(object sender, CustomEventArgs e)
    {
        //You can check for the originating Listview if
        //you have multiple ones and want to implement
        //Multiple Labels
        label1.Text = e.Count.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        customListView1.UpdateList("Hello");
    }

}


text:
Q: How to fix Google Authentication DB access issue in Odoo v13 I have configured the Google Authentication from 'General Settings->Integrations' and provided the Client ID and got the 'Login with Google' button in Login page.
When I provide the gmail details, it creates an user in database and redirects back to login screen with an error like - 'Only employee can access this database. Please contact the administrator.'
How it can be fixed? I'm trying to implement that, any user can login to Odoo through Gmail credentials. Please guide me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Duplicating Div always duplicates TO BETTER UNDERSTAND MY QUESTION AND SEE CODE VISIT THE FIDDLE: http://jsfiddle.net/dnyXC/
I have a script (below) that allows you to click a icon and it duplicates the table allowing for more inputs on the included form. This issue is, once you click the icon once to duplicate it, anywhere you click on the table regardless of position duplicates the table again.
document.getElementById('line-duplicate').onclick = duplicate;
    var i = 0;

        function duplicate() {
            var original = document.getElementById('item-table' + i);
            var clone = original.cloneNode(true); // "deep" clone
            clone.id = "item-table" + ++i; // there can only be one element with an ID
            clone.onclick = duplicate; // event handlers are not cloned
            original.parentNode.appendChild(clone);
        }

Here is the html for the table:

    Item Name
    Qty/Hrs
    Rate
    Tax Rate
    Type
    Cost
    Actions

        <input class="input-medium" type="text" name="" />

        <input class="input-mini" type="text" name="" placeholder="1" />

        <input class="input-mini" type="text" name="" placeholder="0.00" />

        <select class="input-small" name="">
            <option>Standard</option>
            <option>Expense</option>
        </select>

    $0.00

endless duplication is fine, the issue is when you go to type another item into the form, you duplicate the table. I need it so that the only way to duplicate the table is by clicking the plus icon.
TO BETTER UNDERSTAND MY QUESTION AND SEE CODE VISIT THE FIDDLE: http://jsfiddle.net/dnyXC/

A: The issue is that you are binding the onclick for the entire duplicated row to the duplicate() function.
You should make line-duplicate a class (having multiple elements with the same ID is a bad thing), and use document.getElementsByClassName('line-duplicate') both inside and outside the function to bind the duplicate function to every single element with that class name, like so:
document.getElementsByClassName('line-duplicate')[0].onclick = duplicate;

var i = 0;

function duplicate() {
    var original = document.getElementById('item-table' + i);
    var clone = original.cloneNode(true); // "deep" clone
    clone.id = "item-table" + ++i; // there can only be one element with an ID
    original.parentNode.appendChild(clone);
    var listOfLineDuplicateItems = document.getElementsByClassName('line-duplicate'); // this must be after the table has been appended to the DOM
    for (var j = 0; j < listOfLineDuplicateItems.length; ++j) {
        listOfLineDuplicateItems[i].onclick = duplicate;
    }
}

Here's a JSFiddle.


text:
Q: Creating numbered dictionaries with a For loop [python] For 18 different links, I'm trying to create 18 different dictionaries (one for each area of land demarcated in the links) which each contain keys and values for statistics like population, housing units in area, etc.  The key is the name of the statistic, and the value is the value.  I've written the part that iterates through all 18 links and retrieves the population and housing units (and their values), but I can't figure out how to make the dictionaries.  I tried using a for loop like so:
def bgScrape(self):
        i = 0
        for l in self.hrefs:
            html = urlopen('http://www.usa.com' + l)
            soup = BeautifulSoup(html.read(), 'lxml')
            stat = soup.find('table')
            stat = stat.find_next('table')
            population = stat.find('td')
            population = population.find_next('td')
            population1 = population.find_next('a')
            population1 = population1.find_next('a')
            houseunits = population1.find_next('td')
            houseunits1 = population1.find_next('a')
            print(houseunits1)
            for i in range(18):
                stats[i] = {}
                stats[i]['Population'] = population1.text

but this gives me NameError: name 'stats' is not defined, which has led me to believe you can't make dictionaries in a For loop like this.  Is this the case, or am I just writing it incorrectly?  Or is there a better way to achieve this goal entirely?

A: You can replace the whole second loop
for i in range(18):
    stats[i] = {}
    stats[i]['Population'] = population1.text

by :
stats = [{'Population' : population1.text} for i in range(18)]


text:
Q: Where is my implementation of rot13 in JavaScript going wrong? Code in question with syntax highlighting here: via Friendpaste
rot13.js:

ERRONEOUS
<script>
String.prototype.rot13 = rot13 = function(s)
 {
    return (s = (s) ? s : this).split('').map(function(_)
     {
        if (!_.match(/[A-Za-z]/)) return _;
        c = Math.floor(_.charCodeAt(0) / 97);
        k = (_.toLowerCase().charCodeAt(0) - 96) % 26 + 13;
        return String.fromCharCode(k + ((c == 0) ? 64 : 96));
     }).join('');
 };
</script>

As you can see, using quite literally a single line to attach a method to the String object a la prototyping, I'm having a map() method that I previously set up (I know for sure that that code works perfectly; it's simply iterating over each element in the array and applying the function specified in the parameter) go over each character in a string and do what I thought were the proper calculations to transform the string into it's rot13'd counterpart. I was sadly mistaken. Can anybody spot where I went wrong?

A: You could use the super-short:
s.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});

A: var rot13 = String.prototype.rot13 = function(s)
{
  return (s = (s) ? s : this).split('').map(function(_)
  {
    if (!_.match(/[A-Za-z]/)) return _;
    c = _.charCodeAt(0)>=96;
    k = (_.toLowerCase().charCodeAt(0) - 96 + 12) % 26 + 1;
    return String.fromCharCode(k + (c ? 96 : 64));
  }
  ).join('');
};

alert('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.rot13());
yields nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM

Mixing zero-based and one-based indices for the lose.  I blame Netscape.

A: Here's a version that's 80-columns, doesn't update string.prototype, well indented and reasonably short.
function rot13(str) {
  return str.replace(/[a-zA-Z]/g, function(chr) {
    var start = chr <= 'Z' ? 65 : 97;
    return String.fromCharCode(start + (chr.charCodeAt(0) - start + 13) % 26);
  });
}

And an example showing it is working:
rot13('[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]')
"[nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM]"
rot13(rot13('[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]'))
"[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]"

A: One-liner that weighs in at 116 bytes:
function r(a,b){return++b?String.fromCharCode((a<"["?91:123)>(a=a.charCodeAt()+13)?a:a-26):a.replace(/[a-zA-Z]/g,r)}

Usage:
r('The Quick Brown Fox Jumps Over The Lazy Dog.');

A: Here's a solution using replace and indexOf functions:
function rot13(s) {
  return s.replace(/[A-Z]/gi, c =>
    "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"[
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(c) ] )
}

This is made up of:

*

*/[A-Z]/gi regular expression for matching only characters

*replace is used to substitute those characters

*an a replacer function written as an arrow function

*indexOf is to convert the character into a numeric lookup index

*we lookup the index in the substitution array and we're done

A: There is still room for enhancement, checking (c<="Z") is actually a check against the codepoint (that we need later on), following that idea gives us a win !
//versus Kevin M's  style :  115 chars (vs 116)
//102 chars with nodejs Buffer (see below)
function r(a,b){return++b?String.fromCharCode(((a=a.charCodeAt())<91?78:110)>a?a+13:a-13):a.replace(/[a-zA-Z]/g,r)}
//nodejs style
function r(a,b){return++b?Buffer([((a=Buffer(a)[0])<91?78:110)>a?a+13:a-13]):a.replace(/[a-zA-Z]/g,r)}

//versus Ben Alpert style : 107 chars (vs 112)
//93 chars with nodejs Buffer (see below)
s.replace(/[a-zA-Z]/g,function(a){return String.fromCharCode(((a=a.charCodeAt())<91?78:110)>a?a+13:a-13)});
//nodejs style
s.replace(/[a-zA-Z]/g,function(a){return Buffer([((a=Buffer(a)[0])<91?78:110)>a?a+13:a-13])})

// Same code, formated for production
String.prototype.rot13 = function() {
  return this.replace(/[a-zA-Z]/g, function(a){
    return String.fromCharCode(((a=a.charCodeAt())<91?78:110)>a?a+13:a-13);
  });
}

In nodejs, you can use Buffer to cast/serialize codepoints, e.g. :
var a=65;
""+Buffer([a])           == "A" // note that the cast is done automatically if needed
String.fromCharCode(a)   == "A"

var b="A";
Buffer(a)[0]             == 65
a.charCodeAt()           == 65

A: My golfed version is 82 bytes long (vs. Ben Albert, which is 35% heavier, but inspired mine):
S.replace(/[a-z]/gi,c=>String.fromCharCode((c=c.charCodeAt())+((c&95)>77?-13:13)))
Differences:

*

*case-insensitive to catch only English alphabet.

*arrow functions without return and braces.

*delete parameters from charCodeAt.

*test against code insted of string.

*doing +13-26=-13.

*test uppercased (&95) against 77 (78+13=91, overflow).

Extra: If you want to perform ROT5 on digits, add:
.replace(/\d/gi,c=>(c>4?-5:5)+c*1)

A: Combining various techniques here, I came up with this 78 character JavaScript ES6 function, which works on Node:
rot13=s=>s.replace(/[a-z]/ig,c=>Buffer([((d=Buffer(c)[0])&95)<78?d+13:d-13]));

A: This gives correct results.

function rot13(s)
 {
    return (s ? s : this).split('').map(function(_)
     {
        if (!_.match(/[A-Za-z]/)) return _;
        c = Math.floor(_.charCodeAt(0) / 97);
        k = (_.toLowerCase().charCodeAt(0) - 83) % 26 || 26;
        return String.fromCharCode(k + ((c == 0) ? 64 : 96));
     }).join('');
 }

 alert(rot13(rot13("Mark this as accepted answer :)")));

A: Just because it's even shorter and also more understandable/logical:
function rot13(s) {
  return s.replace( /[A-Za-z]/g , function(c) {
    return String.fromCharCode( c.charCodeAt(0) + ( c.toUpperCase() <= "M" ? 13 : -13 ) );
  } );
}

A: Kevin M's solution is compact and elegant. It's got one tiny error, though: the regular expression used with the replace function doesn't limit substitution to alphabetic characters. The [A-z] character range includes punctuation characters ([\] ^ _ `), which will be swapped for letters when they should be left alone.
The fixed version looks like this:
function r(a,b){return++b?String.fromCharCode((a<"["?91:123)>(a=a.charCodeAt()+13)?a:a-26):a.replace(/[a-zA-Z]/g,r)}

It's still only 116 bytes. Remarkably small and quite clever.
(Sorry for the full answer posting; I'm still lacking the 50 rep required to post this as a comment to Kevin's excellent answer.)

A: Here's a JavaScript library that performs ROT-n letter substitution: https://github.com/mathiasbynens/rot

rot is a JavaScript library that performs rotational letter substitution. It can be used to shift any ASCII letters in the input string by a given number of positions in the alphabet. To ROT-13 the string 'abc', for example:
// ROT-13 is the default
rot('abc');
// → 'nop'

// Or, specify `13` explicitly:
rot('abc', 13);
// → 'nop'

A: This is in no way trying to compete with the excellent stuff here, as you see I can't comment but I have my own novice attempt to write this in JS and getting it to work before I read more elegant solutions here - I'm going to share it here.
I tried to write it with indexOf, a switch, by adding 13, by String.fromCharCode() and CharCodeAt(). They were getting too long - the helper function in this one is unnecessary but this was my shortest : )
function rot13(string) {
  var result = '',
      store,
      str = string.toLowerCase();

  //helper function
  function strgBreak(a){
    var result = [];
    return result = a.split('');
  }

  //rot13 arrays
  var alphArr = strgBreak('abcdefghijklmnopqrstuvwxyz');
  var inverseArr = strgBreak('nopqrstuvwxyzabcdefghijklm');

 for ( var i = 0; i < str.length; i++ ) {
     if (alphArr.indexOf( str[i] ) !== -1) {
        result += inverseArr[ alphArr.indexOf( str[i] ) ];
    } else result += str[i];
  }
 return result.toUpperCase();
}

A: Here's a modern approach to the ROT13 substitution cipher:

const ROT13 = s =>
  s.replace(/[a-z]/gi, c =>
    String.fromCharCode(c.charCodeAt() + 13 - 26 * /[n-z]/i.test(c)));

console.log(ROT13('The quick brown fox jumps over 13 lazy dogs.'));

The result of the test case above is:
Gur dhvpx oebja sbk whzcf bire 13 ynml qbtf.

A: While I really like the RegEx solution, I primarily undertook the project to see if I could get it done. Glad to report that I finally did manage to do so:
String.prototype.rot13 = rot13 = function(s)
 {
    return (s ? s : this).split('').map(function(_)
     {
        if (!_.match(/[A-za-z]/)) return _;
        c = Math.floor(_.charCodeAt(0) / 97);
        k = (_.toLowerCase().charCodeAt(0) - 83) % 26 || 26;
        return String.fromCharCode(k + ((c == 0) ? 64 : 96));
     }).join('');
 }

A: CoffeeScript version of @ben-alpert 's answer:
string.replace /[a-zA-Z]/g, (c) -> String.fromCharCode if (if c <= 'Z' then 90 else 122) >= (c = c.charCodeAt(0) + 13) then c else c - 26

Or as function:
ROT13 = (string) -> string.replace /[a-zA-Z]/g, (c) -> String.fromCharCode if (if c <= 'Z' then 90 else 122) >= (c = c.charCodeAt(0) + 13) then c else c - 26
ROT13('asd') # Returns: 'nfq'

A: My favourite and simple to understand version of decision ROT13
function rot13(message) {
  var a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  var b = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
  return message.replace(/[a-z]/gi, c => b[a.indexOf(c)])
}

a - classic alphabet, b - prepered dictionary with 13th replacement, return result with simple RegEx replacement


text:
Q: Ideas for presenting the research question? I know this is a very open questions, however I am looking for some impressions as I am totally unsure in what style I can do this.
I am writing m bachelor thesis right now and want  to present my final Researchquestion inside my introduction.
I was thinking about an environment which is a bit separated from the rest and looks 'good'.
I was trying something like this:
\framebox[\textwidth]{
\begin{tabular}{@{}ll@{}}
\textbf{Researchquestion 1} & How is this done?\\
\textbf{Researchquestion 2} & What is done?\\
\end{tabular}
}

However there maybe some better (packages?) for doing this?

A: \documentclass{article}

\usepackage{enumitem}

\newlist{questions}{enumerate}{2}
\setlist[questions,1]{label=RQ\arabic*.,ref=RQ\arabic*}
\setlist[questions,2]{label=(\alph*),ref=\thequestionsi(\alph*)}

\begin{document}
    \begin{questions}
        \item This is a research question.
        \item This is another research question.
        \item This is a research question with a label.\label{itm:qwithlabel}
    \end{questions}

    \noindent We are very interested in answering~\ref{itm:qwithlabel}.
\end{document}

A: I've seen many kinds of things ranging from the \begin{description}...\end{description} to simple \textbf{...} or \emph{} in papers. You rarely see the box in papers, but papers are not theses. You could also give it a dedicated paragraph \paragraph{Research Question X}.
Right now, I personally prefer the use of \begin{quote}...\end{quote} and \emph{}, whenever we have enough space in a publication. See result below with some random preceding text:

The respective tex code is:
\begin{quote}\emph{RQ T.1: What kinds of formatting options are used for presenting research questions?}\end{quote}

Let me include general advice that hopefully helps you with setting up the formatting. You can use macros for research questions for consistent edits. Typically, you repeat a research question in a dedicated (sub-) section or when you provide a concise answer after presenting your results.
Macro in the preamble (before \begin{document}):
\newcommand{\rqtest}{\begin{quote}
        \emph{RQ T.1: What formatting options are used for presenting research questions?}
\end{quote}}

Wherever you want to put the research question, you just type \rqtest{}. This way, you do not only deal with the presentation in one place but also help the reader to identify research questions in other places throughout your thesis by being consistent.


text:
Q: Is Delete & Redownload The Only Way to Convert PS4 Games to Digital? This month's PS Plus free game got me thinking - I have a physical copy of WipeOut Omega Collection, and it's installed as such on my PS4. However, with PS Plus making WipeOut available digitally for free, I figured it'll save me disc-swapping time to have it installed as a digital game. Obviously I could just delete the physical version's install and redownload it digitally, but I'm wondering if there's a way to not need to do that.

A: You have to delete and redownload
First off, realize that the icon on the home page is just a shortcut, and it points to the start file on your game disk. There is nothing you can do to tell the PS4 to now use your digital version. So you need to remove the disc-based startup and install a local-based version.
Also, and it varies from game to game, but a good percentage of disc-based games do not put all the data on the hardrive; just the most common/most accessed portions. So even if you could somehow change the startup icon, the code on your harddrive is incomplete and has calls to pull data from the disc. So you would need to overwrite large portions meaning you're downloading the digital version anyways.


text:
Q: Apache + Delphi XE7 + Datasnap. Problemas com a memória Desenvolvi um programa com Apache, Delphi XE7 e Datasnap. Meu httpd.exe do Apache consome memória até dar a mensagem "Out of Memory" então eu preciso reiniciar o Apache.
Configurei o ServerModule (componentes FireDac, Mysql) e o WebModule para executar uma simples consulta.
No Cliente eu tenho um DBGrid que mostra os resultado da Query
Com o Gerenciador de Tarefas aberto e monitorando a memória:

*

*Ao conectar e desconectar o TSQLConnection ou abrir e fechar o TClientDataSet a memória aumenta.

O que eu já tentei fazer:
Executei o Pascal Analyzer procurando vazamentos de memória mas está ok, tentei desligar o keep alive do Apache mas não fez diferença, já usei todos os tipos de ciclo de vida do WebModule (Session, Server and Invocation) mas o problema persiste.
Desde já Obrigado.

A: Tenta o código abaixo, acredito que ajude.
procedure TformPrincipal.LimpaMemoria;
var
   MainHandle : THandle;
begin
   try
      MainHandle := OpenProcess(PROCESS_ALL_ACCESS, false, GetCurrentProcessID) ;
      SetProcessWorkingSetSize(MainHandle, $FFFFFFFF, $FFFFFFFF) ;
      CloseHandle(MainHandle) ;

   except
   end;

   Application.ProcessMessages;
end;

A: A solução acima é muito boa, mas para ser utilizada no cliente. No servidor, caso pesquisas maiores sejam feitas, vai ser difícil ter memória para todo mundo.
No servidor, dê preferência a usar a menor quantidade possível. Desligue as opções do FireDac que criam cache das informações e mude o ponteiro do FireDac para unidirecional. Deixe que o cliente guarde os dados em cache (ou transmita eles via json ou o que quer que seja).
Certifique-se também de utilizar o método Release ao invés do método free. Release remove a memória utilizado pelo cursor (e outros comedores de memória), enquanto o free ignora tudo isso.


text:
Q: CSS @keyframe not working I have been going through examples and I've go to be missing something here. I can't get this simple css animation to fire, changing the color of some text. When I run the example below, the text stays black.
I have an animation named "changeColor", applied to class "text" for an h1 element. It will fade from one color to another over 5 second intervals.
<!DOCTYPE html>

Not Working

A: You are applying CSS, not JS. Just remove the quotation marks in your CSS and it will work like a charm.
Demo fiddle
.text {
    display: block;
    -webkit-animation: changeColor 5s infinite; /* Safari 4+ */
    -moz-animation: changeColor 5s infinite; /* Fx 5+ */
    -o-animation: changeColor 5s infinite; /* Opera 12+ */
    animation: changeColor 5s infinite; /* IE 10+ */
}

@keyframes changeColor {
    0% {
        color: red;
    }

    100% {
        color: blue;
    }
}

@-moz-keyframes changeColor {
    0% {
        color: red;
    }

    100% {
        color: blue;
    }
}

@-webkit-keyframes changeColor {
    0% {
        color: red;
    }

    100% {
        color: blue;
    }
}

A: Check this Demonstration
You don't need a new changeColor rule.
This is sufficient:
@-webkit-keyframes NAME-YOUR-ANIMATION {
  0%   { color: red; }
  100% { color: blue; }
}

More Animation info here:


text:
Q: why do I have to pull my own branch from remote before push if I rebase modified master ontop of my banch locally? why do I have to pull my own branch from remote  before push if I have rebased modified master ontop of my banch localy?
I was working on my development branch, meanwhile somebody updated master branch, so I rebased master branch on my development branch and got latest changes from master branch on remote.
Now when I do git status I get message saying My devbranch has divereged from origin/devbranch.
the git status suggest to git pull.
by doing so I am prompted to ammend the merge message.
after that I can push.
if i do not do the above and just do git push it gets rejected.
I was under impression that if I have changes in my development branch and I include changes from master then it should not restrict becuase HEAD of my development branch locally has moved, and upstream is following my branch locally !

A:
so I rebased master branch on my development branch and got latest changes from master branch on remote.

This makes no sense, and you normally would not rebase master on some feature branch.  What I think you actually did is the reverse, namely to rebase your development branch on master to bring in the latest changes.
When you completed the rebase, you rewrote the history of your development branch.  What this effectively does is to create a situation where your local development branch is now diverging from the remote version.  The typical way to remedy this is to just force push:
git push --force origin development

This will overwrite the remote development branch with the rebased version.


text:
Q: Should tweets be done in the background? On a high Twitter app site. Where the app sends tweets via the users oauth credentials. Should the tweets be sent in the background, via a background worker (Resque, Delayed Job, etc)? Or should the web process handle it?

A: It really depends on your use case. Twitter itself I think sends an AJAX request to the API. You could do the same if it makes sense in your interface, but it does mean that you're using a web process to do this. One of the benefits to this is that you can verify that the request was successful before returning a resopnse to the user. This is much easier than a scenario where you queue something in the background, it fails, and you want to alert the user (e.g. through a "real-time" ajax/socket-based message system or a flash notice on another request).
If you aren't worried about showing the Tweets (e.g. your application is sending as part of a larger action), then doing it in the background is definitely the way to go.
Resque is great and jobs are really lightweight, so you could a quick integration to process these in the background pretty quickly.
# app/jobs/send_tweet.rb
class SendTweet
  @queue = :tweets

  def self.perform(user_id, content)
    user = User.find(user_id)
    # send Tweet
  end
end

# app/controllers/tweet_controller.rb
def create
  # assuming some things here, like validation and a `current_user` method
  Resque.enqueue(SendTweet, current_user.id, params[:tweet][:message])
  redirect_to :index
end


text:
Q: Azure App Service: using PerformanceCounters I am trying to setup my Azure Web App to include the use of a third party software, which seems to require access to PerformanceCounters. Locally this works fine, but when I run it in Azure I get the following error:
[UnauthorizedAccessException: Access to the registry key 'Global' is denied.]
Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str) +5230217
Microsoft.Win32.RegistryKey.InternalGetValue(String name, Object defaultValue, Boolean doNotExpand, Boolean checkSecurity) +11769029
Microsoft.Win32.RegistryKey.GetValue(String name) +40
System.Diagnostics.PerformanceMonitor.GetData(String item) +102
System.Diagnostics.PerformanceCounterLib.GetPerformanceData(String item) +186
System.Diagnostics.PerformanceCounterLib.get_CategoryTable() +105
System.Diagnostics.PerformanceCounterLib.GetCategorySample(String category) +17
System.Diagnostics.PerformanceCounterLib.GetCategorySample(String machine, String category) +61
System.Diagnostics.PerformanceCounterCategory.GetCounterInstances(String categoryName, String machineName) +70
System.Diagnostics.PerformanceCounterCategory.GetInstanceNames() +25

According to this answer, I should configure IIS to allow access to the app pool/user, but I don't think that is possible for a Azure Web App. Is there a way to get performance counters working in my situation?

A: On Windows, Performance Counters are accessible through WMI:
https://msdn.microsoft.com/en-us/library/aa392397(v=vs.85).aspx
WMI is restricted in the App Service sandbox.
From https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox#access-to-out-of-process-com-servers:

Access to out-of-process COM servers
Windows Servers have a bunch of COM servers configured and available for consumption by default; however the sandbox prevents access to all out-of-proc COM servers. For example, a sandboxed application cannot call into WMI, or into MSIServer.

From Kudu:
PS D:\home> Get-Counter -Counter "\processor(_total)\% processor time"
Get-Counter : The specified object was not found on the computer.

PS D:\home> Get-WmiObject -Class WIN32_OperatingSystem
Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESSDENIED))

If you absolutely have to use the 3rd party software, look at Azure Cloud Services (with a Web Role). You have full control over the OS there while still being PaaS.


text:
Q: bloquear acesso com Spring Beleza, na configuração que fiz não estou conseguindo bloquear o acesso as paginas que ficam dentro de outra pasta dentro da minha pasta views.

No caso eu estou tentando bloquear o acesso a tudo que tem dentro da pasta controle.

Minha configuração está dessa forma e pelo visto está tudo certo. Precisa ser configurado em outro lugar também?


text:
Q: How can I prevent a user from typing characters in certain positions of a MaskedTextBox? Let me explain with this example, lets say we had a MaskedTexBox with the following mask __-__-____ It's a mask for a date in the mm-dd-yyyy format.
On the first position only valid month enties would be 0 or 1.
This part I got to work so when the user presses 2 thru 9 it automatically makes the MaskedTextBox = 02-__-____ or 03-__-____ or 04-__-____ ... 09-__-____ etc.
Seeing how that worked I tried moving on to the next position.  The second position the only valid entries would be 1-9 if the first digit is 0 OR 0-2 if the first digit was 1.
But by pressing the first digit in the first position the 2nd position is set correctly.  But if the user backspaces or clicks in the 2nd position and presses let say 0 I want to prevent the user from being able to press 0 if the first position is already contains a 0.  Because currently it would look like this 00-__-____ and that's an invalid month.
In the "day" positions (3rd and 4th) 3rd should only be allowed to enter 0, 1, 2, 3. And in the 4th position allow only certain digits depending on what the 3rd position already has.
Logic for position 4:

*

*if 3rd is 0 then position 4 can only allow 1-9

*if 3rd is 1 or 2 then position 4 can only allow 0-9

*if 3rd is 3 then position 4 can only allow 0-1
The "year" positions (5th, 6th, 7th, 8th) also has its own logic.  But to prevent this question from being to complicated or confusing as it might already be i will refrain from posting that logic unless someone asks for it.
So basically each position in the MaskedTextBox string has its own logic that it would need to follow.  I have tried the below code but I have not been able to prevent the user from typing in an invalid digit at said positions.  I was starting to wonder if something like this might not be possible, because other examples i have found that prevent users from entering/typing in a character that is not wanted has just 1 IF/ELSE clause and just 1 e.Handled = false and 1 e.Handled = true.  While mine would require many placed in deep IF/ELSE clauses.
Is this even possible in C# using the KeyPress event?
Code i have tried so far. Excuse the mess as I have been trying many options with no luck. I have not finished the "year" logic in the code below because i wanted to get the month and day portion working first.
    private void mtbTest_KeyPress(object sender, KeyPressEventArgs e)
    {
        Char pressedKey = e.KeyChar;

        mtbTest.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;

        int[] formatLengths = { 0 };

        if (Char.IsNumber(pressedKey))
        {
            if (formatLengths.Contains(mtbTest.Text.Length) && Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 1)
            {
                mtbTest.Text = String.Format("{0}0", mtbTest.Text);
            }

            if (mtbTest.Text.Length == 1)
            {
                if (Convert.ToInt32(mtbTest.Text.Substring(0, 1)) == 0)
                {
                    if (Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 1)
                    {
                        e.Handled = false;
                    }
                }

                if (Convert.ToInt32(mtbTest.Text.Substring(0, 1)) == 1)
                {
                    if (Convert.ToInt32(Char.GetNumericValue(pressedKey)) < 2)
                    {
                        e.Handled = false;
                    }
                }
            }

            if (mtbTest.Text.Length == 2 && Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 3)
            {
                mtbTest.Text = String.Format("{0}0", mtbTest.Text);
            }

            if (mtbTest.Text.Length == 3)
            {
                if (Convert.ToInt32(mtbTest.Text.Substring(2, 1)) == 0)
                {
                    if (Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 0)
                    {
                        e.Handled = false;
                    }
                }
            }

            if (mtbTest.Text.Length == 4 && Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 1)
            {
                e.Handled = false;
            }

            e.Handled = true;
        }
        else
        {
            e.Handled = true;
        }

        mtbTest.TextMaskFormat = MaskFormat.IncludePromptAndLiterals;
    }


text:
Q: Python line-by-line memory profiler? I'm looking to generate, from a large Python codebase, a summary of heap usage or memory allocations over the course of a function's run.
I'm familiar with heapy, and it's served me well for taking "snapshots" of the heap at particular points in my code, but I've found it difficult to generate a "memory-over-time" summary with it. I've also played with line_profiler, but that works with run time, not memory.
My fallback right now is Valgrind with massif, but that lacks a lot of the contextual Python information that both Heapy and line_profiler give. Is there some sort of combination of the latter two that give a sense of memory usage or heap growth over the execution span of a Python program?

A: You might be interested by memory_profiler.

A: I would use sys.settrace  at program startup to register a custom tracer function. The custom_trace_function will be called for each line of code. Then you can use that function to store information gathered by heapy or meliae in a file for later processing.
Here is a very simple example which logs the output of hpy.heap() each second to a plain text file:
import sys
import time
import atexit
from guppy import hpy

_last_log_time = time.time()
_logfile = open('logfile.txt', 'w')

def heapy_profile(frame, event, arg):
    currtime = time.time()
    if currtime - _last_log_time < 1:
        return
    _last_log_time = currtime
    code = frame.f_code
    filename = code.co_filename
    lineno = code.co_firstlineno
    idset = hpy().heap()
    logfile.write('%s %s:%s\n%s\n\n' % (currtime, filename, lineno, idset))
    logfile.flush()

atexit.register(_logfile.close)
sys.settrace(heapy_profile)


text:
Q: Delete button not working in dynamic rows I have added dynamic rows using generic block method.
<?php
namespace Vendor\Module\Block\Adminhtml\Blocks\Edit\Tab;

use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Framework\View\Helper\SecureHtmlRenderer;

class ItemRow extends AbstractFieldArray
{
    protected $authSession;

    public function __construct(Context $context, array $data = [], ? SecureHtmlRenderer $secureRenderer = null)
    {
        parent::__construct($context, $data, $secureRenderer);
    }

    protected function _prepareToRender()
    {
        $this->addColumn('name', ['label' => __('name') , ]);
        $this->_addAfter = false;
        $this->_addButtonLabel = __('Add');
    }
}

Using this, I am able to generate dynamic rows and save data to database and see existing data once added.  Though when page is loaded, it is giving below error in console and I am not able to delete existing rows. Though if I click on add new button and delete new row before saving it, that row is getting deleted.


text:
Q: Extracting place details from JSON I am having an issue here. In my android application, I have the location of the place, so relatively I want to get the type to which this place belongs to. So I found the solution in "types" : [ "restaurant", "food", "establishment" ] but the problem is that I don't know how to extract each type from this JSONObject.
this is an example of something similar to what I want.
 URL googlePlaces = new URL(
                        "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" +URLEncoder.encode(args[0], "UTF-8")+"&sensor=true&key=key");
 URLConnection tc = googlePlaces.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    tc.getInputStream()));

            String line;
            StringBuffer sb = new StringBuffer();
            //take Google's legible JSON and turn it into one big string.
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
                JSONObject predictions = new JSONObject(sb.toString());
 JSONArray ja = new JSONArray(predictions.getString("predictions"));
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                     predictionsArr.add(jo.getString("description"));
                }
            }


text:
Q: Jenkins C# Couldn't find any revision to build Всем привет.
Не могу собрать проект.
Данные из лог файла сборки.

Started by user Pit Piter
Building in workspace C:\Program Files (x86)\Jenkins\workspace\CalculateInConsole
git.exe rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
git.exe config remote.origin.url https://gitlab.com/PitPiter/calculateinconsole.git # timeout=10
Fetching upstream changes from https://gitlab.com/PitPiter/calculateinconsole.git
git.exe --version # timeout=10
using GIT_ASKPASS to set credentials
git.exe fetch --tags --progress https://gitlab.com/PitPiter/calculateinconsole.git +refs/heads/:refs/remotes/origin/
git.exe rev-parse "refs/remotes/origin/master^{commit}" # timeout=10
git.exe rev-parse "refs/remotes/origin/origin/master^{commit}" # timeout=10
git.exe rev-parse "origin/master^{commit}" # timeout=10
ERROR: Couldn't find any revision to build. Verify the repository and branch configuration for this job.
Finished: FAILURE

И на картинках сборки и шаги сборки.

Управление исходным кодом:

Не совсем уверен, что проблема именно в Jenkins. Так как судя по:

git.exe rev-parse "origin/master^{commit}" # timeout=10
ERROR: Couldn't find any revision to build. Verify the repository and branch configuration for this job.

-то вполне может быть проблема и в настройках доступа к ветке мастер в gitlab, но я даже не знаю как проверить строку:

git.exe rev-parse "origin/master^{commit}" # timeout=10

Так как через тот же git в VS 2017 и залился проект на Gitlab.


text:
Q: MS-Access select the greatest value less than current value matching criteria My situation is that I have a table that when simplified, looks like this:
Sort| IsHeader
1   | 0
2   | 0
3   | 1
4   | 0
5   | 0
6   | 1
7   | 0
8   | 0
9   | 0

I am trying to make a query that will Update a new HeaderSort line for each detail line to show which header that line belongs to, with this end result:
Sort| IsHeader| HeaderSort
1   |  0      | 0
2   |  0      | 0
3   |  1      | 3
4   |  0      | 3
5   |  0      | 3
6   |  1      | 6
7   |  0      | 6
8   |  0      | 6
9   |  0      | 6

In T-SQL I can do it quite easily:
update MT set HeaderSort =
(
    select isnull(max(Sort),0) from MyTable where Sort <= MT.Sort and IsHeader = 1
)  as HeaderSort
from MyTable MT

My attempt at an access version is as follows:
Update MyTable set HeaderSort =
(
    select nz(max(Sort),0) from MyTable where Sort <= MT.Sort and IsHeader = 1
)

This, however gives a "Operation must use an updatable query." error.
Is my error in the logic for getting the values, or just some ms-access syntax?

A: The Operation must use an updatable query. is a general error encountered when not all tables referred to in an update statement are updateable. Unfortunately, subqueries rarely are.
You can work around the error by using a DLookup instead of a subquery:
Update MyTable set HeaderSort = DLookUp("nz(max(Sort),0)", "MyTable", "Sort <= " & MyTable.Sort & " and IsHeader = 1")


text:
Q: Seeking corresponding functional to show existence of weak solution to PDE $$-\Delta  u = \lambda u \space, \space\space\space\ x∈Ω$$
$$u(x) = 0\space, \space \space\space\space\space x∈\partial Ω$$
What functional would form a good correspondence, and whose minimization could show that the above function, $u$, has a weak solution in $H^1_0(\Omega)$? Is this analogous solving the case of:
$$-\Delta  u = f(x) \space, \space\space\space\ x∈Ω$$
$$u(x) = 0\space, \space \space\space\space\space x∈\partial Ω$$
taking $f(x)=\lambda u$, or is the there a better way to solve this specific case?

A: If $\lambda\leq 0$ and is known, then the equation is nothing but a regular Poisson equation with an $L^2$-term.

If $\lambda >0$ is is unknown, then this is an eigenvalue problem, the link toypajme's comment is pretty nice and readable. Here I just add a bit more about motivation. Normally for eigenvalue problem, we are minimizing the Rayleigh quotient:
$$
F(u) = \frac{\| \nabla u\|_{L^2(\Omega)}^2}{\| u\|_{L^2(\Omega)}^2},\tag{1}
$$
whereas
$$\int_\Omega u w_i = 0\quad \text{for eigenfunction } w_i, i=1,\ldots,n-1,$$
and the minimizer $u = w_n$ is another eigenfunction while $F(w_n)$ is the $n$-th eigenvalue. Notice problem (1) can be written as the same constraint minimization problem in the link in the toypajme's comment.

If $\lambda = \omega^2$ is known and is not one of the eigenvalues for the operator $-\Delta$, also we have a right hand side $f$, then this is a Helmholtz equation, and it weak formulation
$$
\int_{\Omega}\nabla u\cdot \nabla v - \omega^2 \int_{\Omega}uv = \int_\Omega fv
$$
has a unique solution in $H^1_0$ by Fredholm alternative.


text:
Q: How do I check if the input() is in a given interval? x = int(input("Start: "))
y = int(input("End: "))
z = range (x,y)
print (z)
Interval_1= range(1, 5)
Interval_2 = range (6, 8)
Interval_3 = range (9, 10)

if z in Interval_1:
  print ("Number is in Interval 1")
else: ("Number is not in Interval 1")

I want the user to enter 2 numbers and to a given interval it should check whether it is in the interval or not but it seems like the code does not even run the if query. Is it because of the "in" command?

A: If you want to test whether one range is included in another, you can convert them both to sets and then test if one is a subset of the other:
if set(z) <= set(Interval_1):
    print("Number is in Interval 1")
else:
    print("Number is not in Interval 1")

A: You can easily check range.start and range.stop like so:
x = int(input("Start: "))
y = int(input("End: "))
Interval_1= range(1, 5)

if Interval_1.start <= x < y <= Interval_1.stop:
  print ("Number is in Interval 1")
else:
    print("Number is not in Interval 1")

This assumes the step is 1, and start is smaller than end.

A: Please try the below code. It checks whether the start and end are in interval or not and outputs accordingly.
x = int(input("Start: "))
y = int(input("End: "))
z = range (x,y)
print (z)
Interval_1= range(1, 5)
Interval_2 = range (6, 8)
Interval_3 = range (9, 10)

if z[0] in Interval_1 and z[-1] in Interval_1:
    print ("Number is in Interval 1")
elif z[0] in Interval_2 and z[-1] in Interval_2:
    print ("Number is in Interval 2")
elif z[0] in Interval_3 and z[-1] in Interval_3:
    print ("Number is in Interval 3")
else:
    print("Number is not in any of the intervals")

A: If you need absolutely robust code and don't mind it being slow, you can check every element individually to see if it's in the range.
if all(item in Interval_1 for item in z):

This works even if the ranges you're testing against have a step.

A: To use the in or not in operator for a type (or class) in Python, that class should have the method __contains__(self, item), the range object does have that method, but it only checks a single value in the range or not.
eg.
>>> r = range(1,10)
>>> 8 in r
True
>>> 11 in r
False

However, your use case is different, you want to check if a range object ra in another range object rb. You may need to consider wrap ther standard range object, and create a MyRange to have this feature. Here is an example of a custom range.
class MyRange(object):
    def __init__(self, start: int, end: int):
        self._start = start
        self._end = end

    def __iter__(self):
        return range(self._start, self._end).__iter__()

    def __contains__(self, item):
        return item._start >= self._start and item._end <= self._end

def main():
    base_range = MyRange(10, 20)

    in_range = MyRange(11, 19)

    out_range = MyRange(9, 15)

    for x in base_range:
        print(x)

    print(in_range in base_range) # True
    print(out_range in base_range) # False

if __name__ == '__main__':
    main()


text:
Q: How can I make MANY elements unselectable using jQuery or CSS?
Possible Duplicate:
Is there a way to make a DIV unselectable?

I have seen a number of solutions out there that work for an element. However I have an area with labels and buttons. It's not just one element it's every element within a DIV.
How can I make anything contained within that DIV unselectable? Note that I cannot just put a mask layer over the DIV as the DIV has buttons I need to be able to click.

A: $(".yourdiv").children().css({userSelect: 'none'});

That's in case you want to disable selection using the CSS user-select property. If not, the above can be easily generalized to other methods.
The above only selects direct children, to select all descendants, use the .find() method:
$(".yourdiv").find("*").css({userSelect: 'none'});

You can also do this using pure CSS:
.yourdiv * { /*this selects all elements that are children of yourdiv*/
    /*user-select: none rules*/
}

Or:
.yourdiv > * { /*this selects all elements that are direct descendants of yourdiv*/
    /*user-select: none rules*/
}

A: CSS:
div.unselectable {
    -moz-user-select: -moz-none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
    user-select: none;
}

HTML:

...

Reference:

*

*Is there a way to make a DIV unselectable?

*Disabling Selection in jQuery

A: The proprietary user-select CSS variations are inherited in all browsers that support them. See this example:
http://jsfiddle.net/yD7bM/
Your problem is the browsers that do not support these CSS properties, namely Opera and IE <= 9. Happily both of these implement an alternative: the unselectable attribute. However, it is this attribute that is not inherited.
The best solution is to put an unselectable="on" attribute on every element that you require to be unselectable in the HTML (i.e. do it server-side). However, if this is not an option, you can do it using JavaScript using a recursive function.
If you're using jQuery you could do something like this to add the unselectable attribute to each element with class "unselectable" and all of its descendants:
 $(".unselectable").find("*").andSelf().attr("unselectable", "on");

Demo: http://jsbin.com/ulazic/2


text:
Q: Overlay pmf of true Poisson distribution over histogram of randomly generated samples I'm new to both statistics and R. I've generated 100 random samples from a Poisson distribution with lambda = 2.5 using:
 samples <- rpois(100,2.5)

I've successfully created a relative frequency histogram of the samples:
 hist(samples, prob=TRUE)

Now I need to overlay the pmf of the true Poisson distribution over the histogram but don't know how to generate the true function. I think this is probably very simple but just can't figure out what to do. Any help would be really appreciated.
Thanks!

A: Get the distribution by plugging values from the domain into the Poisson probability mass function.
The domain is 0-infinity.
The pmf is [e^(-lamda)*lamda^k]/k_factorial
See the wikipedia page for details: http://en.wikipedia.org/wiki/Poisson_distribution


text:
Q: How to get numbers to stop using grouping separators in the std::wfstream library? I was using the std::fstream library, and I found out that it was failing to write.  Turns out, it was an mdash.
wchar_t mdash[] = { 0x2014, 0x0000 };

std::wfstream os("filename.txt", std::ios_base::out| std::ios_base::trunc);
os << mdash;
assert(!os.bad()); // fails

I'm not in control of what stuff I'm going to dump to the file, so I needed a way to properly write out the file without crapping out.  So I wrote this function based on this answer.
void set_locale_on_stream(std::wfstream &os)
{
    char* locale = setlocale(LC_ALL, "English"); // Get the CRT's current locale.
    std::locale lollocale(locale);
    setlocale(LC_ALL, locale); // Restore the CRT.
    os.imbue(lollocale); // Now set the std::wcout to have the locale that we got from the CRT.
}

This worked, except now I've got my numbers getting grouping separators added to them, and they are hex, making it totally useless!
Is there a way to stop that from happening?

A: fs.imbue(std::locale(ofs.getloc(), new std::codecvt_utf16<wchar_t, 0x10ffff, std::little_endian>)) is needed to set the locale, unfortunately codecvt_utf16 is deprecated and has no replacement as of yet.
Instead, you can open the file in binary mode and use pubsetbuf. Note, if your file does not have a 2-byte BOM marker at the start then the text editor may not recognize it as UTF16-LE.
int foo()
{
    wchar_t mdash[] = L"—  Test";
    const wchar_t *filename = L"filename.txt";

    wchar_t wbuf[128];
    std::wofstream fout(filename, std::ios::binary);
    if(fout)
    {
        fout.rdbuf()->pubsetbuf(wbuf, 128);

        //optional BOM
        wchar_t bom[1] = { 0xFEFF };
        fout.write(bom, 1);

        fout << mdash;
        fout.close();
    }

    std::wifstream fin(filename, std::ios::binary);
    if(fin)
    {
        fin.rdbuf()->pubsetbuf(wbuf, 128);

        //optional, skip BOM
        std::wstring wstr;
        if(fin >> wstr)
            MessageBoxW(0, wstr.c_str(), 0, 0);
        fin.close();
    }
    return 0;
}


text:
Q: Cargar automaticamente un archivo html en otro (index.html) en un div del index necesito cargar una pagina en una pagina principal. Lo hice con .load("archivo.html") pero solo lo abre en firefox y si inspeccione trae un error de arbol desequilibrado de elementos, y chrome y explorer ni la abren me aparerce acceso denegado en la llamada del load()
Me pueden decir como remplazar el load() .
<!DOCTYPE HTML>

  <meta http-equiv="Content-Language" content="es"/ >
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" type="text/css" href="scripts/estilos.css"/>
  <title>Estación 2</title>


text:
Q: Restricting panning to one globe in Google Maps API I have a map created using the Google Maps API, and I'd like to restrict panning to one globe; by default you can pan continuously east/west, the map repeats endlessly. I'm trying to use henningj's solution posted to this question
var allowedBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(85, -180),
    new google.maps.LatLng(-85, 180)
);
lastValidCenter = map.getCenter();

google.maps.event.addListener(map, "center_changed", function() {
    if (allowedBounds.contains(map.getCenter())) {
        lastValidCenter = map.getCenter();
        return;
    }

    map.panTo(lastValidCenter);
});

What I have currently allows no panning whatsoever, the call to 'contains' always fails. If I log map.getCenter() it all looks sensible enough, I think(?!):
Object { A: 54.683366, F: 25.31663500000002 }

Can anyone see what I'm doing wrong?

A: You have your allowedBounds defined incorrectly.  It should be (from the documentation):

LatLngBounds(sw?:LatLng, ne?:LatLng)  Constructs a rectangle from the points at its south-west and north-east corners.

This:
var allowedBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(85, -180),
    new google.maps.LatLng(-85, 180)
);

Should be:
var allowedBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(-85, -180),  //sw
    new google.maps.LatLng(85, 180)     //ne
);

(negative longitudes are west of positive ones, negative latitudes are south of positive ones)
proof of concept fiddle

A: You can  setting a proper Zoom Level  and resticting the min  e max zoom level
      var mapOptions = {
        center: new google.maps.LatLng(50.431487, 30.539285),
        zoom: 2,
        minZoom: 2,
        maxZomm:19,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }


text:
Q: how could we resolve the transitive provided dependencies in maven? On Dec 10, a severe vulnerability was found in log4j2(CVE-2021-44228), I was asked to detect all the log4j usages (both direct and transitive) in our projects(mostly maven projects). I found it is easy to detect if log4j2 was listed as direct dependencies. I can inspect them through mvn dependency:tree or mvn dependency:build-classpath. Like the tree shown below. I know this is also the method Eclipse Steady and OWASP are using.

my-company:my-app:v1.0
\- org.apache.logging.log4j:log4j-api:jar:2.13.3:compile

However, in some special cases, things are not that easy. For example, I have another project like this:

my-company:my-app2:v1.0
\- com.alibaba:druid:jar:1.2.8:compile

This looks pretty clean, right? But actually, log4j2 is listed as a "provided" dependency in druid 1.2.8. Check pom here. According to maven document, "provided" scope is not transitive, thus log4j is not listed in the tree.
But actually, it is there. I can find the function call of log4j inside this druid:1.2.8.
check here: log4j2 in druid
I also use soot to make sure this function is actually reachable.
According to this page, any string like ${jndi:ldap://example.com/a} can cause such a problem. So theoretically, druid:1.2.8 is infected.
the Actuall tree maybe like this

my-company:my-app2:v1.0
\- com.alibaba:druid:jar:1.2.8:compile
    \-org.apache.logging.log4j:log4j-core:jar:2.13.3:provided

Lets define the relationship between log4j and my-app2 as transitive "provided" dependency
Here is my question:

*

*Why doesn't maven list the transitive provided dependencies in the tree? Just for a better understanding of the dependency relationship.

*Without checking poms one by one manually, how could we resolve the transitive provided dependency?

A: Class and method resolution in java happens during runtime, the first time the class or method is referenced. If the code you linked is run without Logger or LogManager on the classpath this would result in an error being thrown. If it is not actually used, for example if it has to be manually configured somehow, then this is totally fine.
Note also that both Logger and LogManager are part of the log4j-api dependency, while the code affected by the vulnerability is in log4j-core. A dependency on log4j-api should be totally fine and there are projects like log4j-to-slf4j that implement this api and delegate actual logging to a different implementation.


text:
Q: Mock web service created from retrofit RestAdapter and injected through Dagger2 I am using Retrofit and injecting RestAdapter and WebService class/interface through Dagger2
In the tests, I am mocking my web service class as MockWebService200 implements WebService and I am getting this exception from Retrofit
java.lang.IllegalArgumentException: Only interface endpoint definitions are supported.
        at retrofit.Utils.validateServiceClass(Utils.java:102)
        at retrofit.RestAdapter.create(RestAdapter.java:193)

Here is the interface class for WebService
public interface WebService {

@FormUrlEncoded
@POST("/loginByEmail")
void loginByEmail (@Field("emailaddress") String email,
                   @Field("password") String password,
                   @Field("checksum") String checksum,
                   Callback<ServiceModel<User>> callback);
}

And, here is my MockWebService200 class
public class MockWebService200 implements WebService {
    @Override
    public void loginByEmail (@Field("emailaddress") String email,
                          @Field("password") String password,
                          @Field("checksum") String checksum,
                          Callback<ServiceModel<User>> callback) {
    ServiceModel<User> userModel = getServiceModel( getUser() );
    callback.success( userModel, null );
    }

    @Override public <T> ServiceModel<T> getServiceModel (T model) {
        // Skipped
    }

    @Override public User getUser () {
    // Skipped
    }
    }

getUser() and getServiceModel() are skipped here.
Here is the code for the @module which is providing dependencies
@Module
@Singleton
public class ApiModule {
    @Provides
    @Singleton RestAdapter provideRestAdapter () {
        RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint( "some_url" )
                .setClient( /*OkHttpClient*/ );

        return builder.build();
    }

    @Provides
    @Singleton WebService provideWebService (RestAdapter restAdapter) {
        return restAdapter.create( MockWebService200.class );
    }
}

Questions:
1- How to fix this?
2- Is my approach correct to mock web services through polymorphism and what alternatives I can use here?

A: You cannot ask the RestAdapter to implement a class, because the class is the implementation. You have to instantiate it separately in your test using a constructor, possibly just the empty one. So instead of injecting it through Dagger, you just create your own instance with new MockWebService200(). You'll have to implement getServiceModel() too, though.


text:
Q: Why is adding top/bottom/right padding on textarea moving the scrollbar and handle in as well? I would like to apply matching paddings to my text inputs and textareas, but when I apply a padding to a textarea, it moves the little handle for adjusting the text area in as well, and it looks stupid, at least in Firefox. Is there a way to fix this, or am I just being OCD? I personally think it looks horrible.
Thank you.

A: If you're willing to remove the resize handle, just add resize: none to your CSS. See http://jsfiddle.net/2bkMH/2/ for a demo.


text:
Q: Hiding Range of Columns in Excel using VBA based on cell Values I need to hide a range of cells using a macro in excel. C11 contains the column index from where I need to start hiding the columns.
Sub test()

Dim i As Integer
Dim j As Integer

Dim rocket As Range

i = Range("c11").Value
j = 12

rocket = Range(Cells(5, i), Cells(5, j))

Range("Rocket").Select

Selection.EntireColumn.Hidden = True

End Sub

The code is giving some unexpected error and as I am a novice, so have no clue what needs to be done..

A: Tree steps to make your code working:
1st. Add Set key word in appropriate line which is necessary:
Set rocket = Range(Cells(5, i), Cells(5, j))

2nd. Rocket variable represents range, you will NOT need to call it in this way:
Range("Rocket")....

but
rocket....

3rd. Avoid Select method and Selection object always when possible. Therefore the last two lines replace with this single one (which implements 2nd step, too):
rocket.EntireColumn.Hidden = true

A: That last answer was awesome! Just for someone else's FYI, here is what worked in Excel 2007. The first line is always 3, but the ending line needed to be a variable. That's where I had the problem. THIS FIXED IT! The last 4 lines before the "End If" do the work. Hope this helps!
Dim RowsToHide As Range
Dim RowHideNum As Integer

' Set Correct Start Dates for Billing in New File
Workbooks("----- Combined_New_Students_Updated.xlsx").Activate
Sheets("2015").Activate
StartDateLine1 = Format(START_DATE_1, "ww") - 1 ' Convert Start Date to Week Number
StartDateLine1 = (StartDateLine1 * 6) - 2 ' Convert Start Date to Line Number
If StartDateLine1 >= "10" Then
 Cells(4, "q").Value = ""
 Cells(StartDateLine1, "q").Value = STATUS_1
 Cells(StartDateLine1, "z").Value = "START DATE " + START_DATE_1
 RowHideNum = StartDateLine1 - 2
 Set RowsToHide = Range(Cells(3, "a"), Cells(RowHideNum, "ab"))
 RowsToHide.Select
 RowsToHide.EntireRow.Hidden = True
End If


text:
Q: On a two monitor setup how can I keep the game (TF2) open when I click on a tab in the other monitor? If I have TF2 open on one monitor if I click on any other tab in the second monitor it minimizes the game.
Is there any way I can fix this?

A: I believe the setting you're looking for is borderless windowed mode in team fortress 2. As the name suggests, it puts the game in windowed mode but removes the border, so it should still appear as full screen. That should fix your issue and allow you to click without minimizing!

A: I addition to the in-game option mentioned in the main answer, you can use Steam Launch options - I use these for Counter Strike and they work for TF2 as well.
https://support.steampowered.com/kb_article.php?ref=1040-JWMT-2947

-window -noborder -novid -nojoy -w 2560 -h 1080

A: You can switch windows without minimizing by using Borderless windowed mode.
This can be done in a couple ways, the easiest is by going into your "Options> Video" settings in game and setting the game to "Run in a Window".

Alternatively you can modify your launch settings by adding the launch options -windowed -noborder in the TF2s "Properties > General" settings directly in Steam.
Source - an in-depth tutorial on Bordeless Windowed mode for TF2

A: Sup.
One thing you can do is on your keyboard press WIN+MAJ+left arrow key and boom, there you go.
im not sure this work but i researched tf2 fullscreen 2nd screen and this is the answer.


text:
Q: Not getting desired text from BeautifulSoup

               Shift Pattern:

                 No Shift

               Salary:

                     S$3,500.00

                      -

                     S$5,400.00

This is a part of my BeautifulSoup tree. I wish to get the salary range S$3500 - S$5400. Following the suggestion here I use the following code:
salary = bsObj.find(text="Salary:").parent.nextSibling.find("td").get_text()
print(salary)

I get the error:
AttributeError: 'int' object has no attribute 'get_text'

But when I simply print out the integer:
salary = bsObj.find(text="Salary:").parent.nextSibling.find("td")
print(salary)

I get:
-1

Which is not what I want. I have used Selenium to obtain the page, so any javascript is already loaded.
Any ideas?

A: Try the following code, however I don't think your code can get your expect output:
>>> bsObj.find('td', {'align': "left"}).text
'\n\n                     S$3,500.00\n                     \n                      -\n                     \n                     S$5,400.00
\n                    \n'

>>> ' '.join(bsObj.find('td', {'align': "left"}).text.split())
'S$3,500.00 - S$5,400.00'

A: Not sure about this "get_text" attribute, but with BeautifulSoup, I rely heavily on .text as shown below. Is this what you're looking for?
s = ''''''
soup = BeautifulSoup(s, 'html.parser')
bsObj = soup.findAll('td')
for i in bsObj:
    print(i.text)

>>>

                     S$3,500.00

                      -

                     S$5,400.00


text:
Q: Default username and password for LUCI2 I uploaded the LUCI2 from Git to my OpenWrt box. For the first access to the web interface we must input login name and password. What should these two parameters be?
I typed admin/admin, and they did not work. Even if I execute the command: 'passwd admin' and I add 'admin' as new passwd.


text:
Q: Input not being read using certain literals Very new programmer with a seemingly obscure problem:
string currency = "???";
double amount = 0.0;
double amount_final = 0.0;
cin >> amount >> currency;
if (currency == "GBP"){
amount_final = amount*1.47;
}
 else if (currency == "Yen"){
    amount_final = amount*0.0083;
}
else if(currency == "Euro"){
    amount_final = amount*1.07;

Everything works fine except if you enter "Euro" in which case it acts like you didn't enter anything and returns the initial values.
A little bit of testing showed me that the only time I run into problems is if the first letter of the string is E or e and isn't preceded by a whitespace, any other value I tried works fine.
TL;DR: If I change nothing except "Euro" to "Fish" the program works, what's up?

A: The float parser is greedy and consumes the "E" which stands for exponent from the input stream, leaving "uro" as the remainder of the input stream.
Basically the greedy parsing fails here as it is a grammar which would require a lookahead of 1. ("E" followed by number).

A: #include <iostream>
#include <string>

int main() {
    std::string currency = "???";
    double amount = 0.0;
    double amount_final = 0.0;
    std::cin >> amount >> currency;
    if (currency == "GBP"){
    amount_final = amount*1.47;
    }
    else if (currency == "Yen"){
        amount_final = amount*0.0083;
    }
    else if(currency == "Euro"){
        amount_final = amount*1.07;
    }
    std::cout << amount_final << std::endl;
}

[localhost functionTest]$ ./a.out
11 GBP
16.17

[localhost functionTest]$ ./a.out
11 Yen
0.0913

[localhost functionTest]$ ./a.out
11 Euro
11.77

Sorry in my case is working, are you always using Amount Currency ?


text:
Q: The Complex Logarithm of a Function For an analytic function $f$ that does not vanish on a simply connected region, we may define its logarithm to be the function:
$$\log f=g(z):=\int_{y}\frac{f'}{f}dz+c_0.$$
Where $\gamma$ is some path starting at an arbitrary point in the region, and ending at $z$; while $c_0$ satisfies $e^{c_0}=f(z_0)$.
I believe that this logarithm should satisfy under certain conditions that: $$\log f=\log |f|+iarg(f).$$
Am I right, or this is too difficult in general?

A: The function $g$ satisfies $g' = \frac{f'}{f}$ in the given domain, so that
$$
 (f e^{-g} )' = f' e^{-g} - f g' e^{-g} = 0 \\
\implies f e^{-g} = \text{const} = f(z_0) e^{-g(z_0)} = f(z_0) e^{-c_0} = 1 \, .
$$
Therefore $e^g = f$, i.e. $g$ is "a holomorphic logarithm" of $f$  in the domain. In particular
$$
 f(z) = e^{g(z)} = e^{\operatorname{Re} g(z)} e^{ i \operatorname{Im}g(z)}
$$
which implies that
$$
 |f(z)| = e^{\operatorname{Re}g(z)} \implies \operatorname{Re}g(z) = \log |f(z)|
$$
and that $ \operatorname{Im}g(z)$ is an argument of $f(z)$. So
$$
 g(z) = \log |f(z)| + i \operatorname{arg}f(z)
$$
in the sense that $\operatorname{arg}f(z)$ is a continuous function which is an argument of $f(z)$ for each $z$.


text:
Q: Mocha with Grunt: Cannot find module that exists I am having issues with Mocha finding a module that exists. I have a data folder that contains all my test data. This folder exists and is at the correct directory (confirmed with pwd). When I run the test using mocha test filename the tests pass, but when I use grunt test I get the following error.
Running "mochaTest:tests" (mochaTest) task
>> Mocha exploded!
>> Error: Cannot find module '/Users/user/Documents/project/project_dispatcher/tests/data'
>>     at Function.Module._resolveFilename (module.js:339:15)
>>     at Function.Module._load (module.js:290:25)
>>     at Module.require (module.js:367:17)
>>     at require (internal/module.js:16:19)
>>     at /Users/user/Documents/project/project_dispatcher/node_modules/mocha/lib/mocha.js:219:27
>>     at Array.forEach (native)
>>     at Mocha.loadFiles (/Users/user/Documents/project/project_dispatcher/node_modules/mocha/lib/mocha.js:216:14)
>>     at MochaWrapper.run (/Users/user/Documents/project/project_dispatcher/node_modules/grunt-mocha-test/tasks/lib/MochaWrapper.js:51:15)
>>     at /Users/user/Documents/project/project_dispatcher/node_modules/grunt-mocha-test/tasks/mocha-test.js:86:20
>>     at capture (/Users/user/Documents/project/project_dispatcher/node_modules/grunt-mocha-test/tasks/mocha-test.js:33:5)
Warning: Task "mochaTest:tests" failed. Use --force to continue.

I am assuming this is a config issue, but I am lost as to what is causing it. I have the following structure:
->test
-->testfile.js
-->data
---->datafile.json
And I include the json file using:
var requestObj = require('./data/workflowRequest.json');

Is the ./ no longer valid because I am using Grunt which is located above the test folder? I am also confused because the stack trace only contains mocha files, and no test files that I wrote.
Edit Grunt code may be useful too
mochaTest: {
    tests: {
        src:['tests/**/*'],
        options: {
            reporter: 'spec'
        }
    },
    watch: {
        src:['tests/**/*'],
        options: {
            reporter: 'nyan'
        }
    },
    tap: {
        src:['tests/**/*'],
        options: {
            reporter: 'tap'
        }
    }
},


text:
Q: Can we add TLS version 1.2 while using POSTMAN? I am not getting a response in my rest webservice as postman sends request via SSL . Can we change it to TLS ?

A: I think this can be done. It is the other way around, You disable protocols which you don't want to communicate with. So disable it in Postman.
please see the screenshot. My API only accepts TLS1.2 so I disabled all older version and I was able to fix this issue.

A: Click on setting >> Protocols disabled during handshake
as below picture


text:
Q: How to use enum with checkbox rails I want to create a question list, to decide that question has multiple correct answer or not, I use a checkbox field:
<div>
  <%= ff.label :multi_correct, t(".multi"), class: "field-label" %>
  <%= ff.check_box :multi_correct %>
</div>

Here's my question model
class Question < ApplicationRecord
...
  enum multi_correct: {no: 0, yes: 1}
end

When I submit the form, it returns an error said '0' is not a valid multi_correct
My schema.rb:
  create_table "questions", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "content"
    t.integer "multi_correct"

How can I make this checkbox work? When it is unchecked it should send 0 to database and vice versa.

A: Oh nvm, Here's the solution
<%= ff.check_box :multi_correct, {}, "yes", "no" %>

The first one is checked value, the second one is unchecked


text:
Q: Duplicate rules not triggering Currently I am trying to prevent contacts with the matching first and last names from being assigned to the same Account. Currently on contact I have an custom Account Id field on contact that's updated via a workflow rule.
My active matching rule looks like the following:
(Contact: Account_Id EXACT MatchBlank = FALSE) AND (Contact: FirstName EXACT MatchBlank = FALSE) AND (Contact: LastName EXACT MatchBlank = FALSE)

My duplicate rule has the following settings:

*

*Bypass sharing

*Block on update

*Block on edit

*No conditions

*Active

*The matching rule mentioned earlier

I'm unsure of why it's not blocking the creation. At first I thought it was because (according to documentation) workflow rules trigger after Duplication rule checks are made but I ensured those fields were populated and tested it again.
For example:
We have John Smith assigned to Generic LLC. I should be able to add Alex Smith, John Brown, Alex Brown, etc. But I shouldn't be able to add another John Smith to Generic LLC. I should be able to add John Smith to Other Company Inc. but there can't be two contacts with the same first and last name assigned to one account.
Note: When using the Contact object for matching rules this is an example of what the options will look like.

Currently the only issue I'm experiencing is if I create an account that has the same first and last name as an inactive account and is associated with the same account the new contact is not blocked. New / updated Active Contact with existing duplicate Active contact does block.
As suggested I have created a trigger that looks like the following:
trigger ContactTrigger on Contact (after delete, after insert, after undelete,
after update, before delete, before insert, before update) {
    if(Trigger.isBefore && !Trigger.isDelete){
        for(Contact c : trigger.new){
            if(c.RecordTypeId == RecordTypes__c.getValues('Inactive Contacts').Id__c){
                c.Account_Id__c= c.AccountMap__c;
            }
            else{c.Account_Id__c = c.AccountId;}
        }
    }
}

AccountMap is the same thing as AccountId but it's done in a custom field so Inactive contacts don't show up on the account page.
Trouble shooting tip: Sometimes turning off and on duplicate rules fixes things.

A: What you're asking is possible, but not the way you're trying. I see only one option:

*

*Instead of a workflow, use a before trigger to make the change on the Account_Id field.

Also, mind that duplicate rules are only evaluated if the watched fields are evaluated, and that can cause trouble on the testing as well.


text:
Q: Why does Angular injector detect the following provided even if its not in the injector heirarchy? From the official docs, following is an example of lightweight injection token pattern for enabling tree shaking:
abstract class LibHeaderToken {}

@Component({
  selector: 'lib-header',
  providers: [
    {provide: LibHeaderToken, useExisting: LibHeaderComponent}
  ]
  ...,
})
class LibHeaderComponent extends LibHeaderToken {}

@Component({
  selector: 'lib-card',
  ...,
})
class LibCardComponent {
  @ContentChild(LibHeaderToken) header: LibHeaderToken|null = null;
}

My question is that when Angular sees @ContentChild(LibHeaderToken), it will try to look for  a provider with token name as LibHeaderToken, but it'll look for it on the current component or its parents (because its an hierarchical injector). It'll not look in LibHeaderComponent (which is where we have declared the required provider).
So why does this work and why LibHeaderComponent is also searched when looking for providers?

A: If you look for the definition of @Contentchild decorator, it's written in the original docs:

The following selectors are supported.

*

*Any class with the @Component or @Directive decorator

*A template reference variable as a string (e.g. query <my-component
#cmp> with @ContentChild('cmp'))

*Any provider defined in the child component tree of the current
component (e.g. @ContentChild(SomeService) someService: SomeService)

*Any provider defined through a string token (e.g.
@ContentChild('someToken') someTokenVal: any)

*A TemplateRef (e.g. query  with
@ContentChild(TemplateRef) template;)

In the bullet list, the 3rd bullet says "Any provider defined in the child component tree of the current component (e.g. @ContentChild(SomeService) someService: SomeService)". So in the example, LibCardHeader is in the child component tree of LibCardComponent, and the LibHeaderToken is a provider defined in the LibCardHeader -which is child component- which matches with the explanation "Any provider defined in the child component tree of the current component". The current component is LibCardComponent.
edit: docs reference


text:
Q: Firebase query implementation If we query data from Firebase on a key for a child node, does it downloads the whole child node and filter data in the application or it downloads the query specific data? i.e. the filtered data
String myUserId = getUid();
Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId).orderByChild("starCount");
myTopPostsQuery.addChildEventListener(new ChildEventListener() {});

myTopPostsQuery will sort data according to starCount and I will receive data in the addChildEventListener() I want to know that whether this data is being filtered inside my app after receiving or my app downloads only the filtered data from the Firebase.

A: You get the data already filtered. When you use a query, let say, limitToLast(10) you get only those 10 elements. This is happening also in your case with orderByChild("starCount"). In your SnanpShot will find only those filtered elements. Please visit official doc for more details.
Hope it helps.

A: If you use a filter in your query you will download the query specific data without any operation executed on the client side.
Keep in mind that:

*

*You can only use one order-by method at a time. Calling an order-by method multiple times in the same query throws an error.

*You can combine multiple limit or range functions. For example, you can combine the startAt() and endAt() methods to limit the results to a specified range of values.

For any other info take a read here

A: Based on the code you pasted here, your query will just retrieve all the posts for the database path user-posts/<id> with an ordered manner which means that there is not filter. But still you will get back all the available posts under the path you are querying. It can be a "semi-filter" as it will find only the posts which include starCount field
The best thing is to filter during your query in order to retrieve back exactly what is needed and not everything as you are doing right now, imagine that this list of posts can be really big so you will have a big issue with performance later.
Read the following section here about sorting & filtering.
https://firebase.google.com/docs/database/admin/retrieve-data#orderbychild
Apart from that consider to add an index in userId field for speeding up your query.


text:
Q: why 2 and 4 remain in the 2 example? I need to remove all unique objects in the given lists.
My code passes 1,3,4 checks but doesn't pass 2nd one, it returns [2,4], why not []?
def checkio(data):
     for i in data:
         if data.count(i) == 1 :
             data.remove(i)
     return data

if __name__ == "__main__":

    assert isinstance(checkio([1]), list), "The result must be a list"
    assert checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3], "1st example"
    assert checkio([1, 2, 3, 4, 5]) == [], "2nd example"
    assert checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5], "3rd example"
    assert checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9], "4th example"

A: The problem here is that you are removing elements from a list while iterating through it, which you should never do.
The iteration for i in data keeps moving the index it's looking at forward. So, when you remove the first element in the list, the next item is moved to index 0 and the loop moves on to look at the element at index 1, skipping over the item that was moved to index 0.
Instead, you can build up a new list containing items that meet your criteria:
items = []
for i in data:
    if (data.count(i) > 1):
        items.append(i)
return items

Or do something like this:
return [i for i in l1 if l1.count(i) > 1]

A: The 'remove' function automatically recreates the list. So when "1" was removed, "2" was put in that slot, so it won't check that same position again, which is why alternating items are remaining. However, you can still implement the same function as you have, but instead work from the back of the list and iterate to the front:
def checkio(data):
     for i in range(len(data)-1,-1,-1):
         if data.count(data[i]) == 1 :
             data.remove(data[i])
     return data


text:
Q: Notification sometimes skips the first alert, always works on second fire I been working on an extension and I'm ready to release it.
I been learning a lot from all of your guyses experience and I'm ready to help if I can.
I need help with my notification pop up, currently it sometimes works,it always works on the second run.
  Anyone has dealt with this before?
chrome.notifications.create(
                      'success',{
                      type: 'basic',
                      iconUrl: 'coo.png',
                      title: "coo",
                      message: "sent to: " +title ,
                      silent:true,
                      priority:0
                      },
                  function(){});
                  chrome.notifications.clear('success', function (){}) });
                     }

This is what I'm doing to create the notification, perhaps use update instead of create?
Thanks all :)


text:
Q: Having trouble passing in a dependent object to a Javascript Module I have the following code:
var myModule = (function($) {
  // Insert code here
} (jQuery || Zepto));

If I don't have jQuery referenced on the page, the script errors out saying that jQuery is undefined.  There's many times in code where I'll write var foo = missingObj || fallbackObj; and it works fine.
I'm trying to figure out a) why it doesn't work in this context and b) what an alternative would be since I would like to use this projects that use either framework.

A: var foo = missingObj || fallbackObj;
only works if missingObj is not undeclared. For example. this happens when missingObj is an argument whose value is undefined (this is the most common use case for x = y || default)
The code your looking for is
} (window.jQuery || window.Zepto));
So basically the reason it doesn't work is because your confusing objects who have a value undefined and objects which are undeclared.
Accessing jQuery is accessing an undeclared value, which doesn't work. Accessing window.jQuery is accessing an undefined value, which does work.
For example
function jQuery(options) {
  options = options || {};
  ...
}

Works because options is undefined rather then undeclared


text:
Q: How to code "a[i]=b[c[i]]" on ARM NEON SIMD Intrinsic function I'm trying to translating this C/C++ code to SIMD Intrinsic function.
for(int i=0 ; i < length ; i++)
    A[i] = B[C[i]];

I can translate below code (C/C++)
for(int i=0 ; i < length ; i++)
    A[i] = B[i];

to SIMD code (using Intrinsic function)
for(int i=0 ; i < length-16 ; i+=16) {
    uint8x16_t v0 = vld1q_u8(A+i);
    vst1q_u8(A+i, v0);
}

I know that keyword is interleaving to solve this problem. But i can't find solution.
Thanks.
Edit
For more information
unsigned char A [32] = {0,}; // Output Array
unsigned char B [20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; // An array with values to pass to A Array
unsigned int C [32] = {19,15,11,10,5,3,6,4,5,19,10,14,16,14,8,9,10,20,11,1, 0, 3, 5, 19, 20, 11, 13, 9, 30, 31, 7}; // An array with the index information of the B array.

Is there any Intrinsic function that can make the following code form?
int length = 32;
For (int i = 0; i < length-8; i+=8)
{
    Uint8x8_t v_idx = vld1_u8 (C + i);
    Uint8x8_t v = func (A, v_idx); // func (uint8_t, uint32x4_t)
    vst1_u8(C+i, v);
}

Will output 20, 16, 12, 11, 6, 4, 7, 5, 6, 6, 20, 11, 15, 17, 15, 9, 10, 11, 21, 12, 2, 1, 4, 6, 20, 21, 12, 14, 10, 31, 32, 8
[Note]
A and B are uint8_t * types because they are images with values between 0 and 255, and C is a uint32_t * type because they are indexed by B index.

A: It's a bit hard to be sure since you didn't provide a lot of information, but vqtbl1_u8 might be what you're looking for.  It's AArch64-only, though vtbl1_u8 is available on armv7.
A quick example:
int main (void) {
  uint8_t bp[] = { 1,  1,  2,  3,  5,  8, 13, 21 };
  uint8_t cp[] = { 0,  2,  4,  6,  1,  3,  5,  7 };

  uint8x8_t b = vld1_u8(bp);
  uint8x8_t c = vld1_u8(cp);

  uint8x8_t a = vtbl1_u8(b, c);
  uint8_t ap[8];
  vst1_u8(ap, a);

  for (int x = 0 ; x < 8 ; x++)
    printf("%3u ", ap[x]);
  printf("\n");

  return 0;
}

Will output 1   2   5  13   1   3   8  21


text:
Q: Insert UTF-8 txt file into MySql results in ErrorCode 1366 I am trying to insert a delimited txt file into MySQL but it seems there is something wrong with the encoding.  I get Error coe 1366:Incorrect string value in in MYSQL when I try and insert.  When I open the txt file it looks like this on the line that caused the error.

Any idea how can I insert this data?

A: You need to escape special characters. Something like \' for quote and so on

A: Somehow hex 9C got into the file.  In latin1, that is œ.
Plan A:
Edit the file to remove it.  The text around there is all in uppercase English, so I suspect it was not supposed to be œ.
Plan B:
Use the charset option to set the incoming stream to latin1.  Then deal with œ later (or not).


text:
Q: Add SystemSounds to PageView in Flutter I want a sound to play with each page change in PageView. I have imported the services.dart package. There is an onPageChanged property in PageView but I can't figure out how to use it to make this happen. Or do I use GestureDetector? Or something else?
Thanks!

A: As far as I know, Flutter does not support audio playing as of now (Feb 2019).
Use plugins like  this pub.dartlang:audioplayers to play audio.
It can be done by simply calling the function on an action that change the page or simply putting a trigger within the state.


text:
Q: Loop over moving averages in Python I have the following data frame and I have to calculate the projection for this year and next year. For that, I multiply the average of the last 4 years by the average of the last 4 ratios.
The point is that I have to repeat the cycle for this year and next year.
I get to the final value but surely there's a much simpler way.
import pandas as pd
import numpy as np
df = pd.DataFrame({"DATE":[2010,2011,2013,2014,2015,2016,2017,2018,2019,2020],"PROFIT":[40,50,60,75,80,95,110,120,np.nan,np.nan]})

df['PROFIT_LOAG'] = df['PROFIT'].shift(1)
df['RATIO'] = round(df['PROFIT']/df['PROFIT_LOAG'],2)

df['PROF_AVG'] = df['PROFIT'].rolling(window=4).mean()
df['RATIO_AVG'] = df['RATIO'].rolling(window=4).mean()

#Last 2 values to predict
for i in range(8,10):

        df.loc[i,'PROFIT'] = df.loc[i-1,'PROF_AVG']*df.loc[i-1,'RATIO_AVG']
        new_prof= df['PROFIT'].rolling(window=4).mean()
        df.loc[i,'PROF_AVG'] = new_prof[i]
        new_ratio=df.loc[i,'PROFIT']/df.loc[i-1,'PROFIT']
        df.loc[i,'RATIO'] = new_ratio
        new_ratio_avg = df['RATIO'].rolling(window=4).mean()
        df.loc[i,'RATIO_AVG']=new_ratio_avg[i]

So, final output is:
df_output = pd.DataFrame({"DATE":[2019,2020],"OUTPUT":[114.159375,120.530807]})


text:
Q: wrong images in listview because imageview is recycled The code looks like this:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final Contact currContact = getItem(position);

    final ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.contact_item, parent, false);

        viewHolder.profileIV = (ImageView) convertView.findViewById(R.id.profileIV);
        viewHolder.nameTV = (TextView) convertView.findViewById(R.id.nameTV);

        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
**************************PER JAKE WHARTON's RESPONSE******************************************
        Picasso.with(getContext()).cancelRequest(viewHolder.profileIV);
    }

    String currName = currContact.getName();

    /* 1
       Asynchronously GETs https://ajax.googleapis.com/ajax/services/search/images?
       rsz=8&start=0&v=1.0&imgsz=medium&imgtype=linear&q=(currName) */
    APIclient.getImageJson(getContext(), currName, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject imgJson) {
            try {
                JSONObject responseDataValue = imgJson.getJSONObject("responseData");
                JSONArray resultsValue = responseDataValue.getJSONArray("results");
                JSONObject result = resultsValue.getJSONObject(0);
                String imgUrl = result.getString("url");

                // 2
                Picasso.with(getContext()).load(imgUrl).into(viewHolder.profileIV);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

*

*The asynchronous call is launched, and the user scrolls down.

*The call completes, the image url is obtained, and Picasso makes ANOTHER GET request to render the image, but in the wrong imageview because of recycling

The only way I know to get around this is to make the first GET request(to obtain the image link) SYNCHRONOUS, blocking the ui to make sure getView isn't called again before the image is loaded.  Is there a better way to get around this?  Many thanks in advance.

A: The reason you are seeing this behavior is that you are only calling the Picasso object after making another asynchronous request. This means that Picasso has no way of knowing that the view was recycled for a new item.
The easiest way to solve this is by adding a call to Picasso to cancel existing requests for the recycled view.
Picasso.with(getContext()).cancelRequest(viewHolder.profileIV)

This should be done outside of the APIclient.getImageJson call so that it runs synchronously when the adapter is called.


text:
Q: How do you limit the amount of posts shown in a while loop? So, I've been looking all over and tried different methods, but I can't seem to get to limit a number of posts shown. Can anyone help?
<?php while( $loop->have_posts() ) : $loop->the_post(); ?>

<div class="portfolio-item <?php the_field('category'); ?> <?php the_field('thumbnail_size'); ?>">

    <div class="portfolio-img-wrap" data-background="<?php the_field('image'); ?>">

<?php the_title(); ?>
<?php the_field('category'); ?>

<?php endwhile; ?>

A: set a if statement its not so hard:)
then just save then info in get when to start and when to break then u have it:D

A:
You could add a count variable and break out of loop when you want.
  See the code below

$count = 0;
<?php while( $loop->have_posts() ) : $loop->the_post(); ?>
$count++;
<div class="portfolio-item <?php the_field('category'); ?> <?php the_field('thumbnail_size'); ?>">

    <div class="portfolio-img-wrap" data-background="<?php the_field('image'); ?>">

<?php the_title(); ?>
<?php the_field('category'); ?>

if($count == 10){
break;
}

<?php endwhile; ?>

A: Her is something clearly wrong.
A while loop shows all results that you got. If you want to limit that you should change the statement that fetches the posts not the while loop.
Otherwise you will fetch x posts and only output for example 10 ... That is an performance factor.
If you want to change the fetch result you have to modify the wp query (as others mentioned).
But in your example there is no custom query. Its the default one... So you can change the amount of posts per page in your backend under settings. Otherwise you should use a custom query and not the default one:
$myposts = get_posts( array( 'showposts'=>10 ) );

if( $myposts ):

    global $post; foreach( $myposts as $post ): setup_postdata( $post );

        // Your output like the_title() etc

    endforeach:

endif;


text:
Q: document.write() not working in userscript with Firefox I have some userscripts that use
var tab = window.open('', '_blank');
tab.document.write(myCustomHtml);
tab.document.close();

to show an output to the user (myCustomHtml being some valid HTML I defined previously in the code). It sopped working in Firefox since version 27, now I only get an empty document. No console errors whatsoever.
The newly opened document has only this content when inspected with Firefox' console

while the source code is empty.
The code works in Chrome.
Do I need to make any modification for newer Firefox versions (27+) and an updated Greasemonkey (1.15)? I haven't found any recent bug reported to Firefox about this issue.
Here's a test script
// ==UserScript==
// @name           document.write() test
// @namespace      stackoverflow.com
// @description    tests document.write()
// @include        https://stackoverflow.com/questions/22651334/*
// @include        http://stackoverflow.com/questions/22651334/*
// @version        0.0.1
// ==/UserScript==

var tab = window.open('', '_blank');
tab.document.write('

a

b

c

');
tab.document.close();

A: I'm not sure if Greasemonkey or Firefox has buggered this, but window.open to a blank page, from a Greasemonkey script, now triggers a Same Origin Policy violation.
Meanwhile, Page scope, the console scope, and Firebug's console all work fine.
Greasemonkey scope gives:

SecurityError: The operation is insecure

whether @grant none is used or not.
This, plus the general uselessness of GM_openInTab(), lead me to suspect it is a Greasemonkey bug.  I don't have time to look into it right now, but file a bug report, if you wish.
To get this to work on the latest release of Firefox (28.0) and Greasemonkey (1.15), here's what I had to do:

*

*Tell my popup blockers to (temporarily) allow popups from stackoverflow.com.

*Inject the popup code into the page scope.

*Use an explicit about:blank for the URL.

*Wait for the new window to load.

Here's a complete script that works on the latest FF+GM releases:
// ==UserScript==
// @name        document.write () test
// @description tests document.write ()
// @include     http://stackoverflow.com/questions/22651334/*
// ==/UserScript==

function fireNewTab () {
    var newTab = window.open ('about:blank', '_blank');
    newTab.addEventListener (
        "load",
        function () {
            //--- Now process the popup/tab, as desired.
            var destDoc = newTab.document;
            destDoc.open ();
            destDoc.write ('

a

b

c

');
            destDoc.close ();
        },
        false
    );
}

addJS_Node (null, null, fireNewTab);

function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    if (runOnLoad) {
        scriptNode.addEventListener ("load", runOnLoad, false);
    }
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}

A: Try using tab.document.body.innerHTML instead of tab.document.write() and tab.document.close(), that is,
var tab = window.open('', '_blank');
tab.document.body.innerHTML = '

a

b

c

';

(I'm using Firefox v24.4.0 with Greasemonkey v1.15 and that works for me.)
I have no idea regarding the root cause of this issue but when I enclosed document.write() in a try-catch block I got the following error message from alert().
The operation is insecure.
Possibly related: Bug 663406 - document.write does not work in devtools scratchpad and console


text:
Q: PHP functions iconv(), mb_convert_encoding() can't convert KOI8-R to CP1251 After exporting data from Cronos database to a TXT-file using Windows application I've got a problem - exported data can't be properly viewed on Linux-server (vieweing on Windows is OK).
Here is a example:
цНПНД|||пЮИНМ|||сКХЖЮ
I've tried to convert it using PHP, because I'd need to convert it to a huge SQL-file later.
Charset-decoding services showed me, that this text should be converted to CP1251 from KOI8-R, so I've tried it using iconv() and mb_convert_encoding()
So, let's try this:
$string = iconv('KOI8-R', 'CP1251', $string);
Result is:
Notice: iconv(): Detected an illegal character in input string
I've googled //IGNORE and tried again:
$string = iconv('KOI8-R', 'CP1251//IGNORE', $string);
Result is:
same string -
цНПНД|||пЮИНМ|||сКХЖЮ
Then it was mb_convert_encoding without "from-encoding" argument:
$string = mb_convert_encoding($string, 'CP1251');
The result is:
?????|||?????|||?????
... and with "from encoding":
цНПНД|||пЮИНМ|||сКХЖЮ
Then it was mirror-attempts (cp1251 to koi8-r). With iconv() I've got "Detected an illegal character in input string"; mb_convert_encoding gave me something new:
зПТПД|||тБКПО|||хМЙГБ
Trying to convert this to UTF-8 showed a lot of different symbols.
I also wanted to convert this file using Notepad++, but it doesn't allow me to open 2.5GB txt-file :(
I've also tried to use iconv as a binary - same errors.
Everything I need is converting this to a readable russian symbols. The best way is to convert it to a UTF-8 but I don't how to do this
Linux node03 4.4.0-142-generic #168-Ubuntu SMP Wed Jan 16 21:00:45 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
iconv (Ubuntu GLIBC 2.23-0ubuntu11) 2.23
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.33-0ubuntu0.16.04.2, Copyright (c) 1999-2017, by Zend Technologies```

A: To use CP1252 with cyrillic letters is not a good idea. Use UTF-8.
PHP can also process strings with charsets != UTF-8 internally.
Attempting to output these strings on a page with a UTF-8 header will result in an incorrect output.
The hexadecimal notation is a possibility to show such strings on UTF-8 pages or to write in the editor under UTF-8.
The function strToHex2 () provides such a string.
//Returns a string with escaped chars in hexadecimal notation
function strToHex2($str) {
   return '\x'.rtrim (chunk_split(strtoupper(bin2hex($str)), 2,'\x'),'\x');
}

The following lines show that the Iconv performs a conversion from KOI8-R to UTF8 (and vice versa):
$cityUTF8 = "Город|||";

//convert to KOI8-R
$cityKOI8 = iconv('UTF-8','KOI8-R',$cityUTF8);
echo "KOI8: ".strToHex2($cityKOI8)."<br>";
//KOI8: \xE7\xCF\xD2\xCF\xC4\x7C\x7C\x7C
//compare with https://en.wikipedia.org/wiki/KOI8-R

//convert back to UTF-8 from KOI8 for a check
$cityUTF8Back = iconv('KOI8-R','UTF-8',$cityKOI8);

//check if equal
var_dump($cityUTF8 === $cityUTF8Back);  //bool(true)

A: Source encoding wasn't KOI8-R. It was CP1251
I convert file using iconv from CP1251 to UTF-8, it helped.