text:
Q: Weird CSS effect with box shadows - how to solve? See this example:

I have several boxes with white background and huge black, translucent box shadows that overlap the boxes above. However, this leads to an irritating behavior: While the white background gets darker through the overlapping box shadows, nested objects, like text or other boxes, don't!
Could anybody tell me why this occurs? I guess it has something to do with z-index. I would like prevent this - the nested objects should become darker as well. Any solutions?
Thanks in advance!

Here's the code: https://jsfiddle.net/xq20hvp4/3/

Coloured text Box with background

Coloured text Box with background

Coloured text Box with background

Coloured text Box with background

Coloured text Box with background

CSS:
div {
    margin: 20px;
    box-shadow: 0 0 0 250px rgba(0, 0, 0, 0.3);
    font-size: 25px;
    color: red;
    font-weight: bold;
    font-family: Consolas, Arial, sans-serif;
    background-color: #ffffff;
}
div span {
    background-color: #e7e7e7;
    color: #555555;
    font-weight: normal;
    font-size: 17px;
    padding: 1px 5px;
}

A: It's because those elements are on top of the div with the shadow. In order to put them behind, you can use position: relative; on the background element and give it z-index: 1:
div {
  margin: 20px;
  box-shadow: 0 0 0 250px rgba(0, 0, 0, 0.3);
  font-size: 25px;
  color: red;
  font-weight: bold;
  font-family: Consolas, Arial, sans-serif;
  background-color: #ffffff;

  /* Add this */
  position: relative;
  z-index: 1;
}

div .box {
  background-color: #e7e7e7;
  color: #555555;
  font-weight: normal;
  font-size: 17px;
  padding: 1px 5px;
}

Here's an updated fiddle: https://jsfiddle.net/6wwz8usw/.

A: https://jsfiddle.net/fd7tx2c2/
div {
 z-index: 1;
 position: relative;
}

Z-index
Position


text:
Q: In Bootstrap v5.0.0-alpha1 what can I use for media (BS 3/4)? I want to use a media object in Bootstrap v5.0.0-alpha1, but how?
In Bootstrap 3 & 4, I'm using it like this:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">

Media Object

Create a media object with the .media and .media-body classes:

John Doe Posted on February 19, 2016

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et
            dolore magna aliqua.

In v5.0.0-alpha1, which class can I use for a media object? I was unable to find any class named 'media' in Bootstrap 5.

A: Bootstrap 5's documentation illustrates how to use the Cards to achieve the old Media Object layout. https://getbootstrap.com/docs/5.0/components/card/#horizontal
For example:

            <svg class="bd-placeholder-img" width="100%" height="250" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Image" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#868e96"></rect><text x="50%" y="50%" fill="#dee2e6" dy=".3em">Image</text></svg>

Card title

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

A: Since Bootstrap dropped the "media object" in version 5, you will have to use the utility classes instead.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.0/css/bootstrap.min.css"/>

Media Object

Create a media object without .media and .media-body classes (BS5):

John Doe Posted on February 19, 2016

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et
            dolore magna aliqua.

A: For those of you who are just using the grid parts of Bootstrap, you could achieve a media object layout like this:

Look at the cute animal

col-auto shrink-wraps the column to the width of the content (in the above example, an image) and col simply takes up (or distributes, if there's more than one) the remaining space. See the documentation, for more information.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do we need to specify the type template parameter for each class function defintion? Since we define the template type over the class declaration, why do we have to specify it after each function definition? I'm confused because its even in the same file so it seems almost unnecessary to have to specify it over every function and because we are using the :: operator shouldnt it go back to the class declaration and see that T is already defined.
I'm new to c++ and still need to clear up some misunderstandings.
#ifndef __Foo_H__
#define __Foo_H__

template <class T>
class Foobar{

  private:
    bool foo1(T);
    bool foo2(T);

  public:
   FooBar();

};

template <class T> bool FooBar<T>::foo1(T data){
 code..
}

template <class T> bool FooBar<T>::foo2(T data){
 code..
}

#endif

A: First you may rename the argument as for normal function:
template <class U> bool FooBar<U>::foo1(U and_here_too){/**/}

It also manages to handle (partial) specialization:
template <> bool FooBar<int>::foo1(int i){/**/}
template <typename T> bool FooBar<std::vector<T>>::foo1(std::vector<T> v){/**/}

A: Templates are example of generic programming. The idea is to reuse code/algorithms. In languages with strict type control you come across seemingly unnecessary constraints. For instance you may have some sorting function doing great job in one project but incompatible with types used in another.
C++, C#, and Java introduce generic programming as templates (C++) and generics (C#, Java). In generics (let's talk about Java) classes are existing entities and class parameters serve mainly as type control service. That is their purpose in collections. When you inspect how list works you see list gathers Objects and cast back to the parameterized type only when the object is retrieved. When you write class you can only assume the parameterized type is Object or declared interface like in the following example:
class Test<T extends Comparable> {}
Here you can use T as Comparable. Unless you explicitly declare the interface, the parameter is treated as Object.
Now comes the difference between generics and templates. In C++ you can assume much more about the parameterized type in implementation. You can write sorting of objects of unknown type. In Java you have to at least know what is interface the parameter type. This causes that C++ have to build new class for each parameter (in order to check if the code is correct). Vector<int> **is completely separate type from **Vector<float>. While in Java there exists one class Vector<? extends Comparable>.
:: is scope operator. You can access scope of Vector<int> because the class exists, however, Vector does not.
As a result Java can compile generics and C++ cannot. All templates have to be available in headers to all programmers; you cannot hide it (there is some work to compile templates but I don't know what is its status).
So when you use generics you can refer to method Vector.add() while when templates you have to specify parameter template<class T> Vector<T>.
PS. since template parameter is integral part of class name you may use templates for compile time calculations like fibonaci sequence
template<int N> struct Fibonaci {
  static const int element = Fibonacci<N-1>::data + Fibonacci<N-2::data>;
}
template<1> struct Fibonaci {
  static const int element = 1;
}
template<0> struct Fibonaci {
  static const int element = 0;
}


text:
Q: Resize grouped buttons to size of text area? I am making an interface where I need to have the following set up: button - textarea - button.
Using the input groups, the buttons do not scale to match the height of the textarea (as they do with "normal" form inputs)
Here is a Fiddle
The ideal markup:

        <button class="btn">

        </button>

    <textarea class="form-control" rows="3"></textarea>

        <button class="btn btn-danger">

        </button>

Semi-working markup (looks bad, buttons are small and surrounded by grey):

        <button class="btn">

        </button>

    <textarea class="form-control" rows="3"></textarea>

        <button class="btn btn-danger">

        </button>

As you can see, the buttons stay small, and do not match the height of the textarea.
If you replaced the textarea with a text input, the buttons match (as shown in the BS3 docs)
Now, using an "input-group-addon" does make the prepended and appended items match up, but then they won't be buttons. Putting a button inside an "input-group-addon" tag just looks terrible.
So, is there a way to get the buttons to match the height of the textarea?

A: I hope this example can help:

@import url('http://getbootstrap.com/dist/css/bootstrap.css');
.input-arreglo-group{
    padding: 0px 0px;
}
.input-arreglo{
    margin-top: 0px;
    height: calc(100% + 15px);
    border-top-left-radius: 0px;
    border-bottom-left-radius: 0px;
}

    Descripción

        <textarea class="form-control" style="resize:vertical;" rows="7" id="proyecto_descripcion" name="proyecto_descripcion" placeholder="Descripción del Proyecto"></textarea>

            <button class="btn btn-danger input-arreglo">

            </button>

Al cambiar el tamaño de textarea el button se adapta al tamaño.

A: Here is one solution that may work for you. I think the problem is that these are custom font icons inserted with a :before class. So they won't respond to height you'll need to size them with font-size:
Working Demo
The only issue I see here is that you're going to have to hard code them to align correctly with your input box (i've used em's out of preference). I've added a few classes to make things easy and not overwrite the bootstrap css.
HTML:

       <button class="btn">

       </button>

     <textarea class="form-control custom-control" rows="3"></textarea>

       <button class="btn btn-danger">

       </button>

CSS:
.custom-control {height: 5.25em}

.custom-eye {font-size: 4em;}

.custom-remove {font-size: 4em;}


text:
Q: Why is list comprehension taking a long time on one machine vs another? Hello and thanks for reading!
Context
I have two computers A and B.
Computer A is a Dell Latitude E6230
CPU: i5-3320M @ 2.60GHz
RAM: 8GB DDR3 HD: 320GB Hard Disk Drive OS: 64-bit Windows 10
Computer B is a monster
CPU: i9 7920X 12-core
RAM: 8 x 8GB Geil Evo Potenza RAM
HD: 500GB Solid State Drive Samsung 850 Evo
OS: 64-bit Windows 10 Pro
The Problem
For some reason, Computer B is taking much longer to do list comprehension compared to Computer A. I would think Computer B should be faster.
The list comprehension in question is in the _dict_to_list method of the python csv module. This list comprehension takes up most of the time followed by this list comprehension.
On Computer B these operations take about 95% of the program execution time whereas on Computer A it takes about 30%.
In terms of seconds, on Computer B the _dict_to_list method takes 0.0298408s on average whereas on Computer A it takes 0.00204978s.
I profiled the code using pprofile.
Could it be a missing driver on computer B? Or something  related to the Operating System?
All suggestions/feedback are appreciated. Thank you!


text:
Q: Query DB with Ajax and Codeigniter (using Bootstrap modal) Here's a brief description of what I'm trying to achieve: I have an advanced search button that opens a bunch on input fields and select. I have to auto populate the selects with options from the DB, so I have to get the data from there somehow.
Because I don't want to load all the data in the page when it's no need, I want to use AJAX to get the data when the user clicks on the modal button of the advanced search.
I've tried to achieve this using the following code, but nothing really occurs:
View:
<button type="button" class="btn btn-default" id="btnList" data-toggle="modal" data-target="#c_avan">CAUTARE AVANSATA</button>

$('#btnList').click(function() {
    $.ajax({
        url: '<?php echo site_url('/admin/date_cautare_avansata'); ?>',
        type: 'POST',
        data: {
            key: value
        },
        dataType: 'json',
        success: function(data) {
            console.log(data);
        }
    });
});

Controller that I try to reach using Ajax:
function date_cautare_avansata() {
        $data['items'] = $this->cautare_avansata_model->items();
        $data['major'] = $this->cautare_avansata_model->major();

        echo json_encode($data);
    }

The models are not that important since they work fine. Any idea why this is not working at all? Thanks!

A: Problem is with your URL
url: '<?php echo site_url('/admin/date_cautare_avansata'); ?>',
     ^                    ^                            ^     ^

This should be
url: "<?php echo base_url() ?>admin/date_cautare_avansata",

Ajax should place inside
<script></script>

and need to call latest JS Library too

A: Try this...
$('#btnList').click(function() {
// Key must have a value. Assign that.
//Site url no slash in prefix
    $.ajax({
        url: '<?php echo site_url('admin/date_cautare_avansata'); ?>',
        type: 'POST',
        data: {
            key: value
        },
        dataType: 'json',
        success: function(data) {
            console.log(data);
        }
    });
});


text:
Q: How do I get protractor to check for an element before the page loads completely? I am starting off on a non-angular page, clicking a button with browser.findElement.
Upon clicking on the element the user is taken to an angular page that has a spinner until the page load is complete. Using the following code, protractor waits for the page to load completely before doing the below and I would like it to begin checking for the page-busy-indicator as soon as the initial button is clicked because by the time it gets to this code, the spinner is no longer active.
browser.wait(function(){
  element(by.className('page-busy-indicator')).getAttribute('class').then(function(value){
    console.log(value);
    if(value.indexOf('active')>-1){
      return true;
    }
  });
});

A: Thanks to finspin and Barney for their comments that pointed me in the right direction.  In the end, I needed to turn off waitForAngularEnabled and then use the opposite of what Barney had mentioned (presenceOf). Sorry if the question was confusing because of the way I worded it. Thanks again!
Note that what this is doing is setting up a watch for .page-busy-indicator.active and looking for it for 5 seconds before timing out.
browser.waitForAngularEnabled(false);
browser.wait(protractor.ExpectedConditions.presenceOf(element(by.css('.page-busy-indicator.active'))), 5000);


text:
Q: jquery ajax post() request not sent with XHR header The following is the javascript from my erb template. When the user submits the form, it should be hijacked by jquery, the data submitted via a $.post(), and return false should prevent the page from redirecting, and the form submitting in the traditional manner. But im still getting the redirect, and request.xhr? is returning false.
<% javascript_tag do %>
  jQuery(document).ready(function($){

    action = $('.edit_profile').attr('action');

    $('.edit_profile').submit(function(){

      form_data = $('.edit_profile').serialize();

      $.post(action, function($('.edit_profile').serialize()){
        $.colorbox.close();
      });
      return false;
    })
  });
<% end %>

A: Try this, there were a few problems with your script.
$(function(){
    $('.edit_profile').submit(function(){
        var form_data = $('.edit_profile').serialize();
        $.post(this.action, form_data, function(){
            $.colorbox.close();
        });
        return false;
    });
});


text:
Q: Regex captures unwanted characters on repeated group Subsequent captures for a group are including the comma or the closing parenthesis.
The regex:
(?<name1>\?\?\$.*)\s\((?<type1>\w+)\s(?<conv>\w+)\s(?<name2>\w+:?:?)+<(?<type2>[\w\s]+)>\((?<args>.+?(?=[,)]))+\)

The input:
??$PlotBarGroups@C@ImPlot@@YAXQBQBDPBCHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<signed char>(char const * const * const,signed char const *,int,int,double,double,int))
??$PlotBarGroups@E@ImPlot@@YAXQBQBDPBEHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<unsigned char>(char const * const * const,unsigned char const *,int,int,double,double,int))
??$PlotBarGroups@F@ImPlot@@YAXQBQBDPBFHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<short>(char const * const * const,short const *,int,int,double,double,int))
??$PlotBarGroups@G@ImPlot@@YAXQBQBDPBGHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<unsigned short>(char const * const * const,unsigned short const *,int,int,double,double,int))
??$PlotBarGroups@H@ImPlot@@YAXQBQBDPBHHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<int>(char const * const * const,int const *,int,int,double,double,int))
??$PlotBarGroups@I@ImPlot@@YAXQBQBDPBIHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<unsigned int>(char const * const * const,unsigned int const *,int,int,double,double,int))
??$PlotBarGroups@M@ImPlot@@YAXQBQBDPBMHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<float>(char const * const * const,float const *,int,int,double,double,int))
??$PlotBarGroups@N@ImPlot@@YAXQBQBDPBNHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<double>(char const * const * const,double const *,int,int,double,double,int))
??$PlotBarGroups@_J@ImPlot@@YAXQBQBDPB_JHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<__int64>(char const * const * const,__int64 const *,int,int,double,double,int))
??$PlotBarGroups@_K@ImPlot@@YAXQBQBDPB_KHHNNH@Z (void __cdecl ImPlot::PlotBarGroups<unsigned __int64>(char const * const * const,unsigned __int64 const *,int,int,double,double,int))

Actual result:
signed char
char const * const * const
,signed char const *
,int
,int
,double
,double
,int
)

Expected result:
signed char
char const * const * const
signed char const *
int
int
double
double
int

Online sample:
https://regex101.com/r/Fkyk4P/1
Question:
How can I not capture these commas and closing parenthesis?

A: You may try this regex:
(?<name1>\?{0,2}\$.*)\s\((?<type1>\w+)\s(?<conv>\w+)\s(?<name2>\w+:{0,2})+<(?<type2>[\w\s]+)>\((?: *(?<args>[^,)]+)[,)])+

Updated RegEx Demo
Take note of last repeating capture group:
(?: *(?<args>[^,)]+)[,)])+

That matches 1+ of non-comma, non-) characters which must be followed by , or ).
Or if we want to make this regex more strict then use:
(?<name1>\?{0,2}\$.*)\s\((?<type1>\w+)\s(?<conv>\w+)\s(?<name2>\w+:{0,2})+<(?<type2>[\w\s]+)>\( *(?<args>[^,)]+)(?:, *(?<args>[^,)]+))*\)

Here last subpattern is:
\( *(?<args>[^,)]+)(?:, *(?<args>[^,)]+))*\)

RegEx Demo 2


text:
Q: Material table select row export I've got a react application that holds a material table filled with data, and I've been trying to allow users to select specific rows to export to a csv. I've also posted for clarification on this [link][1] to get more guidance. Here's what I've got with some sample data.
import React, { useState, useEffect } from "react";
import "../../App.css";
import { forwardRef } from "react";
import Avatar from "react-avatar";
import Grid from "@material-ui/core/Grid";
import CsvBuilder from "csv-builder";

import MaterialTable from "material-table";
import AddBox from "@material-ui/icons/AddBox";
import ArrowDownward from "@material-ui/icons/ArrowDownward";
import Check from "@material-ui/icons/Check";
import ChevronLeft from "@material-ui/icons/ChevronLeft";
import ChevronRight from "@material-ui/icons/ChevronRight";
import Clear from "@material-ui/icons/Clear";
import DeleteOutline from "@material-ui/icons/DeleteOutline";
import Edit from "@material-ui/icons/Edit";
import FilterList from "@material-ui/icons/FilterList";
import FirstPage from "@material-ui/icons/FirstPage";
import LastPage from "@material-ui/icons/LastPage";
import Remove from "@material-ui/icons/Remove";
import SaveAlt from "@material-ui/icons/SaveAlt";
import Search from "@material-ui/icons/Search";
import ViewColumn from "@material-ui/icons/ViewColumn";
import axios from "axios";

const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => (
        <ChevronRight {...props} ref={ref} />
    )),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => (
        <ChevronLeft {...props} ref={ref} />
    )),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => (
        <ArrowDownward {...props} ref={ref} />
    )),
    ThirdStateCheck: forwardRef((props, ref) => (
        <Remove {...props} ref={ref} />
    )),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />),
};
//api that the data is manipulated from
const api = axios.create({
    baseURL: `https://reqres.in/api/users?page=2`,
});

function DisplayTableSanitized() {
    var COLUMNS = [
        {
            title: "Icon",
            render: (rowData) => (
                <Avatar
                    maxInitials={1}
                    size={40}
                    round={true}
                    src={rowData.avatar}
                />
            ),
        },
        { title: "First Name", field: "first_name" },
        { title: "Last Name", field: "last_name" },
        { title: "Email", field: "email" },
    ];

    //table data
    const [data, setData] = useState([]);
    const [columns, setColumns] = useState(COLUMNS);

    useEffect(() => {
        api.get("")
            .then((res) => {
                setData(res.data.data);
            })
            .catch((error) => {
                console.log("Error");
                console.log(error.data.data);
            });
    }, []);

    return (
        <div className="DisplayTable" style={{ marginTop: "5vh" }}>
            <Grid container spacing={1}>
                <Grid item xs={1}></Grid>
                <Grid item xs={10}>
                    <MaterialTable
                        title="TestDate_Table"
                        columns={columns}
                        data={data}
                        icons={tableIcons}
                        options={{
                            selection: true,
                            exportButton: true,
                            emptyRowsWhenPaging: false,
                            pageSize: 5,
                            pageSizeOptions: [5, 10, 25, 50, 100, 200],
                            overflowX: "hidden",
                            overflowY: "auto",
                        }}
                        actions={[
                            {
                                position: "toolbarOnSelect",
                                icon: SaveAlt,
                                tooltip: "Export the selected rows!",
                                onClick: (e, rowData) => {
                                    const fileName = "TestDate_Table";
                                    const builder = new CsvBuilder(
                                        fileName + ".csv"
                                    );
                                    builder
                                        .setColumns(
                                            columns.map(
                                                (columnDef) => columnDef.title
                                            )
                                        )
                                        .addRows(
                                            rowData.map((rowData) =>
                                                columns.map(
                                                    (columnDef) =>
                                                        rowData[columnDef.field]
                                                )
                                            )
                                        )
                                        .exportFile();
                                },
                            },
                        ]}
                    />
                </Grid>
                <Grid item xs={1}></Grid>
            </Grid>
        </div>
    );
}

export default DisplayTableSanitized;

I'm thinking I might just be flat out wrong with the csvbuilder package I installed, and I'm not sure how I can fix this to allow users to select specific rows to export. I keep getting a builder.setColumns is not a function error when I try to export. Any assistance or guidance on this is much appreciated.
[1]: https://github.com/mbrn/material-table/issues/2136

A: As it turns out, the above works perfectly. I had just been using the wrong module.
import { CsvBuilder } from "filefy";

is the import you actually want.


text:
Q: iOS : In app purchase. Product is paid or free based on user type I am developing an iOS application & I am going to sell products in application based on user type after user login.
If user is of Type A [ Privileged User]
  Then he can download product totally free / Based on promo code / Purchase if Promo Code is InValid (That I can decide based on some flags).
If user is of Type B [ Normal User]
  He have to pay for product & then he can download it on successful payment.
But, I have doubt about it whether Apple is going to approve this or not. At the time of submission of application to app store, I will provide them Normal User (User of Type B) credentials so that they can buy it normally.
Is this approach is right or wrong ?
Other way is, I can set same product with two different identifiers on iTunes connect.
One for free & another for purchase one.
When user logs in based on user Type I can decide which products to load for that user based on product identifiers which I have with me.
Is there any alternate solutions for same ?
Has anybody gone through same scenario ?
Thanking You !

A: I had a free app in the store that was using in-app purchases to enable features.  I also had a place to enter promo codes which could also enable features.  It was rejected by Apple because of the ability to enter a promo code and bypass the app store.  Sounds like the same as what you are trying to do.

A: I have one thought, don't know whether the Apple test engineers will allow it or not, keep in app purchase for non-privileged user and for privileged user instead of asking them to enter the promo code inside the application, update their privilege from WS (IF you are sending them promo code via email that means you have their email ids or user ids with you), make some provision inside the application to identify this and make functionality unlock. Never tried this but for one of my in-app purchase application was not rejected even though it has a flaw in it, when I put the subsequent build version the app got rejected and I needed to correct that flaw. It was about restore purchase button. Once your app is in appstore they don't look further into it. Its just a thought but you need to think before taking the risk.

A: I don't think you can really do it that way. The app can only be free, if it's free. But you can't have the app do nothing if no promo code is entered. Therefore, the best solution seems to be to have a free version of your app with minimal functionality. Privileged users can use the promo code (you cannot link to a site where you can buy this promo code though!) and normal users will have to do an in-app purchase to get the extra functionality.
Hope this helps!


text:
Q: How to transform column values of a dataframe to another dataframe with different indexes? I have two dataframes with equal number of rows.
df_a:

index   Id   X   Y
1       10   x1  -
2       20   x2  -

-----------

df_b:

index   PostId   Text
3       10       abcd
4       20       efg

Now how can I transform values of df_b['Text'] to df_a['Y']. resulting this:
df_a:

index   Id   X   Y
1       10   x1  abcd
2       20   x2  efg

Note that indexes of mentioned dataframes are not the same.

A: Because of the same number of rows, you can assign numpy array:
df_a['Y'] = df_b['Text'].to_numpy()

Older pandas versions:
df_a['Y'] = df_b['Text'].values

If want to map or merge be free to use some of solution from this answer.


text:
Q: Setting the same background colour on UIStatusBar as UINavigationBar I am looking to set a background colour on the UIStatusBar in my app and I want it to match the background colour of the UINavigationBar, same as the Facebook and Instagram apps.
I tried adding this function to the didFinishLaunchingWithOptions method in my AppDelegate:
-(void) setStatusBarColour{

    #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
    {
        UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,self.window.rootViewController.view.frame.size.width, 20)];
        view.backgroundColor=[[UIColor lightGrayColor] colorWithAlphaComponent:0.6];
        [self.window.rootViewController.view addSubview:view];
    }
}

It doesn't seem to be working.
Is there an easy way to do this?

A: On iOS 7 background colour of status bar inherits from colour of navigation bar.
So You can do something like this
[[UINavigationBar appearance] setBarTintColor:[UIColor yellowColor]];
And check out this link:http://www.appcoda.com/customize-navigation-status-bar-ios-7/

A: You don't need to write extra code for that. once you change color of navigationBar, statusBar will adapt the same color & tints for the fonts automatically.
How to change color of navigationBar?
Follow this link
and this is Facebook bar color Hex code : #3B5998
So your code would be :
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:59 green:89 blue:152 alpha:1]];


text:
Q: Hashset Equality override for structs containing reference type I am trying to implement struct containing state of a board game, so I need multiple states of a game in a HashSet.
Data part looks like this:
struct Sokoban
{

    public List<List<char>> data;   // data matrix
    public int sx, sy;              // sokoban's position
    public int bx, by;              // box position
    public int cx, cy;              // final box position

As struct are value types, when I create new instance with:
Sokoban nextState = actualState;

where actualState is a formerly initialized instance,
it should copy all fields of actualState to nextState.
So nextState and actualState now points to the same List>.  .
My question is, how can have a proper copy of this struct?
If I create a constructor like:
public Sokoban(Sokoban originalSokoban)
    {

        this.sx = originalSokoban.sx;
        this.sy = originalSokoban.sy;
        this.bx = originalSokoban.bx;
        this.by = originalSokoban.by;
        this.cx = originalSokoban.cx;
        this.cy = originalSokoban.cy;

        List<List<char>> data2 = new List<List<char>>();

        for (int i = 0; i < originalSokoban.data.Count(); i++)
        {

            data2.Add( new List<char>(originalSokoban.data[i]));
        }
        this.data = data2;
     }

it works.
But, when I add these two distinct instances to hashset they are not recognized as same. This is my code for overriden GetHashCode,Equals, ==, != operators :
    public override int GetHashCode()
    {
        return (( sx+sy+bx+by+ cx+ cy).GetHashCode()+(data).GetHashCode());
    }

    public static bool operator ==(Sokoban x, Sokoban y)
    {
        bool isEqual = true;
        for (int i = 0; i < x.data.Count(); i++)
        {
            for (int j = 0; j < x.data[0].Count(); j++)
            {
                if (x.data[i][j] != y.data[i][j])
                {
                    isEqual = false;
                }
            }
        }

        return isEqual &&
        x.sx == y.sx &&
        x.sy == y.sy &&
        x.bx == y.bx &&
        x.by == y.by &&
        x.cx == y.cx &&
        x.cy == y.cy;
    }

    public static bool operator !=(Sokoban x, Sokoban y)
    {
        return !(x == y);
    }

    public override bool Equals(object obj)
    {
         return obj is Sokoban && this == (Sokoban)obj;
    }

I don't know where I'm making mistake, if you have any comments or remarks I'll gladly accept any help, I'm stuck with this for 3 days, thank you :)

A: Looking on the code, most likely the problem is here
 public override int GetHashCode()
 {
   //(data).GetHashCode() !!! List<T>::GetHashCode()..
   return (( sx+sy+bx+by+ cx+ cy).GetHashCode()+(data).GetHashCode());
 }

data.GetHashCode() is unique for every new instance of the struct, so your resulting GetHashCode() may result in totally different number for instances that are supposed to be equal according to your logic.  Change your GetHashCode() method to meet your needs.


text:
Q: Symmetry of double integral I am a little embarassed that I cannot figure out this on my own, but oh well...
Let $f \colon [a,b] \to \mathbb{R}$ be continuous. Why is it true that
$$
\int_0^1 f(x) \int_0^x f(y) dy \,dx = \int_0^1 f(x) \int_x^1 f(y)dy\,dx~~~~ ?
$$
I can see why this should be correct. I believe that I should use the substitution rule, but do not know which substitution to use.

A: It's "Fubini's theorem" about reducing double integrals, resp.,  the inverse operation. If $$T:=\{(x,y)\>|\>0\leq y\leq x\leq1\}\ ,$$ and $g: \ (x,y)\mapsto g(x,y)$ is a reasonable function defined on $T$ then
$$\int_T g(x,y)\>{\rm d}(x,y)=\left\{\eqalign{&\int_0^1\int_0^x g(x,y)\>dy\>dx \cr &\int_0^1\int_y^1 g(x,y)\>dx\>dy\cr}\right.\quad.$$
In the case at hand $g(x,y)=f(x)\,f(y)$, so that we obtain (taking constant factors out of the inner integrals)
$$\int_0^1 f(x)\int_0^x f(y)\>dy\>dx=\int_0^1 f(y)\int_y^1 f(x)\>dx\>dy\ .$$

A: Step $1:$ Change the order of the integration in LHS to get
$$
\int_0^1\int_y^1 f(x)f(y)dx dy
$$
Step $2:$ Switch the variable names.
$$
\int_0^1\int_x^1 f(y)f(x)dy dx
$$

A: HINT : let $F$ be a primitive of $f$, you should be able to solve the integrale and see that both sides are equal


text:
Q: Swift: Image Preprocessing in CoreML: Resize and Transpose I need to preprocess the UIImage object before feeding to my model.
The model requires 2 transforms:

*

*resize to 224,224

*transpose to CHW

I searched and found there are 2 approaches:

*

*do the preprocessing in Swift

*add the operations to the AI model using Coremltools

I only managed to find how to do the resize in Swift, but have no idea how to do transpose to make sure the image has data format in CHW.
Also have no idea how to see the data format(CHW or HWC) from UIImage.
How to transpose and how to view the data format?

A: Setup Image input type and don't worry about sizes and data formats. Have clear API.
Example:
image_input = ct.ImageType(name="input_image", shape=(224,224))
model = ct.convert(traced_model, inputs=[image_input])


text:
Q: Jquery drag and drop realtime with websocket: error when many people drag at the same time I'm using jquery drag, drop with websocket. When user drag drop item, it will automatically update on other user screens. Like this video: https://youtu.be/JHndS1ps_f0
Library i'm using to drag and drop is: https://github.com/AshesOfOwls/jquery.shapeshift
Basically, the code structure of the drag part is like this:
   if (options.enableDrag) {
        $(".item").draggable({
            start: function (e, ui) {
                $selected = $(e.target);
            },
            drag: function (e, ui) {
                //st code with $selected

            },
            stop: function () {
                //st code with $selected
            }
        });
    }

But, when I'm during drag, other users also drag + drop, now I continue to drag and drop will fail. variable $selected is undifined. It seems to have been reset.

A: I found solution:
if (options.enableDrag) {
        $(".item").draggable({
            start: function (e, ui) {
                $selected = $(e.target);
            },
            drag: function (e, ui) {
                $selected = $(e.target);
                //st code with $selected
            },
            stop: function () {
                //st code with $selected
                $selected = $(e.target);
            }
        });
    }


text:
Q: How to remove a word that matches at the beginning of each line I would like to ask, how could I remove lines contaning the pattern AAA at their beginning?
example:
contents of file.txt:
AAA/bb/cc/d/d/d/d/e
AAA/dd/r/t/e/q/e/tg
AAA/uu/y/t/r/e/w/q
123 234 456 AAA/f/f/f/f/g/g
555 999 000 AAA/y/g/h/u/j/k

I would like to remove the first three lines with this type of pattern but would like to keep the last two lines.
The output of the command should be:
123 234 456 AAA/f/f/f/f/g/g
555 999 000 AAA/y/g/h/u/j/k

How could I do it with a unix command?
Thank you.

A: sed `/^AAA/d` file.txt

The /^AAA/ is a regular expression which matches AAA at the beginning of a line (^). d deletes the selected lines.
man sed for more information on the sed stream editor.


text:
Q: Javascript metaprogramming: get name of currently executing function which was dynamically rewritten I am rewriting one of javascript's core methods:
Element.prototype._removeChild = Element.prototype.removeChild;
Element.prototype.removeChild = function(){
    callback();
    this._removeChild.apply(this,arguments);
}

I want to dynamically get the name of the method (in this case "removeChild") from inside of the function being dynamically rewritten. I use arguments.callee.name but it seems to return nothing, thinking that it is just an anonymous function. How do I get the name of the function that the anonymous function is being assigned to?

A: It is an anonymous function. You are just assigning this anonymous function to the Element.prototype.removeChild property, but that does not make that property a name for the function. You can assign the same function to many variables and properties, and there is no way to know the name by which it has been called.
You can however give the function a proper name which you can access as arguments.callee.name:
Element.prototype.removeChild = function removeChild() {
    ....
}


text:
Q: Delete listbox item I have a Windows Forms application with two listboxes and a delete button. The first listbox displays a foodmenu, quantity and totalprice and the second one displays the totalprice.
When I click the delete button I want the item selected in the first listbox to be deleted in both listboxes. But the item is only deleted from the first listbox.
ListBox1.Items.Remove (ListBox1.Selected.Item)
ListBox2.Items.Remove (ListBox1.Selected.Item)

A: You should read your code thoroughly before posting here.
ListBox2.Items.Remove (ListBox1.Selected.Item)

Tries to delete the selected item in ListBox1 from ListBox2. Since ListBox2 does not contain the very item it cannot be removed.


text:
Q: let $q$ be the number of pairs of linearly independent vectors from $S$. What is the smallest and the largest possible value of $q$? Let $S$ be a set of $n$ nonzero vectors in $\mathbb{R}^2$ such that $S$ spans the whole $\mathbb{R}^2$ and let $q$ be the number of pairs of linearly independent vectors from $S$. What is the smallest and the largest possible value of $q$?
My attempt: Since we are in $\mathbb{R}^2$, $q$ cannot be larger than $2$. Since $S$ does not contain zero vector, minimal $q$ is $1$?
Is this correct?

A: If $n \geq 2$ then $n-1 \leq q \leq \binom{n}{2}$. There are two linearly independent vectors in $S$ let us choose two $v_0, v_1$, then in the worst case all the other vectors are scalar multiples of one of these. But if $0 \neq v \in S$ is a scalar multiple of $v_0$ then $v_1, v$ is is a linearly independent pair. So the smallest possible $q $ is $n-2+1$. And for the largest, any two pairs could be linearly independent in $S$ where $S$ is a collection of nonzero vectors chosen from $n$ distinct lines passing through the origin.

A: Based on how you have defined $q:=$ number of pairs of linearly independent vectors. The answer for maximum value of $q$ should be $\binom{n}{2}$. For example, if
$$S=\left\{\begin{bmatrix}1\\0\end{bmatrix}, \begin{bmatrix}1\\1\end{bmatrix}, \begin{bmatrix}1\\2\end{bmatrix}, \ldots , \begin{bmatrix}1\\n-1\end{bmatrix}\right\}.$$
Then $|S|=n$, $S$ definitely spans $\mathbb{R}^2$ and if you choose any $2$ vectors from $S$, they will form a basis of $\mathbb{R}^2$, hence linearly independent.


text:
Q: mongo cluster collection count showing different every time I had a replica set earlier
which i have converted to cluster now
current configuration is
3 shard
   4 router
   4 config server
Now when i trying to get count of one of collection sometime it is showing null and some time some value , why this is happening?
please help


text:
Q: matplotlib.plot in Pyqt5 I'm trying to embed plot in Pyqt5 widget and i found this class and it works but the range on the plot can be only from 0 to range(). I need plot that ranges from negative x. I tried modyfing it but failed. How could i do this?
class PlotCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
        self.plot()

    def plot(self):
        data = [random.random() for i in range(25)]
        plot = self.figure.add_subplot(111)
        plot.plot(data, 'r-')
        plot.set_title('PyQt Matplotlib Example')
        self.draw()

A: You're almost there, you only need to modify your plot() function and use plot.set_xlim() like so:
...
...
    def plot(self):
        data = [random.random() for i in range(25)]
        plot = self.figure.add_subplot(111)
        plot.plot(data, 'r-')
        plot.set_xlim(left=-10) #<-- added here
        plot.set_title('PyQt Matplotlib Example')
        self.draw()

And it generates this plot:

As you can see, the x-axis has been extended to include negative number starting from -10.


text:
Q: Logical vector with multiple columns in R I have te following dataframe:
a    b     c     d     e
TRUE TRUE FALSE  TRUE  TRUE
FALSE TRUE  TRUE  TRUE FALSE
TRUE TRUE FALSE  TRUE  TRUE
TRUE TRUE  TRUE FALSE  TRUE
TRUE TRUE  TRUE  TRUE  TRUE
TRUE TRUE  TRUE  TRUE  TRUE

I would like to create an extra column , say f, with the following logic:
TRUE = If all the columns in the corresponding row are all TRUE or all FALSE.
FALSE = if one or more colums differ from the other columns in the corresponding row.

In this example the output would be
a    b     c     d     e     f
TRUE TRUE FALSE  TRUE  TRUE  FALSE
FALSE TRUE  TRUE  TRUE FALSE  FALSE
TRUE TRUE FALSE  TRUE  TRUE  FALSE
TRUE TRUE  TRUE FALSE  TRUE  FALSE
TRUE TRUE  TRUE  TRUE  TRUE  TRUE
TRUE TRUE  TRUE  TRUE  TRUE  TRUE

A: Alternatively, exploiting the fact that logical values are just 0s and 1s for arithmetic:
rowMeans(dat) %in% 0:1
[1] FALSE FALSE FALSE FALSE  TRUE  TRUE

A: The answer provided by @Ferdinand.kraft is correct, and is the most readable answer, but a hack is to use rowSums:
DF$f <- rowSums(DF) %in% c(0, 5)

This is about 33% faster on my system:
> system.time(replicate(10000, apply(DF, 1, function(x) {all(x) || all(!x)})))
   user  system elapsed
   3.11    0.00    3.12

> system.time(replicate(10000, rowSums(DF) %in% c(0, 5)))
   user  system elapsed
   1.95    0.00    1.95

But, as I said, this is something of a hack and should probably only be used when speed is important.

A: As far as speed goes, this is pretty fast:
do.call(pmin.int,dat)==do.call(pmax.int,dat)

Speed test:
microbenchmark(
    allorall=apply(dat, 1, function(x) {all(x) || all(!x)}),
    rmeans=rowMeans(dat) %in% 0:1,
    rsum=rowSums(dat) %in% c(0, 5),
    minmax=do.call(pmin.int,dat)==do.call(pmax.int,dat)
)

Unit: microseconds
     expr     min       lq   median       uq      max neval
 allorall 278.598 287.7760 301.8145 340.9585  722.410   100
   rmeans 178.174 182.4925 191.6715 205.9790  471.888   100
     rsum 177.093 182.7625 188.4315 202.4695 1796.304   100
   minmax  17.278  19.9775  22.1375  26.1870   42.115   100

Why isn't there a prange?

A: Use this:
DF$f <- apply(DF, 1, function(x)(all(x) || all(!x)))

where "DF" is your dataframe.


text:
Q: Read an already existing (pre-made) textfile? I couldnt really find an answer to how to read an existing textfile (.txt for example) into my Application.
Basicly I want to give the App a textfile on its way to my phone when I install it, my question is where I have to put the file in my source folder for it to properly work.
I've read somewhere that I have to put it in a folder called "raw", but I cant find anything. Do I need to create it?
Im working with Android Studio if thats somehow important.
Thanks in advance!

A: Make a directory called raw under res
Put your textfile there.
E.g
res/raw/textfile.txt
You can now acquire an InputStream to this file
InputStream intputStream = this.getContext().getResources().openRawResource(R.raw.textfile);


text:
Q: Why is my function turning into a object? I have several ajax requests in my project so to simplify my code i created a function to handle the requests.
I am passing a success function to load when status is == 200 however even though the data is being sent correctly i am receiving "uncaught type error success is not a function" error. Using typeof i can see success starts as a function but then displays as an object.

here is my code
//function to handle ajax requests
function sendRequest(link, requestType, success, data) {
    var request = new XMLHttpRequest(),
        url = link;

    request.open(requestType, url, true);

    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            console.log("success");

            var responseText = request.responseText;
            console.log(typeof(success));

            success(responseText);
        } else {
            consoloe.log("error");
        }
    }

    request.send(data);
}

//calling function passing success function as argument
var jsonText = "json.php";

sendRequest(jsonText, 'GET', function (response) {
    var json = JSON.parse(response),
        postcodesArray = [],
        jsonLength = json.length,
        i;

    for (i = 0; i < jsonLength; i++) {
        postcodesArray.push(json[i].from_postcode);
    }

    var postcodes = postcodesArray.filter(Boolean),
        pstcodeLength = postcodes.length,
        n;

    for (n = 0; n < pstcodeLength; n++) {
        geocodeAddress(postcodes[n]);
    }
});

//EDIT fiddle containing all my code
https://jsfiddle.net/x1qe73s8/

A: Reading your jsfiddle, your code is probably going through the sendLatLng function where you have
sendRequest(url, 'POST', null, data);

typeof null is "object".


text:
Q: Creating a User Defined Point Grid Im trying to write some code (in C#, but any language will do) where the user defines and area, based on Min/Max Long/Lat's, and specifies a distance between points in meters, and the code returns a table of long/lats (WGS84/ESPG:4326) to create a grid.
I wrote some code a while ago that I was under the impression did the job, but after a quick bit of analysis, doesnt quite measure up to the job.  Please see the code below:
decimal minX = -74.002747535706M;
decimal minY = 40.722282672831M;
decimal maxX = -73.98386478424M;
decimal maxY = 40.733470232685M;
decimal distance = 100;
decimal x = 0.0M;
decimal y = 0.0M;
decimal length = 0.0M;
decimal lengthIncrease = 0.0M;

decimal increasePercentage = 0.0M;
int i = 0;

decimal yIncrement = distance / (decimal)111111.111111;

DataTable dt = new DataTable();
dt.Columns.Add("Longitude" , Type.GetType("System.Decimal"));
dt.Columns.Add("Latitude" , Type.GetType("System.Decimal"));

y = minY;

while (y < maxY)
{
    while (x < maxX)
    {
        length = (decimal)111.325 * (decimal)Math.Cos((double)y * (double)0.0174532925199433);
        increasePercentage = (decimal)0.001 / length * 100;
        lengthIncrease = increasePercentage / 100 * distance;
        x += lengthIncrease;
        i++;
        DataRow dr = dt.NewRow();
        dr["Longitude"] = x;
        dr["Latitude"] = y;

        dt.Rows.Add(dr);
    }
    y += yIncrement;
    x = minX;
}

return dt;

The above works fairly well.  It returns long/lats seperated by 100m lat, but by 90m long.  When i change the distance to 25m, it seperates latitude by 25m, but longitude by 22.3m.
EDIT:  C Sharp Version Solution Based on yosukesabai Answer:
int radius = 6378137;
double pi = Math.PI;
double deg2Rad = pi / 180;
double dst2Lat = 360 / (2 * pi * radius);

DataTable dt = new DataTable();
dt.Columns.Add("ID" , typeof(int));
dt.Columns.Add("Longitude", Type.GetType("System.Decimal"));
dt.Columns.Add("Latitude", Type.GetType("System.Decimal"));

x = minX;
y = minY;
while (y < maxY)
{
    double rLat = radius * Math.Cos(deg2Rad * y);
    double dst2Lon = 360 / (2 * pi * rLat);
    while (x < maxX)
    {
        i++;
        x += dst2Lon * distance;
        DataRow dr = dt.NewRow();
        dr["ID"] = i;
        dr["Longitude"] = x;
        dr["Latitude"] = y;

        dt.Rows.Add(dr);
    }
    x = minX;
    y += dst2Lat * distance;

Any help here would be fantastically helpful!
Regards
AM

A: Took ASPMapper's approach but instead of doing math on my own, used geodesic package from PROJ.4 (python binding pyproj, http://code.google.com/p/pyproj/).
from pyproj import Geod

minX = -74.002747535706  # in degrees
minY = 40.722282672831
maxX = -73.98386478424
maxY = 40.733470232685

distance = 100  # in meters

g = Geod(ellps='WGS84')
coords = []
lon,lat = minX,minY
while lat < maxY:
    while lon < maxX:
        coords.append((lon,lat))
        east = g.fwd(lon, lat, 90, distance)
        lon, lat = east[:2]
    lon = minX
    north = g.fwd(lon, lat, 0, distance)
    lon,lat = north[:2]

for lon,lat in coords:
    print lon, lat

REVISED
from math import pi, cos
minX = -74.002747535706  # in degrees
minY = 40.722282672831
maxX = -73.98386478424
maxY = 40.733470232685

distance = 100  # in meters

# radius of earth, dont tell anybody that i am not using wgs84 :p
r = 6378137
deg2rad = pi / 180

# factor to convert meter to degree of latitude
dst2lat = 360 / (2*pi*r)

coords = []

# start with LL corner
lon,lat = minX,minY

# march Northward
while lat < maxY:

    # radius of circle of latitude
    rlat = r * cos(deg2rad * lat)

    # factor to convert meter to degree of longitude
    dst2lon = 360 / (2*pi*rlat)

    # march Eastward
    while lon < maxX:

        # store results
        coords.append((lon,lat))

        # go distance meter to East
        lon += dst2lon * distance

    # done with one latitude parallel
    # prepare for the next parallel
    lon = minX # roll back to western edge
    lat += dst2lat * distance # go distance meter to North

for lon,lat in coords:
    print lon, lat

Revised again
Now I tried to incorporate eccentricity of earth defined in WGS84, instead of sphere approximation.  In north/south, i got very good precision (7 digits or so) but on line of latitude i still got 4 digits precision...
from math import pi, cos, sin, sqrt
minX = -74.002747535706  # in degrees
minY = 40.722282672831
maxX = -73.98386478424
maxY = 40.733470232685

distance = 100  # in meters

# major axis and inverse of flattening of earth, Now I am using WGS
a, invf = 6378137.0, 298.257223563

# conversion factor between degree and radians
deg2rad = pi / 180

# earth eccentricity
f = 1/invf
e = sqrt(f*(2-f))

# meridional cuvature at the middle latitude of entire box
midY = .5*(minY+maxY)
r_meridional_mid = a * (1 - e*e) / ((1 - (e*sin(midY * deg2rad))**2)**1.5)

# factor to convert meter to degree of latitude, at the middle lattitude
dst2lat_mid = 360 / (2*pi*r_meridional_mid)

coords = []

# start with LL corner
lon,lat = minX,minY

# march Northward
while lat < maxY:

    # normal curvature at the latitude
    r_normal = a / sqrt(1-(e*sin(lat*deg2rad))**2)

    # radius of circle of latitude
    rlat = r_normal * cos(deg2rad * lat)

    # factor to convert meter to degree of longitude
    dst2lon = 360 / (2*pi*rlat)

    # march Eastward
    while lon < maxX:

        # store results
        coords.append((lon,lat))

        # go distance meter to East
        lon += dst2lon * distance

    # done with one latitude parallel
    # prepare for the next parallel
    lon = minX

    # procede approximatedly half distance to North
    lat_tmp = lat + dst2lat_mid * distance * .5
    # get meridional curvature at middle latitude of a row
    r_meridional = a * (1 - e*e) / ((1 - (e*sin(lat_tmp * deg2rad))**2)**1.5)
    # factor to convert meter to degree of latitude
    dst2lat = 360 / (2*pi*r_meridional)
    # procede to North using curvature at cell mid-point
    lat += dst2lat * distance

print "lon,lat"
for lon,lat in coords:
    print "%s,%s" % (lon,  lat)

Revised (Fix radius of normal curvature calc)
Found why i screwed up radius of normal curvature (i copied formula wrong).  Fixed it and longitude matches with results with Proj.4 by like 9 digits.  Also I "improved" latitude by calculating radius of meridional curvature at cell mid-latitude, not the mid-latitude of entire box.  It is still approximation, correct way should use elliptic integration or something.  Error accumulates in longitudinal direction as I march northward, and endied up by 6digits accuracy in sample input, referring to proj.4


text:
Q: Regular expressions in C++ Right now I have two regular expressions that does this:
Regex-1 = "(\\{(\\w+)\\})";
Regex-2 = "(\\{([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\})";

I just want to be able to combine the two Regex into one, so that which ever Regex searches first will be the match.
Conceptually i'm thinking regex-1 || regex-2. Is that possible to combine them?
Thanks.

A: You mean like this?
Regex-1_2 = "(\\{(\\w+)\\})|(\\{([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\})";

EDIT:
So, something like this?
{(((\w+)|({\w+}))\|?)*}

EDIT 2:
Your last comment helps. So, work from beginning to end. You know you want to match an opening curly bracket, so that part is easy:
{

Now, after the first curly bracket, there are two options. Either there will be one or more alphanumeric (or underscore) characters, or there will be three groups of zero or more characters separated by pipes. The first two groups must be non-pipe characters, while the last group must be non-curly bracket characters (since a curly bracket will close the expression). That can be expressed using the alternation construct:
{(\w+|[^|]*\|[^|]*\|[^}]*)

Finally, the expression ends with a curly bracket:
{(\w+|[^|]*\|[^|]*\|[^}]*)}

This works with the example you provided. If your rules are different or more specific, you will need to say so.


text:
Q: how to implement Custom Auto suggestion in java like google how to implement Java Based Auto suggestion. suppose I have different types of data like firstName, rollNumber, address.
My first requirement is like if user enter first character on text box, then result should be sorted on natural order based on firstName and 10 results should be display.
after space if use enter second character and if it is numbere then RollNumber else lastName should be sorted on natural order as ascending.
or if user type third character then Address should be display on ascending order. there should be no database, you don't have to implement Solr or other api. how to implement on pure Java.
here I did not implement the text-box,but I Just took an example to demonstrate
    import java.util.*;
    import java.lang.*;
    import java.io.*;

    // A class to represent a student.
    class Student {
        int rollno;
        String name;
        String address;

        // Constructor
        public Student(int rollno, String name, String address) {
            this.rollno = rollno;
            this.name = name;
            this.address = address;
        }

        // Used to print student details in main()
        public String toString(){
            return this.rollno + " " + this.name +
                               " " + this.address;
        }
    }

    class Sortbyroll implements Comparator<Student> {
        // Used for sorting in ascending order of rollno
        public int compare(Student a, Student b) {
            return a.rollno - b.rollno;
        }
    }

    class Sortbyname implements Comparator<Student> {
        // Used for sorting in ascending order of name
        public int compare(Student a, Student b) {
            return a.name.compareTo(b.name);
        }
    }

    // Driver class
    class Main {
        public static void main (String[] args) {
            ArrayList<Student> ar = new ArrayList<Student>();
           //here I have thousand student are inserted into
           //simple collection.

            ar.add(new Student(111, "bbbb", "london"));
            ar.add(new Student(131, "aaaa", "nyc"));
            ar.add(new Student(121, "cccc", "jaipur"));

            System.out.println("Unsorted");
            for (int i=0; i<ar.size(); i++) {
                System.out.println(ar.get(i));
            }

            //collection sorted by rollno
            Collections.sort(ar, new Sortbyroll());

            System.out.println("\nSorted by rollno");
            for (int i=0; i<ar.size(); i++) {
                System.out.println(ar.get(i));
            }

            //sort by Name
            Collections.sort(ar, new Sortbyname());

            System.out.println("\nSorted by name");
            for (int i=0; i<ar.size(); i++) {
                System.out.println(ar.get(i));
            }
        }
    }

A: First of all your question is incomplete and misleading. It does not describes the requirement properly. But overall what I assume
You want Google like (?) suggester in your text box
It does not tell any specific things. What about your front end ? How about your data ?
Any way I think you just wanted to have a console like application where you will give partial String as input and your method will guess the Rest of String as an assumption from your dummy data. Am I right ?
If that is the thing you were looking for then I just sketched a demo code below
static List<String> query(String queryStr, List<Student> list) {
        List<String> suggestion = new ArrayList<>();
        list.forEach(std -> {
            if (isMatched(queryStr, String.valueOf(std.getRoll()))) {
                suggestion.add(String.valueOf(std.getRoll()));
            }

            if (isMatched(queryStr, std.getName())) {
                suggestion.add(std.getName());
            }

            if (isMatched(queryStr, std.getAddress())) {
                suggestion.add(std.getAddress());
            }
        });

        return suggestion;
    }

    private static boolean isMatched(String query, String text) {
        return text.toLowerCase().contains(query.toLowerCase());
    }

And what does this code do ? It actually takes the Partial String that the user input so far and your List<Student> as parameters. Then it iterates over the list and matches for all field for partial match. If any field matches the query it add that value in the suggestion list. In the main you can do like this :
public static void main(String[] args) {

        List<Student> list = new ArrayList<>();
        list.add(new Student(101, "Abc ghi", "USA"));
        list.add(new Student(102, "DEF", "UST"));
        list.add(new Student(103, "Ghi ab", "DSjkD"));
        list.add(new Student(104, "jKL ut", "USN"));
        list.add(new Student(105, "MNP", "TSA101"));
        list.add(new Student(106, "UTC ABC", "ESA"));

        List<String> sugg = query("01", list);
        sugg.forEach(System.out::println);
    }

and you will find the console printed like :
101
TSA101

Does it make sense ? it might not be your whole confusing requirements. But I think you got the idea. You can exploit this to address your own requirements. You could further imply your sorting logic or any kind of filters to it. It should not be that tough thing.
But you should be concerned that with large number of collection or complex associated objects this would not suffice. Real world application does not work this straight forward. You might need lot of other things to consider like memory, i/o and execution time.
Good Luck!

A: Do refer https://github.com/nikcomestotalk/autosuggest/
This implementation is in java based on Patricia trie and Edit distance algorithm.
Some salient features of this application is

*

*Auto correction of keywords

*Bucket support for sorting and personalization support.

*Filtering support.

*Limit support.

*Build in http server.

*Blazing fast search.

And you all are welcome for feedback
Solr/Lucene/Elastic will not give freedom to choose algorithm and personalization support.

A: You can use a Trie data structure for autosuggestion implementation and the time complexity would be O(word_length) for insert and search.
Apache commons provides implementation "org.apache.commons.collections4.Trie"
example:
Trie<String, String> trie = new PatriciaTrie<>();

        trie.put("abcd", "abcd");
        trie.put("abc", "abc");
        trie.put("abef", "abef");

        SortedMap<String, String> map = trie.prefixMap("ab");

        map.forEach((k, v) -> {
            System.out.println(k + "  " + v);
        });


text:
Q: How to get class id of a button in jquery? How to get class id of a button in jquery?
I am trying with this code.

<button id="Button2" class="Default">2. Click to get Class ID.</button>

Thanks in advance!

A: $("#myButton").click( function() {
     var class = $(this).attr("class");
});

Note that this can potentially contain multiple classes though.
If you need to check if a specific class exists in the CSS class list:
$("#myButton").click( function() {
     var isHighlighted = $(this).hasClass("highlight");
});

There's also addClass() and removeClass(). Generally there should be very little reason to ever retrieve the full class attribute as a string - it's much easier to manipulate or compare the attribute by using the jQuery methods instead.

A: <input type="button" id="btn1" class="btnclass" onclick="alert(this.className);" />

or
document.getElementById('btn1').onclick = function () { alert(this.className); }

The second option is the better way to do things.

A: You need to bind click event to button first and then use jQuery attr() to get the class.
Live Demo
$('#Button2').click(function(){
    alert($(this).attr('class'));
})

A: If you want to get all the ids of the clicked button then just capture the target's id of the clicked event:
see this in the fiddle: http://jsfiddle.net/DhjBW/
this the html:

<button id='button 1'>btn1</button>
<button id='button 2'>btn2</button>
<button id='button 3'>btn3</button>

this the jQuery:
$("button").click(function(e) {
    $('span').text($(e.target).attr("id"));
});


text:
Q: Return a generated array in C++ So many of you maybe think that it is an answered question, but my situation is qiuet different //becouse i declare array IN the FUNCTION//. The matter is: i want to make a string splitter, which separates a string into chunks which will be part of an array. The basic source code is:
string separate(string str, int chunk, string mode = "res2end"){

int strlen = str.length();

int full = strlen / chunk;

int arr_size = full+1;

string result[arr_size]; //this is the 25th row

int modf = strlen % chunk;

    for(unsigned i=0; i<full; i++){
        int msr = i*chunk;
        int sp = msr - chunk;
        string subres = str.substr(msr, chunk);
        result[i] = subres;
    }

    if(modf != 0){
        int restm = strlen - (full * chunk);
        result[full+1] = str.substr(restm, modf);
    }

return result;
}

As you see, i tried to set the lenght of the array but nothing! There is an error message:
..\fc.h(25) : error C2057: expected constant expression
..\fc.h(25) : error C2466: cannot allocate an array of constant size 0
..\fc.h(25) : error C2133: 'result' : unknown size

So if anyone should share with me the solution i would be very pleased!

A: Variable-Length Arrays (VLAs) are not part of the C++ standard (yet ?).
You should use a dynamically-allocated array, for which your best bet is std::vector. This will also enable you to return the array at all, since you can't return raw arrays from (or pass arrays to) functions either. Mind changing the return type, too.

A: std::vector< string > separate(string str, size_t chunk, string mode = "res2end"){
    size_t strlen = str.length();
    size_t full = strlen / chunk;
    std::vector< string > result; //this is the 25th row
    int modf = strlen % chunk;

    for(size_t i=0; i<full; i++){
        int msr = i*chunk;
        int sp = msr - chunk;
        result.push_back( str.substr(msr, chunk));
    }

    if(modf){
        int restm = strlen - (full * chunk);
        result.push_back( str.substr(restm, modf) );
    }

    return result;  // This could be a costly copy if prior to move introduced in C++11
}

A: You are creating an array of strings, not a single string. Your function returns single string, but "result" variable is an array.


text:
Q: How to upload image to server in j2me by multipart/form-data? As I am new to j2me,I am trying to upload image from mobile in j2me.It is showing exception in server side.
org.apache.commons.fileupload.FileUploadException: Processing of ``multipart/form-
    data request failed. Stream ended unexpectedly
    at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadB
    ase.java:384)
    at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(
     ServletFileUpload.java:116)
        at org.apache.jsp.photo_jsp._jspService(photo_jsp.java:119)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper
        .java:384)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:3
         20)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
        (ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter
         (ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke
        (StandardWrapperValve.java:228)
        at org.apache.catalina.core.StandardContextValve.invoke
        (StandardContextValve.java:175)
        at org.apache.catalina.core.StandardHostValve.invoke
        (StandardHostValve.java:128)
        at org.apache.catalina.valves.ErrorReportValve.invoke
        (ErrorReportValve.java:104)
        at org.apache.catalina.core.StandardEngineValve.invoke
        (StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service
        (CoyoteAdapter.java:216)
        at org.apache.coyote.http11.Http11Processor.process
        (Http11Processor.java:844)
        at org.apache.coyote.http11.Http11Protocol
        $Http11ConnectionHandler.process(Http11Protocol.java:634)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run
         (JIoEndpoint.java:445)
        at java.lang.Thread.run(Unknown Source)

please suggest me how to solve.
From J2me I am using code to upload image to server is.
    HttpConnection conn = null;
    OutputStream os = null;
   // InputStream is = null;

    try
    {
        System.out.println("url:" + serverurl);
        conn = (HttpConnection)Connector.open(serverurl);
        conn.setRequestMethod(HttpConnection.POST);

      //  String postData = "";

        InputStream imgIs = getClass().getResourceAsStream(FILE);
        byte []imgData = new byte[imgIs.available()];
        imgIs.read(imgData);

        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");

        os = conn.openOutputStream();
       // os.write(message1.getBytes());
     // For First Image uploading

     String message1 = "";
      message1 += "-----------------------------4664151417711" + CrLf;
     message1 += "Content-Disposition: form-data; name=\"photo\";
                    filename=\"" + FILE +    "\"" + CrLf;
     message1 += "Content-Type: image/jpeg" + CrLf; message1 += CrLf;

          os.write(message1.getBytes());

         // SEND THE IMAGE
         int index = 0;
         int size = 1024;
         do{
             System.out.println("write:" + index);
             if((index+size)>imgData.length){
                 size = imgData.length - index;
             }
             os.write(imgData, index, size);
             index+=size;
             progress(imgData.length, index); // update the progress bar.

         }while(index<imgData.length);

        System.out.println("DONE");

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }finally
    {
        System.out.println("Close connection");
        try
        {
            //os.close();
        }
        catch(Exception e){}
        try
        {
           // is.close();
        }
        catch(Exception e){}
        try
        {
          //  conn.close();
        }
        catch(Exception e){}
    }

on serside we use the code:
    System.out.println(".............Images..122223...Images...");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
System.out.println(".............Images...11111..test..."+upload);
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    System.out.println(".............Images...11111..test..."+isMultipart);

if(isMultipart)
{
       System.out.println(".............Images...11111..Images..Images....");
       List items = upload.parseRequest(request);
         System.out.println(".............Images.33333....Images..Images....");

          Iterator iterator = items.iterator();
          while(iterator.hasNext())
          {
                 String fieldName = "";
                  String fieldValue="";
                  String fileName = "";
                   FileItem fileItem=(FileItem)iterator.next();
                   System.out.println(fileItem.isFormField());
    if (fileItem.isFormField())
    {
         fieldName = fileItem.getFieldName();
         fieldValue = fileItem.getString("UTF-8").trim();

         if(fieldName.equals("photo"))
         {
             if(fieldValue!=null && fieldValue!="")
             {
                  photo = fieldValue;
                  System.out.println(photo);
             }
         }
    }
    else

     try
     {
         if(fileItem != null)
         {
             fileName = applicationNumber+"_"+fileItem.getName();
             fieldName = fileItem.getFieldName();
            System.out.println("applicationNumber="+fileName);
         }
         if(fieldName.equals("photo"))
        {
           String x=fileName;
            if(x.indexOf("/")!=-1)
            {
                 uploadStr = x.substring(0,x.lastIndexOf("/") );
                 UploadFile = x.substring(x.lastIndexOf("/")+1,x.length() );
            }
             long sizeInBytes = fileItem.getSize();
             String applicationURL = "C:/Program Files/
               Apache Software Foundation/Tomcat 6.0/webapps/apply_smart/applications";
     StringTokenizer stringTokenizer = new StringTokenizer(UploadFile,"\\");
                int  count=stringTokenizer.countTokens();
                 for(int i=1;i<=count;i++)
                 {
                          String token=stringTokenizer.nextToken();
                           if(i==count)
                          {
                               audioFileName=token;
                          }
                   }
                  applicationURL = applicationURL;
                  System.out.println("Path="+applicationURL);
                  String[] filePath = fileName.split("/");
    uploadedFile = new File(applicationURL+"/"+filePath[filePath.length - 1]);
                    long size=uploadedFile.length();
                   if(size>=11264)
                    {
                       }
                                     try
                                     {
                      fileItem.write(uploadedFile);
                        path = applicationURL.replaceAll
    ("C:/ProgramFiles/ApacheSoftwareFoundation /Tomcat 6.0/ webapps/apply_smart/", "");
                     path= path + "/"+ filePath[filePath.length - 1];
                      System.out.println("path::::::"+path);
                }
                catch (java.lang.Exception e)
                {
                    out.println(e);
                 }
                             }
          }//else
    }
    catch(Exception exe)
    {
     out.println(exe);
     break;
    }
                    }

Please suggest me how to solve the exception and send image to server.
Thanks in advance.
Teja.

A: Sorry I do not have time to check over your code to see what is wrong, but I used previously this solution by Jason Woods


text:
Q: Word for something post-contextualisation Let me use an analogy to clarify what I mean. You obtain 2000 user inputs from a survey. You have data. This data becomes information when it is processed, contextualized and understood in a particular setting. Is there a phrase / word communicative of this transition from data to information?

A: This Wikipedia article uses the word infer to describe the process of transforming data to knowledge.
They quote from Organizing Knowledge: An Introduction to Managing Access to Information:

"Information is inferred from data"


text:
Q: How to test for spatial non-stationarity in R to determine if local regression model is needed? I have a dataset for which I implement a regression model and from which I assume that the coefficients vary locally. If a spatial non-stationarity is given, it makes sense to run a local regression model, in my case a Geographically Weighted Regression (GWR).
To find out, if there is a spatial non-stationarity I am aware of the Koenker test which can be calculated with an Ordinary Least Square (OLS) regression model in any GIS software. But for this project I am working with R and I need to find out, if spatial non-stationarity is given or not. Is there any statistical test implemented in R which can give me that result?
I know of the spgwr package in R, but it is only to implement the GWR, not to test if GWR is necessary.

A: *

*There is the GWmodel package on CRAN. See: https://cran.r-project.org/web/packages/GWmodel/index.html You should check out the function gwr.montecarlo()

*There is a whole book centered around spatial statistics using R with a chapter on stationarity here: https://becarioprecario.bitbucket.io/spde-gitbook/ch-nonstationarity.html


text:
Q: Communicating with an SPI DAC I'm trying to interface the TLV5606 with an mbed via SPI.
The connections I've made are as follows:
Note: mbed is powered from same 5V supply.

I modified the mbed SPI helloworld prorgam:
    #include "mbed.h"

SPI spi(p5, p6, p7); // mosi, miso, sclk
DigitalOut fs(p8);

int main() {
    fs = 0;

    uint16_t fixed = 0x4000;
    uint16_t value = 1024;

    value = value - 1 << 2;
    uint16_t final = fixed | value;

    spi.format(16,1);
    spi.frequency(1000000);

    fs = 1;

    fs = 0;

    spi.write(final);

    fs = 1;

}

The first 4 bits (from the left) should be 0100, and the last 2 bit, 00. The 10-bit value goes in between. This is explained in the datasheet (http://www.tij.co.jp/jp/lit/ds/symlink/tlv5606.pdf).
I've used the bit pattern 0x4000, and XOR'd it with the 10-bit value, which is shifted by two. This should result in a bit pattern accepted by the DAC.
At first, OUT, as measured by the voltmeter is around 9mv (usually -9mv). After between 5 and 20 seconds (approx), the voltage spikes to around 1.6v, and once 3.3v. With a value of 1024, you would expect a value close to 3.3v (the reference). On occasion, the 1.6v spikes up to around 3.3v after a few minutes. Also, after having risen to 1.6v or 3.3v, the voltage will often drop back down to 9mv after some time.
I should mention that I haven't used a capacitor in this circuit, although I don't think it's necessary to test the basic functionality.
Any thoughts on what's going wrong?

A: Three issues stand out in this:

*

*final = fixed ^ (value << 2) gives you 0x5000. As final[12] is a "don't care", then you are actually feeding zero scale to your DAC, which is what you're observing. The mistake here is that the scale runs from 0 to \$2^N-1\$, so you need to do value = 1023 << 2 then OR that together with fixed (rather than XOR; doesn't make a difference in this case but this is the safe way to combine two values). You should be sending 0x4FFC to go to full scale output.

*You say you "haven't used a capacitor". Well, you need to! At the bare minimum, you DAC should have a small (10-220 nF) bypass capacitor at \$V_\mathrm{DD}\$. Never exclude these in digital circuits, eliminate obvious problems first otherwise you won't be able to determine reliably what's causing failures.

*SPI is a pain (it's not a proper standard, just ad hoc), but I think you should be using mode 1, not mode 2. Compare Figure 1 in the datasheet, with this page from the mbed manual, and the following image (from Wikipedia). In mode 1, output is updated on the rising edge, and read on the next falling edge, which corresponds to the DAC's datasheet. As mentioned in the comments, do play with this, it's a very common problem in SPI setup. You will not be the first or last, I promise you!

A: Checking the TLV5616 datasheet (http://www.tij.co.jp/jp/lit/ds/symlink/tlv5616.pdf), this is the pinout I see:

According to your stated connections, you've connected pin 5 to 5V (it should be analog ground) and pin 8 to Ground (it should be VDD).  Other connections are wrong as well.
Either your chip is completely miswired, or you got confused when listing your connections.


text:
Q: How to avoid Deadlock when using singleton Http Client in Winforms application I have a legacy Windows Forms application that I am working on, I made some changes to the http client, I wanted to make it a singleton so that it could be reused throughout the application. It seems to be causing a deadlock.
I am going to paste all the code that I believe is involved below:
This is the calling code where the UI gets frozen, it never unfreezes.
private async void lbGroup_SelectedIndexChanged_1(object sender, EventArgs e)
{
    int groupId = this.lbGroup.SelectedIndex + 1;
    await LoadStores(groupId);

    //The code below freezes the application
    this.lbStore.DataSource = _stores;

    this.txtSearch.Enabled = true;
    this.lbStore.Enabled = true;
}

This is the LoadStores Method where the httpClient is used:
private async Task LoadStores(int group)
{
    try
    {
        HttpResponseMessage res = await _httpClient.GetAsync("api/GetStoresByGroup/" + group.ToString());
        res.EnsureSuccessStatusCode();
        if (res.IsSuccessStatusCode)
        {
            var serializedStores = await res.Content.ReadAsStringAsync();
            _stores = JsonConvert.DeserializeObject<IEnumerable<Store>>(serializedStores).Select(s => s.StoreName).ToList();
            res.Content.Dispose();
        }
    }
    catch (Exception ex)
    {
        ErrorLogger.LogError("Installation", $"Error getting stores list: {ex.Message}");
    }
}

This is the Http Singleton Class:
public static class HttpClientSingleton
{
    private static readonly HttpClient _instance;

    static HttpClientSingleton()
    {
        _instance = new HttpClient();
        _instance.BaseAddress = new Uri("https://www.i-city.co.za/");
        _instance.DefaultRequestHeaders.Accept.Clear();
        _instance.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    }

    public static HttpClient Instance
    {
        get
        {
            return _instance;
        }
    }
}

This is the form constructor where the HttpClient gets initiliazed:
public partial class frmInstallationHelper : Form
{
    private static string _configDir;
    private static string _localConfigDir;
    private static int _storeID;
    private static Activation _activation;
    private static HttpClient _httpClient = HttpClientSingleton.Instance;
    private static IEnumerable<string> _stores;
    private static IEnumerable<string> _franchisees;
    private int _smsCounter;

If I wrap the http request in a using statement inside of the LoadStores method, the app runs fine, but I don't want to dispose of the http Client as that defeats the purpose of making it a singleton.
Update: Problem Found
After following @MongZhu's lead I replicated the program and confirmed that none of the above code was actually causing the deadlock. It was caused by another method that was triggered by the lbStore list Box onSelectChange event displayd below:
private void lbStore_SelectedIndexChanged_1(object sender, EventArgs e)
    {
        string store = this.lbStore.GetItemText(this.lbStore.SelectedItem);
        LoadFranchisees(store).Wait();
        this.lbFranchisees.DataSource = _franchisees;
    }

The way I solved the problem was by changing it to look as follows:
private async void lbStore_SelectedIndexChanged_1(object sender, EventArgs e)
    {
         string store = this.lbStore.GetItemText(this.lbStore.SelectedItem);
         await LoadFranchisees(store);
         this.lbFranchisees.DataSource = _franchisees;
    }

I was busy changing all the .wait() methods to async / await, and I must have forgotten this one.

A: The deadlock arises because you used Wait in a method which was triggered by an async opertaion. Unfortunately it was masked very good by the apparent hanging in the line of the initialization of the DataSource. But this initialization triggered the SelectedIndexChanged of the listbox which had the evil Wait call in it. Making this method async and await the result will evaporate the deadlock.
private async void lbStore_SelectedIndexChanged_1(object sender, EventArgs e)
{
    string store = this.lbStore.GetItemText(this.lbStore.SelectedItem);
    _franchisees = await LoadFranchisees(store);
    this.lbFranchisees.DataSource = _franchisees;
}

I would suggest to return the stores directly from the method instead of using a class variable as transmitter. This way you would also avoid race conditions (to which methods that use class variables are very much prone) If you need it further you could store the returning value inside the _stores variable. But a loading method should rather return the results instead of secretely storing it somewhere hidden from the user of this method.
private async Task<List<Store>> LoadStores(int group)
{
    try
    {
        HttpResponseMessage res = await _httpClient.GetAsync("api/GetStoresByGroup/" + group.ToString()))
        res.EnsureSuccessStatusCode();
        if (res.IsSuccessStatusCode)
        {
            var serializedStores = await res.Content.ReadAsStringAsync();
            res.Content.Dispose();
            return JsonConvert.DeserializeObject<IEnumerable<Store>>(serializedStores).Select(s => s.StoreName).ToList();

        }
    }
    catch (Exception ex)
    {
        ErrorLogger.LogError("Installation", $"Error getting stores list: {ex.Message}");
    }
}

You can await the result in the event:
private async void lbGroup_SelectedIndexChanged_1(object sender, EventArgs e)
{
    int groupId = this.lbGroup.SelectedIndex + 1;
    _stores = await LoadStores(groupId);
    this.lbStore.DataSource = _stores;

    this.txtSearch.Enabled = true;
    this.lbStore.Enabled = true;
}

The same logic applies to the LoadFranchisees method, refactor it so that it returns the data. This makes your code much more understandable. Don't hide information from the reader of a method. It could be you in 6 Month trying to figure out what da heck you did there.... Be nice to your future self at least ;)


text:
Q: How to use same control inside that control in angular? I have used my slitter control inside splitter. I have tried like below it won't work.
In the below sample, I have rendered splitter control inside the splitter

sample - https://stackblitz.com/edit/angular-ndqigp-hnwt7c?file=code-editor-layout.html

But I have found the solution if I tried using ng-container it is working fine. refer below

Sample with ng-container - https://stackblitz.com/edit/angular-ndqigp-dy6dei?file=code-editor-layout.html

And also, I can able to achieve my scenario like below:
I have initialized splitter as a component, then I used it is working

Sample -https://stackblitz.com/edit/angular-ndqigp-ixe646?file=code-editor-layout.html

Please suggest which one is best way and why my first sample not working?


text:
Q: Neo4j Cypher Optimize Create relationship between each node in cartesian product I have a set of nodes, all labeled Word. I want to connect each Word to all the other words with a relationship called Distance. I do the following query:

match (word1:Word)
with word1
match (word2:Word)
where word1 <> word2
merge (word1)-[distance:DISTANCE ]->(word2)
return word1, distance, word2

It runs forever. There are only ~600 nodes and although I expect 600*600 relationships, the query shouldn't run for two hours! It is quicker in Java than in Neo4j. What advice do you have to make it quicker? I have already added an index on one of the properties and it's not improving.

A: Some observations:

*

*Your query will try to perform 2*600*599 (or 718,800) MERGE operations in a single transaction. The reason for the factor of 2 is because every pair of words (say, x and y) will be seen twice (as x/y and y/x). You (presumably) only want to perform half that number of operations.

*The x/y and y/x behavior also causes an attempt to ensure there are 2 DISTANCE relationships for each word pair -- one in either direction. That is (presumably) twice the number of relationships than you want (or need).

*Trying to perform 720K (or even just 360K) operations in a single transaction may cause the DB server to run out of memory.

Here is a modified query that might fix the above issues. The ID(w1) < ID(w2) test makes sure the 2 words in a pair are not the same AND that the same pair is only processed once. It also uses the APOC procedure apoc.periodic.iterate to create 10K relationships at a time in separate transactions, in parallel.
CALL apoc.periodic.iterate(
  'MATCH (w1:Word), (w2:Word) WHERE ID(w1) < ID(w2) RETURN w1, w2',
  'CREATE (w1)-[:DISTANCE]->(w2)',
  {batchSize:10000, parallel:true}) YIELD batches, total
RETURN *

NOTE 1: This query assumes that you start out without any DISTANCE relationships in the DB, so it uses the cheaper CREATE clause instead of MERGE. If DISTANCE relationships exist already, then use MERGE instead (but this could create a second relationship between the same pair if the first relationship was in the opposite direction).
NOTE 2: Performing the batches in parallel should be safe because issue #2 is not possible with the new Cypher code. If 2 transactions were to attempt to create relationships in opposite directions between the same 2 nodes at the same time, that could result in a deadlock, which would cause at least one of the transactions to fail.
NOTE 3: This query assumes that the first statement (with the MATCH clause) does not itself run out of memory or take too long to process. If that assumption is wrong, then using a suitably modified query with apoc.periodic.commit should work.


text:
Q: how to Remove Noise Mix Audio in Android? hi friends, I'm trying to mix 2 audio, and the result is file mixed.wav on SD Card,
but I have a problem, the result is white noise, how to remove the noise and result is good ?
sorry with my English. and this is my code
package com.example.crazydoraemon;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class MainActivity extends Activity {

public static final int FREQUENCY = 44100;
private byte[] output;
private InputStream in1, in2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        mixSound();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private void mixSound() throws IOException {
    AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT, 44100, AudioTrack.MODE_STREAM);

    in1 = getResources().openRawResource(R.raw.a);
    in2 = getResources().openRawResource(R.raw.b);

    byte[] arrayMusic1 = null;
    arrayMusic1 = new byte[in1.available()];
    arrayMusic1 = createMusicArray(in1);
    in1.close();

    byte[] arrayMusic2 = null;
    arrayMusic2 = new byte[in2.available()];
    arrayMusic2 = createMusicArray(in2);
    in2.close();

    output = new byte[arrayMusic1.length];

    for (int i = 0; i < output.length; i++) {
        float samplef1 = arrayMusic1[i] / 128.0f;
        float samplef2 = arrayMusic2[i] / 128.0f;
        float mixed    = samplef1 + samplef2;

        // reduce the volume a bit:
        mixed *= 0.8;
        // hard clipping
        if (mixed > 1.0f)  mixed = 1.0f;
        if (mixed < -1.0f) mixed = -1.0f;

        byte outputSample = (byte) (mixed * 128.0f);
        output[i]         = outputSample;
    }

    properWAV();
}

public static byte[] createMusicArray(InputStream is) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[10240];
    int i = Integer.MAX_VALUE;
    while ((i = is.read(buff, 0, buff.length)) > 0) {
        baos.write(buff, 0, i);
    }

    return baos.toByteArray(); // be sure to close InputStream in calling function

}

public static void convertByteToFile(byte[] fileBytes) throws FileNotFoundException {

    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/mixed.wav"));
    try {
        bos.write(fileBytes);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

/**
 * TODAY
 * more info --> https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
 */
public void properWAV() {
    try {
        long mySubChunk1Size = 16;
        int myBitsPerSample  = 16;
        int myFormat         = 1;
        long myChannels      = 2;
        long mySampleRate    = 44100;
        long myByteRate      = mySampleRate * myChannels * myBitsPerSample/8;
        int myBlockAlign     = (int) (myChannels * myBitsPerSample/8);

        long myDataSize      = output.length;
        long myChunk2Size    = myDataSize * myChannels * myBitsPerSample/8;
        long myChunkSize     = 36 + myChunk2Size;

        OutputStream os = new FileOutputStream(new File(Environment.getExternalStorageDirectory().getPath()+"/mixed.wav"));
        BufferedOutputStream bos = new BufferedOutputStream(os);
        DataOutputStream outFile = new DataOutputStream(bos);

        outFile.writeBytes("RIFF");                                    // 00 - RIFF
        outFile.write(intToByteArray((int)myChunkSize), 0, 4);         // 04 - how big is the rest of this file?
        outFile.writeBytes("WAVE");                                    // 08 - WAVE
        outFile.writeBytes("fmt ");                                    // 12 - fmt
        outFile.write(intToByteArray((int)mySubChunk1Size), 0, 4);     // 16 - size of this chunk
        outFile.write(shortToByteArray((short)myFormat), 0, 2);        // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation
        outFile.write(shortToByteArray((short)myChannels), 0, 2);      // 22 - mono or stereo? 1 or 2?  (or 5 or ???)
        outFile.write(intToByteArray((int)mySampleRate), 0, 4);        // 24 - samples per second (numbers per second)
        outFile.write(intToByteArray((int)myByteRate), 0, 4);          // 28 - bytes per second
        outFile.write(shortToByteArray((short)myBlockAlign), 0, 2);    // 32 - # of bytes in one sample, for all channels
        outFile.write(shortToByteArray((short)myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)?  usually 16 or 24
        outFile.writeBytes("data");                                    // 36 - data
        outFile.write(intToByteArray((int)myDataSize), 0, 4);          // 40 - how big is this data chunk
        outFile.write(output);                                         // 44 - the actual data itself - just a long string of numbers

        outFile.flush();
        outFile.close();

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

}

 public static byte[] getBytesFromFile(File file) throws IOException {
     InputStream is = new FileInputStream(file);

     long length = file.length();
     if (length > Integer.MAX_VALUE) {
     }

     byte[] bytes = new byte[(int)length];
     int offset   = 0;
     int numRead  = 0;
     while (offset < bytes.length && (numRead = is.read(bytes, offset, Math.min(bytes.length - offset, 512*1024))) >= 0) {
             offset += numRead;
     }

     if (offset < bytes.length) {
         Log.i("xxx", "Could not completely read file");
     }
     is.close();

     return bytes;
}

private static byte[] intToByteArray(int i) {
        byte[] b = new byte[4];
        b[0]     = (byte) (i & 0x00FF);
        b[1]     = (byte) ((i >> 8)  & 0x000000FF);
        b[2]     = (byte) ((i >> 16) & 0x000000FF);
        b[3]     = (byte) ((i >> 24) & 0x000000FF);
        return b;
}

public static byte[] shortToByteArray(short data) {
        return new byte[]{(byte)(data & 0xff),(byte)((data >>> 8) & 0xff)};
}

public static long byteArrayToLong(byte[] b) {
    int  start = 0;
    int      i = 0;
    int    len = 4;
    int    cnt = 0;
    byte[] tmp = new byte[len];
    for (i = start; i < (start + len); i++) {
        tmp[cnt] = b[i];
        cnt++;
    }
    long accum = 0;
    i = 0;
    for (int shiftBy = 0; shiftBy < 32; shiftBy += 8) {
        accum |= ((long) (tmp[i] & 0xff)) << shiftBy;
        i++;
    }
    return accum;
}
}


text:
Q: postgresql initdb.exe option flags not working in command line in cmd.exe command line i go to the directory where there's initdb.exe and then i run :
initdb.exe -D "C:/data/" -U postgres -E UTF8
then the database is created with this message (in french, but i translated it in english for here) :
The files belonging to this database system will be owned by user "MyComputerUserName".
This user must also own the server process.

The database cluster will be initialized with locale "French_France.1252".
The default text search configuration will be set to "french".

My problem is that the command line flag for the user is not set to postgres and i get a 1252 Encoding instead of utf8.
But for a strange reason, the directoty flag work well and the data directory is created.
i tried to launch cmd.exe either with or without admin rights, but i get the same problem.
i use the version postgresql-13.1-1-windows-x64-binaries
any ideas on why the command line not working correctly? (´・ω・`)?
Thanks for your help.

A: There is nothing wrong here (or at least, no evidence of it).  -U controls the name of the boot-strap superuser within PostgreSQL, while the message tells you the name of the OS user who will own the files.  It is not a contradiction for those to be different.
UTF8 is an encoding, while "French_France.1252" is a locale.  Again, it is not a contradiction for those to be different.  Indeed they have to be different, as there is no locale named 'UTF8'.
If you start up the database, I think you will find that the superuser's name is postgres the encoding is UTF8.


text:
Q: Generating tree with repeatable elements I want to generate the following tree using google charts:

The top ones are roots, and the bottom ones are their childs. One child can be included inside many roots.
I want to make organization chart to achieve that.
How can I do that?
Because right now, the child belonging to two roots is not being displayed.


text:
Q: Automatically close the Form window after submitting I have a Google Form as an iframe in a Google Sheet.
I need to close the form automatically after submitting answers.
Ideal scene would be:
a person hits submit button, the answers have been recorded and the window
    closes automatically.
But there is a following window ("thank you for you response" window) which (from my experience) is probably not possible to disconnect from the form and not to lose answers.
In this case it would be good to automatically close this second window right after it appears.
p.s. For submitting the form I use
 <button type="SUBMIT">Submit</button>
(I copied and pasted, then modified the html because the form didn't work properly in an iframe mode)

A: Fully handled all issues by implementing elements from Materialize framework into my dialog withing a Spreadsheet.
Amazing look and functionality!
For the dialog I used  SpreadsheetApp.getUi().showModelessDialog().
Thank you for your answers and reactions which made me search for better options and discover such amazing solutions for myself.


text:
Q: Change File Directory of microlog4android? I'm using microlog4android to log my details into a File.
Do any one know how to change the Textfile path of the microlog.txt created in the SD Card while using microlog4android.
or suggest me with anyother good logging method.

A: You can use the Log4j to add logs to your project
check here for details LOG4J in Android

A: Instead of using the microlog you can simply use the log4j
the complete tutorial is here