text:
Q: Buscar uma linha específica em um arquivo .txt e alterar o conteúdo Estou com um arquivo contendo em cada linha um número de CPF, nome e login, separados por vírgula. Ex:
  12345678910, gabriel barbosa, gabriel.barbosa@ifnet.com.br
  09876543211, carlos silva, carlos098@ifnet.com.br

O usuário deverá poder alterar o nome, localizando-o atráves do CPF, que será informado pelo próprio. Se o CPF não existir no arquivo, o programa deve informar que não existe.
Usei este código:

Estou com dois arquivos txt:

O arq.txt está assim:

O novo_arquivo.txt está vazio.
Executando o código:

o conteúdo do arq.txt vai para o novo_arq.txt, com as alterações no nome:

Até aí tudo bem, porém, quando vou alterar outra linha, o conteúdo de novo_arq.txt é sobrescrito e a alteração anterior é perdida:

O que posso fazer para resolver?

A: O que você tem é um arquivo CSV (Comma-separated values, literalmente "valores separados por vírgulas"), então uma boa alternativa é usar o módulo csv para lê-lo. Um esboço inicial:
import csv

with open('arquivo.txt') as arquivo:
    reader = csv.reader(arquivo)
    for registro in reader:
        cpf = registro[0].strip()

Primeiro eu abro o arquivo dentro de um bloco with, pois isso me garante que o arquivo é corretamente fechado ao final da execução.
Depois eu uso csv.reader para iterar pelos registros do arquivo. No caso, a cada iteração do for, a variável registro será uma lista de strings, sendo que cada elemento da lista é um dos registros (ou seja, o primeiro elemento é o CPF, o segundo é o nome, etc).
Depois eu pego o CPF e uso strip() para remover os espaços do início, pois não está claro na pergunta se eles fazem parte do arquivo ou se foi erro de digitação. De qualquer forma, agora bastaria comparar este CPF com o que foi digitado. Ficaria algo assim:
import csv

cpf_informado = input('informe o CPF: ')
with open('arquivo.txt') as arquivo:
    reader = csv.reader(arquivo)
    for registro in reader:
        cpf = registro[0].strip()
        if cpf == cpf_informado:
            print('CPF encontrado')
            break
    else:
        print('CPF não encontrado')

Se o CPF for encontrado, eu posso sair do loop com break. Se não for encontrado, ele cai no else. E repare que este else é do for, não do if: em Python isso é possível, e ele cai no else se o loop não for interrompido pelo break (no caso, se nenhum CPF for encontrado).

Você também disse que quer atualizar o nome quando o CPF for encontrado. Neste caso, uma alternativa é criar outro arquivo contendo os registros atualizados:
import csv

cpf_informado = input('informe o CPF: ')
with open('arquivo.txt') as arquivo, open('novoarquivo.txt', 'w', newline='') as novo_arquivo:
    reader = csv.reader(arquivo)
    writer = csv.writer(novo_arquivo)
    encontrou = False
    for registro in reader:
        cpf = registro[0].strip()
        if cpf == cpf_informado:
            encontrou = True
            registro[1] = input('Digite o novo nome: ')
        writer.writerow(registro)

    if not encontrou:
        print('CPF não foi encontrado')

Agora não dá mais para usar break porque eu preciso continuar o loop escrevendo todos os registros no novo arquivo.
Esse algoritmo não ficou tão bom assim, pois caso o CPF não seja encontrado, eu criei o novo arquivo à toa. Então você poderia guardar os registros em uma lista, e só criar o novo arquivo se o CPF for encontrado:
import csv

cpf_informado = input('informe o CPF: ')
with open('arquivo.txt') as arquivo:
    reader = csv.reader(arquivo)
    encontrou = False
    registros = [registro for registro in reader]
    for registro in registros:
        cpf = registro[0].strip()
        if cpf == cpf_informado:
            encontrou = True
            registro[1] = input('Digite o novo nome: ')

    if not encontrou:
        print('CPF não foi encontrado')
    else:
        with open('novoarquivo.txt', 'w', newline='') as novo_arquivo:
            writer = csv.writer(novo_arquivo)
            for registro in registros:
                writer.writerow(registro)

A linha registros = [registro for registro in reader] cria a lista registros, contendo os registros do arquivo. Ela usa a sintaxe de list comprehension, bem mais sucinta e pythônica.
Repare que agora eu só abro o novo arquivo se o CPF for encontrado. Senão, eu só imprimo a mensagem.
Só lembrando que esta solução carrega todo o arquivo na memória, então se o arquivo for muito grande, ela não é adequada, exigindo aí outras soluções. Mas creio que isso já foge ao escopo da pergunta.

Quanto ao seu outro problema, de "perder" as alterações feitas, isso acontece porque você sempre lê do arquivo original e atualiza no novo arquivo (ou seja, você lê dos dados originais, e o novo arquivo sempre tem somente a última atualização).
Neste caso, você poderia sobrescrever o próprio arquivo ao final:
import csv

cpf_informado = input('informe o CPF: ')
with open('arquivo.txt') as arquivo:
    reader = csv.reader(arquivo)
    encontrou = False
    registros = [registro for registro in reader]
    for registro in registros:
        cpf = registro[0].strip()
        if cpf == cpf_informado:
            encontrou = True
            registro[1] = input('Digite o novo nome: ')

if not encontrou:
    print('CPF não foi encontrado')
else:
    with open('arquivo.txt', 'w', newline='') as novo_arquivo:
        writer = csv.writer(novo_arquivo)
        for registro in registros:
            writer.writerow(registro)

Ou seja, primeiro eu leio o arquivo e gero a lista com os registros.
Depois, fora do bloco with, eu verifico se o CPF foi encontrado, e sobrescrevo o próprio arquivo com os novos registros. Desta forma você não "perde" as alterações feitas na próxima vez que for alterar outro registro.

A: Gabriel, sua pergunta está um pouco confusa ou não tem informações suficientes. De qualquer forma interpretei e fiz um código simples que busca se o CPF está ou não contido no arquivo. Para testes basta colocar o código a seguir no mesmo diretório do arquivo teste.txt (ou o nome que desejar):
print("Hello! Type the CPF number:")
search = input()

print("Searching...")
file = open("teste.txt","r")
for line in file.readlines():
    if (search in line):
        print("Great! We have found your search!")
        break

A: Olá Gabriel Barbosa e colegas de programação.
Solução:
print("Hello! Type the CPF number:")
search = input()

print("Searching...")
file = open("teste.txt", "r")

def result(search, file):
    resultado = "Not Found"
    index = 0
    lines = file.readlines()
    file_text = "".join(lines)
    for line in lines:
        dados = line.split(", ")
        cpf = dados[0].replace(" ", "")
        if (cpf == search):
            resultado = "Great! We have found your search!"
            print("Your new username:")
            value = input()
            dados[1] = value
            lines[index] = ", ".join(dados)
            file_text = "".join(lines)
            break
        index += 1
    return {
        "resultado": resultado,
        "file_text": file_text
    }

print(result(search, file)["file_text"])

A: Mano quando você usa o with open('arquivotal', 'w'....)
Esse 'w' sobrescreve o arquivo TXT, você precisa usar o 'a' pois ele concatena o arquivo...
Assim:
with open('seuarquivo.txt', 'a') as file:
    file.write('o que você digitar aqui ele concatena no
    arquivo e não apaga o que tinha antes!')
É nois...


text:
Q: Compare/match/find similar value between data frame/matrix in R I am very confused on value matching in R. I ve tried match, %in%, which, round .. and etc. However no luck to compare 2 data sets each other.
Some part of my data intersect on 3D space. Sample coordinates are stored in data frame as below :
(X,Y,Z)  (100.234,150.656,35.678)
Data set is huge. When I compare data sets with %in% function. it does not response true.
I've read some forum pages and somebody mention floating point values. How to fix the matching problem in R? Any sample R code for matching 2 data set which intersect some parts?

A: Welcome to the R-section!
I don't know exactly what type of data your are trying to work with nor the purpose of the comparison of your data.
However here are some ways you can find that information out (with slightly different outputs):
xdat<-c(10,13,32,17)
ydat<-c(32,17,10,5,19)

> which(xdat %in% ydat)
[1] 1 3 4

> match(xdat,ydat)
[1]  3 NA  1  2

> xdat %in% ydat
[1]  TRUE FALSE  TRUE  TRUE

> unlist(sapply(xdat,function(x) grep(x,ydat)))
[1] 3 1 2

Also, this short R reference card could be helpful for finding functions for different operations.
It is hard to know what problems you are running into, and why. You could for instance try to change number of digits shown in your values by: options(digits=7) to see if you can find the cause.
Furthermore, you can use round and signif functions depending on your data, see examples below:
> round(123.786582307,digits=8)%in%round(123.786582308,digits=8)
[1] TRUE

> round(3.786582307,digits=8)%in%round(3.786582308,digits=8)
[1] TRUE

> signif(123.786582307,digits=11)%in%signif(123.786582308,digits=11)
[1] TRUE

> signif(3.786582307,digits=9)%in%signif(3.786582308,digits=9)
[1] TRUE

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does Andrew Grayson have his 9mm pistol back before dropping down to New Svalbard? In Points of Impact by Marko Kloos, Captain Andrew Grayson is given a dressing down, by the CO of the ship Ottawa, for having a personal pistol in his room, after being asked to turn them all in upon boarding.
He fears getting thrown in the brig, and ends up getting off relatively easy, having only to sacrifice alcohol while on board ship.
However, when he suits up for the last drop, he pulls the gun out of his locker and straps it on to do the drop.
Is this an inconsistency in the books? Or did I miss something where they allowed him to keep it, even though it was a flagrant broken rule?

A: There's no answer in the book. The author explains in a  blog post that it was an error introduced during editing/revision of the text.

Andrew's personal sidearm gets confiscated by the master-at-arms and ends up on the shelf in the CO's office, yet he retrieves it from his locker again prior to the final battle. That continuity error snuck in because I inserted the dressing-down scene during the developmental edits and forgot to remove the later mention of the pistol. If you want, we can pretend that his sympathetic CO arranged to return the gun on the quiet because of its sentimental value (and/or because she thinks he made a fair point in his defense.)

A: I don't think it's possible to explain this by reference to the book. It seems like a straightforward error. Until Grayson takes the pistol out of his locker, the last reference to it is when Colonel Yamin puts in on a shelf.

She sighs and visibly pulls herself together. Then she takes the
  pistol off the desk and puts it on a shelf behind her.

Even Grayson mentally recognizes that this is a fair punishment, and that Yamin could have done worse, such throwing him in the brig or demoting him, so I don't think it would have been likely that Yamin would have decided that Grayson could have his pistol back, nor that it would have gone without note if she had.
Besides, as mentioned earlier in the book, it's not simply a matter of Grayson having failed to inform anyone that he had brought the pistol with him. Sidearms are simply not allowed on the ship, whether stored in the armory or not.

"Talking about following orders. You aren't a nugget fresh out of
  officer school. You know that sidearms, personal or issued, aren't
  allowed on this ship."

For Grayson to have been able to put the gun back in his locker, either they would have had to have given him special dispensation, or he somehow would have needed to have taken the gun back from Yamin's office. Those events seem unlikely, and more unlikely still is that they wouldn't merit a mention in the story.


text:
Q: Multiple foreign keys to same table using Elixir I am new to ORMs in general. I have a table (lets call it Entity) with columns --

*

*ID

*expression

*type ( can be 'long_word', 'short_word' or 'sentence' )

Often, the first two types occur in a 'sentence', so, I want to maintain another table which maps 'Sentences' to 'long_word' or 'short_word' using the 'ID' field.
All i need is another table with 2 'Integer fields' referring to 'ID' as a foreign key.
But, how do i do this in Elixir?
Edit : I was afraid it will come to this eventually. No sweat, SQLAlchemy is solid, it will be worth it in the long run. But i really wish Elixir had worked. Cant have everything the way you want.
Thanks a lot...


text:
Q: How to open dynamically a new page in Django I have made a Django application to show a list of clustered news articles. I want in the first page to show just a three of articles, and if the user wants to show them all, he can click the "See the real coverage" link and see the overall list of the articles (as GoogleNews functions). In the main page, I have the list of articles in a variable called lista. And I want to publish only the first three elements in the main page, and I want to transfer the list of articles in the the new page which, let's, I call theme. I add the theme function in the views.py file as:
def theme(request,argument):
    lista=argument
    return render(request,'theme.html', locals())

And the main.html code where i call the theme function is as follows:

or I try:

The urls.py code is:
urlpatterns = patterns('',
    ('^main/$', main),
    ('^all/$', tegjitha),
    ('^(sport)/$', gen),
    ('^(teknologji)/$', gen),
    ('^(showbiz)/$', gen),
    ('^(bota)/$', gen),
    ('^(ekonomi)/$', gen),
    ('^(kulture)/$', gen),
    ('^(theme)/$', theme),

It gives me: NoReverseMatch at /main/ error.

A: You need to realize the approach you are trying to take will not work. All that the url template tag does is to produce a simple string - an URL for a particular resource. So the result of the tag might be a string like "/post", "/post/24" etc. And that's it. The function doesn't do anything besides producing the URL string, and there is no place for a list of complex python objects in a simple web URL.
You need to also realize that the web, on the most basic level, is stateless. You can not just pass python objects between requests, because each requests is completely separate. You can simulate keeping state between requests using sessions, but I don't think this is the right tool in this particular case.
What you should do instead is to have a unique identifier for each list and pass the identifier in the URLs (in opposite to passing a whole list in an URL). You would then use the identifier in your view, to retrieve the list again, and display the result.

A: you need to direct your urls.py as absolute strings just like the url tag in the template. So main would look like this:
('^main/$', 'mysite.views.main'),

You can also define at the top the path to your patterns:
urlpatterns = patterns('mysite.views',
    ('^main/$', 'main'),
    … etc

But notice you still need to reference it as a string


text:
Q: GET function doesnt work in autocomplete search script i have problem with this, i want to pass 1 search results to another, i used get to pass it to search.php , and a the end i get category and subcategory with autocomplete search, everything works when i put fixed $parent but when i want to use get it doesnt work
index.php:

<input type="text" class="search" id="searchid" placeholder="e.g." />

Channel's name:

<input type="text" class="search1" id="searchid1" placeholder="e.g." />

search.php:
   <?php
include('db.php');
if (isset($_POST['search'])){
$pp=$_POST['search'];
$sql_rest=mysql_query("SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA = 'xdd' AND TABLE_NAME LIKE '%$pp%' LIMIT 5");
while($row=mysql_fetch_array($sql_rest))
{
$country=$row['TABLE_NAME'];
$b_country=''.$pp.'';

$final_country = str_ireplace($pp, $b_country, $country);

?>

<?php echo "$final_country"; ?>

<?php
}

}
if (isset($_POST['search1'], $_GET['result'])){
$parent = $_GET['result'];
$database = mysql_select_db('plavo_channels') or die(mysql_error());
$q=$_POST['search1'];
$sql_res=mysql_query("SELECT chann FROM $parent WHERE chann LIKE '%$q%' LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$username=$row['channel'];

$b_username=''.$q.'';

$final_username = str_ireplace($q, $b_username, $username);

?>

<?php echo $final_username; ?>

<?php

}}
?>

i dont usually do ajax and jquery
tnx all

A: the input will be like this
<form action method="POST">
  <input type="text" id="first" />
  <input type="text" id="second" list="list1"/>
  <input type="text" id="third" list="list2"/>
</form>

and will add to html page at end
<datalist id="list1">
</datalist>
<datalist id="list2">
</datalist>

javascript will be like this
$(document).ready( function(){
    $("#first").keyup(function(){
        first=$("#first");
        xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","autocomplete.php?first="+first,false);
        xmlhttp.send();
        document.getElementById("list1").innerHTML=xmlhttp.responseText;
    });
    $("#second").keyup(function(){
        first=$("#first");
        first=$("#second");
        xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","autocomplete.php?first="+first+"&second="+second,false);
        xmlhttp.send();
        document.getElementById("list2").innerHTML=xmlhttp.responseText;
    });
});

autocomplete.php will be
<?php
if($_GET['first']&&$_GET['second'])
{
    // here list2
    echo"<option>option1</option>";
    echo"<option>option2</option>";
}
if($_GET['first'])
{
    //here list1
    echo"<option>option3</option>";
    echo"<option>option4</option>";
}
?>

but u will change options to be from databasse


text:
Q: How to check the page load times of pages generated by Mobify-js I am looking for measuring the time required for loading a page which has been generated by Mobify-js. As mentioned on the website, when the js is used, the page load times is optimizated. So, I wanted to understand, against what benchmarks (original) file can I measure the performance of mobify-js.
One thing that comes to my mind is, simply removing the import of the mobify-js for a sample page like "resizeImages-img-element/index.html" in the source code, and comparing the page load times of with and without mobify-js. Mobify-js  community, any thoughts on the same? Any help in this regards will be appreciated.

A: You can get some timing data about the different parts of the Mobify transformation by looking at Mobify.timing.points. Using this you can measure the time difference between when the page begins loading and a collection of different events.
// Measure time between 'finished document' and 'DOMContentLoaded'
var loadTime = Mobify.timing.points[11][0] - Mobify.timing.points[0][0]


text:
Q: Colimits of algebras for $\infty$-Monad I would like to know in anyone has developed method for constructing colimits in the category of algebra for a monad in the $(\infty,1)$-categorical framework, using transfinite constructions.
I have in mind an analogue of Kelly's construction of such colimits in the $\infty$-categorical framework. Though any explicit construction of colimits in the category of algebra for an accessible monad on a presentable categories would be of interest.
Lurie is proving the existence of colimits in the special case of algebras for operads, but I don't think its proof can be extended to more general monads, but there might some things to be done...
My motivations: I want to prove that a certain class of morphisms between algebras for a monad are stable under colimits. This doesn't seems to follow from formal properties, so I need a concrete construction of these colimits to prove it. If I naively assume that Kelly's construction works in $\infty$-categories, then I can prove what I want by induction on the transfinite construction. But of course Kelly's construction doesn't work without modification in $\infty$-category theory, so I'm wondering if someone has developed some tools to explicitly construct such colimits.


text:
Q: Create CSS Arrow at cursor (or clicked element) location? I have two vertical Divs on my page.  The one on the left has a table of properties.  Clicking a property results in the right div appearing and displaying details for that property.  I'm using a CSS arrow as explained at http://cssarrowplease.com/ and all looks and works great.  The problem is that the arrow is always in the same place.  I would like it to be at the same height as the element/row that was clicked.
Here is what I tried:  (By the way, I'm using Knockout so this is coming from a knockout click event.  I have confirmed that "position" is correct)
function viewConflicts(data, event) {
    var position = $(event.target.parentElement).position();
    $('.arrow_box:after').css('top', position.top);
    $('.arrow_box:before').css('top', position.top);
}

And here is the CSS adapted from the site above:
.arrow_box:after, .arrow_box:before {
    right: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}

.arrow_box:after {
    border-color: rgba(136, 183, 213, 0);
    border-right-color: #cbcece;
    border-width: 30px;
    /*top: 50%;*/
    margin-top: -30px;
}
.arrow_box:before {
    border-color: rgba(194, 225, 245, 0);
    border-right-color: red;
    border-width: 31px;
    /*top: 50%;*/
    margin-top: -31px;
}

Normally it's vertically centered, obviously due to the "top: 50%".  When I comment that out and use my function above it puts the two elements at different positions vertically, both towards the top.

A: Apparently you cannot set pseudo classes directly using jquery.  See Changing width property of a :before css selector using JQuery
This solution works great:
$('body').append('<style>.arrow_box:before{top:' + (position.top + 8) + 'px !important;}</style>');
$('body').append('<style>.arrow_box:after{top:' + (position.top + 8) + 'px !important;}</style>');

Also, I had to replace .position() with .offset() as position returned the relative value.
var position = $(event.target.parentElement).offset();


text:
Q: Inheriting from QWidget and make class a Template I hope this is not a silly question, but I am very inexperienced in templating, and this problem goes over my head. I work on a project that relies heavily on QT Designer for GUI Design, and I want to make available a special QWidget subclass which allows to abstract interaction with a complicated service mechanism. This widget needs class specific Information, to resolve the services. The coding itself is done in Visual Studio 2008.
So what I want to create is a templated QWidget Subclass. With my limited knowledge, I tried slapping the usual template statement in front of the class:
template <class T>
class QmitkMyWidget :public QWidget

unsuprisingly, this does not work that easily. The generated moc classes act up.
error PRJ0019: A tool returned an error code from "Generating Qmitk/moc_QmitkMyWidget.cxx"

Which seems kind of logical to me since I "didn't tell them what to do". I figure I have to specify templating inside of QT Designer, but i really do not no how, and unfortunaley searching finds tons of result for code templates in QT Designer, but none about the generic programming concept. I'd really appreciate any hint && || helpful sources/articles. Thanks for your time!
Edit: Silly typo in the first code =/

A: I have confirmed that this is impossible.
Source: Limitations mof the moc concept
The gist is, that mocs are preprocessed, but templates are only translated into actual code on compile time.
Edit: I may add that instead of making the class itself templated, I am now only templating the public functions, which works quite well so far, though it of course requires to consumer to type out the declaration everytime he calls the function.


text:
Q: Check if JSON string in Orbeon repeating grid contains a specific value Working with the repeating grids through the form builder.
I have a custom control that has a string value represented in json.
{
  "data": {
    "type": "File",
    "itemID": "12345",
    "name": "Annual Summary",
    "parentFolderID": "fileID",
    "owner": "Owner",
    "lastModifiedDate": "2016-10-17 22:48:05Z"
  }
}

In the controls outside of the repeating grid, i need to check if name = "Annual Summary"
Previously, i had a drop down control and using Calculated Value $dropdownControl = "Annual Summary" it was able to return true if any of the repeated rows contained the value. My understanding is that using the = operator, it will validate against all rows.
Now with the json output of the control, I am attempting to use
contains($jsonStringValue, 'Annual Summary')

However, this only works with one entry and will be null if there are multiple rows.
2 questions:

*

*How would validate whether "Annual Summary" (or any other text) is present within any of the repeated rows?

*Is there any way to navigate the json or parse it to XML and navigate it?

Constraint:

*

*within the Calculated Value or Visibility fields within form builder

*manipulating the source that is generated by the form builder

A: You probably want to parse the JSON string first. See also this other Stackoverflow question.
Until Orbeon Forms 2016.3 is released, you would write:
(
    for $v in $jsonStringValue
    return converter:jsonStringToXml($v)
)//name = 'Annual Summary'

With the above, you also need to scope the namespace:
xmlns:converter="org.orbeon.oxf.json.Converter"

Once Orbeon Forms 2016.3 is released you can switch to:
$jsonStringValue/xxf:json-to-xml()//name = 'Annual Summary'


text:
Q: Is it possible to change an object's type from inside itself I have a shape class with square and triangle as inheriting classes
Square square = new Square();
square.SideCount = 4;
//Logic
square.SideCount = 3;

if(square is Triangle)
   {
   //...

If I instantiate a new square with SideCount = 4, then if I change it's SideCount to 3, can I put code into the SideCount's Setter to convert Square to Triangle if sides are set to 3?

A: Not directly no, an instance of Square cannot be changed to an instance of Triangle.
You could have a method, which returns an instance of Shape defined on the base class Shape:
public abstract class Shape
{
    public Shape Mutate(int numberOfSides)
    {
        // over simplified example:
        if(numberOfSides == 3)
           return new Triangle();
    }
}

public class Triangle : Shape {}
public class Square : Shape {}

usage
var squ = new Square();
var triangle = squ.Mutate(3);

A: Now, you can't. Types are rigid respect to their instance content.
In C++ you can have generic type parametrized by integer value.
Generally, if you want to change something at runtime, you should not make it belonging to a type. So, don't make SideCount writable. Let user create new instance if he want another value for this property.


text:
Q: How to convert a long to date? I have a long value in Rails, 134740800, which is the number of milliseconds since the epoch.
How do I convert that to a date in mm-dd-yyyy format?
I figure the formatting would be done with something like strftime but I can't seem to find the right method to convert the long into a valid date.

A: secs = 134740800/1000 # millisecs / 1000
t = Time.at(secs)
t.strftime("%m-%d-%Y")

Output
"01-02-1970"

A: Try this:
require 'date'
DateTime.strptime("1318996912",'%s')

A: I assume you mean seconds since the epoch.
Time.at seconds_since_epoch

You can also pass a float. If you have milliseconds, divide by 1000.0 first.
You can then call strftime on the returned Time object.

A: Use Time.at:
irb(main):003:0> Time.at(134740800)
=> Tue Apr 09 08:00:00 -0400 1974

A: This is an advisory... It's often a good idea to look at how fast some answers run. Here's a simple benchmark:
require 'benchmark'
require 'date'

SECS = 134740800
LOOPS = 1_000_000

puts Time.at(SECS).strftime('%m-%d-%Y')
puts Date.strptime(SECS.to_s, '%s').strftime('%m-%d-%Y')

Benchmark.bm(14) do |x|
  x.report('Time.at:') { LOOPS.times { Time.at(SECS) }}
  x.report('Date.strptime:') { LOOPS.times { Date.strptime(SECS.to_s, '%s') }}
end

And the output is:
04-09-1974
04-09-1974
                     user     system      total        real
Time.at:         0.370000   0.020000   0.390000 (  0.392761)
Date.strptime:   6.320000   0.050000   6.370000 (  6.373248)


text:
Q: How is the actual baryonic density calculated from critical mass? The Planck 2018 results give the Baryonic Density as: $\Omega_B h^2=0.0224$.  I want to calculate the actual density based on the parameters.  The same report tells us that $H_0=67.4$.  We know that the critical density is:
$$\rho_c=\frac{3 H^2}{8 \pi G}$$
$$\rho_c=8.53\times 10^{-27}\space kg\space m^{-3}$$
So if I want to get an actual value for the current baryon density, do I perform this operation:
$$\Omega_B h^2\space \rho_c = 0.0224 * (\frac{67.4}{100})^2 * 8.53\times 10^{-27}\space kg\space m^{-3}=8.68\times 10^{-29}\space kg\space m^{-3}$$
or is the right way to interpret the density as (note that we don't use the $h^2$ factor):
$$\Omega_B\space \rho_c = 0.0224 * 8.53\times 10^{-27}\space kg\space m^{-3}=1.91\times 10^{-28}\space kg\space m^{-3}$$
Or, is the notation really, really, really backwards and it should be:
$$\Omega_B h^{-2}\space \rho_c = 0.0224 * (\frac{67.4}{100})^{-2} * 8.53\times 10^{-27}\space kg\space m^{-3}=4.21\times 10^{-28}\space kg\space m^{-3}$$
The last one seems to make the most sense, because it gives a baryonic percent of critical density of 5%, which is what you hear quoted often.
Which is the right Hubble-adjusted value for baryonic density and, if the last formula is right, why is the value quoted as $\Omega_B h^2$ instead of $\Omega_B h^{-2}$ in the Planck study?

A: It would appear that dislexia got in the way of interpreting the $\Omega_B h^2=0.0224$ notation properly.  As the conversation above goes, the answer - based on the Planck 2018 results - is:
$$\Omega_Bh^2=0.0224$$
$$\Omega_B=\frac{0.0224}{h^2}$$
$$\Omega_B=0.0224h^{-2}$$
$$\rho_B=\Omega_B\cdot \rho_c=0.0224\cdot 0.674^{-2}\cdot 8.53\times 10^{-27}\space kg\space m^{-3}=4.21\times 10^{-28}\space kg\space m^{-3}$$
I'd appreciate it if someone could just double check that this is the right value.


text:
Q: How to get Composer to leave a package alone I have two packages that was pulled to my project with composer.
I don't want to have composer pull updates on these packages from anywhere and don't want composer to try and override my files with any repository.
If I remove the packages from my composer.json file it deletes the packages an removes the autoloaders.
How do I get composer to leave the packages alone and allow me to work on the code without losing the files or autoloaders on update.

A: I figured out how to do this.
What you want to do is create an artifact directory.
Thus in your main composer.json file you need to do something like this:
"repositories": [
    {
        "type": "artifact",
        "url": "custom/artifact/"
    },
    ..........

the url var should be the file path to the zip files relative to composer.json file.
Now you only need to add a composer.json file with a name and version to a zip file.
If the package already contains a composer.json file you only need to add a version.
example:
vendor-package-1.0.zip needs a composer.json file with:
{
    "version": "1.0",
    "name": "vendor/package",
    "type": "library",
    ........... etc
}

It is important to define the version in the composer.json file or it will not find it.
Now you call this package by version from your projects composer file:
"require": {
    "vendor/package": "1.0",

Now you can create and update files in your package without the worry that some online change or offline server will cause any problems.
As long as the version stays the same it should leave your files alone.
The good thing is that files added or removed will still update the autoloaders as specified in the zip package's composer.json file.

A: Give a specific version for that package, so it will not be updated when new versions come up
If you don't have too many packages, you can use
composer update package1 package2


text:
Q: Blocking failed logins using PAM I heard Centos can block user based on failed logins.
http://www.cyberciti.biz/tips/lock-unlock-set-number-of-login-attempts.html
The post says by default it checks for /var/log/faillog how do I change this to another log file to keep trace of failed logins.
I have a Plesk-managed server. I have to check /var/log/secure and
/usr/local/psa/var/log/maillog. Can any one advise.

A: the faillog that page is referring to is a special file used by pma_tally. It doesnt scan logs looking for login failures.
Basically whenever you have a failed login, pam_tally records the entry in the faillog. Then whenever you go to log in, it looks in the faillog to see if you've exceeded the threshold. Once you have it starts refusing logins.
If you want to deny remote ssh logins based on log parsing you want either fail2ban or denyhosts. Both read logs to track login failures and add iptables or tcpwrapper deny rules to block access from the source IP (not based on user).


text:
Q: How to add column in Pivot table with custom calculation or work with multiple sheets I am trying to work with Pivot table with some calculation from another sheet then its range. Can it possible to add column inside pivot able  or at end of pivot table with custom calculation.
Sheet 1 format

A B C D

Sheet 2 format

D E F C B

Sheet 3 format

D E F C B A

another option for this is How to make pivot table with different source of data in all sheet B is conman for everyone.I tried SQL query but it will not work until it will be in same format for all.
It will be helpful if you can provide some solution to the situation.

A: You can do it in both ways:

*

*Calculated Fields in the Pivot Table: you can find a step by step guide at this link.

*MySQL query to a database:

*

*create three tables, one for each sheet

*make sure that you can link the tables to each other (a common ID or something similar)

*if so, you can join the different tables in the same query and make your calculation

I would say that the easier solution is to create calculated fields.
A database will be much more powerful but it might be out of the scope of your needs.
Edit after reading your file
It seems that you need to compare the balance according to three data sources:

*

*Sap Data tab

*Company Code ICR tab

*Trading Partner ICR tab

Since you have in common the most of information, you might want to map all the data on the same page and then to do a PivotTable.
E.g. Add to Snap Data tab the information of Company Code ICR

*

*Choose a unique identifier for the same item in both sheets (Document No.)

*Choose the column you want to get

*Add a column to your original tab

*Use VLOOKUP function

If you need more details, leave a comment and I will include more elements to the answer


text:
Q: How to supress any title or caption for \lstinputlisting? I am using
\lstinputlisting[]{javacode/DatabaseManager-getUser}

to show some java code. However the following caption appears underneath the listing (see picture marked with red arrow):

In my preamble I have used \lstset to set title={}, however I don't want anything there, no title or caption. Is this possible? And if so how would I go about doing it?

A: See MattAllegros comment in OP. It made me find the issue. In my preamble I had the following setup:
\usepackage{listings}
\lstset{ %
  backgroundcolor=\color{grayC},
  basicstyle=\ttfamily\small,
  breakatwhitespace=false,
  breaklines=true,
  captionpos=b,
  commentstyle=\color{greencomments},
  deletekeywords={...},
  escapeinside={(*@}{@*)},
  extendedchars=true,
  frame=single,
  keepspaces=true,
  keywordstyle=\color{bluekeywords},
  language=Java,
  morekeywords={partial, var, value, get, set},
  numbers=left,
  numbersep=5pt,
  numberstyle=\tiny\color{black},
  rulecolor=\color{Dgray},
  showspaces=false,
  showstringspaces=false,
  showtabs=false,
  stepnumber=1,
  stringstyle=\color{redstrings},
  tabsize=2,
  morekeywords= {new, std::*,},
  title={}
}

I commented out captionpos=b and title={}, and now I get nothing underneath the listing as was what I wanted in OP. for output comparrison see:


text:
Q: Proper syntax for an AMPScript block Hope you can help me on this.
Still a newbie, but I'm finding myself using AMPScript more and more when creating dynamic content for my marketing sends.
But I constantly find an inconsistency in how examples of AMPScript are posted.
Sometimes I find AMPScript encapsuled like this:
<script runat="server" language="ampscript">
VAR @dyncountry, @country

SET @dyncountry = UPPERCASE([Country Code])

IF
@dyncountry == "DK" THEN
SET @country = "5315"
ELSE
SET @country = "5365"
ENDIF

Output(ContentBlockByID(@country))

</script>

And sometimes like this:
%%[
VAR @dyncountry, @country

SET @dyncountry = UPPERCASE([Country Code])

IF
@dyncountry == "DK" THEN
SET @country = "5315"
ELSE
SET @country = "5365"
ENDIF

Output(ContentBlockByID(@country))

]%%

I've tried both and they seem to output exactly the same.
So, is one the better option.. Or do they come with different advantages?

A: They have the same general effect while rendering. See below reference material from SFMC for more information on the technical aspect.
I tend to use the script tag for my ampscript, but mostly only due to aesthetics.  In using the %%[ and ]%%, the ampscript can show up, not just in third party editors, like Dreamweaver, and browsers but also inside the editor preview inside SFMC.  When you place it into the script tag, by default all editors hide the content inside (as long as you format it correctly).
A lot of the people I work with do not understand technology that well, so the less I need to explain why there is, as they call it, 'gobblety gook' on the email, the better.
Below taken from AMPScript Syntax Guide - more specifically from function calls section:

Tag-based Syntax for AMPscript
Tag-based syntax for AMPscript standardizes the syntax used to declare AMPscript blocks with the syntax of server-side JavaScript. This syntax eases the burden on developers to write in a different syntax when switching between AMPscript and server-side JavaScript. Use the information below to format your AMPscript calls. AMPscript calls are case-insensitive.

Minimum Syntax
This sample illustrates the minimum syntax necessary to declare an AMPscript block.
<script runat=server language=ampscript>
    [INSERT AMPSCRIPT HERE]
</script>

Full Syntax
This sample illustrates the complete syntax used to declare an AMPscript block.
<script runat=server language="ampscript" executioncontexttype="Post" executioncontextname=test>
    [INSERT AMPSCRIPT HERE]
</script>

The AMPscript block must be closed in the same syntax that opens it. For example, if you open a block using <script>, you must close it with </script> and not ]%%.

Delimiter Comparison
The table below demonstrates the similarities between standard AMPscript delimiters and server-side delimiters.
  Standard AMPscript Delimiter
  Tag-based AMPscript Delimiter

%%[
<script runat=server language=ampscript>

%%[[type=post;name=blockname] <script runat=server language=ampscript                                                        executioncontexttype="Post" executioncontextname=blockname>

]%%                                                </script>

%%[]%%                                          <script runat=server language=ampscript />

A: It's the same.  The Server-Side JavaScript Syntax Guide
says that:

For the Language parameter, you can specify either JavaScript or
  AMPscript. If no parameter is specified, the system defaults to
  JavaScript.

A: They appear to function the same, however OMM does not give detail on AMPscript errors (in Send Preview) if you have tag-based delimiters; it just throws a generic error:
An error occurred when attempting to evaluate a TreatAsContent function call. See inner exception for details.
An error occurred when attempting to parse HtmlEmailBody content for HTML content.
MemberID: 7230771
JobID: 0
ListID: 52
Content Begins With:

You need to change the delimiters to the standard delimiters to see error detail.


text:
Q: ActiveRecord::RecordNotFound in BooksController#update I am new to ruby as well as rails I am getting the following error while I clicked the update button
ActiveRecord::RecordNotFound in BooksController#update
                Couldn't find Book without an ID
                Extracted source (around line #35):
                def update
                  @book = Book.find(book1_params[:id])........here it is line number 35
                  if @book.update_attributes(params[:book])
                    redirect_to :action => 'show', :id => @book

                activerecord (4.0.3) lib/active_record/relation/finder_methods.rb:266:in `find_with_ids'
                activerecord (4.0.3) lib/active_record/relation/finder_methods.rb:35:in `find'
                activerecord-deprecated_finders (1.0.3) lib/active_record/deprecated_finders/relation.rb:122:in `find'
                c:in `find'
                app/controllers/books_controller.rb:35:in `update'

books_controller.rb
I am getting above error in update method.
class BooksController < ApplicationController
      def list
        @books = Book.find(:all)
      end
      def show
        @book = Book.find(params[:id])
      end
      def new
        @book = Book.new
        @subjects = Subject.find(:all)
      end
      #  private
      def book_params
        params.require(:book).permit(:title,:price,:subject,:description)
      end
      def create
        @book = Book.new(book_params)
        if @book.save
          redirect_to :action => 'list'
        else
          @subjects = Subject.find(:all)
          render :action => 'new'
        end
      end
      def edit
        @book = Book.find(params[:id])
        @subjects = Subject.find(:all)
      end

      def book1_params
        params.require(:book).permit(:id)
      end

      def update
        #below is the line I am getting the error....
        @book = Book.find(book1_params)

        if @book.update_attributes(params[:book])
          redirect_to :action => 'show', :id => @book
        else
          @subjects = Subject.find(:all)
          render :action => 'edit'
        end
      end
      def delete
        Book.find(params[:id]).destroy
        redirect_to :action => 'list'
      end
      def show_subjects
        @subject = Subject.find(params[:id])
      end
    end

routes.rb
LibrarayWebApplication::Application.routes.draw do

    get 'books/list'
    get 'books/new'
    post 'books/create'
    post 'books/update'
    get 'books/list'
    get 'books/show'
    get 'books/edit'
    get 'books/delete'
    get 'books/update'
    get 'books/show_subjects'
  end

view
The below code gets the data from database and it displays the user. If user required he/she can  update the information, but when I pressed update button its showing the error.
I am using rails4 and eclipse IDE, and mysql2 gem and MySQL database. I am able to perform create,delete,list or show operation but I am unable to perform update operation. I am helpless and can give a suggestion to know the rails4 details with complete application

Edit Book Detail

<%=form_tag :action => 'update', :id => @book %>

    Title:
    <%= text_field 'book', 'title' %>

    Price:
    <%= text_field 'book', 'price' %>

    Subject:
    <%= collection_select(:book, :subject_id, enter code here @subjects, :id, :name) %>

    Description

    <%= text_area 'book', 'description' %>

  # the below line is to update the content in the database
  <%= submit_tag "Save changes" %>
  <%= link_to 'Back', {:action => 'list'} %>

A: replace
def update
        #below is the line I am getting the error....
        @book = Book.find(book1_params)

        if @book.update_attributes(params[:book])
          redirect_to :action => 'show', :id => @book
        else
          @subjects = Subject.find(:all)
          render :action => 'edit'
        end
      end

to
def update
  #below is the line I am getting the error....
  @book = Book.find(params[:id])

  if @book.update_attributes(book_params)
    redirect_to @book
  else
    @subjects = Subject.all
    render 'edit'
  end
end


text:
Q: Use Google Cloud backend with GCM for android version before ICE CREAM SANDWICH I tried to follow this tutorial to deploy backend with Google Cloud Engine, then I follow this and this to register push notification with GCM to run the sample project and got the success. The problem is my app need to support android version 2.2+ (api level 8), but the cloud backend require minimum API level of 15 (ICE CREAM SANDWICH MR1).
I tried to set api level down to 8, then replace all fragments and activities with the support package library, but it gave me an exception Failure delivering result on runtime:
   02-15 13:41:23.266: E/AndroidRuntime(5209): FATAL EXCEPTION: main
   02-15 13:41:23.266: E/AndroidRuntime(5209): Process: com.google.cloud.backend, PID: 5209
   02-15 13:41:23.266: E/AndroidRuntime(5209): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {com.google.cloud.backend/com.google.cloud.backend.sample.guestbook.GuestbookActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.app.ActivityThread.deliverResults(ActivityThread.java:3488)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3531)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.app.ActivityThread.access$1300(ActivityThread.java:157)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1295)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.os.Handler.dispatchMessage(Handler.java:102)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.os.Looper.loop(Looper.java:157)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.app.ActivityThread.main(ActivityThread.java:5293)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at java.lang.reflect.Method.invokeNative(Native Method)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at java.lang.reflect.Method.invoke(Method.java:515)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1259)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at dalvik.system.NativeStart.main(Native Method)
   02-15 13:41:23.266: E/AndroidRuntime(5209): Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1343)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1354)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at com.google.cloud.backend.sample.guestbook.GuestbookActivity.initiateFragments(GuestbookActivity.java:212)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at com.google.cloud.backend.sample.guestbook.GuestbookActivity.onActivityResult(GuestbookActivity.java:168)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.app.Activity.dispatchActivityResult(Activity.java:5581)
   02-15 13:41:23.266: E/AndroidRuntime(5209):  at android.app.ActivityThread.deliverResults(ActivityThread.java:3484)

Is there any alternate way to make it works on android API level less than 15? Since the GCM support minimum level 2.2+, from the document:

The GCM-enabled Android application that is running on a device.  This
  must be a 2.2 Android device that has Google Play Store installed, and
  it must have at least one logged in Google account if the device is
  running a version lower than Android 4.0.4.  Alternatively, for
  testing you can use an emulator running Android 2.2 with Google APIs.

Update: I just run this example from Google and change all Fragment to  android.support.v4.app.Fragment and Activity to     android.support.v4.app.FragmentActivity because I change minSdkVersion to 8 in manifest.


text:
Q: change notification on domain objects (Hibernate/Java) Is there a solution available to subscribe for domain object changes for Hibernate or any other mainstream O/R mapping framework? For example if I have a table in a database called "Apple" I'd like to be able to say "notify me when any Apple object changed" or "notify me when field "colour" of any Apple object changed". Of course I'd expect not just "something changed" notification but rather a list of id's of changed objects or a list of changed objects. Would be nice such solution to be scalable.
to summarize requirements:

*

*All changes to a DB will go through an ORM

*It should be a complete solution where it's possible to place a subscription using an expression like "subscribe for Question q where q.title like '%hibernate%'" where "Question" is an entity (Java object mapped to a table in a database) I'm interested in updates for. No need to be a string query but there should be a generic way to place a request.

A: Will all the changes that generate these notifications go through the ORM, or is it possible that data might be changed via JDBC or another application accessing the same database?
If all changes go through the ORM and you are using Hibernate, then you could use Hibernate's interceptors and events.
On the other hand, if all the changes to the data don't go through the ORM and the code that processes the notifications is fairly simple, database triggers might be a better bet.


text:
Q: Mongoose: How to update nested fields with fields present in request body only? Looking to update lookupSchema images nested fields
var lookupSchema = new Schema({
    images:{
      "img1":String,
      "img2":String,
      "img3":String,
      "img4":String
    }
 }

As I don't know which fields are available in request body during findOneAndUpdate operation, I am unable to assign like this
$set: {
    'images.img1':  req.body.img1,
    'images.img2':  req.body.img2,
    'images.img3':  req.body.img3
}

If I code like above and specify all fields, already available fields become empty after update due to unavailable fields in request.
Need something like this to update available fields
$set: { "images.$[element]" : req.body  }

I have searched a lot but unable to find a solution.

A: You can simply create a function like below to be able to achieve your result.
function update() {
   let temp = {};
   for(let field in req.body) {
   temp["images."+field] = req.body[field];
   }

  db.collection.findOneAndUpdate({._id:...},{$set:temp},{upsert:true},function(err,result)
  {...});
  }


text:
Q: Why checkout step not recorded in the Google Analytics report? I'm making an enhanched ecommerce tracking with google analytics. I'm following the existing implementation in gtag.js. I have 4 checkout steps including shipping method data, payment method data, pending payment, and also paid (purchase). I've made the codes for each step below:
1. Shipping Method
<script>
    gtag('event', 'set_checkout_option', {
        "checkout_step": 1,
        "checkout_option": "shipping method",
        "value": ""
    });
</script>

2. Payment Method
<script>
    gtag('event', 'set_checkout_option', {
        "checkout_step": 2,
        "checkout_option": "payment method",
        "value": ""
    });
</script>

3. Pending Payment
$("#order-now-action").on('click', function() {
    gtag('event', 'set_checkout_option', {
        "checkout_step": 3,
        "checkout_option": "pending",
        "id": ""
    });
})

This is the checkout funnel that I created in Ecommerce Settings.

And this is a report in the checkout behavior menu. The shipping method is recorded, but why in step 2 (payment method) to step 4 (purchase) is it not recorded?

even though, in the sales performance menu, the transaction is recorded?

for steps 1-3 is in 1 page, while the purchase (step 4) I did on the backend using a single url. Is it because it's on 1 page so it's not recorded?

A: I'm very confused in solving this problem but I found the right answer why my checkout step is not recorded. This happened because set_checkout_option could not be used multiple times in one page, so I replaced it with the checkout_progress event. Because as in this Measure checkout steps documentation, To measure each subsequent checkout step, send a checkout_progress. I also modified my code a bit to be like this:
1.Shipping Method
<script>
    function checkoutProgressShippingMethodGA() {
        gtag('event', 'checkout_progress', {
            "checkout_step": 1,
            "checkout_option": "Shipping Method",
            "value": ""
        });
    }
    checkoutProgressShippingMethodGA();
</script>

2.Payment Method
<script>
    function checkoutProgressPaymentMethodGA() {
        gtag('event', 'checkout_progress', {
            "checkout_step": 2,
            "checkout_option": "Payment Method",
            "value": ""
        });
    }
    checkoutProgressPaymentMethodGA();
</script>

and tadaaaa... my checkout step has been recorded (**purchase has not been recorded because I have not implemented it on the backend)

A: Generally, your setup looks fine. I would, however, suggest to do it as
shown in Google's documentation: https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce

function onShippingComplete(stepNumber, shippingOption) {
  ga('ec:setAction', 'checkout_option', {
    'step': stepNumber,
    'option': shippingOption
  });

  ga('send', 'event', 'Checkout', 'Option', {
     hitCallback: function() {
       // Advance to next page.
     }
  });
}

But let's debug:

*

*Either in the Network tab, or through a debugger extension like adswerve's, make sure you're actually sending the calls to the collect endpoint. Go through the checkout funnel, trigger the events and inspect them. Pay attention to the property id (it's in the tid field of the payload sent to google's collect endpoint)

*Make sure you're generating reports on the data that has been fully processed by GA, so at least 2-day-old data for non-360 accounts and at least 4 hour-old for 360.

*Make sure your session is not broken between the first step and the actual purchase. For this, you either have to use the user explorer and actually see where the checkout session breaks for a specific client id. Or track a session id in a custom dimension and see that you can see all the checkout events when inspecting specific session id in a custom report. Session breakage often occurs when the source changes, or when the user id consistency breaks. A good real life example for it would be shopify's checkout being on a different TLD.

*Make sure you're looking at an unfiltered view just to exclude the possibility of filters interfering with the data and deleting your events.


text:
Q: CSS Background-image not loading on mobile safari when using absolute URL CSS
  #header {
    background: url('https://somecdn.com/myapp/public/img/mobile/header.jpg') top center no-repeat;
    width: 640px !important;
    position: relative;
    height: 98px;
  }

HTML

...

This works fine on any other browser, but on my friend's mobile safari (works on mine), it doesn't.  When we looked in the developer tool after connecting the phone to a mac, it shows that the browser loads the url as http://domainname.comhttps://somecdn.com/myapp/public/img/mobile/header.jpg, so basically it is interpreting the absolute url as relative path...  What is going on here?

A: Here is what happened. As you can see in my post. Our site is NOT on https, but the asset was. Most browsers handled this gracefully, but this particular mobile browser did not handle it. We simply used http version of assets and all is well... – Ryan Her 45 secs ago edit


text:
Q: How to interact with python terminal in front end I'm trying to convert a python project Im working on into a website. I was going to write it in Django/React.
The project uses telethon to get messages from telegram, and to start the session, an interactive program runs in the python terminal. Ex:
Client.start()
##enter phone number:
##enter passcode we sent:
##enter 2fa password:

How would I be able to interact with this from the frontend?


text:
Q: why is the html image right next to each other? I want to display two images but why are they right next each other when I change image size to 300px even with display property inline-block? Shouldn't the imagine be one on top of the other? How did the image size changed the position of the image even with inline-block property?

h1 {
  margin-top: 0;
}

p {
  padding-bottom: 0;
}

body {
  margin: 0;
  text-align: center;
}

.top-container {}

.middle-container {}

.bottom-containter {}

.top-cloud {
  width: 300px;
  display: inline-block;
}

.bottom-cloud {
  width: 300px;
  display: inline-block;
}

.mountain {
  display: inline-block;
}

Hi, this is Jin

aProgrammer, Baller

A: Apply to the mountain element a margin in the left.
.mountain {
  display: inline-block;
  margin:0 0 0 2em;
}


text:
Q: Modification of cells, JTable My project involves a JTable with a custom TableModel. Since I want the user to be able to modify each cell in the table, I choose to have my custom TableModel (CSVModel) extend DefaultTableModel.  However, for some reason CSVModel throws an exception when I try to edit a cell in my table. The only hint I have is from the last line of the stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 0 at
3 is the row number of the cell I was trying to modify. So maybe a problem with my data going out of scope? Here is the code:
class CSVModel extends DefaultTableModel {
        private String[] columnNames;
        private ArrayList<String[]> Data =  new ArrayList<String[]>();

        public void AddCSVData(ArrayList<String[]> DataIn) {
            this.columnNames = DataIn.get(0);
            DataIn.remove(0);
            this.Data=DataIn;

            this.fireTableStructureChanged();
        }

        @Override
        public int getColumnCount() {
            if (columnNames != null)
                return columnNames.length;//length;
            else
                return 0;
        }
        @Override
        public int getRowCount() {
            if (Data != null)
                return Data.size();
            else
                return 0;
        }

        public void setRowCount() {
            Data=null;
            columnNames=null;

            this.fireTableStructureChanged();
        }

        @Override
        public String getColumnName(int col) {
            System.out.println("getcol");
            return columnNames[col];
        }

        @Override
        public Object getValueAt(int row, int col)
        {
            return Data.get(row)[col];

        }

        public ArrayList<String[]> ReadCSVFile(File dataFile) {
            // When user presses load, read in the selected CSV file
            CSVFile temp = new CSVFile();

            return temp.ReadCSVfile(dataFile);
        }

Before editing I load a CSV file into the table using this class:
public class CSVFile {
            private ArrayList<String[]> Rs = new ArrayList<>();
            private String[] OneRow;

            // Method for reading CSV file
            public ArrayList<String[]> ReadCSVfile (File DataFile) {
                try {
                    BufferedReader brd = new BufferedReader (new FileReader(DataFile));

                    String st = brd.readLine();
                    while (st != null) {
                        OneRow = st.split(",");
                        Rs.add(OneRow);
                        st = brd.readLine();
                    } // end of while
                    brd.close();
                } // end of try
                catch (Exception e) {
                    String errmsg = e.getMessage();
                    System.out.println ("File not found:" +errmsg);
                } // end of Catch

                return Rs;
            }// end of ReadFile method
         }// end of CSVFile class

The full stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3 >= 0
    at java.util.Vector.elementAt(Unknown Source)
    at javax.swing.table.DefaultTableModel.setValueAt(Unknown Source)
    at javax.swing.JTable.setValueAt(Unknown Source)
    at javax.swing.JTable.editingStopped(Unknown Source)
    at javax.swing.AbstractCellEditor.fireEditingStopped(Unknown Source)
    at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(Unknown Source)
    at javax.swing.DefaultCellEditor.stopCellEditing(Unknown Source)
    at javax.swing.JTable$GenericEditor.stopCellEditing(Unknown Source)
    at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(Unknown Source)
    at javax.swing.JTextField.fireActionPerformed(Unknown Source)
    at javax.swing.JTextField.postActionEvent(Unknown Source)
    at javax.swing.JTextField$NotifyAction.actionPerformed(Unknown Source)
    at javax.swing.SwingUtilities.notifyAction(Unknown Source)
    at javax.swing.JComponent.processKeyBinding(Unknown Source)
    at javax.swing.JComponent.processKeyBindings(Unknown Source)
    at javax.swing.JComponent.processKeyEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Thanks for the help!

A: The solution was to extend AbstractTableModel instead of DefaultTableModel. I also had to include appropriately overloaded versions of two methods of AbstractTableModel:

@Override
 public boolean isCellEditable(int row, int col) {
            return true;
          }

@Override
        public void setValueAt(Object value, int row, int col) {

            Data.get(row)[col] = (String) value;

            fireTableCellUpdated(row, col);
        }


text:
Q: Issue with opportunity query I have the following query:
Opportunity opp = [SELECT Id, Name, OwnerID, accountID, CreatedBy from Opportunity where CreatedDate<:Date.today() and CreatedBy.UserRoleId=:Inside_Sales.Id  ];

And this is the error I'm receiving:
No such column 'CreatedBy' on entity 'Opportunity'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.
I need to make the query so it only looks for opportunities that where created by users with a specific role.
How can I use the CreatedBy field in a query?

A:
SELECT Id, Name, OwnerID, accountID, CreatedBy

This syntax is invalid. If you just need the user Id, use CreatedById, or if you want a specific field from the user object, use the dot-notation (e.g. CreatedBy.Name).


text:
Q: Removing text between two specific strings I have a file as below:
mime PI Name: ISHO SUCCESS RATE RT, Value: 95.663826
scr  PI Name: RRC Access Failures due to UU, Value: 0.13394141
prog PI Name: RRC Access Failures due to UU, Value: 0.16077702
sch PI Name: RRC Access Failures due to UU, Value: 0.11781933

I want to remove text PI till Value:. I tried
sed '/<PI>/,/<\/Value:>/d'

Any help?

A: Using the d command in sed will delete the whole line. Also, I'm not sure why you're using < and >. Perhaps you're confusing them with \< and \> that grep uses to denote word boundaries? In that case, you should know that sed uses \b for both types of word boundaries (beginning and ending). So you can write something like this:
sed -i 's/\bPI\b.*\bValue:\b//' your_file

For extra robustness, I would use perl for lazy quantification of . so that you only delete the text between the first occurrence of PI and the first occurrence of Value:. Of course it all depends on your use case.
perl -pi -e 's{ \b PI \b .*? \b Value: \b}{}x' your_file

A: Use this below code to remove multiple lines between patterns (including lines with patterns):
sed "/PI/,/Value:/d" your_file

If you want to modify your_file directly:
sed -i "/PI/,/Value:/d" your_file

A: Replace everything from PI to Value: with empty string:
sed 's/PI.*Value://'


text:
Q: Adverserial search troubles I'm writing a Connect4 game with an AI opponent using adversarial search techniques and I have somewhat run into a wall. I feel that I'm not far from a solution but that there's perhaps a problem where I'm switching perspectives (as in: the perspective of which participant I'm basing my evaluation scores on), missing a minus sign somewhere or something like that.
The problem is either that in the variations that I've tried that the AI chooses not to block the player when the player has three-in-a-row but otherwise the AI plays a perfect game, or that he prefers to block the player, even if he has the chance to win the game. It also seems to matter whether or not the search depth is an even or an uneven number, as the AI is pants-on-head retarded at a 6-ply search, which is pretty telling that something is wrong.
Search
The algorithm used is negamax with alpha-beta pruning and is implemented as follows:
private int Negamax(int depth, int alpha, int beta, Player player)
{
  Player winner;
  if (Evaluator.IsLeafNode(game, out winner))
  {
    return winner == player ? (10000 / depth) : (-10000 / depth);
  }

  if (depth == Constants.RecursionDepth)
  {
    return Evaluator.Evaluate(game, depth, player);
  }

  foreach (var move in moves)
  {
    int row;

    if (board.DoMove(move, player, out row))
    {
      var value = -Negamax(depth + 1, -beta, -alpha, (Player)1 - (int)player);

      board.UndoMove(move, row, player);

      if (value > alpha)
      {
        alpha = value;
        if (player == Player.AI)
        {
          bestColumn = move;
        }
      }

      if (alpha >= beta)
      {
        return alpha;
      }

    }
  }
  return alpha;
}

I don't suspect that the problem is in this function, but it might be.
Evaluation
I've based the evaluation function off of the fact that there are only 69 possible ways to get four-in-a-row on a 7x6 board. I have a look-up table of about 350 items that contains the hardcoded information for every column and row which win-combinations the row+column is a part of. For example, for row 0 and column 0, the table looks like this:
//c1r1
table[0][0] = new int[3];
table[0][0][0] = 21;
table[0][0][1] = 27;
table[0][0][2] = 61;

This means that column 0, row 0 is part of win-combination 21, 27 and 61.
I have a second table, that contains for both players how many stones it has in each of the win-combinations. When I do a move then I do the following:
public bool DoMove(int column, Player p, out int row)
{
  row = moves[column];

  if (row >= 0)
  {
    Cells[column + row * Constants.Columns] = p;

    moves[column]--;

    var combinations = this.Game.PlayerCombinations[p];

    foreach (int i in TerminalPositionsTable.Get(column,row))
    {
      combinations[i]++;
    }

    return true;
  }
  else
  {
    return false;
  }
}

The opposite is of course being done for UndoMove.
So after doing a move on column 0, row 0 by Player.Human, the table will be filled with a value of 1 at index 21, 27 and 61. If I do another move in a cell that is also part of win-combination 27, then the player combination table gets incremented at index 27 to 2.
I hope I have made that clear, as it's used in the evaluation function to very quickly determine how close a player is to scoring four-in-a-row.
The evaluation function, where I suspect the problem lies, is as follows:
public static int Evaluate(Game game, int depth, Player player)
{
  var combinations = game.PlayerCombinations[player];

  int score = 0;

  for (int i = 0; i < combinations.Length; i++)
  {
    switch (combinations[i])
    {
      case 1:
        score += 1;
        break;
      case 2:
        score += 5;
        break;
      case 3:
        score += 15;
        break;
    }
  }

  return score;
}

So I simply loop through the 69 possible win-combinations and add an amount to the score based on whether it's a single stone, two-in-a-row or three.
The part I'm still confused about in this whole adversarial search is whether I should care which player is doing a move? I mean, should I pass in the player like I do here, or should I always evaluate the board from the perspective of the AI player? I've tried many combinations of aiScore - humanScore, or just always look from the perspective of Player.AI, and such. But I've hit a dead end and every combination I've tried was pretty flawed.
So:

*

*Is the logic of my evaluation solid in its basis?

*When should I 'switch perspective'?

Any help would be much appreciated.
Update
I've implemented Brennan's suggestions below, and while it has definitely much improved, for some reason it doesn't block three-in-a-rows on any column but the two left and right-most, and only when the search-depth is uneven. The AI is unbeatable at even search depths, but only until depth 8 and up. Then it refuses to block again. This is pretty telling that I'm probably very close, but still have some crucial flaw.
Perhaps this has to do with me setting the column the AI should drop a stone in as Brennan commented, but I don't know when else to set it. Setting it only at depth 0 doesn't work.
Update 2
Edited the code as it looks like now with Brennan's changes.
Update 3
Created a Github repo with the full code. If you don't know how to work Git, just download a zip file from here.
It's a .NET 4.0 project, and running it will create log files of the negamax algorithm in your documents/logs directory. The solution also contains a test project, that contains a test for every board column whether or not the AI chooses to block the player when the player has three-in-a-row there.

A: This stuff makes my brain hurt, so I'm not positive that this answer is correct, but here goes.
In negamax, the score is always evaluated relative to the player currently on move. If it's white's move, then a high score is good for white. If it's black's move, then a high score is good for black. So if you have a leaf node, whether the score is +inf or -inf is determined not by whether the node is a win for white or black, but whether it's a win for the player you're currently evaluating. Replace this:
return winner == Player.AI ? (10000 / depth) : (-10000 / depth);

with this:
return winner == player ? (10000 / depth) : (-10000 / depth);

There is a similar problem in your evaluation function. Replace this:
return player == Player.AI ? score : -score;

with this:
return score;

Again, I'm not sure this is right. But I hope you try those two changes and let me know if it works. I'm very curious!

A: If it's not blocking certain combinations it sounds like you have a flaw in your table of possible wins.
I also see a problem in your evaluation function:  It gives value to moves that have NO hope of winning.  Suppose you have xoo.x, you're playing o.  Your routine says it's worth 15 points to play here when in reality it's worth 0.  Any win pattern that already contains tiles from both players is of no value to anyone.
I have found that when debugging this sort of thing the debugger is of little value as it doesn't let you see the big picture very well.  Try writing to a log file each pattern it's checking--put an actual drawing in the log.


text:
Q: Why #pragma is not working on ideone? Consider the below program:
#pragma startup foo1
#pragma exit foo2

void foo1()
{
    printf("Called before main\n");
}

void foo2()
{
    printf("Called after main\n");
}

int main()
{
    printf("main called\n");
    return 0;
}

I am getting the output as: http://ideone.com/ooMFI
main called

Why the pragma is not working here?
Why foo1() & foo2() are not called?

A: Because none of these pragmas are recognized by GCC. In general, stay clear of pragmas if you're trying to write portable code, because they differ per compiler and even per platform within the same compiler family.


text:
Q: Link an user to his profile page How do I link the logged in user to his profile page?
{% if user.is_authenticated %}

Profile

Here are the involved parts:
views.py
@login_required
def profile(request, profile_id):
    if profile_id == "0":
        if request.user.is_authenticated:
            userProfile = UserProfile.objects.get(pk=profile_id)
    else:
        userProfile = UserProfile.objects.get(pk=profile_id)

    return render_to_response('blog/profile.html', {'userProfile':userProfile}, RequestContext(request))

urls.py
url(r'^profile/(?P<profile_id>\d+)/$', views.profile),

models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    bio = models.TextField(max_length=500, blank = True, default=('keine Angabe'), null=True)
    image = models.FileField(null=True, blank=True)

    def __unicode__(self):
       return self.user.username

A: In you template you are trying to use url tag with named urls even though you haven't passed name keyword argument to url function in your urlpatterns.
In your urls function pass name argument, like this:
url(r'^profile/(?P<profile_id>\d+)/$', views.profile, name='profile'),

make sure you namespaced the app as 'blog' in your root url conf.
In your template to access current user's profile id by request context's user object. Like this:
{% if user.is_authenticated %}

    Profile


text:
Q: Looking for differentiable functions $f$ such that the set of points at which $|f|$ is not differentiable has some particular properties I know that $\sin x$ is differentiable at all points but $|\sin x|$ is not differentiable at countably many points namely at integer multiples of $\pi$ . So I am asking the following questions
i) Give example of a differentiable function $f:\mathbb R \to \mathbb R$ such that the set of points at which $|f|$ is  not differentiable is countable and dense in $\mathbb R$
ii) Give example of a differentiable function $f:\mathbb R \to \mathbb R$ such that the set of points at which $|f|$ is  not differentiable is uncountable and not dense in $\mathbb R$
iii) Give example of a differentiable function $f:\mathbb R \to \mathbb R$ such that the set of points at which $|f|$ is  not differentiable is uncountable and  dense in $\mathbb R$
$ UPDATE$:- As mentioned in the comments if $f$ is differentiable and and at some point non-zero then since by continuity $f$ will have same sign in a  neighborhood of that point , $|f|$ will be differentiable ; thus $|f|$ is not differentiable $c$ only when $f(c)=0$ but then as  John pointed out , if such points are dense then this leads to a contradiction , resolving i) and iii) in the negative ; this leaves us with (ii) only

A: I CLAIM THAT THE ANSWER TO (ii) IS NEGATIVE. PROOF.
Lemma: If $f$ is differentiable over $%
%TCIMACRO{\U{211d} }%
%BeginExpansion
\mathbb{R}
%EndExpansion
$ and $c$ is a SIMPLE zero of $f$ then it is isolated, it means there
exists $\varepsilon >0$ such that $for$ all $x\in \left( c-\varepsilon
,c+\varepsilon \right) ,$ $f(x)=0$ iff $x=c.$ Proof. Assume the contrary
holds. Then there exists a sequence $x_{n}$ of zeros of $f$ converging to $c,
$ then $$f^{\prime }(c)=\lim_{x\rightarrow c}\frac{f(x)-f(c)}{x-c}%
=\lim_{n\rightarrow \infty }\frac{f(x_{n})-f(c)}{x_{n}-c}=\lim_{n\rightarrow
\infty }\frac{0-0}{x_{n}-c}=0.$$ Then $$f(c)=f^{\prime }(c)=0.$$ Contradicting
the simplicity of the zero $c.$
It follows that the Answer to (ii) is negative. In fact, every isolated subset
of $%
%TCIMACRO{\U{211d} }%
%BeginExpansion
\mathbb{R}
%EndExpansion
$ is countable.

A: This answer is incomplete but gives some results and extends the observation that the answer to questions (i) and (iii) is negative.
If $f:\mathbb R\to\mathbb R$ is differentiable, $|f|$ fails to be differentiable at a point $x\in\mathbb R$ if and only if $f(x)=0$ and $f'(x)\neq0$.
Continuity of $f$ follows from differentiability.
We are interested in the set $A=f^{-1}(0)\setminus(f')^{-1}(0)$ where $|f|'$ doesn't exist.
Some results:

*

*$A$ is nowhere dense (its closure has empty interior).
Reason:
Suppose this is not the case.
Then there is an open interval $I$ so that $A\cap I$ is dense in $I$.
In particular this implies that $f^{-1}(0)\cap I$ is dense in $I$, which by continuity implies that $f|_I\equiv0$.
It follows that also $f'|_I\equiv0$, a contradiction.

*$A$ need not be closed even if $f'$ is continuous.
Example:
$f(x)=x^3\cos(1/x)$ for $x\neq0$ and $f(0)=0$.
Now $f$ is continuously differentiable and $0\in\partial A\setminus A$.
Zeros of $f$ accumulate at zero but the derivative doesn't vanish at other zeros.

*If $f'$ is continuous, $A$ has zero measure.
Reason:
If $f$ is continuously differentiable, it is locally Lipschitz, and so is $|f|$.
Lipschitz functions are differentiable almost everywhere by Rademacher's theorem, so the set of nondifferentiability has to have zero measure.

It seems that $A$ should be something like a Cantor set if we want it to be uncountable.
I faintly recall seeing a paper in arXiv where the author(s?) constructs a function which vanishes on the ternary Cantor set but its derivative is nonzero in this set.
Unfortunately I couldn't find the paper, and advice against taking my memory as a decisive argument.


text:
Q: Hide an element in ASP.net based on an if inside a Repeater I know how to use a simple If statement wrapped in the <%# tags to hide something, but I don't know how to do it in a repeater when I need to access Container.DataItem, as in I need the dataItem currently being 'repeated'
eg
if (CurrentValidationMessage.Link != "")
{
  show a hyperlink
}

Markup:
<asp:Repeater ID="repValidationResults" runat="server">
        <HeaderTemplate>
        </HeaderTemplate>
        <ItemTemplate>
            <a href='<%# ((MttImportValidationMessage)Container.DataItem).EditLink  %>'> Link to erroneous Milestone
            <%# ((MttImportValidationMessage)Container.DataItem).Message %>

        </ItemTemplate>
    </asp:Repeater>

A: It might be more maintainable if you just tagged the controls in the repeater with id's and runat='server' and reference the DataItem in the ItemDataBound event by using e.Item.DataItem.
Then use e.Item.FindControl to reference your controls in the ItemTemplate and perform your logic.
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
    {
        Domain.Employee employee = (Domain.Employee)e.Item.DataItem;
        Control myControl = (Control)e.Item.FindControl("controlID");
        //Perform logic
    }
}

A: use ItemDataBound Event with repeater, and make the "a" tag with a runat="server" property and ID
 protected void repValidationResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
 {
     RepeaterItem item = e.Item;
      if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
        {

           HyperLink link = (HyperLink)    item.FindControl("link");
           //Do all your logic here :)
        }

 }

MarkUp:
 <asp:Repeater ID="repValidationResults" runat="server">
    <HeaderTemplate>
    </HeaderTemplate>
    <ItemTemplate>
         Link to erroneous Milestone
        <%# ((MttImportValidationMessage)Container.DataItem).Message %>

    </ItemTemplate>
</asp:Repeater>


text:
Q: How to use a custom authorizer and custom authenticator for ember simple-auth in ember cli I don't understand how I'm supposed to include my custom authenticator and custom authorizor with ember cli.
Where to put it and what to include and how to do it. The cli example for simple-auth provided unfortunately does not cover custom authorizer and authenticator.
The build is successfully, but when running it in the browser, I get the error
TypeError: SimpleAuth.Authenticators is undefined

I'm aware that I'm doing something wrong, but could you please guide me or point me to the right documentation on how to do this, I can't find anything :(
My initializer looks like this:
import Ember from 'ember';
import CustomAuthenticator from "../models/customauthenticator";

export default {
  name : 'authentication',
  before : 'simple-auth',
  initialize : function(container) {
    container.register('authenticator:custom', CustomAuthenticator);
    //container.register('authorizer:custom', CustomAuthorizer);
  }
};

My authenticator looks like this
import Ember from "ember";
import App from '../app';
import SimpleAuth from "simple-auth/authenticators/base";

App.CustomAuthenticator = SimpleAuth.Authenticators.Base.extend({
  tokenEndpoint: '/api/RestUser.php/users/core/access/',

  restore: function(data) {
    [...]
  },
  authenticate: function(credentials) {
    [...]
  },
  invalidate: function() {
    [...]
  }
});

What am I missing? Thanks in advance!

A: Change that to:
...
import Base from "simple-auth/authenticators/base";

export default Base.extend({
...


text:
Q: Embded files in a compiled .exe I am working on a project that is about making a video player with built in libraries.
What I want to do is create a custom video player in Flash CS5, Python (Using Phonon) or C# which can play any video file (independent of the extension). The idea is that when I run my program, the video files that are embedded in the complied .exe will be played.
Is there a way I can include the video file with the compiled .exe?
EDIT: the video files will be around 100 MB in size.

A: Let me see if I understood your question correctly. I am assuming you want to embed a video file into a video player application that you are creating. The video can be on any type (.avi, .mp4, .flv) and the application will be an executable (.exe).
If this is the case then what you need to do is, using Visual Studio, add your video file as a resource in your project, rebuild the project and access the resource from your code.
For example, if you have added MyVideo.avi to your project, after building the project you can access it as MyNamespace.MyVideo.avi.
Here are a couple of SO posts that provide more concrete examples of embedded resources within a project:

*

*How To Store Files In An EXE

*How to embed a text file in a .NET assembly?


text:
Q: Receive sound button click when the phone is locked I need to receive long sound button press event even if my phone is locked.
I tried using SettingsContentObserver and AudioManager but it only works when the music is playing.
Source: https://stackoverflow.com/a/15292255/4757621
Currently I am creating wakelock in OnCreate method to keep CPU running when phone is locked but still, no success.
Any ideas?


text:
Q: How does transaction suspension work in Spring? My question is basically the same as is here, but I'm not satisfied with the answer so I'm writing this question.
In Spring Framework manual it is stated that for a PROPAGATION_REQUIRES_NEW the current transaction will be suspended. How is this actually implemented? I know that most databases don't support nested transactions and can have only one transaction running in one connection. This means that you can't just "not use" original transaction and start a new one - before starting new one you must commit or rollback original transaction.
Example:

START TRANSACTION
SELECT ...
UPDATE ...
-- Now we run method with PROPAGATION_REQUIRES_NEW
-- How do we "suspend" transaction so we can start new one?
START TRANSACTION
UPDATE ...
COMMIT
-- We returned from the method, result was commited
-- Now we'd like to "unsuspend" the original transaction so it can be commited/rollbacked, but how?

Or is this possibly implemented using another connection (Session object)? So that we stop using the original connection and create a new one where we can start new transaction?
I am missing here something so obvious that nobody cares to explain it (at least not in Spring docs, Spring in Action, Spring persistence with Hibernate).
Thanks a lot!

A: The point of suspending a transaction is to change the current transaction for a thread to a new one. This would NOT line up with the semantics of nested transactions because the new and suspended transactions are completely independent of each other. There is no connection-level API to support suspending transactions so this has to be done by using a different connection. If you are using JTA with Spring, this is done by the JTA transaction manager. If you are using DataSourceTransactionManager, you can look in the code and see that it will be saving off the current connection as a "suspended resource" and grabbing a new connection from the data source for the new transaction.


text:
Q: I would like to do a bar plot with two different values in the y-axis and those being dodged in the x-axis I have been looking at a bunch of answers but I could not find anything that answers my problem.
I have the following dataset:
structure(list(Quail = c("28", "28", "28", "28", "29", "29",
"29", "29", "30", "30", "30", "30", "4", "4", "4", "4", "4",
"5", "5", "5", "5", "5", "6", "6", "6", "6", "16", "16", "16",
"16", "17", "17", "17", "17", "17", "18", "18", "18", "18", "52",
"52", "52", "52", "53", "53", "53", "53", "54", "54", "54", "54"
), day = c(1, 3, 5, 7, 1, 3, 5, 9, 1, 3, 5, 7, 1, 3, 5, 7, 9,
1, 3, 5, 7, 9, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7, 9, 1, 3, 5,
7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7), Group = c("var", "var",
"var", "var", "var", "var", "var", "var", "var", "var", "var",
"var", "varL", "varL", "varL", "varL", "varL", "varL", "varL",
"varL", "varL", "varL", "varL", "varL", "varL", "varL", "varLQ",
"varLQ", "varLQ", "varLQ", "varLQ", "varLQ", "varLQ", "varLQ",
"varLQ", "varLQ", "varLQ", "varLQ", "varLQ", "varQ", "varQ",
"varQ", "varQ", "varQ", "varQ", "varQ", "varQ", "varQ", "varQ",
"varQ", "varQ"), Equi = c(NA, 5.966699108, 2.179348795, NA, NA,
5.47029668, 4.606832566, 4.123227924, NA, 6.200198499, 3.807239274,
2.121998353, NA, 6.122346998, 3.161297444, 2.618107834, 2.488914738,
NA, 5.80659996, 3.272308721, 3.012209525, 2.750162661, NA, 5.752224579,
4.885757526, 2.515186667, NA, 5.494711674, 4.665176685, 4.017052221,
NA, 6.165528697, 4.969614582, 2.894064483, 2.600701052, NA, 6.368332793,
4.316409804, 6.030505124, NA, 5.173073878, 4.038968216, 2.859379995,
NA, NA, 4.17091987, 2.916909106, NA, 5.926815246, 5.910377652,
NA), Norm.pi = c(5.8, 3.9, 3.1, 2.5, 4.7, 2.5, 5.1, 10.1, 3.4,
2.8, 5.4, 2.6, 4.3, 0.9, 4, 7.3, 4.1, 5.8, 1.8, 4.2, 8.5, 20.4,
4.6, 2.1, 4.3, 11.3, 2.5, 2.9, 4, 4.4, 2.7, 2.2, 2.7, 5.6, 4.5,
2.5, 2, 4.5, 7.1, 5.4, 2.6, 5.1, 8.3, 6.7, 2.8, 3.6, 4.6, 5.8,
3, 3, 6.3)), row.names = c(NA, -51L), groups = structure(list(
    Quail = c("16", "16", "16", "16", "17", "17", "17", "17",
    "17", "18", "18", "18", "18", "28", "28", "28", "28", "29",
    "29", "29", "29", "30", "30", "30", "30", "4", "4", "4",
    "4", "4", "5", "5", "5", "5", "5", "52", "52", "52", "52",
    "53", "53", "53", "53", "54", "54", "54", "54", "6", "6",
    "6", "6"), day = c(1, 3, 5, 7, 1, 3, 5, 7, 9, 1, 3, 5, 7,
    1, 3, 5, 7, 1, 3, 5, 9, 1, 3, 5, 7, 1, 3, 5, 7, 9, 1, 3,
    5, 7, 9, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7),
    Group = c("varLQ", "varLQ", "varLQ", "varLQ", "varLQ", "varLQ",
    "varLQ", "varLQ", "varLQ", "varLQ", "varLQ", "varLQ", "varLQ",
    "var", "var", "var", "var", "var", "var", "var", "var", "var",
    "var", "var", "var", "varL", "varL", "varL", "varL", "varL",
    "varL", "varL", "varL", "varL", "varL", "varQ", "varQ", "varQ",
    "varQ", "varQ", "varQ", "varQ", "varQ", "varQ", "varQ", "varQ",
    "varQ", "varL", "varL", "varL", "varL"), .rows = list(27L,
        28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L,
        39L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L,
        13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 40L,
        41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L,
        23L, 24L, 25L, 26L)), row.names = c(NA, -51L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

I am using ggplot as:
DI.pi.equi.extended %>%
  ggplot() +
    geom_bar(aes(x=day, y=Norm.pi), stat = "identity", fill = "red") +
    geom_bar(aes(x=day,y=Equi), stat = "identity") +

  theme(panel.grid.major =  element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        axis.line = element_line(colour = "black"),
        axis.text.x = element_text(),
        axis.title.y = element_text(face = "bold", size = 22),
        legend.direction = "vertical", legend.box = "horizontal") +
  scale_x_continuous(breaks = c(1,3, 5, 7, 9), limits = c(0,10))  +
    scale_y_continuous(sec.axis = sec_axis(~ . + 10)) +
  facet_grid(.~Quail + Group, scales = "free_y")

This is producing the following stacked plot:

What I am trying to plot is actually pi.Norm and Equi side by side, as dodged, but I could not make it work so far.
Suggestions?
Thank you very much in advance.

A: The trick is to convert the dataset to long format before plotting using e.g. tidyr::pivot_longer. Try this:
library(ggplot2)
library(dplyr)
library(tidyr)

DI.pi.equi.extended %>%
  tidyr::pivot_longer(c(Equi, Norm.pi), names_to = "name", values_to = "value") %>%
  ggplot() +
  geom_bar(aes(x=day, y=value, fill = name), stat = "identity", position = "dodge") +
  scale_fill_manual(values = c(Norm.pi = "red", Equi = "grey")) +
  theme(panel.grid.major =  element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        axis.line = element_line(colour = "black"),
        axis.text.x = element_text(),
        axis.title.y = element_text(face = "bold", size = 22),
        legend.direction = "vertical", legend.box = "horizontal") +
  scale_x_continuous(breaks = c(1,3, 5, 7, 9), limits = c(0,10))  +
  scale_y_continuous(sec.axis = sec_axis(~ . + 10)) +
  facet_grid(.~Quail + Group, scales = "free_y")
#> Warning: Removed 15 rows containing missing values (geom_bar).

Created on 2020-05-19 by the reprex package (v0.3.0)


text:
Q: How to generate an encoding key from a string? - Python I am creating myself a password saver in which I could enter my passwords and it would be securely stored, like 1Password. Once you enter, you must enter/create yourself a password and I would like it to encode the saved passwords using this one. How can I do so?
Help is appreciated :)


text:
Q: Insert multiple records into an table based on condition I have main table called customer where columns
MainCustID   AssocativeCustID
11           22
33           33
45           56
38           90
56           1234
356          356

Now I need to insert this value records to one more table based on the condition

*

*if MainCustID and AssocativeCustID are the same, then only 1 entry is to go into one more table called collection (that is the MainCustID entry)

*if MainCustID and AssocativeCustID are different, then 2 entries will go into table called collection (MainCustID and AssocativeCustID)
How can I achieve this concept?
I know this can be done based on cursors, is there any other way that we can achieve this.

A: You could break it into three sub-tasks:
insert into Collection
    select MainCustID
    from Customer
    where MainCustID = AssocativeCustID;
insert into Collection
    select MainCustID
    from Customer
    where MainCustID <> AssocativeCustID;
insert into Collection
    select AssocativeCustID
    from Customer
    where MainCustID <> AssocativeCustID;

*

*First insert all MainCustID where it's equal to the AssocativeCustID

*Then all MainCustID where it's unequal to the AssocativeCustID

*Then the other side, all AssocativeCustID where it's unequal to MainCustID
Here's a demo: http://sqlfiddle.com/#!2/60026/1/0

A: Without the use of cursor you need to run these two insert queries:-
insert into collection values (select MainCustId from customer where MainCustID = AssocativeCustID);

insert into collection values (select MainCustId,AssocativeCustID from customer where MainCustID <> AssocativeCustID);


text:
Q: Editable URL Rewrite Map for CloudFront/S3 Website using Lambda@Edge I'm migrating a static website from IIS to Amazon S3, using CloudFront for https. The old site used the URL Rewrite module and had 301 redirect maps with over 200 entries. Here is an example:
example.com?pageID=1234 => example.com/about/history
I want to make sure that all the redirects are migrated with the website. Many of the entry keys include query strings, so I don't think S3 XML redirection rules or object metadata redirects will work for them (correct me if I'm wrong).
I want to use a CloudFront user request event trigger with a Lambda@Edge function to create a rewrite map of key-value pairs (something like what is described in this guide). The function would grab the request URI and, if it matches any of the keys in the map, change the request to reflect the corresponding value.
I could hard code the rewrite map into the Lambda function, but new entries will be added to the map over time. I would prefer not to create a new version of the function, and then edit the CloudFront behavior to use this new version, whenever a new vanity URL is needed. It feels kind of dangerous and prone to errors that could mess with CloudFront.
Does anyone know of a way to create a rewrite map (a JSON file or something?) that can be attached to a Lambda function and edited without altering the Lambda function itself? Thanks!

A: I would save the JSON config file in a S3 bucket and made the Lambda@Edge read it upon startup (not for every request though! only once at Lambda start up).
Give the Lambda proper IAM permission to read the file from S3 and you're done.

*

*you'll have the config separated from the code

*no need to re-deploy Lambda or reconfigure CloudFront

*config changes will propagate globally within minutes (you can configure a config expiration time in the Lambda if you want to re-download it every few minutes)

Hope that helps :)