Q: Show all capes/products when i filter them through price range // React imports
import { useCallback, useEffect, useState } from 'react'

import { GetServerSideProps } from 'next'
import Link from 'next/link'
import { ParsedUrlQuery } from 'querystring'
import { capesApi } from 'api'
import {
    CapeCategoryEnum,
    CapeTypeEnum,
    GetCapesResponse
} from 'mantle-api-client'

// Component imports
import { ShopLayout } from '@components/Shop/ShopLayout'
import { Container, Text } from '@components/utils'
import { Pagination } from '@components/Pagination'
import { useRouter } from 'next/router'
import { RenderedMineman } from '@components/RenderedMineman'
import { capeTypes, capeCategories } from 'config'
import Checkbox from '@components/Checkbox/Checkbox'
import { toDollars } from '@helper/price'

// Types
interface Props {
    query: ParsedUrlQuery
    capeData: GetCapesResponse
}

/**
 * The MVP shop page. This is a public page.
 */
const Shop = ({
    capeData: initialCapeData,
    query: { page: initialPage }
}: Props) => {
    /**
     * State
     */
    const [page, setPage] = useState(initialPage ? Number(initialPage) : 1)
    const [capeData, setCapeData] = useState(initialCapeData)
    const [fetching, setFetching] = useState(false)
    const [filterCategories, setFilterCategories] = useState<CapeCategoryEnum[]>([])
    const [filterTypes, setFilterTypes] = useState<CapeTypeEnum[]>([])

    /**
     * Helpers
     */

    // Access the router.
    const router = useRouter()

    // This helper will add or remove selected categories to the categories state.
    const addOrRemoveCategoryToFilter = (categoryValue: CapeCategoryEnum) => {
        if (filterCategories.includes(categoryValue)) {
            setFilterCategories(
                filterCategories.filter((value) => value !== categoryValue)
            )
        } else {
            setFilterCategories(filterCategories.concat(categoryValue))
        }
    }

    // This helper will add or remove selected types to the types state.
    const addOrRemoveTypesToFilter = (typeValue: CapeTypeEnum) => {
        if (filterTypes.includes(typeValue)) {
            setFilterTypes(filterTypes.filter((value) => value !== typeValue))
        } else {
            setFilterTypes(filterTypes.concat(typeValue))
        }
    }

    const { capes, totalPages, count } = capeData

    // This client-side helper will fetch additional capes depending on filters passed to it.
    const fetchCapes = useCallback(
        async (page: number) => {
            setPage(page)
            setFetching(true)

            const capesDataR = (
                await capesApi.getCapes({
                    page,
                    sortBy: 'createdAt DESC',
                    categories: filterCategories,
                    types: filterTypes
                })
            ).data

            setCapeData(capesDataR)
            setTimeout(() => setFetching(false), 100)
        },
        [filterCategories, filterTypes]
    )

    // This helper will perform a client-side re-render of the page.
    const handlePageChange = (page: number) => {
        router.push(`/shop?page=${page}`, undefined, { shallow: true })
    }

    // Whenever the route changes or if we are fetching more capes, make sure to fetch more capes.
    useEffect(() => {
        fetchCapes(router.query.page ? Number(router.query.page) : 1)
    }, [router.query, fetchCapes])

    const[checkVal1, setCheckVal1]= useState(false);
    const[checkVal2, setCheckVal2]= useState(false);
    const[checkVal3, setCheckVal3]= useState(false);
    const[checkVal4, setCheckVal4]= useState(false);
    const[checkVal5, setCheckVal5]= useState(false);

this handleCheckData ftn returns the filtered data of only 1 page. meaning if I click the checkbox of price range >2$ it will show the prices >2$ on page 1 only and not rest of the products and i have to go to page 2 to see the rest of the filtered products
    const handleCheckData=(cape:any)=>{

        if(checkVal1===true){
            return cape.price>=1
        }
        else if(checkVal2===true){
            return cape.price>=200 && cape.price<=300
        }
        else if(checkVal3===true){
            return cape.price>=300 && cape.price<=400
        }
        else if(checkVal4===true){
            return cape.price>=400 && cape.price<=500
        }
        else if(checkVal5===true){
            return cape.price<=500
        }
        else{
            return cape.price>=0
        }

    }

    return (
        <>
            <Container>
                <ShopLayout>

                            {/* sidebar*/}

                                                <Text as='h4' tag='h2'>
                                                    Filter Capes
                                                </Text>

                                            <Text as='h4' tag='h2'>
                                                Price
                                            </Text>

                                        {/* 2nd: make the price checkbox a separate component */}

                                            {/* 1st checkbox */}

                                                 {'>'} $1.99
                                                <input type='checkbox' onClick={()=>setCheckVal1(!checkVal1)} />

                                            {/* 2nd checkbox */}

                                                $2.00 - $2.99
                                                <input type='checkbox' onClick={()=>setCheckVal2(!checkVal2)}/>

                                            {/* 3rd checkbox */}

                                                $3.00 - $3.99
                                                <input type='checkbox' onClick={()=>setCheckVal3(!checkVal3)}/>

                                            {/* 4th checkbox */}

                                                $4.00 - $4.99
                                                <input type='checkbox' onClick={()=>setCheckVal4(!checkVal4)}/>

                                            {/* 5th checkbox */}

                                                 {'<'} $5.00
                                                <input type='checkbox' onClick={()=>setCheckVal5(!checkVal5)}/>

                    {/*filtering by categories */}

                                            <Text as='h4' tag='h2'>
                                                Categories
                                            </Text>

                                            {capeCategories.map(
                                                ({ name, value }) => (

                                                        <Checkbox
                                                            labelClassName='text-sm text-gray-400 mr-4'
                                                            label={name}
                                                            handleClick={() =>
                                                                addOrRemoveCategoryToFilter(value)
                                                            }
                                                            className={`bg-gray-800 text-gray-400 rounded border border-stone-200 space-x-3 ${
                                                                filterCategories.includes(value)
                                                            }`}
                                                        />

                                                )
                                            )}

                  {/*filtering by types*/}

                                            <Text as='h4' tag='h2'>
                                                Types
                                            </Text>

                                            {capeTypes.map(({ name, value }) => (

                                                    <Checkbox
                                                        labelClassName='text-sm text-gray-400 mr-4'
                                                        label={name}
                                                        handleClick={() =>addOrRemoveTypesToFilter(value)
                                                        }
                                                        className={`bg-gray-800 text-gray-400 rounded border border-stone-200 space-x-3 ${
                                                            filterTypes.includes(value)
                                                        }`}
                                                    />

                                            ))}

the capes we will show plus the price filter ftn

                            {capes.filter((cape) => handleCheckData(cape)).map((cape) => (

                                                    <RenderedMineman
                                                        capes={[cape]}
                                                        rotation={
                                                            cape.type ===
                                                            CapeTypeEnum.Cape
                                                                ? 'back'
                                                                : 'front'
                                                        }
                                                    />

                                                    <Text
                                                        as='h3'
                                                        tag='h3'
                                                        className='text-current'
                                                    >
                                                        {cape.name}
                                                    </Text>

                                                    <Text as='h4' tag='p'>
                                                        ${toDollars(cape.price)}
                                                    </Text>

                                        </Link>

                                ))}{' '}

                {/* This pagination allows users to filter through pages of products. */}
                <Pagination
                    handlePageChange={handlePageChange}
                    pages={totalPages}
                    currentPage={page}
                    count={count}
                    perPage={16}
                    fetching={fetching}
                    displayNumberOfItems={false}
                />
            </ShopLayout>
        </Container>
    </>
)}

export const getServerSideProps: GetServerSideProps = async ({ query }) => {
    const capeData = (
        await capesApi.getCapes({
            page: query.page ? Number(query.page) : 1,
            sortBy: 'createdAt DESC'
        })
    ).data

    return {
        props: {
            query,
            capeData
        }
    }
}

export default Shop


Q: String returned by pyodbc different than a normal string? I used pyodbc to get some data from an mssql db. The returned text contains \n whenever a newline is necessary. I loaded all the text into the "row" variable.
var=row.somecolumnfromdatabase
var2=str('Some text\nand the newline.')

print(RichText(var))
print(RichText(var2))

However, if I use a function like RichText (from docxtpl) to transform the string, I receive different results. In the case of "var" (text loaded from db), the \n symbol is preserved. In the case of var2 (where I input the text by hand), the \n is transformed correctly. Simply printing var and var2 without transformations shows no difference and I would expect the contained strings to be identical - e.g. the RichText function should receive the exact same input.
What am I missing?


Q: Unable to I to display the list value in dropdown which I am passing as list from my java class in my JSP.My code works perfectly if I am using table I am passing list from my java class in my JSP where I want to display the list value in dropdown.
While debugging I checked that the list is containing desired values but not displaying in my JSP dropdown.
Though the values are coming if I am displaying in Table form.
Please, tell me where I am going wrong and how can I make my code to work?
Java Code:
    // add the event list to the model
    theModel.addAttribute("event", theEvents);
    return "fundContributionCollectionListPage";

JSP Code:
    <select name="eventSelected">
    <c:forEach var="tempEvents" items="${event}">
      <option value="tempEvents.eventName">${tempEvents.eventName}</option>
    </c:forEach>
    </select>


Q: how send tinymce content using jquery method post I had a form.
like this
<form id=form ><input type='text' name='input1'  ><textarea name='text' ></textarea></form>

when I do this
var $dados = $("#form").serialize()

I get all the values, to send via jquery post like this
       $.ajax({
            url: "action.php",
            data:  $dados,
            type: 'POST',
            timeout: 6000,
            success: function (retorno) {

            }
        });

The beginning of the problem is, my textarea is a TinyMCE, and I get the val using this
 $("#form").find('textarea').each(function(){
        $dados = $dados + "&" + $(this).attr('name') + "=" +  tinyMCE.get( $(this).attr('id') ).getContent();

    });

My variable $dados is something likes this
field=value & filed2 = value ....

Now the problem..
when I put a text like this
"Olá mundão"
My value of the TinyeMCE is (whit the spaces to show ) Ol & #xE1; Mund &#xE3 ;o
The value is a value with HTML entity
So, I have this particular caracter "&" in the tinyMCE value.
and my variable $dados become like this
input1=value & input2 = val & ue

This particular caracter makes mess with my tinyMCE value,
So someone can help me?

A: Why don't you use something like this to generate your $dados object?
There is no need to build your data as a html ajax GET Parameter string.
var $dados = {};
$("#form").find('textarea').each(function(){
    $dados[$(this).attr('name')] = tinyMCE.get($(this).attr('id')).getContent();
});


Q: MySQL: Select between September and September I am showing the sales in my Database using this select
SELECT YEAR( ordered_date ) AS Jahr, SUM( preis ) AS Preis, count(*) as Anzahl FROM wccrm_orders where typ = 'Brautkleid' GROUP BY YEAR(ordered_date) ORDER BY ordered_date ASC

This is working fine, currently the output is year (1-12), the number and the price. Now I need to achieve the following:
The Price, Count(*) and Year should not be shown from Jan to Dec, but from Sep to Sep. Is this possible? How can I achieve this?
Kind Regards,
Stefan

A: Subtract 9 months or add 3 months (I'm not sure what you want to call "Jahr"):
SELECT YEAR( ordered_date + interval 3 month) AS Jahr,
       SUM( preis ) AS Preis, count(*) as Anzahl
FROM wccrm_orders
WHERE typ = 'Brautkleid'
GROUP BY Jahr
ORDER BY Jahr ASC;


Q: Set a Default Path in express.js app.set('views', path.join(__dirname,'views'))
What is the meaning of the line above? And what is the purpose of it?

A: That line of code indicates the main path of your views, for example if you have this hierarchy:

views/index.html
views/home/index.html
views/home/news/index.html

would render your views like this:

res.render('/index.html',  /*...*/);
res.render('home/index.html',  /*...*/);
res.render('home/news/index.html', /*...*/);


Q: How to make appropriate statements concerning simultaneity or sequence of pitches? This answer The example of relativity of simultaneity given by Einstein to a recent question related to Einstein's thought-experimental definition of (how to determine) simultaneity contained the following statement:

Suppose two people, $C$ and $D$, stand equal distances from you and are known to pitch balls at exactly the same speed. With everyone standing at rest, $C$ and $D$ each toss you a ball. You get the ball from $C$ before the one from $D$. This is not a logical inconsistency. It simply means $C$ threw a ball before $D$ in your reference frame [emphasis added].

I believe that I understand the described setup and the conclusion ("It simply means $C$ threw a ball before $D$") as such. But I question whether it is necessary to add the qualification "in your reference frame".
Carefully applying Einstein's definition of (how to determine) simultaneity, as referenced above, which for the given setup involves a suitable observer "at the midpoint between $C$ and $D$", is there even any reference frame at all (necessarily other than "your reference frame") "in which" $C$ threw a ball *simultaneous to* $D$ throwing a ball ?
Or is there even any reference frame at all (again necessarily other than "your reference frame") "in which" $C$ threw a ball *after* $D$ ?
(If there are no such reference frames, then the qualification "in your reference frame" is apparently not necessary; and, indeed, it would seem inappropriate and misleading to add such a qualification as if it were necessary.)

A: Try thinking in terms of events and spacetime.  Event C is the toss of the ball from pitcher C and Event D is the toss of the ball from pitcher D.  In your frame of reference, C occurs before D.
Now, if events C and D have a spacelike interval (meaning they are farther apart in space than in time), then there is a frame of reference in which they are simultaneous and there are frames of reference in which D occurs before C.
But, if events C and D have a timelike interval (meaning they are farther apart in time than in space), or a light-like interval (meaning they are as far apart in time as in space), then there is no frame of reference in which C does not occur before D.
Here is an interactive spacetime diagram that you can "play" with to help make these results visually clear.


Q: jQuery stop custom function from working if width is a certain size How do I make the imagePopUp function stop executing if the screen goes smaller than 768px when resizing? Here is my code:
// Image pop up
function imagePopUp() {
  $('.pop-up-img').click(function () {
    var pizza_img = $(this).attr('src');
    var close_button = "";
    var pop_up_dark_bg = "

";
    var shown_img = "

";
    $('body').append(close_button);
    $('body').append(pop_up_dark_bg);
    $('body').append(shown_img);
  });
};

function closeImage() {
  $('.pop-up-bg-div').remove();
  $('.shown-img-div').remove();
  $('.close-img-btn').remove();
};

$(document).ready(function() {
  if ($(window).width() > 768) {
    imagePopUp();
  }
});

I tried:
$(window).resize(function() {
  if ($(window).width() > 768) {
    imagePopUp();
  }
});

but the function doesn't start unless the screen is resized. Also it just keeps adding on the imagePopUp function every time the screen is resized, so if you drag the screen to resize it, it starts running the function like 20 times.
What I want and imagine should look like is something like this:
$(document).ready(function() {
  if ($(window).width() > 768) {
    on loading the page, check the width and run the function once if its more than 768px width
  }
});

$(window).resize(function() {
  if ($(window).width() > 768) {
    run the function only once if it wasnt running already.
  } else {
    when the screen goes smaller than 768, stop the function from running completely
});

Right now I just "fixed" the problem by adding css display: none with @media to everything when the width is less than 768px. It still runs the code and adds the divs and images to the html after resizing but it just doesnt show them.
EDIT:
Thank you. I solved my problem. It's probably not the best way to do it but it works as intended. Here is the code if anyone else will need something similar in the future:
var running = false;

function imagePopUp() {
    running = true;
    $('.pop-up-img').click(function () {
      var pizza_img = $(this).attr('src');
      var close_button = "";
      var pop_up_dark_bg = "

";
      var shown_img = "

";
      $('body').append(close_button);
      $('body').append(pop_up_dark_bg);
      $('body').append(shown_img);
    });
};

function closeImage() {
  $('.pop-up-bg-div').remove();
  $('.shown-img-div').remove();
  $('.close-img-btn').remove();
};

$(document).ready(function() {
  if ($(window).width() > 768 && running == false) {
    imagePopUp();
  }
});

$(window).resize(function () {
  if ($(window).width() < 768) {
    $(".pop-up-img").unbind();
    running = false;
  }
  else if ($(window).width() > 768 && running == false) {
    imagePopUp();
  }
});

As suggested I added the variable "running = false".
To make the function stop from working I used "unbind".
So when the screen becomes < 768px width when resizing, the event doesn't work anymore and the variable "running" goes from "true" to "false" again.
That was needed so when the screen goes back to > 768px, the function would only be added once, because after it is added the "running" variable becomes "true", so it doesn't fit the "else if" statement requirements anymore.

A: You can make use of the .on() function in order to fire an event once the window is resized or loaded.
Example of non working code:
var running = false;

function imagePopup() {
  running = true;
  do the rest here
}

$(window).on("load resize",function(e){
    if ($(window).width() > 768 && running == false) {
       imagePopup();
    }
});

Read more here about on() - that's one way of doing it, if you're showing an image, you can always use a css selector to see if its showing or not rather than a flag (true, false).
At the end of the day; I believe; what you want is called a modal image; you can see an example of how to do it here.


Q: Static landing page on Angular I'm learning Angular and I'm having trouble to set a static landing page. What I would like is to have a static html landing page that has 2 buttons that call /login and /signup
and from there I would like to bootstrap angular app (calling app-root). I serve my app with nginx.
1- Where do I set my landing page? I tried adding a landing.html at root level with index.html, and changed at angular.json :
my landing.html on project root
"architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "outputPath": "dist/",
        "index": "src/index.html", <--- //changed for src/landing.html
        "main": "src/main.ts",

I read other questions where they used index.html as a static page, but I could not understand how to call later for my app-root (that bootstrap my SPA), anyway when I delete app-root from my index.html I have a blank page with this error:
Error: The selector "app-root" did not match any elements
    at DefaultDomRenderer2.selectRootElement (vendor.js:201546)
    at BaseAnimationRenderer.selectRootElement (vendor.js:141558)
    at locateHostElement (vendor.js:170017)
    at ComponentFactory$1.create (vendor.js:188576)
    at ApplicationRef.bootstrap (vendor.js:194164)
    at vendor.js:193812
    at Array.forEach (<anonymous>)
    at PlatformRef._moduleDoBootstrap (vendor.js:193811)
    at vendor.js:193770
    at ZoneDelegate.invoke (polyfills.js:572)

If someone can give me some light, I really would like to understand where the magic happens to use a static landing page and as a second step (login or signup) calls my SPA.
PS1.: I did not set any LandingModule or this.router.url == '/landing' or this.router.url == '/index'
PS2.: if someone knows also what to do at the nginx after...
Thanks!!!

A: Here is option to build everything in Angular without Nginx

*

*Create a App/Home component, which renders your landing page including Login & Register buttons.

*Build a normal app/routing for Login & Register.

*During compile time (ng build), pre-render the App component using AppShell technique.

Here is blog for your reference https://medium.com/technext/boost-your-angular-app-using-appshell-217651af6698


Q: Отключение Яндекс советника Есть задача отключить Яндекс советник, решил этот вопрос своим скриптом, ссылка https://github.com/ozzbabym/kick_sovetnik , если есть решения лучше, подскажите(работает OZON, Wildberries)
function kickSovetnik () {
    var elems = document.querySelectorAll('body > div[id]');
    var styles = document.querySelectorAll('style');

    Object.keys(elems).forEach(function(item) {
        if (/[a-z0-9]{11,13}$/.test(elems[item].id)) {
            elems[item].remove();
        }
    });

    Object.keys(styles).forEach(function(item) {
        if (styles[item].style && styles[item].innerHTML.includes('38px !important;')) {
            styles[item].remove();
        }
    });

    document.querySelector('html').style.marginTop = '0';
};

observer = new MutationObserver( kickSovetnik );
var  options = {
    'childList': true
};
var body = document.querySelector( 'body' );

observer.observe( body , options );

A: Изменения:

*

*Заменил Object.keys, на Object.values, потому что вы значение ключа используете только для того чтобы достать значение. И естественно переписал обращения к значениям

*Переписал ф-ии в forEach как стрелочные, просто так :)

*Объявил все переменные как const, просто так надёжнее

*Писать в селекторе body div[id] бесполезно и так все div-ы находятся только в body, потому убрал его

*Заменил document.querySelector('html') на более короткую запись document.documentElement. Обязательно прочтите заметку, не всегда можно так заменять

*Заменил document.querySelector('body') на более короткую запись document.body

*Заменил ykickSovetnik на kickSovetnik, т.к. в исходнике у вас так написано

Код:
function kickSovetnik() {
  const elems = document.querySelectorAll('div[id]');
  const styles = document.querySelectorAll('style');

  Object.values(elems).forEach((item) => {
    if (/[a-z0-9]{11,13}$/.test(item.id)) {
      item.remove();
    }
  });

  Object.values(styles).forEach((item) => {
    if (item.style && item.innerHTML.includes('38px !important;')) {
      item.remove();
    }
  });

  document.documentElement.style.marginTop = '0';
};

const observer = new MutationObserver(kickSovetnik);
const options = {
    'childList': true
};
const body = document.body;

observer.observe(body , options);


Q: 2 pagination for 2 tabs on a page From HTML to Wordpress, I made a page with 2 tab as below.
NEWS and EVENT tab
Each NEWS and EVENT will show the posts for its own category, then I inserted pagination.
I click on "Page 2" on NEWS tab, then click EVENT tab, it also takes EVENT to Page 2 (EVENT should be Page 1 by default)...I Hope each one has its own pagination.
I searched for Multiple Custom Loop in One Page with Pagination in many places but the advices quite different to my case.
Is there any way to fix it? Thank all in advanced!
page-news.php

<input class="radio" id="one" name="group" type="radio" checked\>
<input class="radio" id="two" name="group" type="radio"\>

        NEWS
        EVENT

          <?php
          $my_query1 = new WP_Query(

            array(
              'post_type' => 'post',
              'paged' => $paged,
              'posts_per_page' => 3,
              'category_name' => 'news',
            )
          );

          if ($my_query1->have_posts()):
            echo '
';
            while ($my_query1->have_posts()):
              $my_query1->the_post();
          ?>

            <a href="<?php the_permalink(); ?>">
              <?php the_title(); ?>

              <?php the_time('Y.m.d') ?>

              <?php the_post_thumbnail(); ?>

          <?php
            endwhile;
            echo '
';
            my_paginate($my_query1);
            wp_reset_postdata();
          endif;
          ?>

          <?php
          $my_query2 = new WP_Query(
            array(
              'post_type' => 'post',
              'paged' => $paged,
              'posts_per_page' => 3,
              'category_name' => 'event',
            )
          );

          if ($my_query2->have_posts()):
            echo '
';
            while ($my_query2->have_posts()):
              $my_query2->the_post();
          ?>

            <a href="<?php the_permalink(); ?>">
              <?php the_title(); ?>

              <?php the_time('Y.m.d') ?>

              <?php the_post_thumbnail(); ?>

          <?php
            endwhile;
            echo '
';
            my_paginate($my_query2);
            wp_reset_postdata();
          endif;
          ?>

Functions.php
function my_paginate($query_name = '')
{
  $settings = array(
    'side_range' => 3,
    // 現在ページの左右の表示数.
    'txt_prev' => '<',
    // 一つ戻るテキスト.
    'txt_next' => '>',
    // 一つ進むテキスト.
    'txt_first' => '|<',
    // 最初へ移動テキスト.
    'txt_last' => '>|', // 最後へ移動テキスト.

  );

  if ('' !== $query_name) {
    $query = $query_name;
  } else {
    global $paged, $wp_query;
    $query = $wp_query;
  }
  $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
  $showitems = ($settings['side_range'] * 2) + 1;
  $pages = $query->max_num_pages;

  if (1 !== $pages) {
    echo "
\n";
    echo "
\n";
    for ($i = 1; $i <= $pages; $i++) {
      if (1 !== $pages && (!($i >= $paged + $settings['side_range'] + 1 || $i <= $paged - $settings['side_range'] - 1) || $pages <= $showitems)) {
        echo ($paged === $i) ?
          '
' . esc_html($i) . "
\n" :
          '
' . esc_html($i) . "
\n";
      }
    }
    echo "
\n";
    echo '
Page ' . esc_html($paged) . '/' . esc_html($pages) . "
\n";
    if ($paged > 2 && $paged > $settings['side_range'] + 1 && $showitems < $pages) {
      echo '  ' . esc_html($settings['txt_first']) . "\n";
    }
    if ($paged > 1) {
      echo '  ' . esc_html($settings['txt_prev']) . "\n";
    }
    if ($paged < $pages) {
      echo '  ' . esc_html($settings['txt_next']) . "\n";
    }
    if ($paged < $pages - 1 && $paged + $settings['side_range'] - 1 < $pages && $showitems < $pages) {
      echo '  ' . esc_html($settings['txt_last']) . "\n";
    }
    echo "
\n";
  }
}


Q: BigQuery batch load execution time and frequency I'm considering switching from Streaming insert to Batch loading for my BigQuery insertion. However, I can't find some information I'd need.

*

*Time: Let's say I have a csv file with 1 million record. Roughly, how much time does a load take? Are we talking hours or minutes?

*Frequency: Can I have a load job every 10 minutes or so?

*Concurrency: Can two jobs happen at the same time, or do I need to wait for the previous one to finish?

A: For uncompressed CSV files with 1 million records expect around 10-15 seconds of processing time. But the question to put here is where the file is stored, and how long it will be taken to be uploaded, as that can be more than the above time section.
We have successfully imported in 2 minutes CSV files up to 5TB of data in it.
Your project can run up to 100,000 load jobs per day. Failed load jobs count toward this limit.
But be aware:
Your project can make up to 5,000 partition modifications per day to an ingestion-time partitioned table.
Your project can make up to 30,000 partition modifications per day for a column-partitioned table.
Your project can run up to 50 modifications per partitioned table every 10 seconds.
You can have multiple load jobs in parallel.
BigQuery is really petabyte scaling, so large jobs fit nice.
Although it has some Quotas, but they are quite decent, see them here.


Q: How to create a variable in a bash script that contains the data from a postgres database I'm looking to create a script than can find a specific date/time based on a field in a database
Currently i do it manually...
# psql gttvdb -U postgres
gttvdb=# select patch_date from version_history where version ='1.1.1';

What i need is to be able to reference that date as a variable in a bash script
#! /bin/sh
patchdate=$("select patch_date from version_history where version ='1.1.1';")
echo "last update was " $patchdate

A: Try this:
patchdate=` psql -t -q -c "select patch_date from version_history where version ='1.1.1'"`


Q: Prevent record duplication in Rails I don't really have any examples, but I have forms that create new records in my ActiveRecord database that do not really have any unique attributes other than their given ID. It has come to my attention that Users are submitting their form, but realized they mistyped something, so they have been pressing the browser's back button and resubmitting the same content, which causes duplication of that record.
I want to prevent this from happening, there is no need to post code, I would just like some suggestions.
Thanks!

A: In the record's Model, add a uniqueness validation as detailed in this Rails Guide. You can apply a scope on that validation, so that the uniqueness is determined using multiple record attributes.
Alternatively, if you really don't want to mark these records as unique, add an easy way for the user to update their submission to the post record creation page. i.e. they add a new record, the ability to edit that record immediately pops up in their view so that, rather than hitting back and creating a new record, they update the one they just made.


Q: Ordinary reduction of abelian varieties For an abelian variety $A$ over a number field $F$, it is believed that $A$ has good ordinary reduction at a set of places of Dirichlet density one after passing to a suitable finite extension. It is also conjectured that the minimum extension such that the $l$-adic monodromy groups are connected is sufficient.
The well-known examples include:

*

*$End(A) = \mathbb{Z}$ with the $l$-adic monodromy groups of type $A$ or $B$ (Pink's 1998 paper).

*Abelian varieties of small dimension.
What are the cases for which this is known?


Q: Purpose of MySQL data type Often when creating a new web app and configuring MySQL, certain fields will need to change in format as the app develops.  For instance, I may change the format of a date field or a field which once was just int now needs a letter or what not.  So usually I just make every field Varchar 255 until Im finished at which time Ill change data types to correct ones.
So my question is, how important are data types? Whats the purpose?  Speed?

A: Data types are extremely important - without them, there's no way to be sure what data is actually stored in the column.  For example, a VARCHAR(255) could be anything - string, numeric, date/time...  It makes things extremely difficult to find particular data if you can't guarantee what the data is or any form on consistency.
Which means data typing also provides basic validation - can't stick letters into a column with a numeric or date/time data type...
The speed of data retrieval is also improved by using indexes on a column, but an index can not be used if you have to change the data type of the data to something else before the data can be compared.
It's a good thing to realize what the difference is between data, and presentation.  Like the case with date field formatting - that's presentation, which can be easily taken care of if the data type is DATETIME (or converted to DATETIME).

A: Short answer: Speed, optimal data storage, Index, Search ability.
Your database can better make use of the internal works when everything has the correct datatype. You can also make better use of the special database function.
If you want to retrieve all data from a certain month. You can use special database functions to just group by a month when using a date time datatype for instance. When using a varchar to store a date, you lose all of that functionality.
Most databases are able to search or retrieve data faster from a table when the index has been created on a INT datatype. So if you had created that storage field as a varchar you would have lost performance

A: Performance is one reason but so far no ones talked about running these types of queries (which wouldn't be possible if all types are VARCHAR)
SELECT SUM(total) total FROM purchases WHERE status = 'PAID';
SELECT * FROM users WHERE DATE_ADD(last_login, INTERVAL 3 MONTH) < NOW();


Q: Logical consequence in all structures in Kripke semantics I read* the following definition of logical consequence in all structures within Kripke semantics:$$X\models A\iff\text{ for every } (W,R),\text{ if }(W,R)\models X,\text{ then }(W,R)\models A$$ $$\iff\text{ for every } (W,R),\quad(W,R),X\models A$$where $X$ and $A$ are sets of formulae and $(W,R)$ is a structure with a set of worlds $W$ and an accessibility relation $R$.
I do not understand why the definition of the first line is the same as the second one.
I know that $(W,R)\models X$ means that for any interpretation $I$, $(W,R,I)\models X$, i.e., for any interpretation $I$ and for any world $u\in W$, $(W,R,I),u\models X$. I also know that $(W,R),X\models A$ means that, for any interpretation $I$, $(W,R,I),X\models A$, i.e., for any interpretation $I$ and for an world $u\in W$, $(W,R,I),u\models X\Rightarrow(W,R,I),u\models A$.
Using quantifiers I would say that the first line means that, for every $(W,R)$,$$\forall I\forall u\in W\quad(W,R,I),u\models X\quad\Rightarrow\quad\forall I\forall u\in W\quad(W,R,I),u\models A $$which I am not sure to be licitly identified with the second line, which I would understand to mean that, for every $(W,R)$,$$\forall I\forall u\in W\quad[(W,R,I)\models X\Rightarrow (W,R,I)\models A].$$I suspect I am misunderstanding something, but I am not sure what. Could anybody explain what the two definitions of $X\models A$ mean and why they are the same? Thank you very much for any answer!
*D. Palladino, C. Palladino, Logiche non classiche, 'non-classical logics', 2007.

EDIT: No proof of the written equivalence has been received as of Mar 1'15. Nevertheless the two "long comments" seems to point to some typographical problem in the statement of the equivalence, and therefore, in the absence of a further proof, or in the presence of the argument that the equivalence would not hold in general without additional hypothesis, I have decided to chose the longer "long comment" as an answer, heartily thanking both Carl and Mauro for their invaluable help.
Anyhow, since $(W,R),X\models A$ means that $A$ is a logical consequence of $X$ in structure $(W,R)$, it is an obviously acceptable definition that $A$ is a logical consequence of $X$ in all structures if and only if, for every $(W,R)$, $(W,R),X\models A$.

A: This is too long for a comment, although it does not completely solve the problem.
It is more typical to view a Kripke frame $F$ as coming with a variable interpretation. So let us say that a K-frame is a triple $(W,R,I)$ such that
$W$ is a set of worlds, $R$ is an accessibility relation, and $I$ gives a valuation of propositional variables on each world of $W$.   We say that $F \vDash \phi$ if the formula $\phi$ holds at every world of $W$, using the normal definition of truth-in-a-world in Kripke frames.
Attempting to follow the definitions in the question, let us say that $F,\phi \vDash \psi$ if every world of $F$ that satisfies $\phi$ also satisfies $\psi$. (If we are talking about intuitionistic Kripke frames, this is not the same as $F \vDash \phi \to \psi$.)
With that definition of a K-frame, consider these statements quantifying over K-frames $F$ and formulas $\phi,\psi$:

*

*If $F \vDash \phi$ then $F \vDash \psi$

*$F,\phi \vDash \psi$.
Then we have that (2) implies (1), by a relatively simple argument.
But (1) does not imply (2), because (1) is true in any K-frame $F$ with $F \not \vDash \phi$, and we can make a K-frame with $F \not \vDash \phi$ such that $F,\phi \not \vDash \psi$. For example, we can make $\phi$ false in one world, and in another world make $\phi$ true and $\psi$ false.
So I am struggling to make sense of the particular definitions in the book that was mentioned in the question. I do not see how to easily arrive at the claim mentioned. Unfortunately, I don't have the book, and probably could not read it if I did. But something unusual is indeed going on.

A: This is only a long comment ...
I'm not familiar with this kind of issue, and I'm a little bit perplexed (like you).
Forget for a moment about Kripke's model.
In classical logic, we have two "similar" relations :

we say that a formula $\psi$ is logical consequence of a formula $\varphi$, in symbols : $\varphi \vDash \psi$ when :

for all models $\mathcal M$, if $\mathcal M \vDash \varphi$, then $\mathcal M \vDash \psi$ --- (1).

This relation is different from :

if $\vDash \varphi$, then $\vDash \psi$,

which is :

if $\mathcal M \vDash \varphi$, for all $\mathcal M$, then $\mathcal M \vDash \psi$, for all $\mathcal M$ --- (2).

The two are linked by the relation :

(1) implies (2);

we can prove it easily by the property of the universal quantifier with respect to $\to$ :

$∀x(α → β) → (∀xα → ∀xβ)$.

The converse does not hold in general.

In modal logic we have two definitions [see Dale Jacquette (editor), A Companion to Philosophical Logic (2008), page 425] :

What does logical consequence mean for modal languages? Just like we have local and
  global notions of truth and validity, we have two consequence relations for modal formulas. A piece of terminology: if $\mathcal S$ is a class of models, then a model from $\mathcal S$ is simply a model $\mathcal M$ in $\mathcal S$; if $\mathcal S$ is a class of frames, then a model from $\mathcal S$ is a model based on a frame in $\mathcal S$.
DEFINITION 3 Let $\mathcal S$ be a class of models or a class of frames. Let $\Sigma$ and $A$ be a set of modal formula and a single formula. We say that $A$ is a (local) semantic consequence of $\Sigma$ over $\mathcal S$ (notation: $\mathcal S \vDash_{\mathcal S} A$) if for all models $\mathcal M$ from $\mathcal S$, and all states $w \in \mathcal M$, if $\mathcal M,w \vDash \Sigma$, then $\mathcal M,w \vDash A$.
As an example, suppose that we are working with $\mathsf{Tran}$, the class of frames $(W,R)$ in which $R$ is a transitive relation. Then $\{ \diamond \diamond p \} \vDash_\mathsf{Tran} \diamond p$, but $\diamond p$ is not a local consequence
  of $\{ \diamond \diamond p \}$ over the class of all frames.
DEFINITION 4 Let $A, \Sigma$ and $\mathcal S$ be as in Definition 3. Then $A$ is a global semantic consequence of $\Sigma$ over $\mathcal S$ (notation: $\Sigma \vDash^g_{\mathcal S} A$) if for all structures (i.e. models or frames) $S \in \mathcal S$, if $S \vDash \Sigma$, then $S \vDash A$.
The local and global notions are different, yet there is a systematic connection between
  them. One can show that, for $\Sigma$ a set of formulas and $F$ a class of frames, $\Sigma \vDash^g_F A$ is equivalent to $\{ \square^{n} B \mid B \in \Sigma, n \in \omega \} \vDash_F A$.


Q: MySQL UPDATE with INNER JOIN has warnings but will not show them I'm getting warnings when updating a table but the warnings are not showing. Through tedious and lengthy trial-and-error, the cause of the warnings has been tracked down to the INNER JOIN. I need a better way to debug a warning.
Setup is OK. I know warnings are on because MySQL command prompt was started with option '--show-warnings' and warnings are turned on warnings with '\W':
mysql> \W
Show warnings enabled.

mysql> show variables like '%warn%';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_warnings  | 0     |
| sql_warnings  | ON    |
| warning_count | 0     |
+---------------+-------+
3 rows in set (0.01 sec)

To make sure warnings were on, I forced a truncating warning on a VARCHAR(255) field:
mysql> UPDATE course
    -> SET course.transcript_title = 'Field transcript_title is VARCHAR(255). This is over 255 characters to force truncating warning. Field transcript_title is VARCHAR(255). This is over 255 characters to force truncating warning. Field transcript_title is VARCHAR(255). This is over 255 characters to force truncating warning.'
    -> WHERE course.title LIKE '%SLP%'
    -> AND course.year = 2008
    -> AND course.gid = 35;
Query OK, 104 rows affected, 104 warnings (0.19 sec)
Rows matched: 104  Changed: 104  Warnings: 104

Warning (Code 1265): Data truncated for column 'transcript_title' at row 1
Warning (Code 1265): Data truncated for column 'transcript_title' at row 2
.... etc.

I want to get the warning from this type of query:
mysql> UPDATE course
    -> INNER JOIN group_info ON course.gid = group_info.id
    -> SET course.description = 'Foo.'
    -> WHERE course.title LIKE '%SLP%'
    -> AND course.year = 2008 AND group_info.id = 35;
Query OK, 0 rows affected (0.02 sec)
Rows matched: 104  Changed: 0  Warnings: 104

mysql> SHOW WARNINGS;
Empty set (0.00 sec)

From trial and error, I know the error is from having the INNER JOIN clause. If I remove the INNER JOIN and directly use the gid (group id) field in the course table, then no warnings:
mysql> UPDATE course
    -> SET course.description = 'Bar.'
    -> WHERE course.title LIKE '%SLP%'
    -> AND course.year = 2008
    -> AND course.gid = 35;
Query OK, 104 rows affected (0.01 sec)
Rows matched: 104  Changed: 104  Warnings: 0

But I need the INNER JOIN clause because what I really want to do is use the more friendly 'name' field in the joined 'group_info' table:
UPDATE course
INNER JOIN group_info ON course.gid = group_info.id
SET course.description = 'Foo.'
WHERE course.title LIKE '%SLP%'
AND course.year = 2008
AND group_info.name = 'One-to-One Meeting Time';

I've been googling, reading, and debugging the warning for over 1 hour. I've searched for answers or explanations for why this would not show warnings but no luck.
How do I get warnings to show for the INNER JOIN type of UPDATE?


Q: Fiware IoT Broker and IoT Configuration Manager XML Validation I figured out I had to have another GE, the IoT Configuration Manager working parallel to the IoT Broker in order to manage the entities from which we will get data. Now, it seems that the XMLValidator code is giving me some trouble. I registered an entity via HTTP POST osgi9 directly with the configuration manager. Then I try to access it by communicating via osgi10 with the IoT broker. The IoT Broker communicates with the IoT DIscovery service and gets a response, but then the XMLValidator says the XML is wrong even tough it clearly is not.
This is the IoT Broker asking for the availability of a resource to the IoT ConfMan:
2014-11-27 10:31:13,682 | INFO | (HttpConnectionClient.java:initializeConnection:170) | Output

Stream: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<discoverContextAvailabilityRequest>
<entityIdList>
<entityId isPattern="false">
<id>Dorm</id>
</entityId>
</entityIdList>
<attributeList/>
<restriction>
<scope>
<operationScope>
<scopeType>IncludeAssociations</scopeType>
<scopeValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">SOURCES</scopeValue></operationScope>
</scope>
</restriction>
</discoverContextAvailabilityRequest>

Then IoT Broker gets:
2014-11-27 10:31:13,947 | INFO | (HttpConnectionClient.java:initializeConnection:188) |
<?xml version="1.0" encoding="UTF-8"?><discoverContextAvailabilityResponse>
<contextRegistrationResponseList>
<contextRegistrationResponse>
<contextRegistration>
<entityIdList>
<entityId type="Room" isPattern="false">
<id>Dorm</id>
</entityId>
</entityIdList>
<contextRegistrationAttributeList>
<contextRegistrationAttribute>
<name>temperature</name>
<type>degree</type>
<isDomain>false</isDomain>
<metadata>
<contextMetadata>
<name>ID</name>
<type>string</type>
<value/>
</contextMetadata>
<contextMetadata>
<name/>
<type/>
<value/>
</contextMetadata>
</metadata>
</contextRegistrationAttribute>
</contextRegistrationAttributeList>
<providingApplication>http://192.168.100.1:70
</providingApplication>
</contextRegistration>
</contextRegistrationResponse>
</contextRegistrationResponseList>
<errorCode>
200
<reasonPhrase>OK</reasonPhrase>
Result
</errorCode>
</discoverContextAvailabilityResponse>

2014-11-27 10:31:13,949 | INFO | (HttpConnectionClient.java:initializeConnection:218) | Connection Closed!
2014-11-27 10:31:13,987 | INFO | (XmlValidator.java:error:128) |
ERROR
org.xml.sax.SAXParseException; lineNumber: 0; columnNumber: 0; cvc-complex-type.2.4.b: The content of element 'contextRegistration' is not complete. One of '
{registrationMetaData, providingApplication}
' is expected.

It is clearly seen by the received xml that at least the providingApplication is received but XMLValidator is not seeing this.

A: In the meantime new releases with a lot of bug fixes have been issued, so your problem should be no longer existent.
In addition we added a configuration manager 'light' into the IoT broker, which enables you to use it standalone.
P.S. I became aware of this help request only recently. I am very sorry that we therefore could not provide you an answer in due time.


Q: How to use a variable as the input for a form field in Google Colaboratory? The official example shows how to use Form Fields in Google Colaboratory: https://colab.research.google.com/notebooks/forms.ipynb.
Let's say we have a list:
fruit_list = ['apples', 'bananas', 'mangoes']
Now I would like to add the elements of this list as a dropdown in the Form:
#@title # Select Your Choice of Fruit
fruit_selected = 'apples' #@params fruit_list {input: string}

As of now I can think of some hacks like this one:
#@title Boolean fields { run: "auto", vertical-output: true }
this_list = ["False", "True"]
boolean_checkbox = False #@param {type:"boolean"}
boolean_dropdown_asis = False #@param ["False", "True"] {type:"raw"}
boolean_dropdown_var = this_list[1] #@param {type:"raw"}

print(boolean_checkbox)
print(boolean_dropdown_asis)
print(boolean_dropdown_var)

But I would prefer to have another type of input: variable instead of just raw/string. The final implementation could be like this:
#@title # Select Your Choice of Fruit
fruit_list = ['apples', 'bananas', 'mangoes']
fruit_selected = 'apples' #@params fruit_list {input: variable}

I worked on some OVERKILL. You are free to look at it. Comments are welcome! :)

Anyone, any better idea?
Notes: There is another stackoverflow discussion where Sergio Lucero raised a similar question. But the main thread has a different question.

A: If you use the widget like in the notebook of blois, you can use the following code to call the value:
fruit_picker.value

This will return the value of your chosen fruit.
The code in total will look like this:
import ipywidgets as widgets
fruit_list = ['pomegranate', 'watermelon', 'lychee']
fruit_picker = widgets.Dropdown(options=fruit_list, value='watermelon')

fruit_picker

fruit_picker.value

A: Your original code almost has the solution.
If you look carefully you will find it in the documentation.
Instead of
fruit_list = ['apples', 'bananas', 'mangoes']
fruit_selected = 'apples' #@params fruit_list {input: string}

Use
fruit_selected = 'new' #@param ['apples', 'bananas', 'mangoes'] {allow-input: true}

And you will be able to choose from the list OR enter new elements.

If you want to input the name of an existing variable, you could do this
fruits=['apples', 'bananas', 'mangoes']
other={"a": 1, "b": 2}

fruit_selected = 'b' #@param ['apples', 'bananas', 'mangoes'] {allow-input: true}

#---- Find it in a dictionary

if fruit_selected not in fruits:
  if fruit_selected in other:
    print(f'{other[fruit_selected]}')
  else:
    print("Fruit selected NOT in other")

#---- Find it by name

a="x2"

if fruit_selected in globals():
  print(f'Got {fruit_selected}')

But for this kind of interactions maybe ipywidgets is a better tool.


Q: how to submit the form in jquery to server side by escaping or bypassing the Validations that were set how to submit the form in jquery to server side by escaping or bypassing the Validations that were set

A: You can just call the DOM (not jQuery) form.submit() method, like this:
$("form")[0].submit();

Or if it's by ID:
document.getElementById('myForm').submit();
//or
$("#myForm").get(0).submit();

This bypasses the jQuery event handlers and prevents them from running, instead it directly submits the <form>.


Q: "cd" in linux shell script returns "command not found!" I have written a shell script called "a.sh" in linux with one line:
cd ..
: and then I run this with:
chmod +x a.sh
sh ./a.sh

: how do I run this without getting :
"Command not found" or "Can't cd". Maybe I have been looking at this code too long or am I doing something obviously wrong??
Note: I have since found out what was wrong. Emacs was inserting some strange "^m" character at the end of every line

A: cd is a builtin to your shell. Anything like /usr/bin/cd or /bin/cd just there for weird magical reasons.
First run this.
which sh

This will output the path to your sh executable
Try adding a shebang to your script. So the entire file looks like this
#!/bin/sh
cd ..

If that doesn't work then clarify the steps you've taken as Stefan has asked. As well as paste the exact error message.

A: what if you put /bin/cd in it's place.


Q: Singleton events I am refactoring some old code, where I have a lot of static events like this
public static event Action Updated;
public static void OnUpdated()
{
    if (Updated != null)
        Updated();
}

I found out what using lazy singletons is often better than using static classes:

*

*no memory is consumed until first Instance call;

*private serialization/deserialization.

So that I refactor those to singletons and now I have Code Analysis complains.
Such events clearly offend CS1009 but I have some doubts:

*

*for static events sender doesn't makes sense, why and in what scenario would singleton sender be of any use? I can only think about deserialization, but it's an internal class implementation (moreover class is sealed), so I can take care to not use events and if I need one, I can create private event.

*creating e (deriving from EventArgs) is unnecessary complication to simply pass parameters, the biggest part I hate is to move it into namespace level, the only thing which EventArgs adds (could be useful sometimes) is Empty and then you have dozens of classes ...EventArgs. I could think what sometimes you need Cancel or Handled mechanics, but it was neverd needed for me.
When using event does everybody expect (object sender, SomeEventArgs args) and this is the only reason?
To summarize, here is my main question (but I would appreciate clarifying other questions as well): CS1009 and singletons, should I fix events or simply suppress the message?
P.S.: related subjects: this, this and this.

I found this question. According to event design guidelines I have to use Event<T> (disregards to this question), where T is based on EventArgs class.
Regarding sender in static events:

On static events, the sender parameter should be null.

This is a  design guideline, which may not looks pretty to me, but will be very welcomed by anybody else (who is reading/maintaining my code).
It breaks both KISS and YAGNI principles as for me. And the more I think about it, the less and less I am sure of what to do.

A: I would fix your error. The general design guideline is indeed the (object sender, EventArgs e) signature.
It's a convention and is all about code consistency, code readability...etc. Following this pattern will help other people attaching handlers to your events.
Some general tips/answers:

*

*For a static event, you should indeed use null as sender (because there is no sender instance per definition).

*If you have nothing to pass for the e parameter, use EventArgs.Empty instead of new EventArgs() or null.

*You could use EventHandler and EventHandler<T> to simplify the definition of your events.

*For the sake of simplicity, you could use a custom EventArgs<T> class inheriting from EventArgs if you want to pass a single value to your event handler.

If you want to use the singleton pattern with a Lazy<T> definition, here's a complete example. Do note no event is static, so the sender parameter contains a reference to the singleton instance:
public class EventArgs<T> : EventArgs
{
    public EventArgs(T value)
    {
        this.Value = value;
    }

    public T Value { get; set; }
}

public class EventArgs2 : EventArgs
{
    public int Value { get; set; }
}

internal static class Program
{
    private static void Main(string[] args)
    {
        Singleton.Instance.MyEvent += (sender, e) => Console.WriteLine("MyEvent with empty parameter");
        Singleton.Instance.MyEvent2 += (sender, e) => Console.WriteLine("MyEvent2 with parameter {0}", e.Value);
        Singleton.Instance.MyEvent3 += (sender, e) => Console.WriteLine("MyEvent3 with parameter {0}", e.Value);

        Singleton.Instance.Call();

        Console.Read();
    }
}

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    /// <summary>
    /// Prevents a default instance of the <see cref="Singleton"/> class from being created.
    /// </summary>
    private Singleton()
    {
    }

    /// <summary>
    /// Event without any associated data
    /// </summary>
    public event EventHandler MyEvent;

    /// <summary>
    /// Event with a specific class as associated data
    /// </summary>
    public event EventHandler<EventArgs2> MyEvent2;

    /// <summary>
    /// Event with a generic class as associated data
    /// </summary>
    public event EventHandler<EventArgs<int>> MyEvent3;

    public void Call()
    {
        if (this.MyEvent != null)
        {
            this.MyEvent(this, EventArgs.Empty);
        }

        if (this.MyEvent2 != null)
        {
            this.MyEvent2(this, new EventArgs2 { Value = 12 });
        }

        if (this.MyEvent3 != null)
        {
            this.MyEvent3(this, new EventArgs<int>(12));
        }

        Console.Read();
    }
}

EDIT:
You could also build some EventArgs<T1, T2> if you need to pass two values. Ultimately, EventArgs<Tuple<>> would also be possible, but for more than 2 values I would build a specific XXXEventArgs class instead as it's easier to read XXXEventArgs.MyNamedBusinessProperty than EventArgs<T1, T2, T3>.Value2 or EventArgs<Tuple<int, string, bool>>.Value.Item1.
Regarding KISS/YAGNI: remember the (object sender, EventArgs e) convention is all about code consistency. If some developer uses your code to attach an handler to one of your events, I can assure you he will just love the fact that your event definition is just like any other event definition in the BCL itself, so he instantly knows how to properly use your code.
There even are others advantages than just code consistency/readability:
I inherited my custom XXXEventArgs classes from EventArgs, but you could build some base EventArgs class and inherit from it. For instance, see MouseEventArgs and all classes inheriting from it. Much better to reuse existing classes than to provide multiple delegate signatures with 5/6 identical properties. For instance:
public class MouseEventArgs : EventArgs
{
    public int X { get; set; }
    public int Y { get; set; }
}

public class MouseClickEventArgs : MouseEventArgs
{
    public int ButtonType { get; set; }
}

public class MouseDoubleClickEventArgs : MouseClickEventArgs
{
    public int TimeBetweenClicks { get; set; }
}

public class Test
{
    public event EventHandler<MouseClickEventArgs> ClickEvent;
    public event EventHandler<MouseDoubleClickEventArgs> DoubleClickEvent;
}

public class Test2
{
    public delegate void ClickEventHandler(int X, int Y, int ButtonType);
    public event ClickEventHandler ClickEvent;

    // See duplicated properties below =>
    public delegate void DoubleClickEventHandler(int X, int Y, int ButtonType, int TimeBetweenClicks);
    public event DoubleClickEventHandler DoubleClickEvent;
}

Another point is, using EventArgs could simplify code maintainability. Imagine the following scenario:
public MyEventArgs : EventArgs
{
    public string MyProperty { get; set; }
}
public event EventHandler<MyEventArgs> MyEvent;
...
if (this.MyEvent != null)
{
    this.MyEvent(this, new MyEventArgs { MyProperty = "foo" });
}
...
someInstance.MyEvent += (sender, e) => SomeMethod(e.MyProperty);

In case you want to add some MyProperty2 property to MyEventArgs, you could do it without modifying all your existing event listeners:
public MyEventArgs : EventArgs
{
    public string MyProperty { get; set; }
    public string MyProperty2 { get; set; }
}

public event EventHandler<MyEventArgs> MyEvent;
...
if (this.MyEvent != null)
{
    this.MyEvent(this, new MyEventArgs { MyProperty = "foo", MyProperty2 = "bar" });
}
...
// I didn't change the event handler. If SomeMethod() doesn't need MyProperty2, everything is just fine already
someInstance.MyEvent += (sender, e) => SomeMethod(e.MyProperty);


Q: Does it need to DeleteObject after CBrush () Does DeleteObject need to be called after CBrush ()
Does it is need to call deleteObject() if CBrush bNewBrush(RGB(255, 255, 255));
Thank you in advance.

A: No, you do not have to manually call it. The destructor of CBrush calls DeleteObject() for you...actually the destructor for CGdiObject from which CBrush is derived.
To make sure bad things don't happen, you should also make sure that the brush is not selected into a device context when the destruction occurs.

A: no, you can find in the msdn an exemple of code.
http://msdn.microsoft.com/fr-fr/library/btwwha51.aspx


Q: Meaning of “as soon as school was out for the day”
As soon as school was out for the day, they always came to play there.

What should I understand when I read this expression: ”as soon as school was out for the day”

A: It means the children's time of attending school for the the day has ended. It is said that "school has let out", or "school is out".
School can be "out for the summer" when the school year has ended. It is out for the day when the school day has ended.
So, the sentence means that the children came to play right after they were released from school.


Q: Probability of same feature inside a population
Let us have a population of many units, each unit has $n$ features, with $p$ of them are set to $1$ and other to $0$.
Question:
What is the probability, that if O take 2 random different units and compare one random feature, the value of both will be 1?

My naive answer:
Since probability of a feature for one unit to be 1 is p/n, the probability of 2 units to have it is
$$
(p/n)^2
$$
I want to ask, if this calculation correct, or it is naive and I must involve further distributions, like binominal, whatever but I do not understand how to apply them here.
Yes, i assume the features are independent, that is why i calculate like that.
Also it is known Hardy–Weinberg principle
https://en.wikipedia.org/wiki/Hardy%E2%80%93Weinberg_principle
what tells the same.

A: You seem to be assuming independence between the features of different units and that the features are equally likely.
If that is true then your calculation is correct. If not then not, and you would need to know more than the question states.


Q: What score-assigning function would maximize this desired shape? Let's say I have a setup where an agent places blocks into bins in such a way as to maximize its "score". The score is a function of the number of bins filled and the number of blocks in each bin. The bins are automatically sorted largest to smallest. The arrangement I wish to have the highest score is this:

A trivial function would be "Number of blocks in the largest bin" which would maximize this:

Or "Number of bins filled" which would maximize this:

You could take the product of "Size of largest bin" and "Number of bins", but that would have this maximize the score:

So what scoring function could I give that would give me the roughly smoothly-decreasing arrangement of blocks that I desire? Preferably the least complicated, the better.

A: Let $x_b$ be the number of blocks in bin $b$ and maximize
$$\min\limits_{b\in \{1,\dots,n-1\}} (x_b-x_{b+1}).$$
This will make the decreases uniform.
If you prefer steeper decreases at the beginning, maximize
$$\min\limits_{b\in \{1,\dots,n-1\}} b(x_b-x_{b+1}).$$


Q: Send a number of "Toast"s spaced by 2 seconds I need to display 4 "Toast"s spaced by 2 seconds between them.
How do I do this in such a way that they wait for each other and that the program itself waits until the last of them has displayed?

A: simply use handlers.
handler has a method called sendMessageDelayed(Message msg, long delayMillis).
just schedule your messages at the interval of 2 seconds.
here is a sample code.
    int i=1;
    while(i<5){

    Message msg=Message.obtain();
    msg.what=0;
    hm.sendMessageDealayed(msg, i*2);
i++;
    }

now this code will call handler's method handleMessage after every 2 seconds.
here is your Handler
Handler hm = new Handler(){

public void handleMessage(Message msg)
{
//Toast code.
}
};

and you are done.
Thanks.

A: Handlers are definitely the way to go but I would just postDelayed instead of handling an empty message.
Also extending Toast and creating a method for showing it longer is nice.
Sample Code:
// make sure to declare a handler in the class
private final Handler mHandler = new Handler();

// The method to show longer
/**
  * Show the Toast Longer by repeating it.
  * Depending upon LENGTH_LONG (3.5 seconds) or LENGTH_SHORT (2 seconds)
  *  - The number of times to repeat will extend the length by a factor
  *
  * @param number of times to repeat
  */
    public void showLonger(int repeat) {
    // initial show
    super.show();

    // to keep the toast from fading in/out between each show we need to check for what Toast duration is set
    int duration = this.getDuration();

    if (duration == Toast.LENGTH_SHORT) {
        duration = 1000;
    } else if (duration == Toast.LENGTH_LONG) {
        duration = 2000;
    }

    for (int i = 1; i <= repeat; i++) {
        // show again
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                show();
            }
        }, i * duration);
    }
}


Q: Meaning of phrase "in broken sentences" I just started reading a short story by Kate Chopin: "The Story of an Hour", and got stuck on the phrase "in broken sentences". What does it mean?

It was her sister Josephine who told her, in broken sentences; veiled hints that revealed in half concealing. Her husband's friend Richards was there, too, near her.

A: Here are the first two paragraphs of the story in which the quoted sentences appear:

Knowing that Mrs. Mallard was afflicted with a heart trouble, great care was taken to break to her as gently as possible the news of her husband's death.
It was her sister Josephine who told her, in broken sentences; veiled hints that revealed in half concealing. Her husband's friend Richards was there, too, near her. It was he who had been in the newspaper office when intelligence of the railroad disaster was received, with Brently Mallard's name leading the list of 'killed.' He had only taken the time to assure himself of its truth by a second telegram, and had hastened to forestall any less careful, less tender friend in bearing the sad message.

The idea conveyed by "broken sentences" is of speech in which the message is expressed in halting or faltering words, so that the effect is as though the speaker were making several attempts to express the message but abandoning the line of thought partway through each time, or or as though the speaker were unable to complete the message through an excess of emotion.
So, in the story in question, instead of saying something like this:

"My dear sister, I am so terribly sorry to have to tell you this, but the train that your beloved husband was riding on this morning has gone off the tracks and crashed, and he is among the passengers who have lost their lives."

Josephine must have said something like this:

"My dear sister, I am so terribly—I hardly know where to begin... I must implore you, dear Louise—but please sit down first. We must be strong—and you must steel yourself... At a time like this... Oh, what a calamity! If only he had not been on that train—and on this day of all days! But what I mean to say, dear, is that your beloved husband, poor Brently—oh, it is too hard! But we must, as I say, be brave..."

These are broken sentences because, even though one can find complete sentences (such as "I hardly know where to begin" and "We must be strong") in the course of the quotation, the speaker is not assembling her words, sentences, and fragments into a coherent narrative.


Q: How to populate struts 2 ui select tag by json returned list using jquery? //struts.xml
    <package name="ajax" namespace="/" extends="struts-default,json-default">
        <action name="CheckUserAction" class="com.controller.ajax.AjaxAction">
            <result type="json">
            <param name="root">jsonData</param>
            </result>
        </action>
    </package>

    //Action Class
public class AjaxAction extends ActionSupport {
private String capacity;
private String greeting;
private List<String> countryList;
private Map<String, Object> jsonData;
public String execute() throws Exception {
    jsonData = new LinkedHashMap<String, Object>();
    greeting = "HI " + "AMIT";
    countryList = new ArrayList<String>();
    countryList.add("US");
    countryList.add("UK");
    countryList.add("Russia");
    jsonData.put("capacity", this.getCapacity());
    jsonData.put("countryList", countryList);
    jsonData.put("countryMap", countryMap);
    jsonData.put("greeting", greeting);
    return SUCCESS;
}
//Getter and setters

}
//Script
$(document).ready(function() {
        $("#capacity").change(function() {
            var capacity = $("#capacity").val();
            $.getJSON('CheckUserAction.action', {
                capacity : capacity
            }, function(data) {
                $('#abc').append('
' + data.capacity);
                $('#abc').append('
' + data.countryList);
                $('#xyz').attr('value', data.greeting);
                $('#pqr').attr('list', data.countryList);
            });
            return false;
        });
    });

//JSP code

            <s:label for="capacity" value="Capacity" />
            <s:textfield name="capacity" placeholder="100" id="capacity"
                    value="abc"></s:textfield>

            <s:label for="dynamic" value="Ajax" />
            <s:textfield name="dynamic" value="learning" id="xyz"></s:textfield>

            <s:label for="flightId" value="Flights" />
            <s:select list="#{'1':'1' }" name="fightId" id="pqr"></s:select>

Initial

I want to populate list(id:pqr) with json returned list countryList, i am able to change attribute  value of textfield(id:xyz),i also appended it to div(id:abc) but i am not able to change attribute list of struts select tag.
Is it has something to do with how struts tag are populated in HTML.
Also i am not using struts-jquery plugin nor dojo plugin.
Thanks

A: What kind of data you are receiving in data.countryList? Can u post that data? I hope there is no attr property named list for dropdown. List property provided by Struts. You can compose the data for dropdown like
<option value="1">India</option>
<option value="2">United States</option>
<option value="3">United Kingdom</option>

and if you are sending new list you can do fill the countryList like,
$('#pqr').html(composed_country_list);

Else you are updating counrty means you can append the data to dropdown like,
$('#pqr').append(composed_country_list);

Let me know if this helps..

A: The following code worked for me
     //JSP
    <s:select list="{}" name="fightId" id="pqr"></s:select>

Script File
    $(document).ready(function() {
    $("#capacity").change(function() {
        var capacity = $("#capacity").val();
        $.getJSON('CheckUserAction.action', {
            capacity : capacity
        }, function(data) {

            countryListItem = data.countryList;
        });
        return false;
    });
});

    var pqr = $('#pqr');
    pqr.find('option').remove();
    pqr.append('<option value=-1>--Select--</option>');
     for(var i = 0; i < countryListItem .length; i++) {
            var opt = document.createElement('option');
            opt.innerHTML = countryListItem [i];
            opt.value = countryListItem [i];
            pqr.append(opt);

        }

Used javascript to populate the list by creating option attribute.
The struts select tag actually generates this kind of HTML internally.


Q: How Delete session from visitor browser I have problem with session, I try unset($_SESSION) and session_unset() and session_destroy() session destroyed but still show in browser (cookie extension)
I want remove it finality like session_start(['cookie_lifetime' => 10]) but I not want set a time, I want only remove it in a location on my php code, any idea?
My code here:
<?php
session_start();
$_SESSION['style'] = $style;
echo "Your style is : " . $style;
unset($_SESSION['style']);
session_destroy();

A: The session cookie stored in the browser simply contains a reference to the session ID on the server and does not contain any actual session data. All of that is stored solely on the server and it would actually be a huge security issue if it were stored client-side. If you delete the session on the server, this deletes all data stored on the server to do with that session and any attempt to re-authenticate using the old session ID will fail. If the browser sends an old session cookie back to the server after the session has been destroyed, it will simply be ignored by the server. Therefore there is no need to delete the session cookie from the user's browser since this will be done automatically by the browser when the window is closed. The recommended way to kill a session is simply to do:
$_SESSION = array();

However, with that said, if you want to manually force the cookie to be deleted for whatever reason:
<?php
session_start();
$_SESSION['style'] = $style;
echo "Your style is : " . $style;
unset($_SESSION['style']);

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', -1,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

session_destroy();


Q: Why is an Action not implicit convertable to Action when T : U? Consider this code:
class BaseEvent {}
class DummyEvent : BaseEvent {}

void FooBase(BaseEvent e) {}
void FooDummy(DummyEvent e) {}

void main(String[] args) {
   Action<BaseEvent> actionBase = FooBase;
   Action<DummyEvent> actionDummy = FooDummy;

   // Works implicit
   Action<DummyEvent> actionDummy2 = actionBase;
   // Only explcit
   Action<BaseEvent> actionBase2 = (Action<BaseEvent>)actionDummy;
}

I dont understand why it works like this, wouldn´t it make more sense the other way around considering how it works with object references?
void main(String[] args) {
   BaseEvent baseEvent = new BaseEvent();
   DummyEvent dummyEvent = new DummyEvent();

   // Works implicit
   BaseEvent baseEvent2 = dummyEvent;
   // Only explicit
   DummyEvent dummyEvent2 = (DummyEvent)baseEvent2;
}

I want to write code which stores a Map of Action and pass in diffrent Events like this:
class EventManager {
   Dicionary<int, Action<BaseEvent>> eventHandlers = new Dicionary<int, Action<BaseEvent>>();

   public void AddHandler(int eventType, Action<BaseEvent> eventHandler) {
      eventHandlers.Add(eventType, eventHandler);
   }
   public void TriggerEvent(BaseEvent e) {
      eventHandlers[e.EventType](e);
   }
}

void HandleDummyEvent(DummyEvent e)
{
   // Some code
}

void main(String[] args) {
   EventManager eventManager = new EventManager();
   eventManager.AddHandler(DummyEvent.EventType, HandleDummyEvent);
   eventManager.TriggerEvent(new DummyEvent());
}


Q: OSB Production Logs Mixing up - Work Manger We are using custom loggers through Java code in OSB. It was working fine till before Production environment. In production under heavy load, all application logs are getting mixed up. I need to Configure Work Manager (WM) for each application. For an OSB project, I have configured for Proxy service one WM and for multiple Business Services One WM setting max Thread Constraint to 7 [Done multiple trial and error for Max Thread]. But still under heavy loads logs are getting mixed up. What values should I actually set for Work Manager properties?


Q: How to make two openlayers map work synchronized I create two openlayer maps in my page, now I want them work synchronized.
For example, one map's center or zoom is changed, then another have change its accordingly.
And vice versa.
Which event should I registed to the map?

A: This is indeed possible, as I have just done it. You need to trap the 'moveend' and 'move' events from the map being panned or zoomed (moveend is triggered at the end of a zoom, but you could trap 'zoomend' as well to be on the safe side). If you trap these using the parent map as the context then you can get the new map centre. Bear in mind that the map centre can change when the map is zoomed if the navigation control is being used and the zoom is done using the mouse. Then use the moveTo method (childmap.moveTo().
I've chosen the moveTo method as (although not well documented) this is what is always finally called in any pan or zoom event on any map. As an aside, calling moveTo will also cause the 'move', 'moveend' events to be triggered on the child map.
If you make a collection of maps using json, and use jQuery, the actual code would look something like this (I'm assuming you know how to trap map events in OpenLayers);
var newCentre = zoomedMap.getCenter();

$.each(maps, function (ind, map) {
            if (map !== zoomedMap) map.moveTo(newCentre, newZoom);
        });

where maps is my collection of maps, zoomedMap is the map the user actually triggered the pan or zoom event on (I've called it zoomeMap but it could just as easily be called pannedMap), and (obviously) map is the map in the collection that needs moving.
I played around a bit before I settled for the above code. The advantage here is that $.each doesn't wait for the moveTo function to return, so you get a much slicker looking synch. Of course this wouldn't really be an issue if you're only synching two maps.
I'm sorry to have posted this so long after the question was asked, but maybe it will help any new searchers out there.


Q: jquery event not working on mozilla and work for other browser i have been try to make a responsive design but the click event seems locked on mozilla and work just fine on other browser i have the following  codes

jQuery(document).ready(function($){

 $("#serach-button").click(function() {
 var display=$("#head-form").css("display");
 if(display!="none"){
  $("#head-form").fadeOut();
 }else{
  $(".menu").hide();
  $("#head-form").show();
 }
 });
  });

<button class="button-responsiv"></button>
<button class="button-responsiv"></button>
<button class="button-responsiv" >

</button>

i had tried the e.preventDeafualt() but still not working.

A: You may want to try live binding the event and see if that makes a difference. The other issue may be your css as the italic tag is an inline element you may not have a decent target area for the click event (this space can vary from browser to browser). You may want to try binding to the parent button tag instead as this should contain the child element. Also since there is no default action to an italic tag or button there is no reason to include a preventDefault() or return false.
$(function(){
    $(document).on("click", "#serach-button", function() {
      if($("#head-form").is(":visible")){
         $("#head-form").fadeOut();
      }else{
         $(".menu").hide();
         $("#head-form").show();
      }
   });
});

Also take note of how you are spelling your class names and id's as pointed out by other people in this thread there are several misspellings and several answers have tried correcting that spelling for you.

A: Actually I will upvote your question because it leads to an issue I didn't know before :
elements embedded inside a buttton in FF will lose their click event.

$("#p").click(function() {
  alert('hello');
});

document.getElementById('i').addEventListener('click', function(e) {
  alert('hello2');
}, false);

<button id="b">

  elements embedded inside a buttton in FF will lose their click event.
</button>

I don't know if it's a bug as specs only state that

It is illegal to associate an image map with an IMG that appears as the contents of a BUTTON element.

So for you the solution is to reattach the event to the button (either by giving the serach-button id to your real button element, or with $("#serach-btn").parent().click(function() {.

jQuery(document).ready(function($) {

  $("#serach-button").parent().click(function() {
    alert('hello');
  });
  $("#real-button").click(function() {
    alert('hello');
  });
});

  <button class="button-responsiv">
  </button>
  <button class="button-responsiv" id="real-button">
  </button>
  <button class="button-responsiv">

  </button>

A: Your button has this class .search-btn so, you can try this:
$(function(){
   $(".search-btn").click(function() {
      if($("#head-form").is(":visible")){
         $("#head-form").fadeOut();
      }else{
         $(".menu").hide();
         $("#head-form").show();
      }
   });
});

A: Try changing "serach" to "search".
Also you can change jQuery to $:
$(document).ready(function () {
    $("#search-button").click(function () {
        var display = $("#head-form").css("display");
        if (display != "none") {
            $("#head-form").fadeOut();
        } else {
            $(".menu").hide();
            $("#head-form").show();
        }
    });
});


Q: What is the difference between nohup and crontab? Say I want to delete the contents of a directory every hour, what is the difference between having let's say a python script do this for me: nohup python dir_cleaner.py & vs setting a cronjob to do this for me? Couldn't find a cut-clear explanation for this difference. Let's say I'd also like to have every hour the exact date + the files listed that were in that directory and have this output to a file prior to the files being deleted. What is the best approach? Apologies if duplicate.

A: If you run a python script via nohup, it is run only once. So the script must itself work in an infinite loop and repeat deleting of the directory every hour.
Also, if your script fails for any reason and stops running, or it is killed, it won't restart by itself - you must restart it manually. You also won't know that your script isn't running anymore (other than occassionally checking the process list or the output file that you create).
If you setup a cron job to run every hour, then this job will be repeated automatically forever. Even if it fails one time, it will be run again the next hour.
Also, if you have mail set up on your system (you have some MTA installed and configured), then any output produced by a cron job (if any) will be mailed to you. So if your job normally does not produce any output, there will be no mail; but if it fails and there will be some error message, it will be mailed to you.
These are main differences to me. In my opinion a cron job is therefore more reliable than just letting a script run in background via nohup.


Q: CSS image not properly sized I have this paralax image on my website (the big nature one)
This is how the page is normally seen
But its not properly sized. When i open chrome dev tools it looks like the image below and that's how i want it to be.
this is the image how it needs to be (the nature image)
so what i want: I want the nature image seen on the pics above to be shown as it is in the second picture (with devtools). I know that the image is not properly sized for the box. But i don' t know how to fix it and can' t find something on the internet.
Can someone help me?
If my question is not clear enough please reply what i should add!
My CSS code attached to the image-paralax:
 .header{
        background-image: url("nav-bg.png"); //The background image
        border-bottom-right-radius: 20px;
        border-bottom-left-radius: 20px;
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-size: 100% 100%;
    }

    .parallax-2 {
    background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

HTML code:

Hope to see your answer soon!
Beldr
Note:
Suggestions from the answers below:

*

*background-size: contain no-repeat; (does not work)

*object-fit: contain and object-fit: cover (does not work)

*width&height 100% (nope)

My code on JSfiddle: https://jsfiddle.net/BeldrProductions/k5f70dy9/

A: You have to wrap your background image container in another div.
Check the HTML, CSS snippets along with screenshot.

A: Thanks to everyone that has helped me. But i just used it without a image
Thanks, Bye!
if there still is anyone who has a solution. Please leave it below. I would love to see it.


Q: How to calculate the Euclidean distance in python I have a dataset in .csv format. contains 2099846 rows and 38 columns
I want to calculate the Euclidean distance of any pair of rows and set to another 2d array.
import pandas as pd
import numpy as np

data = pd.read_csv('fraudDataset.csv', encoding= 'unicode_escape')
row = len(data)

data = data.astype(int)

distanceMatrix = np.zeros((np.shape(data)))

for datai  in range(len(data)):
     for dataj in range( datai + 1,len(data)):
            distanceMatrix[datai,dataj] = np.linalg.norm(data[3] - data[4], ord=None, axis=None, keepdims=False)

but it gives the error
   return self._engine.get_loc(casted_key)

  File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1675, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1683, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 3

Could you please help me how to do this task?

A: I cannot replicate the problem, as there is inadequate information about the type of data, thus suggesting a fix to the error message.
But from your problem description, I think cdist function from scipy.spatial* could solve your problem. As you have not provided an example data row, I created an integer matrix A.
from scipy.spatial.distance import cdist
A=np.random.randint(10, size=(10,10))

B=cdist(A, A, metric='euclidean')

B is a symmetric matrix, naturally.
* https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html


Q: ReSharper Unit Test Runner ignores deployment items configuration I'm using Resharper 6.1 for unit testing a new project and it seems to ignore the the Deployment section of my local.testsettings file.
I tried to configure in "ReSharper -> Options -> Unit testing -> MSTest -> Use this test run configuration" to explicitly use the local.testsettings file, how is suggested in this question: ReSharper Unit Test Runner: Support for Deployment Items, but nothing happens.
Desperately I tried to move the files out of the test project, create another Test Settings file, move the test project to another solution, but still nothing.
Any tips?

A: This is also a ReSharper-Configuration problem that I encounter myself. May this help you.
When I try to run the application, it get this ReSharper error: "The project to be run with this configuration is not present in the solution"

In Resharper help page, I found the path to the run configurations:
https://www.jetbrains.com/help/resharper/2016.2/Run_Configurations.html
ReSharper | Tools | Run Configurations...

Since the project doesn't exist anymore, I delete that connfiguration:
{Project Name} > Configure > Delete...

A: This issue (http://youtrack.jetbrains.com/issue/RSRP-295311) should be fixed in ReSharper 7 here: http://www.jetbrains.com/resharper/download/index.html.
Thank you!

A: I got the same ReSharper error in VS2019, VS2022:

ReSharper – Failed to execute run configuration
The project to be run with this configuration is not present in the
solution.

Turns out that you don’t have to necessarily run the project that is problematic. If there is some configuration saved for another project in ReSharper, and that project is not present anymore (for example, you’ve switched branches or deleted some project from the solution), this error will pop-up. It was my case.
Solution is as described above:
Go to Extensions -> ReSharper -> Tools -> Run configurations… -> nonExistingProject -> Configure -> Delete
This will delete configuration that is preventing ReSharper to work well and blocks your run at the IDE.
Apparently, still not fixed...


Q: Style for naming a function that is setting an argument by reference? So pretend I'm developing a car class and I want one of the car class's functions to return a list of passengers, except I'd like to put a list reference as an argument and just set that list instead of returning a list.
void GetPassengerList(PassengerList &passengerList); //sets the list

I don't know if I should call it GetPassengerList or SetPassengerList, or something else. I feel like using the words get / set make it seem like there is a private variable that is being manipulated like the typical getter / setter methods. What's a good naming convention to use here?

A: In our team for input/output arguments we either use
void AdjustPassengerList(PassengerList&);

or
void AddPassengersTo(PassengerList&);

Depending on the use-case. For example the first one could be used if you want a list created from more than one car. The second usually reads well in code, something like:
car.AddPassengersTo(list);


Q: Julia - How to get the minimum of each row of matrix? I tried to make that code but it get the value of the last index in the  row
function heuristicCalculate(distanceBetweenCities,numOfCities)
#distanceBetweenCities is a 29*29 array
#Use this function to calculate the tour length using nearest neighbor heuristic Lnn
mindist=zeros(29,1)
  for i=1:29
    for j=1:29
    mindist[i,1]=Base.minimum(distanceBetweenCities[i,j])
    end
  end
  mindist
  return Lnn, tau0
  #Lnn  tour length using nearest neighbor heuristic
  #tau0  a value representing the initial phermone amount =1/(n*Lnn)
end

A: The simplest solution would probably be
mindist = minimum(distanceBetweenCities,2)

where the ,2 denotes the dimension over which the minimum is searched.


Q: import error in django-sendsms I'm trying to use django-sendsms based on this documentation
I downloaded the package,copied it's folder in c: and ran this command in shell
c:
cd django-sendsms
python setup.py install

these commands installed django-sms in sitepackages folder.then based on the documentation I added this backend to settings.py:
SENDSMS_BACKEND = 'sendsms.backends.console.SmsBackend'

and in views.py :
from sendsms import api
api.send_sms(body='I can haz txt', from_phone='+41791111111', to=['+41791234567'])

but I get this error:
No module named importlib

every thing is based on the documentation,I don't know what's wrong with it!

A: Which version of Python are you using? It seems that module (in sendsms/util.py) will import the library called importlib which only exists in Python 2.7. If you are using Python 2.6 or lower, that library do not exist.


Q: a basic doubt about building from source Suppose I installed a Debian package using the Ubuntu Software Center, and then suppose I wish to install the same program by compiling it from source. Then can I simply proceed by installing the same program compiling from source? Will this replace the previous version installed via deb package?

A: Debian packages generally install the binaries and libraries in /usr/bin/ and /usr/lib directories. Whereas when you compile the softwares from source, you are able to specify the prefix for the directories in which you want to install it. In general, the /usr/local/bin/ and /usr/local/lib directories are default in standard gnu softwares / foss (sort of de-facto standard). You can compile the softwares by specifying the prefix while running configure command.
e.g. Say you want to install the software in /usr/local/ prefix, you should run these commands:

*

*./configure --prefix=/usr/local

*make

*sudo make install

You can specify --prefix to be any directory e.g. it can be ~/.local/ or any other directory for that matter.
Now you have two binaries with the same name but in different directories installed. Which one of these will be used when you invoke the command (binary file) name, depends on the PATH variable of your shell. If the directory you installed the software is before the standard /usr/bin/ directory in the PATH variable value, it'll be run and debian one'll not be run.
  Check the PATH variable by running echo $PATH in terminal.


Q: heroku cannot connect to MySQL server I am using flask-sqlalchemy to connect to mysql
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:''@127.0.0.1/pharmbase'

While this works fine locally, heroku cannot connect to MySQL server when deployed.
Below is a trackback message
2021-01-19T15:36:19.137152+00:00 app[web.1]: sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)")

Please any solution on how to solve this

A: 127.0.0.1 as an IP address means "this machine". More formally, it's the loopback interface.   On your laptop you have a MySQL server running.  Your heroku dyno does not, so your connection attempt fails.
You won't be able to connect from your program running on your heroku dyno to your laptop's MySQL server without some network configuration work on your office or home router / firewall. But to begin doing that work you'll need to come up to speed on networking. (Teaching you how is beyond the scope of a Stack Overflow answer.)
You can add a MySQL add-on to your Heroku app from a third party. Heroku themselves offer a postgreSQL add-on with a free tier, but not MySql. For US$10 per month you can subscribe to one of these MySQL add-ons and you'll be up and running.


Q: Right Click event not firing in VSTO code for PowerPoint 2010 I'm attempting to add a Context Menu option to PowerPoint 2010 that only appears when text is selected.  Unfortunately the WindowBeforeRightClick event does not seem to fire if the mouse is inside of a TextBox.
Is there a different event I need to be listening to or a better way to add that context menu?


Q: How can you group data by multiple fields with separate totals in SQL or Power query I have a set of data that I want to count by multiple characteristics.
I am starting with something likes this (True/False for catagories)

week
PP
SEN

1
T
F

1
T
T

1
F
F

2
T
F

2
T
T

2
F
F

2
F
F

3
T
F

3
F
F

I want to end up with something along the lines of

week
PP
SEN
Total

1
2
1
3

2
2
1
4

3
1
0
2

As far as I can see I can only get something that would give me nested results
eg

week
PP
SEN
Total

1
T
T
1

1
T
F
1

1
F
T
0

1
F
F
1

It may be that this is really straight forward and I just have not found the correct search term, or it's just impossible via a query...but all suggestions welcome.

A: I think you just want conditional aggregation:
select week, count(*) as total,
       sum(case when pp = 'T' then 1 else 0 end) as num_pp,
       sum(case when sen = 'T' then 1 else 0 end) as num_sen
from t
group by week;

A: In powerquery, something like this
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source, "Total", each "1"),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Added Custom", {"week"}, "Attribute", "Value"),
#"Changed Type1" = Table.TransformColumnTypes(#"Unpivoted Other Columns",{{"Value", type text}}),
#"Replaced Value" = Table.ReplaceValue(#"Changed Type1","T","1",Replacer.ReplaceText,{"Value"}),
#"Replaced Value1" = Table.ReplaceValue(#"Replaced Value","F","0",Replacer.ReplaceText,{"Value"}),
#"Changed Type" = Table.TransformColumnTypes(#"Replaced Value1",{{"Value", type number}}),
#"Pivoted Column" = Table.Pivot(#"Changed Type", List.Distinct(#"Changed Type"[Attribute]), "Attribute", "Value", List.Sum)
in  #"Pivoted Column"


Q: Dailymotion API request returning blank result I am using the following code to retrieve video ID, title, thumbnail, duration and tags.
$dailymotion = "https://api.dailymotion.com/video/xreczc?fields=title,duration,thumbnail_url,id,tags";
$curl = curl_init($dailymotion);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
$results = json_decode($return, true);
print_r($results);

However it returns empty/blank page. I am using this on my localhost what could be wrong? I can call https://api.dailymotion.com/video/xreczc?fields=title,duration,thumbnail_url,id,tags directly in the browser and it works.
Any help, or ideas?

A: Please try with this one.
$dailymotion = file_get_contents("https://api.dailymotion.com/video/xreczc?fields=title,duration,thumbnail_url,id,tags");

$results = json_decode($dailymotion, true);

print_r($results);

A: You are trying to fetch a https link via curl which has known issues. See the following links to see if they help your issue.
Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
Regards,

A: This code seems to fix it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.dailymotion.com/video/".$id."?fields=id,title,thumbnail_url,tags,duration,embed_url");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$results = curl_exec($ch);
curl_close($ch);
$results = json_decode($results);
if (!$results || $results->error->code) {
    return false;
} else {
    return $results;
}