text:
Q: Flask form validation design I'm not new to programming but I am new to Python and Flask.  I have a design question regarding form validation.
I have a registration form that captures the user information as well as the company they belong to.  The form then validates whether the email is already in use but I want to also validate whether or not the company has been signed up before.  I don't want the same company to sign up more than once.
Trying to match solely on company name will likely cause issues because users don't necessarily spell things the same (ie: adding or omitting punctuation).  My thought is to validate on the first X number of characters in the company name, the street address number, and zip code.  If there is a match, the user isn't allowed to sign up and they will have to call in (or some other process to be determined).
Ok, the real question... Is it a better to add the validation to the WTF form?  Or add a helper function in the model?  I'm validating three fields and didn't know which was best practice.
EDIT - I'm really asking if I have to validate on more than one field, do I add it to the Form or with a helper function in the model?
Thanks for your assistance.
Jimmy

A: Validating using WTForms is likely better in this case. It will be easier to send an error message to the user.
In WTForms, it is easy to add a custom validator:
class MyForm(Form):
company = TextField('Company', [Required()])

def validate_company(form, field):
    if len(field.data) > 50:
        raise ValidationError('Name must be less than 50 characters')

In your case, however, this will not work because you want to do multiple fields. WTForms to the rescue! You can validate all of your company fields through a field enclosure. This will allow you to treat "company info" as one field and validate over each of them.
class CompanyForm(Form):
    name = StringField('Company name', [validators.required()])
    address    = StringField('Address', [validators.required()])

class RegistrationForm(Form):
    first_name   = StringField()
    last_name    = StringField()
    company = FormField(CompanyForm, [your_custom_validation])

You can also add uniqueness requirements to your DB model. Not sure what your database is, but MongoDB provides a unique_with requirement. But that won't do any validation, it will just throw an error if you try to create non-unique db entries.


text:
Q: Connecting to Meteor DDP from Java with Docker container I am here just to share some experience with java DDP Client Meteor and Docker
Hello I am accessing to a meteor docker container from a J2EE docker container and it fails because there are some trouble at the connection with the server name (corresponding to "meteor" in my compose file) and the port "82".
In this case it doesn't take into account the port and it replaces it with a default value 80... so the connection fails...

A: WHY ?
because URI don't handle domain name without dots
e.g. :

*

*connect to meteor_1 port 3000

*the uri is ws://meteor_1:3000/websocket

*but int port = uri.getPort(); -> -1 and the ddp client fallback to 80 by default

I'll give a try this evening with a image name with a dot as it passes in java but I yet didn't test with the docker compose

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to inject a class for all option elements from wp_get_archives()? I'm generating a list of all posts in a dropdown like so:
wp_get_archives('type=postbypost&format=option&show_post_count=0');

This works, but doesn't allow me to modify/add things to each option element.  The result needs to look something like this:
<select>
    <option value="">Select Post</option>
    <option class="level-0" value="285">20 Most Popular Health Care Products</option>
    <option class="level-0" value="305">About</option>
</select>

with the "value" being the post ID.
Essentially I'm looking for a wp_dropdown_posts() but there is no such function.  How can I replicate the behavior of wp_dropdown_pages() but for posts?

A: If there is none, we can write one:
function my_very_own_wp_dropdown_posts($args) {
    $args = shortcode_atts(array(
        'posts_per_page'   => 5,
        'offset'           => 0,
        'category'         => '',
        'category_name'    => '',
        'orderby'          => 'date',
        'order'            => 'DESC',
        'include'          => '',
        'exclude'          => '',
        'meta_key'         => '',
        'meta_value'       => '',
        'post_type'        => 'post',
        'post_mime_type'   => '',
        'post_parent'      => '',
        'author'       => '',
        'post_status'      => 'publish',
        'suppress_filters' => true,
        'echo' => true
    ), $args, 'wp-dropdown-posts');
    $echo = $args['echo'];
    unset($args['echo']);
    $all_posts = get_posts( $args );
    $output = false;
    if ($all_posts) :
        $output = '
            <select name="archive-dropdown">
                <option value="">'. esc_attr( __( 'Select Post' ) ).'</option>';
        foreach ($all_posts as $post) :
            setup_postdata($post->ID);
            $output .= "<option class='level-0' value='$post->ID'>".$post->post_title."</option>";
        endforeach;
        wp_reset_postdata();
        $output .= '</select>';
    endif;
    $result = $output ?: esc_attr( __( "No posts found")).'.';
    if ($echo) echo $result; else return $result;
}
add_shortcode('wp-dropdown-posts', 'my_very_own_wp_dropdown_posts');

To get a dropdown with all your posts, just add [wp-dropdown-posts post_per_page="-1"] in any post or page (by default it only brings 5). If you want to use it in backend, you'll have to wrap it in a do_shortcode():
do_shortcode("[wp-dropdown-posts post_per_page="-1"]");

Important: If you only want the HTML of the select returned, not echoed so you can echo it yourself inside a more complex function/class/plugin, replace echo with return in this line:
echo $output ?: __("No posts found").'.';

If you have more than 10 posts, you might want to combine this with a visual helper for selects (such as WP Chosen, a WordPress plugin wrapper for Chosen). While I recommend the library, I am not endorsing the WordPress plugin, nor have I extensively tested it. It's just an example and it's up to you to research and find a better one for the purpose.
If you have more than 50 posts, you might want to consider testing this plugin for your purpose, which has the advantage of dynamically populating your dropdown with search results based on what you type in. Typically, you want to avoid selects with more than 30 options. Again, I am not endorsing or supporting the plugin, nor have I tested it. It's a(nother) WordPress plugin wrapper for Select2.
And, if you have more than 1000 posts, you might consider harnessing the power of Solr (or any other viable alternative). A quick search has revealed someone already made a Solr plugin for WordPress. Again, untested.

Updated the code based on the extra info from comments. Also added an echo paramter, true by default.


text:
Q: What is primary assembly I am trying to use ILMerge in our build process.
ILMerge has the Kind enumeration, which contains the SameAsPrimaryAssembly field.
What is the this primary assembly? How can I set the primary assembly?

A: ILMerge takes a set of input assemblies and merges them into one target assembly. The first assembly in the list of input assemblies is the primary assembly. When the primary assembly is an executable, then the target assembly is created as an executable with the same entry point as the primary assembly. Also, if the primary assembly has a strong name, and a .snk file is provided, then the target assembly is re-signed with the specified key so that it also has a strong name. Check this:
http://rongchaua.net/blog/c-how-to-merge-assembly/
http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en
Here's how to set it:
ilmerge /out:Merged.dll /keyfile:key.snk Primary.dll Secondary.dll


text:
Q: ReactJS - Customer messenger CHAT violates the following Content Security Policy directive: "frame-ancestors I test on my local environment the plugins react-messenger-customer-chat.
I just installed the plugin and insert this folowing code in my render view

    render() {
        const { src, title, tracks, scrollTop } = this.state;
        return (
            <div id="lz-app">
                <Header scrollTop={scrollTop}/>
                <main className="main">
                    <MessengerCustomerChat
                            pageId="xxxxxx"
                            appId="xxxxxx"
                     />
                </main>
                <Footer/>

                </div>
            </div>
        );
    }

When run my react app , i have the error :
Refused to frame 'https://web.facebook.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors https://web.facebook.com".

How I resolve this issue please?
Thanks

A: I found the solution here
Solution here
https://www.youtube.com/watch?v=8e_4KIj4jBs

A: You need to whitelist your domain in the Facebook page settings. To do this, navigate to: Your FB Page > Settings > Advanced Messaging > White-listed domains and enter your domain here.


text:
Q: Balance/flush columns at the end of each chapter in twocolumn layout In a twocolumn layout, how can I balance columns at the end of each chapter?

*

*Package multicol is not appreciated because it doesn't offer nice float placement in the columns (floats are not allowed inside multicols
environment, [H] placement is not floating)

*Package flushend does the jobs, but only for the last page of the document... why not for the last page of every chapter ?

*FWIW, every chapter of my document starts on a new page

*FWIW, I use the memoir class, but I don't think it matters here

A: You may use balance package (though you have to insert \balance manually some where in the first column of last page of each chapter)
\documentclass[twocolumn]{memoir}
\usepackage{balance}
\usepackage{lipsum}
\begin{document}

\chapter{One}
\lipsum

Lorem ipsum dolor sit amet, consectetuer adip-
iscing elit.
Ut purus elit, vestibulum ut, placerat
ac, adipiscing vitae, felis. Curabitur dictum gravida
mauris.
\balance                         %%% Note this line here
Nam arcu libero, nonummy eget, con-
sectetuer id, vulputate a, magna.
Donec vehicula
augue eu neque. Pellentesque habitant morbi tris-
tique senectus et netus et malesuada fames ac turpis
egestas. Mauris ut leo. Cras viverra metus rhon-
cus sem. Nulla et lectus vestibulum urna fringilla
ultrices. Phasellus eu tellus sit amet tortor gravida
placerat. Integer sapien est, iaculis in, pretium quis,
viverra ac, nunc.
Praesent eget sem vel leo ultri-
ces bibendum. Aenean faucibus. Morbi dolor nulla,
malesuada eu, pulvinar at, mollis ac, nulla.
Cur-
abitur auctor semper nulla. Donec varius orci eget
risus. Duis nibh mi, congue eu, accumsan eleifend,
sagittis quis, diam. Duis eget orci sit amet orci dig-
nissim rutrum.
Nam dui ligula, fringilla a, euismod sodales, sollic-
itudin vel, wisi. Morbi auctor lorem non justo. Nam
lacus libero, pretium at, lobortis vitae, ultricies et,
tellus.
Donec aliquet, tortor sed accumsan biben-
dum, erat ligula aliquet magna, vitae ornare odio
metus a mi. Morbi ac orci et nisl hendrerit mollis.
Suspendisse ut massa. Cras nec ante. Pellentesque
a nulla. Cum sociis natoque penatibus et magnis dis
parturient montes, nascetur ridiculus mus. Aliquam
tincidunt urna. Nulla ullamcorper vestibulum turpis.
Pellentesque cursus luctus mauris.
Nulla malesuada porttitor diam. Donec felis erat,
congue non, volutpat at, tincidunt tristique, libero.
Vivamus viverra fermentum felis. Donec nonummy
pellentesque ante. Phasellus adipiscing semper elit.
Proin fermentum massa ac quam. Sed diam turpis,
molestie vitae, placerat a, molestie nec, leo. Maece-
nas lacinia. Nam ipsum ligula, eleifend at, accumsan
nec, suscipit a, ipsum. Morbi blandit ligula feugiat
magna. Nunc eleifend consequat lorem. Sed lacinia
nulla vitae enim. Pellentesque tincidunt purus vel
magna. Integer non enim. Praesent euismod nunc
eu purus. Donec bibendum quam in tellus. Nullam
cursus pulvinar lectus. Donec et mi. Nam vulpu-
tate metus eu enim. Vestibulum pellentesque felis eu
massa.
Quisque ullamcorper placerat ipsum. Cras nibh.
Morbi vel justo vitae lacus tincidunt ultrices. Lorem
ipsum dolor sit amet, consectetuer adipiscing elit.

\chapter{Two}
\lipsum

\end{document}


text:
Q: Combining multiple optional variables in .htaccess rewrites Trying to handle multiple potential re-writes in one .htaccess
each subdomain should resolve to a folder
each /a/username should resolve to /?a=username
I have each rule working on their own.  But I cannot figure out how to get them both working at the same time.

examples (working now):

*

*www.domain.com -> no change

*black.domain.com -> www.domain.com/black (works)

*white.domain.com -> www.domain.com/white (works)

*www.domain.com/a/username -> www.domain.com/?a=username  (works)

What I need to get working:

*

*white.domain.com/a/username -> www.domain.com/white/?a=username (fails - becomes only www.domain.com/white)

*black.domain.com/a/username -> www.domain.com/black/?a=username (fails - becomes only www.domain.com/black)

RewriteEngine on
RewriteRule ^index\.php?$ / [NC,R,L]

#RewriteRule ^(.*).domain.com$ http://www.domain.com/$1 [QSA,R=302,L]

RewriteCond "%{HTTP_HOST}" !^www.* [NC]
RewriteCond "%{HTTP_HOST}" !^admin.* [NC]
RewriteCond "%{HTTP_HOST}" !^mail.* [NC]
RewriteCond "%{HTTP_HOST}" !^email.* [NC]

RewriteCond "%{HTTP_HOST}" ^([^\.]+).domain.*$
RewriteRule ^(.*)$ http://www.domain.com/%1 [R=302]

RewriteRule ^a/(.*)$ http://www.domain.com/%1?a=$1 [R=302,L]

A: Try changing your rules to:
RewriteEngine on
RewriteRule ^index\.php?$ / [NC,R,L]

#RewriteRule ^(.*).domain.com$ http://www.domain.com/$1 [QSA,R=302,L]

RewriteCond "%{HTTP_HOST}" !^www.* [NC]
RewriteCond "%{HTTP_HOST}" !^admin.* [NC]
RewriteCond "%{HTTP_HOST}" !^mail.* [NC]
RewriteCond "%{HTTP_HOST}" !^email.* [NC]
RewriteCond "%{HTTP_HOST}" ^([^\.]+).domain.*$
RewriteRule ^$ http://www.domain.com/%1 [R=302]

RewriteCond "%{HTTP_HOST}" !^www.* [NC]
RewriteCond "%{HTTP_HOST}" !^admin.* [NC]
RewriteCond "%{HTTP_HOST}" !^mail.* [NC]
RewriteCond "%{HTTP_HOST}" !^email.* [NC]
RewriteCond "%{HTTP_HOST}" ^([^\.]+).domain.*$
RewriteRule ^a/(.*)$ http://www.domain.com/%1?a=$1 [R=302,L]


text:
Q: SQL Server - calculate age in day, month, year in select query I have found a couple of examples that have helped me to break this down, however none that can be used on a table of data.
I have a list of names and dates in a table, and I want to calculate how old each person in in terms of the day, month and year from today, for example:
   Name          DOB        Years      Months      Days
Joe Bloggs     01/10/2012     4          0         11
Steven Wright  29/02/2004     12         7         13

This is the query I am currently using:
SELECT
Person.Name,
Person.DOB,
DATEDIFF(yy, Person.DOB, GETDATE()) - CASE WHEN (MONTH(Person.DOB) > MONTH(GETDATE())) OR (MONTH(Person.DOB) = MONTH(GETDATE()) AND DAY(Person.DOB) > DAY(GETDATE())) THEN 1 ELSE 0 END AS Years,
DATEDIFF(m, Person.DOB, GETDATE()) - CASE WHEN DAY(Person.DOB) > DAY(GETDATE()) THEN 1 ELSE 0 END AS Months,
DATEDIFF(d, Person.DOB, GETDATE()) AS Days
FROM Person
Where DOB IS NOT NULL

This will display the following for Joe Bloggs from the SQL Query above:
   Name            DOB        Years      Months      Days
Joe Bloggs      01/10/2012      4          48        1472

Basically what is happening is the years aren't being deducted from the months, and so on.. so this is the total days, total months and total years, instead of them breaking down as shown above.
How can I amend the above query to get this to work using a table of data called Family, with the fields Name and DOB?

A: I TRIED some boundary conditions on this!  Seems ok so far have a go if you like.
declare @dob datetime = '19800229';           --date of birth
DECLARE @DAT datetime = '20160301';           --calculation date

SELECT YEAR(@DAT) - YEAR(@dob) -
            CASE WHEN MONTH(@DAT) < MONTH(@DOB) OR MONTH(@DAT) = MONTH(@DOB) AND DAY(@DAT) < DAY(@DOB) THEN 1 ELSE 0 END YEARS,
        (YEAR(@DAT)*12 - YEAR(@dob)*12 + MONTH(@DAT) - MONTH(@dob) -
        CASE WHEN DAY(@DAT) < DAY(@DOB) THEN 1 ELSE 0 END) % 12 MONTHS,

    datediff(day,
    dateadd(month,(YEAR(@DAT)*12 - YEAR(@dob)*12 + MONTH(@DAT) - MONTH(@dob) -
        CASE WHEN DAY(@DAT) < DAY(@DOB) THEN 1 ELSE 0 END) % 12,

    dateadd(year, YEAR(@DAT) - YEAR(@dob) -
            CASE WHEN MONTH(@DAT) < MONTH(@DOB) OR MONTH(@DAT) = MONTH(@DOB) AND DAY(@DAT) < DAY(@DOB) THEN 1 ELSE 0 END ,@dob)
            ),@DAT) DAYS

A: How about
declare @dob date = '22Aug1982'
declare @Yr int = 2016
declare @mon int = 6
declare @dom int = 13
Select @Yr - Year(@dob) - 1 +
case when @mon > Month(@dob) then 1
     when @mon < Month(@dob) then 0
     else case when @dom >= Day(@dob) then 1
else 0 end end

But I suggest you add a computed column to the table:
alter table Family
    add AgeYears
    as Year(getdate()) - Year(dob) - 1 +
        case when Month(getdate()) > month(dob) then 1
             when month(getdate()) < month(dob) then 0
             else case when day(getdate()) >= day(dob) then 1
         else 0 end end

If you also need the additional months old, and days old, then add columns for those as well:
alter table Family
    add AgeYears as Year(getdate()) - Year(dob) - 1 +
           case when Month(getdate()) > month(dob) then 1
                when month(getdate()) < month(dob) then 0
                else case when day(getdate()) >= day(dob) then 1
             else 0 end end,
    AgeMonths as case when Month(getdate()) >= Month(dob)
             then Month(getdate()) - month(dob)
             else month(dob) - Month(getdate()) end,
    AgeDays as case when day(getdate()) >= day(dob)
             then day(getdate()) - day(dob)
             else day(dob) - day(getdate()) end

A: I have at TVF which may look like overkill, but it is very fast and accurate
Declare @YourTable Table (Name varchar(25),DOB Date)
Insert Into @YourTable values
('Joe Bloggs'   ,'2012-10-01'),
('Steven Wright','2004-02-29')

Select A.*
      ,B.*
 From  @YourTable A
 Cross Apply [dbo].[udf-Date-Elapsed](A.DOB,GetDate()) B

Returns
Name            DOB         Years   Months  Days    Hours   Minutes Seconds
Joe Bloggs      2012-10-01  4       0       11      11      3       17
Steven Wright   2004-02-29  12      7       13      11      3       17

The UDF
CREATE FUNCTION [dbo].[udf-Date-Elapsed] (@D1 DateTime,@D2 DateTime)
Returns Table
Return (
    with cteBN(N)   as (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
         cteRN(R)   as (Select Row_Number() Over (Order By (Select NULL))-1 From cteBN a,cteBN b,cteBN c),
         cteYY(N,D) as (Select Max(R),Max(DateAdd(YY,R,@D1))From cteRN R Where DateAdd(YY,R,@D1)<=@D2),
         cteMM(N,D) as (Select Max(R),Max(DateAdd(MM,R,D))  From (Select Top 12 R From cteRN Order By 1) R, cteYY P Where DateAdd(MM,R,D)<=@D2),
         cteDD(N,D) as (Select Max(R),Max(DateAdd(DD,R,D))  From (Select Top 31 R From cteRN Order By 1) R, cteMM P Where DateAdd(DD,R,D)<=@D2),
         cteHH(N,D) as (Select Max(R),Max(DateAdd(HH,R,D))  From (Select Top 24 R From cteRN Order By 1) R, cteDD P Where DateAdd(HH,R,D)<=@D2),
         cteMI(N,D) as (Select Max(R),Max(DateAdd(MI,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteHH P Where DateAdd(MI,R,D)<=@D2),
         cteSS(N,D) as (Select Max(R),Max(DateAdd(SS,R,D))  From (Select Top 60 R From cteRN Order By 1) R, cteMI P Where DateAdd(SS,R,D)<=@D2)

    Select [Years]   = cteYY.N
          ,[Months]  = cteMM.N
          ,[Days]    = cteDD.N
          ,[Hours]   = cteHH.N
          ,[Minutes] = cteMI.N
          ,[Seconds] = cteSS.N
     From  cteYY,cteMM,cteDD,cteHH,cteMI,cteSS
)
--Max 1000 years
--Select * from [dbo].[udf-Date-Elapsed] ('1964-07-29 09:35:00.000',GetDate())

A: Try Below solution, I have not tested it thorubut it may work :
DECLARE @DOB DATE = '1991-11-19'
SELECT  DATEDIFF(M,@DOB,GETDATE())/12 [Year],
        DATEDIFF(M,@DOB,GETDATE())%12 [Month],
        DATEDIFF(DD,
        CASE
            WHEN DATEADD(MM,DATEDIFF(MM,@DOB,GETDATE()),@DOB) > GETDATE()
                THEN DATEADD(MM,DATEDIFF(MM,@DOB,GETDATE())-1,@DOB)
            ELSE DATEADD(MM,DATEDIFF(MM,@DOB,GETDATE()),@DOB)
        END,
        GETDATE()) [Day]


text:
Q: Calcular diferença de dias entre duas datas [PHP] Boa tarde a todos!
Fiz pesquisa antes de fazer a pergunta, mas não obtive resposta para a minha duvida em nenhuma delas.
Preciso de ajuda em fazer com que o seguinte código receba as duas datas pela variável $_GET, exemplo (.php?data1=23-09-16&data2=20-09-16).
Basicamente apresentar por extenso as datas inseridas e mostrar a diferença de dias entre as mesmas.
Fiz um exercicio funcional, qual a melhor forma de o adaptar para receber as datas do exterior?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>teste dias</title>
</head>
<body>

<?php

$br="<br>";

$agora=mktime(17,00,00,9,23,2016);
$agora=date("F d, Y - g:i:s a", $agora);
echo "Hoje e agora são: ".$agora.$br;

$dia1=mktime(0,0,0,1,1,2016);
$dia2=mktime(0,0,0,2,1,2016);

echo (($dia2-$dia1)/60/60/24)." dias".$br;
echo $br;

?>

</body>
</html>

Obrigado!

A: Para o formato DD-MM-AA especificado na pergunta, precisamos separar os componentes da data para converter o ano para 4 dígitos:
$data1 = explode( '-', $_GET['data1'] );
$data2 = explode( '-', $_GET['data2'] );

echo $dia1 = mktime( 0, 0, 0, $data1[1], $data1[0], 2000+$data1[2] );
echo $dia2 = mktime( 0, 0, 0, $data2[1], $data2[0], 2000+$data2[2] );

echo ( $dia2 - $dia1 ) / 86400;

Veja funcionando no IDEONE.
Uma maneira mais simples, se você puder já enviar o valor com 4 dígitos no ano, é essa:
$dia1=strtotime( $_GET['data1'] );
$dia2=strtotime( $_GET['data2'] );

echo ( $dia2 - $dia1 ) / 86400;

Veja funcionando no IDEONE.
A função strtotime faz a interpretação da string conforme o separador.

*

*Datas com / são consideradas como MM/DD/AAAA;

*Datas com - são consideradas como DD-MM-AAAA;
Se suas datas estiverem em formato MM/DD/AA, e você preferir usar outro critério de conversão, essa postagem pode ser útil:

Como inverter datas no php, independente do formato?

A: Use o método DateTime::createFromFormat para transformar a data em um objeto DateTime a partir de um formato.
Em seguida, use o método DateTime::diff para computar a diferença entre datas.
$d1 = DateTime::createFromFormat('d-m-y', $_GET['data1'])
$d2 = DateTime::createFromFormat('d-m-y', $_GET['data2'])

$d2->diff($d1)->format('%a');

O método diff retornará uma instância do objeto DateInterval.
Veja aqui a tabela de  símbolos que podem ser usados para formatação da diferença entre datas (DateInterval).

*

*http://php.net/manual/pt_BR/datetime.createfromformat.php


text:
Q: Automatic referencing vice-versa from lookup-fields from one list to another on the same site we started to attach multiple items (e.g. technicians) in a lookup-field within one list (e.g. customers). What is the fastest way for automatic referencing vice-versa from these lookup-fields? For this example I want to find out within the list of technicians for what customers they are responsible for. In the list of "customers" I would add two technicians "Gary" and "Todd" from the "technicians"-list in the lookup-field "technicians". I would expect to get a kind of calculated field "customers" in the list of "technicians", where Sharepoint automatically fills in all customers that have the specific technician in their "technicians"-lookup-field. How could I do that?
Thanks in advance!
Best regards
Claus


text:
Q: Magento 2 - Using KOJS template for filter component? On the same page I have several custom product grids with above them a filter toolbar.
To simplify the case :
<?php foreach ($grids as $id => $grid): ?>

        <div id="item-<?php echo $id; ?>"
             class="item"
             data-bind="scope:'filter'"
        >

Product 1

Product 1

Product 1

Product 2

<?php endforeach; ?>

My JS Component file :
# \Foo\Bar\view\frontend\web\js\filter.js

define([
    'jquery',
    'uiComponent',
    'jquery/ui'
], function ($, Component) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Foo_Bar/filter'
        },
        options: {
            option1: 'option1',
            option2: 'option2'
        },
        initialize: function () {
            this._super();
            this.applyFilters();
            this.getTrigger().on('click', $.proxy(this.triggerFilter, this))
        },
        triggerFilter: function (event) {
            this.applyFilters();
        },
        applyFilters: function () {
            // logic
        },
        getCurrentElement: function () {
            return $(this.currentElement);
        }
    });
});

With that I would like that my filter component is linked to the <div id="item-<?php echo $id; ?>"> element that I can work with the
 element.
My questions are :

*

*Is JS Component + KOJS template the best way / practice to perform that?

*Do I have to simply use Magento block + Magento template + RequireJS plugin?

*Is there a simple way to retrieve the current targeted element in UiComponent without using config node as in my example for the KOJS way?


text:
Q: One Nginx Error Page to Rule Them All The Dream
I have a number of server blocks that come and go with the wind. I would really like to create and maintain one PHP template to handle ALL server related errors (404, 403, etc) ...no matter on which block or under which domain they occur, and without having to setup standard server error pages on a block by block basis.
I am detailing my setup here with the thought that it might also be a solution others find useful and would like to implement.
The Setup
In /etc/nginx/ I have a file called errors.conf, which should try and pass errors to a error.php file in /var/www/admin/public

# All the errors...

error_page 401      /error.php?c=401;
error_page 403      /error.php?c=403;
error_page 404      /error.php?c=404;
error_page 500      /error.php?c=500;
error_page 502 503 504  /error.php?c=50x;

# Serve error.php from www/admin/public

location = /error.php {
    root /var/www/admin/public;
    include fastcgi.conf;
    auth_basic off;
}

errors.conf is included in every server block, which would typically look something like this.
server {

    listen       80;
    server_name  demosite.domain.com;
    root   /var/www/demosite/public;
    access_log  /var/www/demosite/logs/demosite.domain.com.access.log;
    error_log  /var/www/demosite/logs/demosite.domain.com.error.log;

    location = /favicon.ico {
        return          204;
        access_log      off;
        log_not_found   off;
    }

    location / {
        index  index.html index.htm index.php;
    }

    include errors.conf;

    location ^~ /public/errors {
        auth_basic      off;
        allow           all;
    }

    # Pass the PHP scripts to FastCGI server listening on the php-fpm socket
    location ~ \.php$ {
        try_files       $uri =404;
        fastcgi_pass    unix:/run/php/php7.0-fpm.sock;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;

}

And where a very simple, un-styled version of the actual error page (error.php) might look like this...
    <!DOCTYPE html>

      <?php

      // Map error code to message string
      $_err = Array("401" => "Authorization Required",
          "403" => "Access Restricted",
          "404" => "File Not Found",
          "500" => "Some Sort of Server Error",
          "50x" => "Temporarily Unavailable");

      // Get the error string
      function errorString($error)
      {
          global $_err;

          foreach ($_err as $key => $val) {
              if ($key == $error)
                  return $val;
          }

          return "Unknown Error";
      }

      isset($_GET['c']) or die("Unknown Error");
      $error = $_GET['c'];
      $str = errorString($error);

      ?>

        <meta charset="UTF-8">
        <title><?= $error ?> - <?= $str ?></title>

<?= $error ?> – <?= $str ?>

Something went wrong. Horribly wrong.

The Outcome
What happens now with, for example, a 404 error is that the error.php file is not executed, but downloaded. And the title of the downloaded file is the last segment of the URL.
So when trying to access, for example, demosite.domain.com/blah/some_file.html a download of our error.php file named some_file.html will be initiated.
So we're close! And I am sure the fix is relatively simple. Any help or insight would be appreciated.

Update
fastcgi.conf is as follows...
    fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param  QUERY_STRING       $query_string;
    fastcgi_param  REQUEST_METHOD     $request_method;
    fastcgi_param  CONTENT_TYPE       $content_type;
    fastcgi_param  CONTENT_LENGTH     $content_length;

    fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
    fastcgi_param  REQUEST_URI        $request_uri;
    fastcgi_param  DOCUMENT_URI       $document_uri;
    fastcgi_param  DOCUMENT_ROOT      $document_root;
    fastcgi_param  SERVER_PROTOCOL    $server_protocol;
    fastcgi_param  REQUEST_SCHEME     $scheme;
    fastcgi_param  HTTPS              $https if_not_empty;

    fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
    fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

    fastcgi_param  REMOTE_ADDR        $remote_addr;
    fastcgi_param  REMOTE_PORT        $remote_port;
    fastcgi_param  SERVER_ADDR        $server_addr;
    fastcgi_param  SERVER_PORT        $server_port;
    fastcgi_param  SERVER_NAME        $server_name;

    # PHP only, required if PHP was built with --enable-force-cgi-redirect
    fastcgi_param  REDIRECT_STATUS    200;


text: Q: How to send packets in ProtocolLib (spigot 1.18.2) i wanted to ask in there is a simple was to send a packet to The Server in minecraft spigot 1.18.2 using ProtocolLib. I haven't found a simple answer anywhere.


text:
Q: Method for checking Mode I have this method here, checking for the Mode (most frequent element) in an array. Although there is a twist I need to account for and i'm not sure how to go about doing this. For example: if my array is {1,2,2,3,3,5} .. I need to print out 'NaN' , because 2 and 3 both occur 2 times. Any help on how to add this is appreciated.
My code:
  public double mode() {
    double maxValue=0, maxCount=0;
    boolean flag=false;

    for (int i = 0; i < data.length; ++i)
        {
            double count = 0;
                for (int j = 0; j < data.length; ++j)
                    {
                        if (data[j]==(data[i])) ++count;
                    }
                if (count > maxCount)
                {
                        if(count>1)flag = true;
                        maxCount = count;
                        maxValue = data[i];
                }
        }
        if(flag)
        {
            return maxValue;
        }
        else return 0.0;
    }

A: Seeing as you return 0.0 when you don't find a mode, how about using this ternary when you call the mode() function:
final double mode = this.mode();
System.out.println(mode == 0.0 ? "NaN" : mode);

Or to put it in full if you prefer:
final double mode = this.mode();
if(mode == 0.0)
{
    System.out.println("NaN");
}
else
{
    System.out.println(mode);
}

A: I suppose your current code is not exactly giving out the result you wanted.
Here's a code snippet updated:
public double mode() {
        // Sort array
        Arrays.sort(data);

        double maxValue = 0.0, maxCount = 0.0;
        for (int i = 0; i < data.length; ++i) {

            // Count number of elements with same value
            int count = 0;
            int index = i;
            while (index < data.length) {
                if (data[i] == data[index]) {
                    count++;
                    index++;
                } else {
                    break;
                }
            }

            if (count > maxCount) {
                maxCount = count;
                maxValue = data[i];
            } else if (count == maxCount) {
                maxCount = count;
                maxValue = 0.0;
            }
        }

        return maxValue;
    }

Then, from the point where you call mode(), do the following:
double m = mode();
System.out.println(m == 0.0 ? "NaN" : m);


text:
Q: RegisterGlobalFilters and HandleErrorAttribute not working After struggling with RegisterGlobalFilters and HandleErrorAttribute forever I decided to go back to the bare bones. I created a new MVC 3 project in VS10, using the template. Add a throw DivideByZeroException in the About-action and fired up the dev server. Expected not to see a yellow screen.
But I did.
Why won't this work for me?
Update
archil's and Adam Tuliper's suggestion kind of worked. The Error view was called.
Then I proceed to add this in RegisterGlobalFilters.
filters.Add(new HandleErrorAttribute { ExceptionType = typeof(DivideByZeroException), View = "DivideByZeroException", Order = 1 });
filters.Add(new HandleErrorAttribute { View = "AllOtherExceptions", Order = 2 });

The AllOtherExceptions view was called. Why not the DivideByZeroException view?
The followup question has been posted here.

A: HandleErrorAttribute works when following conditions are met

*

*CustomErrors is enabled in web config

*If exception is HttpException, its error code is 500.

As in your case second condition is met, ensure you have custom erros turned on
<system.web>
     <customErrors mode="On"></customErrors>
</system.web>

A: Do you have custom errors turned ON in your web.config?
If not turn it on, and it should work.


text:
Q: Getting right side numbers of my Id I have a query which returns IDs.
SELECT Id from MyTable;

The result is something like this:
2400044
243000178
12300044

Now I would like to get only numbers on the right side of 000 (three zeros).
So:
44
178
44

A: This returns the original number when no matches on 000 is found, it will find the first occurance of 000 and return the number after that:
DECLARE @t table(a int)
INSERT @t
values(2400044),(243000178),(12300044),(10002000)

SELECT a%(power(10,len(a)-charindex('000',a)))
FROM @t

This require that the number is an actual integer or bigint. Float or varchar  with characters which isn't numeric(0-9) will fail

A: Solution using CHARINDEX() and SUBSTRING()
SELECT SUBSTRING([Id], CHARINDEX('000', [Id])+3, LEN([Id]))
FROM MyTable

A: Use SUBSTRING AND CHARINDEX Function as below:
DECLARE @myNumber VARCHAR(50)='2400057744'
SELECT REVERSE(SUBSTRING(REVERSE(@myNumber),0,CHARINDEX('000',REVERSE(@myNumber))))

Output:
2400044 to 44
243000178 to 178
12300044 to 44
200030004 to 4

In table form
SELECT a Raw, REVERSE(SUBSTRING(REVERSE(a), 0, CHARINDEX('000', REVERSE(a)))) Number
from ( values (2400044), (243000178), (12300045), (2430001789), (2430033), (20003000101)
     ) k(a)

A: Use patindex() with substring() function to get the right side value
select
      substring(Id, patindex('%[0][0][0]%', Id)+3, len(Id)) Id
from MyTable

A: Assuming ID is an INT or BIGINT, with a return of 5 digits or less:
create table #MyTable (Id int)

Insert Into #MyTable Values (2400044), (243000178), (12300044)

select id%100000 from #MyTable

IF it is a string:
Select Cast(Cast(id as bigint)%100000 as varchar(10)) from #MyTable


text:
Q: "ModuleNotFoundError: No module named 'flask'" on Heroku I see a I am getting a "ModuleNotFoundError: No module named 'flask'". This is stopping my application from loading on Heroku. I have already installed flask on virtual environment as well as on my system and the issue still persists. When I check the requirements, it says satisfied.
HERE ARE MY LOGS
2020-04-24T13:17:39.316886+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2020-04-24T13:17:39.316887+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-04-24T13:17:39.316887+00:00 app[web.1]: self.callable = self.load()
2020-04-24T13:17:39.316887+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2020-04-24T13:17:39.316888+00:00 app[web.1]: return self.load_wsgiapp()
2020-04-24T13:17:39.316888+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2020-04-24T13:17:39.316889+00:00 app[web.1]: return util.import_app(self.app_uri)
2020-04-24T13:17:39.316889+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2020-04-24T13:17:39.316889+00:00 app[web.1]: __import__(module)
2020-04-24T13:17:39.316890+00:00 app[web.1]: File "/app/app.py", line 2, in <module>
2020-04-24T13:17:39.316890+00:00 app[web.1]: from flask import Flask, render_template, url_for, request, redirect
2020-04-24T13:17:39.316898+00:00 app[web.1]: ModuleNotFoundError: No module named 'flask'
2020-04-24T13:17:39.317183+00:00 app[web.1]: [2020-04-24 13:17:39 +0000] [11] [INFO] Worker exiting (pid: 11)
2020-04-24T13:17:39.441061+00:00 app[web.1]: [2020-04-24 13:17:39 +0000] [4] [INFO] Shutting down: Master
2020-04-24T13:17:39.441187+00:00 app[web.1]: [2020-04-24 13:17:39 +0000] [4] [INFO] Reason: Worker failed to boot.
2020-04-24T13:25:42.000000+00:00 app[api]: Build started by user prakharrathi25@gmail.com
2020-04-24T13:26:50.779076+00:00 heroku[web.1]: State changed from crashed to starting
2020-04-24T13:26:50.551463+00:00 app[api]: Deploy 75ff8400 by user prakharrathi25@gmail.com
2020-04-24T13:26:50.551463+00:00 app[api]: Release v4 created by user prakharrathi25@gmail.com
2020-04-24T13:27:11.485811+00:00 heroku[web.1]: State changed from starting to crashed
2020-04-24T13:27:11.342925+00:00 app[web.1]: [2020-04-24 13:27:11 +0000] [4] [INFO] Starting gunicorn 19.9.0
2020-04-24T13:27:11.343731+00:00 app[web.1]: [2020-04-24 13:27:11 +0000] [4] [INFO] Listening at: http://0.0.0.0:29934 (4)
2020-04-24T13:27:11.344060+00:00 app[web.1]: [2020-04-24 13:27:11 +0000] [4] [INFO] Using worker: sync
2020-04-24T13:27:11.349766+00:00 app[web.1]: [2020-04-24 13:27:11 +0000] [10] [INFO] Booting worker with pid: 10
2020-04-24T13:27:11.360106+00:00 app[web.1]: [2020-04-24 13:27:11 +0000] [10] [ERROR] Exception in worker process
2020-04-24T13:27:11.360124+00:00 app[web.1]: Traceback (most recent call last):
2020-04-24T13:27:11.360130+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2020-04-24T13:27:11.360218+00:00 app[web.1]: worker.init_process()
2020-04-24T13:27:11.360220+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2020-04-24T13:27:11.360220+00:00 app[web.1]: self.load_wsgi()
2020-04-24T13:27:11.360220+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2020-04-24T13:27:11.360221+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2020-04-24T13:27:11.360230+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-04-24T13:27:11.360231+00:00 app[web.1]: self.callable = self.load()
2020-04-24T13:27:11.360231+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2020-04-24T13:27:11.360231+00:00 app[web.1]: return self.load_wsgiapp()
2020-04-24T13:27:11.360232+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2020-04-24T13:27:11.360232+00:00 app[web.1]: return util.import_app(self.app_uri)
2020-04-24T13:27:11.360232+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2020-04-24T13:27:11.360233+00:00 app[web.1]: __import__(module)
2020-04-24T13:27:11.360233+00:00 app[web.1]: File "/app/app.py", line 2, in <module>
2020-04-24T13:27:11.360233+00:00 app[web.1]: from flask import Flask, render_template, url_for, request, redirect
2020-04-24T13:27:11.360291+00:00 app[web.1]: ModuleNotFoundError: No module named 'flask'
2020-04-24T13:27:11.360477+00:00 app[web.1]: [2020-04-24 13:27:11 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-04-24T13:27:11.392341+00:00 app[web.1]: [2020-04-24 13:27:11 +0000] [4] [INFO] Shutting down: Master
2020-04-24T13:27:11.392461+00:00 app[web.1]: [2020-04-24 13:27:11 +0000] [4] [INFO] Reason: Worker failed to boot.
2020-04-24T13:27:12.000000+00:00 app[api]: Build succeeded
2020-04-24T13:28:07.813602+00:00 heroku[web.1]: State changed from crashed to starting
2020-04-24T13:28:24.647126+00:00 heroku[web.1]: State changed from starting to crashed
2020-04-24T13:28:24.442681+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [4] [INFO] Starting gunicorn 19.9.0
2020-04-24T13:28:24.443179+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [4] [INFO] Listening at: http://0.0.0.0:6805 (4)
2020-04-24T13:28:24.443379+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [4] [INFO] Using worker: sync
2020-04-24T13:28:24.447064+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [10] [INFO] Booting worker with pid: 10
2020-04-24T13:28:24.453997+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [10] [ERROR] Exception in worker process
2020-04-24T13:28:24.453998+00:00 app[web.1]: Traceback (most recent call last):
2020-04-24T13:28:24.453998+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2020-04-24T13:28:24.453998+00:00 app[web.1]: worker.init_process()
2020-04-24T13:28:24.453998+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2020-04-24T13:28:24.453999+00:00 app[web.1]: self.load_wsgi()
2020-04-24T13:28:24.453999+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2020-04-24T13:28:24.453999+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2020-04-24T13:28:24.453999+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-04-24T13:28:24.454002+00:00 app[web.1]: self.callable = self.load()
2020-04-24T13:28:24.454002+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2020-04-24T13:28:24.454002+00:00 app[web.1]: return self.load_wsgiapp()
2020-04-24T13:28:24.454002+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2020-04-24T13:28:24.454002+00:00 app[web.1]: return util.import_app(self.app_uri)
2020-04-24T13:28:24.454002+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2020-04-24T13:28:24.454003+00:00 app[web.1]: __import__(module)
2020-04-24T13:28:24.454003+00:00 app[web.1]: File "/app/app.py", line 2, in <module>
2020-04-24T13:28:24.454003+00:00 app[web.1]: from flask import Flask, render_template, url_for, request, redirect
2020-04-24T13:28:24.454006+00:00 app[web.1]: ModuleNotFoundError: No module named 'flask'
2020-04-24T13:28:24.454171+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-04-24T13:28:24.470439+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [11] [INFO] Booting worker with pid: 11
2020-04-24T13:28:24.476282+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [11] [ERROR] Exception in worker process
2020-04-24T13:28:24.476283+00:00 app[web.1]: Traceback (most recent call last):
2020-04-24T13:28:24.476284+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2020-04-24T13:28:24.476284+00:00 app[web.1]: worker.init_process()
2020-04-24T13:28:24.476285+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2020-04-24T13:28:24.476285+00:00 app[web.1]: self.load_wsgi()
2020-04-24T13:28:24.476285+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2020-04-24T13:28:24.476286+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2020-04-24T13:28:24.476286+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2020-04-24T13:28:24.476287+00:00 app[web.1]: self.callable = self.load()
2020-04-24T13:28:24.476287+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2020-04-24T13:28:24.476287+00:00 app[web.1]: return self.load_wsgiapp()
2020-04-24T13:28:24.476288+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2020-04-24T13:28:24.476289+00:00 app[web.1]: return util.import_app(self.app_uri)
2020-04-24T13:28:24.476289+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2020-04-24T13:28:24.476289+00:00 app[web.1]: __import__(module)
2020-04-24T13:28:24.476290+00:00 app[web.1]: File "/app/app.py", line 2, in <module>
2020-04-24T13:28:24.476290+00:00 app[web.1]: from flask import Flask, render_template, url_for, request, redirect
2020-04-24T13:28:24.476295+00:00 app[web.1]: ModuleNotFoundError: No module named 'flask'
2020-04-24T13:28:24.476455+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [11] [INFO] Worker exiting (pid: 11)
2020-04-24T13:28:24.581572+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [4] [INFO] Shutting down: Master
2020-04-24T13:28:24.581678+00:00 app[web.1]: [2020-04-24 13:28:24 +0000] [4] [INFO] Reason: Worker failed to boot.
2020-04-24T13:29:35.587344+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=flair-prediction-app.herokuapp.com request_id=24015513-f2af-4174-a057-3e0d95406412 fwd="122.162.96.112" dyno= connect= service= status=503 bytes= protocol=https
2020-04-24T13:29:37.330254+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=flair-prediction-app.herokuapp.com request_id=8caba2a9-f9ba-4c9b-9bb9-2a66a24044e9 fwd="122.162.96.112" dyno= connect= service= status=503 bytes= protocol=https
2020-04-24T13:30:04.497866+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=flair-prediction-app.herokuapp.com request_id=2773ad5b-b466-4a23-aa58-96091748fb0f fwd="122.162.96.112" dyno= connect= service= status=503 bytes= protocol=https
2020-04-24T13:31:42.603319+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=flair-prediction-app.herokuapp.com request_id=1b9f111c-c505-4796-a2f8-012346ae306a fwd="122.162.96.112" dyno= connect= service= status=503 bytes= protocol=https

A: Add Flask in your requirements.txt
Flask==1.1.1


text:
Q: Can I use openMP parallel for with an object oriented loop iterator that I want to have saved? I am working with a simulation that consists of a cells, objects that interact with each other and evolve over time. I am looking at parallelizing my code using the OpenMP parallel for imperative and want my cells (objects) to be updated per timestep in parallel, below you can see part of the code.
#pragma omp parallel for default(none) shared(cells, maxCellReach, parameters, cellCellJunctions, timestepDistance) firstprivate(timestep), reduction(+ : centerOfMass)
    for (auto it = cells.begin(); it != cells.end(); it++) {
        maxCellReach = std::max(it->getNucleus()->getCellReach(), maxCellReach);
        it->ApplyIntercellularForce(cellCellJunctions, Constants::junctionCreateDistance, parameters);
        it->step(timestep, parameters);
        centerOfMass += it->GetCenterOfMass();
    }

I have read that the loop iterator variable of a openMP parallel for loop is always private. I however, want all the cells to be updated together. Does this code achieve that or do I need a different approach with openMP?
I looked around online, but could not find anything on making loop iterators shared variables or something similar in a for loop.

A: To be able to use OpenMP on a for loop, it has to fulfill the "Canonical Loop Form" as specified by the standard. For example it is described in the OpenMP 4.5 Specification section 2.6 (starting on page 53) and in the OpenMP 5.0 Specification Section 2.9.1 (starting on page 95).
Both standards specify the loop form to be

for (init-expr; test-expr; incr-expr) structured-block

with differing restrictions on init-expr, test-expr and inc-expr.
While 4.5 already allows random-access-iterator-type to be used here specifically from C++, it doesn't allow for != in the test-expr. This was fixed by the 5.0 standard which is almost completely implemented by the newest versions of gcc and clang at the time of writing this answer. For compatibility with older versions of these compilers you might have to use < instead if possible. For more information on which versions of which compiler implements which standard, see here.
If your iterators are not allowing random access, things get more complicated. See for example the tasking code in this answer.
On page 99 the 5.0 standard even allows for range-based for loops from C++11, so you could write your loop even more elegantly.
As of OpenMP 5.2 there is still at least one special case (#pragma omp simd) which does not work on non-pointer random access iterators.


text:
Q: Sessions vs. Token based authentication I want to know which is more safe to implement for authentication and why?
Session based authentication OR Token based authentication?
I know sessions can be used for other things as well, but right now I am only interested about authentication.
Is it true that nothing is stored on server side if using tokens (not even in memory)? If yes, then how it identifies against expired tokens as that had also been signed using the same secret?

A: The question on Information Security linked in the comment above has a lot of relevant information. That being said, a few additional concerns raised in this question should be addressed:
Safety
Knowing nothing about the server implementation, both methods can be as secure. Session-based authentication mostly relies on the guessability of the session identifier (which, as described in the Information Security answer, it in itself a very simple token). If the session identifier is a monotonously incrementing numeric id, then it is not very secure, OTOH it could be an opaque cryptographically strong unique ID with a huge keyspace, making it very safe. You are probably going to use the session implementation offered by your server framework of choice, so you need to check that. After that, using session authentication, your server implementation needs to verify that the server stored session contains the relevant authorization (i.e. user account data, role, etc) - as a lot of server session frameworks will be default auto-generate empty sessions as needed, the fact that a session exists must not be relied upon as proof enough for a valid authentication and authorization.
For example, PHP's internal session ID generation uses a completely random 288 bits number (default setting) so it is considered safe, OTOH - by default it generates sessions automatically so the previous comment must be adhered to (or to disable automatic session creation and make sure the server only creates session as needed).
Also, if the session ID is passed using an HTTP URL query string, as was the default in days of old, then the session can be stolen quite easily and that makes the whole process insecure.
Token safety is mostly based around secure token generation: if the server generates tokens in a secure manner - i.e. non-guessable and verifiable - as demonstrated in the Information Security answer. A naive implementation (that I saw one time) might be to MD5 hash a known token, such as a user name, and that makes it very unsafe, even when salted. When using cryptographic tokens, safety is closely related to the strength of encryption which is determined by the algorithm used, length of the key, and - most importantly - how well the server key is secured: if the server key is hard-coded into the server implementation and that code is then open-sourced...
Storage
Whether the server needs to store anything generally depends on the implementation of the tokens.
A lot of implementations use the concept of an "API key" as "token authentication" and so often tokens are just some cryptographically secure ID to a database that records which "API keys" have been generated. This requires storage but has the advantage of a simpler implementation and - more importantly - the ability to revoke tokens.
The other approach is to have the token carry its own authenticity - this allows the server to essentially offload the storage of tokens to the client and use the client as the database - very much like how HTTP Cookies allow servers to offload some storage requirements to the client (often used for client's specific settings, like whether the user wants a light interface or a dark interface).
The two patterns used for this are demonstrated well in the Information Security answer: signing and encrypting.

*

*Signing: The token is some simple encoding (like JSON or CSV) of the authenticator credentials (such as the username) and possibly the token's expiry time (if you want to have tokens expire - generally a good idea, if you can't revoke tokens), and then the server signs the generated text using a server secret and adds that to the token. When the client submits the token, the server can extract the clear text from the token, re-sign it and compare the new signature to the signature part in the submitted token - if they are identical, then the token is valid. After validation, you probably want to check the validated expiry date against the current time. The main disadvantage here is that care should be taken that the clear-text authentication details are strongly insufficient for an attacker to re-authenticate - otherwise, it harms the safety requirement. i.e. don't send the password as part of the token, or any other internal detail.

*Encrypting: the token is generated by again encoding all the relevant authentication details and then encrypting the clear-text with a server secret and only submitting the encrypted result. If the encryption scheme can be trusted, the authentication details can include internal data - but care should be taken as having a large crypt-text available offline to an attacker is a larger attack surface than a small signature and weak encryption algorithms will be less resilient in this usage than in just signing.
In both methods, safety is closely related to the strength of the encryption/signing algorithm - a weak algorithm will allow an attacker to reverse engineer the server secret and generate new valid tokens without authentication.
A personal note
In my opinion, cryptographic token-based authentication tends to be less safe than session-based, as it relies on the (often single) developer doing everything right from design to implementation to deployment, while session-based authentication can leverage existing implementations to do most of the heavy lifting, where it is very easy to find high-quality, secure and massively used and tested session storage implementations. I would need a very compelling reason as to why session storage is unwanted before recommending using cryptographic tokens.
Always remember the no.1 rule of cryptographic security: never design your own single-use cryptographic measures.


text:
Q: Cannot resolve all parameters for AppComponent in Plunker This is a minimal example: http://plnkr.co/edit/p0ORaBt2JGV0QlC5YBLw?p=preview
I set the Providers and @Injectable, but it still complains about Cannot resolve all parameters for AppComponent
Could someone have a look and kindly tell me why? I checked some similar existing posts and the solutions to them don't seem to work . (E.g. add @inject)

A: Change app.components.ts as below :
import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpModule, Http } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class AService {

  constructor(private http: Http) {

  }

  do() {
      let a = this.http.get('abc').subscribe();
  }
}

@Component({
  selector: 'my-app',
  template: '
Angular
'
})

export class AppComponent implements OnInit {

  constructor(private service: AService) {

  }

  ngOnInit() {
    console.log('abc');
    this.service.do();
  }
}


text:
Q: Initialization command I noticed in the Cell > Cell properties menu an item I assume was recently added, but I really wouldn't know for sure (8.0.4/Win here). It's called Initialization Command:

Nothing about it to be found in my documentation center. Neither does it seem to be in the online reference:

Any idea what this is supposed to do? As far as I can see its effect is the same as the Initialization Cell menu item.


text:
Q: Why does $\arg (f \circ \gamma)' (t_0) = \arg (f'(z_0)) + \arg (\gamma' (t_0))\ $?
Can anybody help me understanding as to why $\arg (f \circ \gamma)' (t_0) = \arg (f'(z_0)) + \arg (\gamma' (t_0)) $ holds?
I know that $\arg (z_1z_2) \neq \arg (z_1) + \arg (z_2)$ unless $-\pi \lt \arg (z_ 1) + \arg (z_2) \leq \pi.$
How do I make sure that $\arg (f'(z_0)) + \arg (\gamma'(t_0)) \in (-\pi, \pi]\ $? Any help in this regard will be highly appreciated.
Thanks in advance.

A: Use the formula for the derivative of the composition of two functions:
$$(f \circ \gamma)' (t_0) = f'(z_0)\gamma' (t_0)$$
then, take the argument of both sides:
$$\arg (f \circ \gamma)' (t_0) = \arg (f'(z_0)) + \arg (\gamma' (t_0))$$


text:
Q: Remove duplicate fields in a given column (after ID check) I'd like to remove from a given column ($2 in the example) the duplicate fields (comma separated), but only if the ID column ($1 in the example) is the same.
Input:
A    1,2,3,4
A    8,9,10,11
A    2,3,4,11,12
B    4,5,6,7
B    6,8,9,10

Expected output:
A    1,2,3,4
A    8,9,10,11
A    12
B    4,5,6,7
B    8,9,10

A: This is easy enough in awk using an array, split, and a regular loop:
{
    split($2, elements, ",")
    out = ""
    for (i in elements) {
        el = elements[i]
        key = $1 " " el
        if (!(key in used)) {
            out = out el ","
        }
        used[key] = 1
    }
    sub(/,$/, "", out)
    $2 = out
}
1

For each line, we split the second column by commas and save the bits into an array elements. We then build up the new value for that column with a loop, checking whether we've seen the value before or not.
We're keeping the set of values we've already seen in the (associative) array used. We construct a string key containing both the value of the first column and the value from the second we're currently looking at. If key is in used, we've seen this one before for this ID and shouldn't put it in the output; otherwise, it's new, and we concatenate the value to out. So that we don't use it again, we store key (which will be something like "A 3") into our set of seen elements.
Finally, we put the constructed list back into the second column. This is essentially the approach you'd take in any other language.
Put the code above into a file and run it with awk -f, or single-quote all of it as an argument on the command line.

A: perl -lpe 's/(\S+)\s+\K\S+/join ",", grep {!$seen{$1}->{$_}++} split ",", $&/e'


text:
Q: Permutations on circular table so that i cannot go to i or i+1. Suppose $n$ objects are placed in a circular table in clockwise order. Find the no of permutations where $i$ cannot go to $i$ or $i+1$. i.e. $1$ cannot be mapped to $1$ or $2$, $2$ cannot be mapped to $2$ or $3$,... , $n$ cannot be mapped to $n$ or $1$.
Say the required no is $T(n)$.
What I did, first I fix $1 \in \{1,2,..,n\}.$ Now, $1$ can go to some $k \in \{3,4,..,n\}$ in $\binom{n-2}{1} = n-2$ ways.
Case 1. If $k\neq n$, then two subcases appear.
SubCase 1. $k \to 1$ and $1 \to k$. Rest can be arranged in $T(n-2)$ ways.
SubCase 2. $k \to$ some other element and from some other element comes back to $1$. We can consider 1 and k as same unit and can consider arrangement in $n-1$ elements in $T(n-1)$ ways.
Total count for case 1 is $(n-2)*\{T(n-2)+T(n-1)\}$.
Case 2. If $k = n$. This is the case where I stucked. Now how to proceed. Any help will be appreciated.

A: you may should try come to the problem from another angle: take the amount of all the permutations in a circle, which is $(n-1)!$, and decrease all the problematic permutations (every one's which mapping at least one element to itself) by using the "inclusion-exclusion principle".
for more info look at https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle


text:
Q: .NET ConcurrentDictionary.ToArray() ArgumentException Sometimes I get the error below when I call ConcurrentDictionary.ToArray. Error Below:

System.ArgumentException: The index is equal to or greater than the length of the array, or the number of elements in the dictionary is greater than the available space from index to the end of the destination array.
     at System.Collections.Concurrent.ConcurrentDictionary2.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair2[] array, Int32 index)
     at System.Linq.Buffer1..ctor(IEnumerable1 source)
     at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)
     at ...Cache.SlidingCache2.RemoveExcessAsync(Object state) in ...\SlidingCache.cs:line 141
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
     at System.Threading.ThreadPoolWorkQueue.Dispatch()

I noticed that in multithreaded scenarios you sometimes get exceptions when sorting the ConcurrentDictionary. See stack overflow question here. So I started using ConcurrentDictionary.ToArray before sorting instead. It appears there are still problems while creating the array as well.
The concurrent dictionary is being used for a cache that maintains objects and flushes the last accessed objects when the set maximum number of elements for the cache is reached. The cache is accessed by multiple threads and the above error occurs when trying to remove older elements so new elements can be added to the array. Please see some code snippets below:
public class SlidingCache<TKey, TValue> : IDictionary<TKey, TValue>
{
    public int MinCount { get; private set; }
    public int MaxCount { get; private set; }
    private readonly IDictionary<TKey, CacheValue> _cache = new ConcurrentDictionary<TKey, CacheValue>();

    public SlidingCache(int minCount=75000, int maxCount=100000)
    {
        if (minCount <= 2)
            throw new ArgumentException("minCount");

        if (maxCount <= minCount)
            throw new ArgumentException("maxCount");

        MinCount = minCount;
        MaxCount = maxCount;
    }

    #region IDictionary<TKey, TValue>

    public int Count
    {
        get { return _cache.Count; }
    }

    public TValue this[TKey key]
    {
        get
        {
            return _cache[key].Value;
        }
        set
        {
            _cache[key]=new CacheValue(value);
            RemoveExcess();
        }
    }
...

    #endregion

    private void RemoveExcess()
    {
        if (this.Count <= this.MaxCount || Interlocked.Increment(ref _removingExcess) != 1)
            return;

        ThreadPool.QueueUserWorkItem(RemoveExcessAsync, null);
    }

    private int _removingExcess;
    private void RemoveExcessAsync(object state)
    {
        var remove = _cache.ToArray().OrderByDescending(i => i.Value.LastRequestTime).Take(MaxCount - MinCount);
        foreach (var pair in remove)
        {
            _cache.Remove(pair.Key);
        }

        Interlocked.Exchange(ref _removingExcess, 0);
    }

Can anyone kindly explain the potential reason for the above exception and any workarounds?
Thanks.

A: That is because Enumerable.ToArray is not safe to use with concurrent collections.
You should declare your internal variable to be of type ConcurrentDictionary and not IDictionary, as this would use the ToArray implementation implemented by the dictionary itself, instead of relying on the extension method:
private readonly IDictionary<TKey, CacheValue> _cache = new ConcurrentDictionary<TKey, CacheValue>();

In particular, Enumerable.ToArray ends up using a Buffer class internally, and here is how the constructor of that class is defined (the start of it):
(from Enumerable.cs - reference source)
internal Buffer(IEnumerable<TElement> source) {
    TElement[] items = null;
    int count = 0;
    ICollection<TElement> collection = source as ICollection<TElement>;
    if (collection != null) {
        count = collection.Count;
        if (count > 0) {
            items = new TElement[count];
            collection.CopyTo(items, 0);
        }
    }

As you can see, it uses the Count property of the dictionary, creates an array, then copies the elements to the array. If the underlying dictionary has gotten at least one other item after reading Count but before CopyTo you get your problem.
You can contrast that with the implementation of ToArray inside the dictionary itself which uses locking:
(from ConcurrentDictionary.cs - reference source)
public KeyValuePair<TKey, TValue>[] ToArray()
{
    int locksAcquired = 0;
    try
    {
        AcquireAllLocks(ref locksAcquired);
        int count = 0;
        checked
        {
            for (int i = 0; i < m_tables.m_locks.Length; i++)
            {
                count += m_tables.m_countPerLock[i];
            }
        }

        KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[count];

        CopyToPairs(array, 0);
        return array;
    }
    finally
    {
        ReleaseLocks(0, locksAcquired);
    }
}


text:
Q: How do I get the grey color/translucency I see on UIPickerDate default view on my own custom Picker? I have created a UI Picker but the default is just it being transparent. I would like to use/be given the RGB + translucency values that makes the grey color that is commonly used on picker views.
It is the same grey like the defualt color for a programmatic UI Date Picker. Thank you! I need this to be in alignment with Apple's Human Interface Guidelines.
Added a picture of the background color/translucency I need below:

A: iPhone SDK has two types of gray color both have opacity 1.
iOS 13 also introduces a range of six opaque gray colors you can use in rare cases where translucency doesn't work well.
https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/color/
And for changing the background color.
light gray color:
picker.backgroundColor = UIColor.lightGray

dark gray color:
picker.backgroundColor = UIColor.darkGray

if you want some transparency on the picker view. You can add Gradient on it.
        let view = UIView(frame: CGRect(x: 0, y: 0, width: picker.frame.width, height: picker.frame.height))
        let gradient = CAGradientLayer()

        gradient.frame = view.bounds
        gradient.colors = [UIColor.white.cgColor, UIColor.lightGray.cgColor]

        picker.layer.insertSublayer(gradient, at: 0)

find the image as it looks with gradient and light gray color.
picker view with gradient

A: Hex color - #e8e9ed
RGB color - UIColor(red: 232/255, green: 233/255, blue: 237/255, alpha: 1)
or you can use #f7f7f7
I hope it works.


text:
Q: Adblock Plus losing subscriptions and filters since last update Adblock Plus recently updated itself (it opened the "Adblock Plus has been installed" tab), and since then it has not been saving filter lists (subscriptions) nor manually entered filters ("add your own filters") between Chrome session.
All previous config has apparently been wiped, and anything added only lasts until Chrome is closed/re-opened - at which point the config is blank again.
There have been no changes (by me) to Chrome or any extensions, but of course no way to tell if Google have done anything, or if any other extensions have updated without knowledge/approval.
Is there any way to check versions / downgrade to a working version? Or to debug the extension data, maybe making it read-only after appropriate config to see if that stops it being blanked?
Version info:-
Chrome 33.0.1750.154 m
Adblock Plus 1.7.4.1131

A: Disabled and re-installed extension from http://adblockplus.org seems to work so far. This version only says 1.7.4 (not 1.7.4.1131) so might still get upgraded and break. Knowing how to rollback if that happens would be useful.

A: I know this is an old post but, since it comes up as the second result when googling "adblock not saving filters", I feel it's still relevant to post here.
If you have NoScript installed, uninstall it and use something like uMatrix instead.  NoScript, despite being labeled as a security plugin, makes money from advertising and supports Google adsense, among others.  It specifically interferes with AdBlock Plus.
You can test this: Reset Firefox/Chrome and install AdBlock Plus, making sure to set at least one subscription.  Install any other addons you wish, restart after each install and check the AdBlock subscription status by hovering over the AdBlock icon. The sbuscriptions will remain.  Install NoScript.  Before restarting your browser, check AdBlock. The filter subscriptions will still be there.  Restart and suddenly they're gone. Remove NoScript, restart, and add your subscriptions again.  They should persist after restarting again.  If they don't you will need to reset your browser again.
Since NoScript has code that targets AdBlock specifically in order to disable features, you will need to reset anyway in order to get all of the subscription options to return.  At this point, Firefox will have a corrupted profile that requires the aforementioned reset.
https://adblockplus.org/blog/attention-noscript-users


text:
Q: Visual Studio replace magic number integers with doubles Can a regular expression be used to find all magic number integers in Visual Studio and convert them to doubles?
The regular expression to find them is beyond my skill, here is what I came up with so far:
(?!=[\s\(])(?<!\.)\d+(?=[\s\)])

This will find all the integers, but erroneously matches
15.527 = "1"5.5"2""7"

Even with a perfect match, is there a way to replace with same number? For example 7 would be replaced by 7.0 and 16 would be replaced by 16.0

A: Using the regex provided by @Wiktor Stribiżew

*

*Close all documents

*Open the problematic documents

*Ctrl+h

*Set search to regex

*Set scope to All Open Documents

*Search for (?<![0-9]\.)\b[0-9]+\b(?![.0-9])

*Replace with $&.0

*Replace all

*Review fix any strings that should not have been affected

A: It seems the pattern I suggested works in almost 99% of cases, so, let me explain the (?<![0-9]\.)\b[0-9]+\b(?!\.) pattern:

*

*(?<![0-9]\.) - a negative lookbehind failing the match if there is a digit and a . symbols right before the digit matched with [0-9]+ pattern

*\b - a leading word boundary (i.e. the previous char cannot be a letter/digit/underscore)

*[0-9]+ - 1 or more digits

*\b - a trailing word boundary (i.e. the next char after the last matched digit cannot be a letter/digit/underscore)

*(?!\.) - a negative lookahead that fails the match if the next char after the last digit matched by the [0-9]+ subpattern is followed with ..

Why [0-9]+ instead of \d? See this SO thread, \d is Unicode aware and matches more than just 0..9 digits.
See the pattern demo.


text:
Q: Python IPC - Twisted, RabbitMQ, I want to create 2 applications in Python which should communicate with each other. One of these application should behave like a server and the second should be the GUI of a client. They could be run on the same system(on the same machine) or remotely and on different devices.
I want to ask you, which technology should I use - an AMQP messaging (like RabbitMQ), Twisted like server (or Tornado) or ZeroMQ and connect applications to it. In the future I would like to have some kind of authentication etc.
I have read really lot of questions and articles (like this one: Why do we need to use rabbitmq), and a lot of people are telling "rabbitmq and twisted are different". I know they are. I really love to know the differences and why one of these solutions will be superior than the other in this case.
EDIT:
I want to use it with following requirements:

*

*There will be more than 1 user connected at a time - I think there will be 1 - 10 users connected to the same program and they would work collaboratively

*The data send are "messages" telling what user did - something like remote calls (but don't focus on that, because the GUIS can be written in different languages, so the messages will be something like json informations).

*The system should allow for collaborative work - so it should be as interactive as possible. (data will be send all the time when user something types or performs some action).

Additional I would love to hear why one solution would be better than the other not only in this particular case.

A: Twisted is used to solve the C10k networking problem by giving you asynchronous networking through the Reactor Pattern. Its also convenient because it provides a nice concurrency abstraction as threading/concurrency in Python is not as easy as say Erlang. Consequently some people use Twisted to dispatch work tasks but thats not what it is designed for.
RabbitMQ is based on the message queue pattern. Its all about reliable message passing and is not about networking. I stress the reliable part as there are many different asynchronous networking frameworks (Vert.x for example) that provide message passing (also known as pub/sub).
More often than not most people combine the two patterns together to create a "message bus" that will work with a variety of networking needs with out unnecessary network blocking and for great integration and scalability.
The reason a "message queue" goes so well with a networking "reactor loop" is that you should not block on the reactor loop so you have to dispatch blocking work to some other process (thread, lwp, separate machine process, queue, etc..). In practice the cleanest way to do this is distributed message passing.
Based on your requirements it sounds like you should use asynchronous networking if you want the results to show up instantly and scale but you could probably get away with a simple system that just polls given you only have handful of clients. So the question is how many total users (Twisted)? And how reliable do you want the updates to be delivered (RabbitMQ)? Finally do you want your architecture to be language and platform agnostic... maybe you want to use Node.js later (focus on the message queue instead of async networking... ie RabbitMQ). Personally I would take a look at Vert.x which allows you to write in Python.

A: When someone is telling you that Twisted and RabbitMQ is different is because compare both is like compare two things with different target.
Twisted is a asynchronous framework, like Tornadao. RabbitMQ is a message queue system. You can't compare each one straight for.
You should turn your ask into a two new questions, the first one wich protocol should I use to communicate my process ? The answer can be figure out with words like amqp, Protocol Buffers ...
And the other one, which framework should I use to write my client and server program  ? Here the answer can fall on Twisted, Tornado, ....


text:
Q: Newbie: Setting up a thesis template this might be a stupid question, but I am trying to use this template
% documentclass options:
% ngerman is needed for hyphenation if the thesis contains parts written in German
% BCOR is binding correction
% if you'd rather have a one sided thesis, add `onside' to the documentclass
\documentclass[11pt, a4paper, BCOR=10mm, english, ngerman]{scrbook}

% include all packages and define commands in setup.tex
\input{setup}

\begin{document}
    \pagestyle{empty} % no header and no page number
    % disable hyper links to remove warning "destination with same identifier"
    % this means within this section nothing can be referenced with a hyperlink
%    \hypersetup{pageanchor=false}
    \include{chapters/0_0-titlepage}
    \pagestyle{plain} % remove chapter name from top, page number at the bottom
    \frontmatter  % roman page numbers
    \include{chapters/0_1-declaration}
    \include{chapters/0_2-abstract}
    \tableofcontents
    \listoffigures
    \listoftables
    \listofalgorithms
    \hypersetup{pageanchor=true}  % re-enable hyperlinking

    \mainmatter  % Arabic page numbers
    \include{chapters/1-introduction}
    \include{chapters/2-relatedwork}
    \include{chapters/3-background}
    \include{chapters/4-approach}
    \include{chapters/5-experiments}
    \include{chapters/6-conclusions}
    \include{chapters/7-acknowledgments}

    % bibliography is not in the table of contents per default, add it manually
    \addcontentsline{toc}{chapter}{Bibliography}
    \bibliographystyle{ieeetr}
    \bibliography{bib/topic1,bib/topic2}
    \newpage
    \thispagestyle{empty}
    \mbox{}

\end{document}

and I keep getting an error asking where the setup.tex file is, now when I loo for it I have another tex file called setup.tex which is
%------------------------------------------------------------------------------
%       package includes
%------------------------------------------------------------------------------
    % font encoding is set up for pdflatex, for other environments see
    % http://tex.stackexchange.com/questions/44694/fontenc-vs-inputenc
    \usepackage[T1]{fontenc}  % 8-bit fonts, improves handling of hyphenations
    \usepackage[utf8x]{inputenc}
    % provides `old' commands for table of contents. Eases the ability to switch
    % between book and scrbook
    \usepackage{scrhack}

    % ------------------- layout, default -------------------
    % adjust the style of float's captions, separated from text to improve readabilty
    \usepackage[labelfont=bf, labelsep=colon, format=hang, textfont=singlespacing]{caption}
    \usepackage{chngcntr}  % continuous numbering of figures/tables over chapters
    \counterwithout{equation}{chapter}
    \counterwithout{figure}{chapter}
    \counterwithout{table}{chapter}

    % Uncomment the following line if you switch from scrbook to book
    % and comment the setkomafont line
    %\usepackage{titlesec}  % remove "Chapter" from the chapter title
    %\titleformat{\chapter}[hang]{\bfseries\huge}{\thechapter}{2pc}{\huge}
    \setkomafont{chapter}{\normalfont\bfseries\huge}

    \usepackage{setspace}  % Line spacing
    \onehalfspacing
    % \doublespacing  % uncomment for double spacing, e.g. for annotations in correction

    % ------------------- functional, default-------------------
    \usepackage[dvipsnames]{xcolor}  % more colors
    \usepackage{array}  % custom format per column in table - needed on the title page
    \usepackage{graphicx}  % include graphics
    \usepackage{subfig}  % divide figure, e.g. 1(a), 1(b)...
    \usepackage{amsmath}  % |
    \usepackage{amsthm}   % | math, bmatrix etc
    \usepackage{amsfonts} % |
    \usepackage{calc}  % calculate within LaTeX
    \usepackage[unicode=true,bookmarks=true,bookmarksnumbered=true,
                bookmarksopen=true,bookmarksopenlevel=1,breaklinks=false,
                pdfborder={0 0 0},backref=false,colorlinks=false]{hyperref}

    %==========================================
    % You might not need the following packages, I only included them as they
    % are needed for the example floats
    % ------------------- functional, custom -------------------
    \usepackage{algorithm,algpseudocode}
    \usepackage{bm}  % bold greek variables (boldmath)
    \usepackage{tikz}
    \usetikzlibrary{positioning}  % use: above left of, etc

    % Improves general appearance of the text
    \usepackage[protrusion=true,expansion=true, kerning]{microtype}

%------------------------------------------------------------------------------
%       (re)new commands / settings
%------------------------------------------------------------------------------
    % ----------------- referencing ----------------
    \newcommand{\secref}[1]{Section~\ref{#1}}
    \newcommand{\chapref}[1]{Chapter~\ref{#1}}
    \renewcommand{\eqref}[1]{Equation~(\ref{#1})}
    \newcommand{\figref}[1]{Figure~\ref{#1}}
    \newcommand{\tabref}[1]{Table~\ref{#1}}

    % ------------------- colors -------------------
    \definecolor{darkgreen}{rgb}{0.0, 0.5, 0.0}
    % Colors of the Albert Ludwigs University as in
    % https://www.zuv.uni-freiburg.de/service/cd/cd-manual/farbwelt
    \definecolor{UniBlue}{RGB}{0, 74, 153}
    \definecolor{UniRed}{RGB}{193, 0, 42}
    \definecolor{UniGrey}{RGB}{154, 155, 156}

    % ------------------- layout -------------------
    % prevents floating objects from being placed ahead of their section
    \let\mySection\section\renewcommand{\section}{\suppressfloats[t]\mySection}
    \let\mySubSection\subsection\renewcommand{\subsection}{\suppressfloats[t]\mySubSection}

    % ------------------- marker commands -------------------
    % ToDo command
    \newcommand{\todo}[1]{\textbf{\textcolor{red}{(TODO: #1)}}}
    \newcommand{\extend}[1]{\textbf{\textcolor{darkgreen}{(EXTEND: #1)}}}
    % Lighter color to note down quick drafts
    \newcommand{\draft}[1]{\textbf{\textcolor{NavyBlue}{(DRAFT: #1)}}}

    % ------------------- math formatting commands -------------------
    % define vectors to be bold instead of using an arrow
    \renewcommand{\vec}[1]{\mathbf{#1}}
    \newcommand{\mat}[1]{\mathbf{#1}}
    % tag equation with name
    \newcommand{\eqname}[1]{\tag*{#1}}

    % ------------------- pdf settings -------------------
    % ADAPT THIS
    \hypersetup{pdftitle={The great title!},
                pdfauthor={FirstName LastName},
                pdfsubject={Undergraduate thesis at the Albert Ludwig University of Freiburg},
                pdfkeywords={deep learning, awesome algorithm,  undergraduate thesis},
                pdfpagelayout=OneColumn, pdfnewwindow=true, pdfstartview=XYZ, plainpages=false}

    %==========================================
    % You might not need the following commands, I only included them as they
    % are needed for the example floats

    % ------------------- Tikz styles -------------------
    \tikzset{>=latex}  % arrow style

    % ------------------- algorithm ---------------------
    % Command to align comments in algorithm
    \newcommand{\alignedComment}[1]{\Comment{\parbox[t]{.35\linewidth}{#1}}}
    % define a foreach command in algorithms
    \algnewcommand\algorithmicforeach{\textbf{foreach}}
    \algdef{S}[FOR]{ForEach}[1]{\algorithmicforeach\ #1\ \algorithmicdo}

but to be honest I don't really know what this means. I just want this template to run, and I don't know how to

A: 1- Save the template code in a file, say, main.tex, located in a particular directory,
2- Save the secondary snippet in a file called setup.tex in the same directory,
3- Call pdflatex.


text:
Q: How to generate Table Of Contents using OpenXML SDK 2.5? I've read and understand this and this Stackoverflow question but there all about OpenXML SDK 2.0. In OpenXML SDK 2.0 there is no real way to update the Table of Content (ToC). There are a few workarounds like marking the document dirty which will ask the user to update the ToC on opening the document, update the ToC using office automation or update the ToC using a word macro.
Unfortunately, none of this solutions fits for my problem.
Is there an more convenient way to update the ToC using Open XML SDK 2.5?

A: The problem is not related to openxml and its versions. In openxml , as document standard, you only define the need of pagination (by a formula place holder) but the pagination only occurs at RENDERING phase (which is not related to openxml). As you have already seen whenever opening a word document, the pagination is running live at bottom of the word editor.
So the only way is simulating it and it can only be happened by office automation ( or a similar tool) or making it dirty.
Note that in PDF generation the problem is a little different. The pages are specified at definition level not rendering level.


text:
Q: `jekyll serve` causing Load errors in console. Unable to start jekyll server locally I'm trying to run a locally Jekyll server to check my side but after the run: jekyll serve command, I get:
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/yaml.rb:5:in `<top (required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your ruby.
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:120:in `require': incompatible library version - /usr/local/rvm/gems/ruby-2.3.1/gems/psych-2.2.2/lib/psych.bundle (LoadError)
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:120:in `require'
    from /usr/local/rvm/gems/ruby-2.3.1/gems/psych-2.2.2/lib/psych.rb:8:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:120:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:120:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/yaml.rb:6:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:120:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:120:in `require'
    from /usr/local/rvm/gems/ruby-2.3.1/gems/safe_yaml-1.0.4/lib/safe_yaml/load.rb:2:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'
    from /usr/local/rvm/gems/ruby-2.3.1/gems/jekyll-3.5.2/lib/jekyll.rb:29:in `<top (required)>'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'
    from /System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require'
    from /usr/local/rvm/gems/ruby-2.3.1/gems/jekyll-3.5.2/exe/jekyll:6:in `<top (required)>'
    from /usr/local/bin/jekyll:26:in `load'
    from /usr/local/bin/jekyll:26:in `<main>'

A: Check first if you can install libyaml:

*

*on MacOS

*or on Linux
Then gem install psych
Check out also rbenv/ruby-build issue 1251 and the GEM_HOME setting.


text:
Q: JavaFx can't get the node coordinate relative to scene My code:
Button btn1 = new Button("Button");
    Button btn2 = new Button("The second Button");

    VBox vbox = new VBox();
    vbox.getChildren().addAll(btn1,btn2);
    Scene scene = new Scene(vbox, 300, 300);

    System.out.println(btn2.getBoundsInLocal());
    System.out.println(btn2.getBoundsInParent());
    System.out.println(btn2.getLayoutBounds());
    System.out.println(btn2.layoutBoundsProperty());

Print:
BoundingBox [minX:0.0, minY:0.0, minZ:0.0, width:0.0, height:0.0, depth:0.0, maxX:0.0, maxY:0.0, maxZ:0.0]
BoundingBox [minX:0.0, minY:0.0, minZ:0.0, width:0.0, height:0.0, depth:0.0, maxX:0.0, maxY:0.0, maxZ:0.0]
BoundingBox [minX:0.0, minY:0.0, minZ:0.0, width:0.0, height:0.0, depth:0.0, maxX:0.0, maxY:0.0, maxZ:0.0]
ReadOnlyObjectProperty [bean: Button@5f3c42b9[styleClass=button]'The second Button', name: layoutBounds, value: BoundingBox [minX:0.0, minY:0.0, minZ:0.0, width:0.0, height:0.0, depth:0.0, maxX:0.0, maxY:0.0, maxZ:0.0]]

My question is: When I get the coordinate of btn1, the MinX and MinY is 0, I can understand. but about btn2, the MinY should not be 0; and MaxX and MaxY also should not be 0. So how can I get the real coordinate of the left corner of the button in the VBox.   To be clear, I need the coordinate of the node which is relative to VBox. Thanks.

A: I believe you have to get the parent bounds and then specify what you want relative to those.
System.out.println(btn2.getBoundsInParent().getY());
System.out.println(btn2.getBoundsInParent().getX());


text:
Q: Generic OrderBy method I am trying to create a generic method to get the latest item ordered by a date property. Something like the following:
public async Task<DateTime> GetLatestModifiedDateAsync<T>() where T : new()
    {
        var result = await db.Table<T>()
                             .OrderByDescending(e => e.OrderedProperty)
                             .FirstOrDefaultAsync();

        return result.ModifiedAt;
    }

This obviously does not work because the property OrderedProperty cannot be found on the generic type, but how can I go about to get this working?

A: If you're sure that all your T has OrderedProperty property, just create an interface
interface IHaveOrderedProperty
{
    int OrderedProperty { get ; }
}

and force T as IHaveOrderedProperty
public async Task<DateTime> GetLatestModifiedDateAsync<T>()
      where T : IHaveOrderedProperty, new()


text:
Q: Selenium to Ranorex For the past few months, I have been automating using Selenium. We are planning to move to Ranorex. Is there a way to move my Selenium scripts (in Java) to Ranorex?
I don't want to execute the Selenium scripts from Ranorex using the connector from Ranorex IDE, but want to port the code, so I don't have to maintain scripts in Selenium and Ranorex.
Any suggestions/options will be great…

A: How/if you can do this is highly dependent on the type of application you are testing, the way your test framework is structured, etc..
Worded as it is, your question doesn't give me enough information to give you an answer. If, however, you are asking if there is some automated way to translate a Selenium script to a Ranorex Script, then no, there really isn't.
Going forward, I recommend go onto the Ranorex forum and ask for specific advice regarding whatever bottlenecks you encounter. It's a pretty active community and some very knowledgeable people are regulars there.
Link: http://www.ranorex.com/forum/

A: @Raj Even there is some port for Java code to C#, there are lots of bottlenecks for which you may not do this automatically.

*

*There is no such counterpart of Selenium in Ranorex

*You need your classes in Recording module format.

*If you do not maintain a static repo file, you cannot match with Ranorex repo.

However, as John_The_Schnauzer, you always can get some expert feedback from their forums.
Best of luck!


text:
Q: Reload inline and src defined scripts during AJAX page transition I'm trying to implement barba.js on a HubSpot site.
Issue with HubSpot is that it renders our js related to forms or js related to custom modules within <script><script> tags.
As such, currently, with my barba implementation, if I transition over to a page with a HubSpot form for example, that form will not show and js related to my modules (such as slick js, they do not work either.
Using the hooks defined below (from the docs), I've added an ajax call to attempt to reload scripts that have a src defined. However, I cannot test if that is working because the js from my custom modules are not working.

Property
Description

data.current
Current page related

data.next
Next page related

data.trigger
Link that triggered the transition

Question being, is there a way for me to reload scripts without src defined?
Here is my current implementation:

function delay(n){
  n = n || 2000;
  return new Promise((done) => {
    setTimeout(() => {
      done();
    }, n);
  });
}

barba.init({
  sync: true,
  prefetchIgnore: true,
  debug: true,
  transitions: [{

    async leave(data){
      const done = this.async();
      await delay(200);
      done();
    },

    async beforeEnter({ next, container }) {
      $(container).find('script').each(function (i, script) {
        var $script = $(script);
        $.ajax({
          url: $script.attr('src'),
          cache: true,
          dataType: 'script',
          success: function () {
            $script.trigger('load');
          }
        });
      });
    },

    async enter(data){
      let scrollX = 0
      let scrollY = 0

      barba.hooks.leave(() => {
        scrollX = barba.history.current.scroll.x;
        scrollY = barba.history.current.scroll.y;
      });

      window.scrollTo(scrollX, scrollY);
    },

    async once(data){
      console.log("test");
    },

  }]
});

Here is a working demo

*

*Page 1

*Page 2
Follow these steps:

*

*Click on page 1. Notice how the HubSpot form loads.

*Click on page 2

*Notice how the slick slider module isn't working

*Now refresh page 2 and you will see slick is working.

*Navigate to page 1 and you'll see the form is not working now.

Visual of issue:


text:
Q: an error message is displays while running the app.how can i fix Error: Invalid configuration of route ''. One of the following must be provided: component, redirectTo, children or loadChildren
In app.module.ts,
RouterModule.forRoot([
  {
    path:'',
    loadChildren:'./mainhomemodule/mainhomemodule.module#MainhomeModule'
  }
])

In mainhome.module.ts,
RouterModule.forChild([
  {
    path:'',
    component:HomeComponentComponent,
    children:[{
      path:'',
      component:HomeComponent
    }]
  }
])
],

A:     add in app-routing.module.ts file and you can direct access children component
app-routing.module.ts file
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {BlogListComponent} from "./blog/blog-list/blog-list.component";
import {BlogDetailComponent} from "./blog/blog-detail/blog-detail.component";

const appRoutes: Routes = [

{ path: 'blog', children: [{path: '',
    component: BlogListComponent,
    data: {
        title: 'Blog',
        urls: [{url: '/blog', title: 'Blog'}, {title: 'Blog'}],
    }}, {
    path: 'detail/:id',
    component: BlogDetailComponent,
    data: {
        title: 'Blog Details',
        urls: [{url: 'blog/detail/:id', title: 'Blog Details'}, {title: 'Blog
    Details'}],
    }
   }]},

  ];

@NgModule({

  imports: [RouterModule.forRoot(appRoutes, { useHash: true })],
  exports: [RouterModule],
})
export class AppRoutingModule {
}

    or you can try this code -> both are working
app.module.ts
//blogModule import in app.module.ts
@NgModule({
imports: [BlogModule]
})

blog.module.ts
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {BlogListComponent} from './blog-list/blog-list.component';
import {BlogDetailComponent} from './blog-detail/blog-detail.component';
import {BlogRoutingModule} from './blog-routing.module';

@NgModule({
 declarations: [BlogListComponent, BlogDetailComponent],
 imports: [
    CommonModule,
    BlogRoutingModule
 ]
})
export class BlogModule {
}

blog-routing.ts file
import {NgModule} from '@angular/core';
import {Routes} from "@angular/router";
import {BlogListComponent} from "./blog-list/blog-list.component";
import {BlogDetailComponent} from "./blog-detail/blog-detail.component";

 export const BlogRoutes: Routes = [
 {
    path: '',
    component: BlogListComponent,
    data: {
        title: 'Blog',
        urls: [{url: '/blog', title: 'Blog'}, {title: 'Blog'}],
    }
 },
 {
    path: 'detail/:id',
    component: BlogDetailComponent,
    data: {
        title: 'Blog Details',
        urls: [{url: 'blog/detail/:id', title: 'Blog Details'}, {title: 'Blog
    Details'}],
     }
  }
];

@NgModule()
export class BlogRoutingModule {
}


text:
Q: Windows 7, Ubuntu 12.04 dual boot hard drive issues I have recently bought a new laptop, and as I use Ubuntu on my desktop, but want to play games on my laptop, i installed both windows 7 and Ubuntu 12.04 on the laptop. It all went pretty well, I can boot both without any problems, but i noticed something strange. I divided the 1 TB hard drive into partitions the following way: 10 GBs for the Ubuntu itself, 8 GB for home, 8 GB for swap, and 25 GB for the windows partition. I partitioned the rest as one FAT32 partition-using Ubuntu's disk utility, which said it is around 930 GBs. However, when I boot into windows, it sees it alright, though it sees it as a 875 GBs partition. My concern is not about the space loss, I just don't know what causes the difference, and I don't know if it'll cause any problems in the future.

A: 930 * (10^9) / (2^30) ~= 866. It is possible that Ubuntu disk utility reports 930 GB (gigabytes = 10^9 bytes), while Windows reports GiB (gibibytes = 2^30 bytes).
However, this doesn't explain why Windows reports 875 rather than 866.


text:
Q: Get Context in a Service Is there any reliable way to get a Context from a Service?
I want to register a broadcast receiver for ACTION_PHONE_STATE_CHANGED but I don't need my app to always get this information, so I don't put it in the Manifest.
However, I can't have the broadcast receiver be killed by the GC when I need this information so I'm registering the broadcast receiver in a Service.
Hence, I need a Context to to call registerReceiver().
 When I no longer need the ACTION_PHONE_STATE_CHANGED I unregister it.
Any tips?

A: Service is a Context

A: Since Service is a Context, the variable context must be this:
DataBaseManager dbm = Utils.getDataManager(this);

A: Service extends ContextWrapper which extends Context. Hence the Service is a Context.
Use 'this' keyword in the service.

A: As Service is already a Context itself
you can even get it through:
Context mContext = this;

OR
Context mContext = [class name].this;  //[] only specify the class name
// mContext = JobServiceSchedule.this;

A: *

*Service extends ContextWrapper

*ContextWrapper extends Context
So....
Context context = this;

(in Service or Activity Class)

A: just in case someone is getting NullPointerException, you need to get the context inside onCreate().
Service is a Context, so do this:
private Context context;

@Override
public void onCreate() {
    super.onCreate();
    context = this;
}

Note:
Read: "Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)" Do you know what context classes are? Activity is one of them, and you should not store Activity as a static field, (or it will leak memory). However, you can store Context (as long as it is the application context) as a static field, since it outlives everything.

A: If you want service context then use this keyword. if you want activity context you can access that by using by making static variable like this
public static Context context;

in the activity onCreate()
context=this;

now you can access that context inside the service