text:
Q: Java generics on method Might be a dumb question but I would like to ask how to make this possible in Java. I have an interface that has a method with the following signature
public <ComponentType> void attachFacilitiesTable(ComponentType comp);

On my concrete implementation I would like override it to something like:
public void attachFacilitiesTable(Node comp);

Thanks
Regards,
Ezekiel

A: If I understand correctly, ComponentType is a base class, and Node is something that extends it?
If it is so, then I think this is the syntax you are looking for:
public <T extends ComponentType> void attachFacilitiesTable(T comp);

This way, you say, T is a generic type that must extend from ComponentType.
Your example is equivalent to
public <T> void attachFacilitiesTable(T comp);

Where T is a type, without any restrictions. You are just using a different "variable" name, which, although named ComponentType, doesn't have anything to do with the class named ComponentType.


text:
Q: Showing that ideals are principal in ring of integers of cubic field
Let $K = \mathbb{Q}(\sqrt[3]{6})$. Factorise $\langle p \rangle$ into prime ideals in $\mathcal{O}_K$ for $p = 2, 5, 13$, checking
  that the factors are principal.

I used the Dedekind-Kummer Theorem to get the factors, but I haven't been able to show that all of them are principal. I've managed to do the factors of $\langle 2 \rangle, \langle 5 \rangle$ using some difference of cubes stuff, but I'm not sure how one would find generators for the factors of $\langle 13 \rangle$. For example, $\langle 13, -2+\sqrt[3]{6} \rangle$ (the others have $-7,-12$ instead of $-2$; I hope these are correct). I suspect it's something relatively simple but I can't see it as none of the obvious ones like $-2+\sqrt[3]{6}$ or $11+\sqrt[3]{6}$ seem to work. Help would be appreciated.

A: The ideal $\langle13\rangle\subset\mathcal{O}_K$ is itself prime because $X^3-6$ is irreducible over $\Bbb{F}_{13}$, which is easily seen by checking that it has no roots in $\Bbb{F}_{13}$. In particular, to answer your question, the unique factor $\langle13\rangle$ is principal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: R data.table reshape data I reshape data using data.table.
library(data.table)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))
market
#     stkcd type roa2013 roa2014 lev2013 lev2016
# 1:     1    1       2       4       6       8
# 2:     2    0       3       5       7       9
melt(market,
     measure.vars = patterns("^roa", "^lev"),
     variable.name = "year",
     value.name = c("roa","lev"))
#     stkcd type year roa lev
# 1:     1    1    1   2   6
# 2:     2    0    1   3   7
# 3:     1    1    2   4   8
# 4:     2    0    2   5   9

This is how the final data should look like.
#     stkcd type year roa lev
# 1     1    1 2013   2   6
# 2     1    1 2014   4  NA
# 3     1    1 2016  NA   8
# 4     2    0 2013   3   7
# 5     2    0 2014   5  NA
# 6     2    0 2016  NA   9

Does anybody have any good ways for it?
Thanks.

A: We can do this easily with splitstackshape.   Create a delimiter between the numeric and non-numeric part in the columns of interest, then use merged.stack to reshape into 'long' and change the '.time_1` column name to 'year'
library(splitstackshape)
names(market) <- sub("(\\d+)", "_\\1", names(market))
res <- merged.stack(market, var.stubs = c("roa", "lev"), sep="_")
setnames(res, ".time_1", "year")
res
#   stkcd type year roa lev
#1:     1    1 2013   2   6
#2:     1    1 2014   4  NA
#3:     1    1 2016  NA   8
#4:     2    0 2013   3   7
#5:     2    0 2014   5  NA
#6:     2    0 2016  NA   9

A: 1.use reshape {stats},
library(data.table)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))

market[,`:=`(roa2016=NA,lev2014=NA)]
long <- reshape(market,
        idvar = "stkcd",
        varying = c("roa2013","lev2013",
                    "roa2014","lev2014",
                    "roa2016","lev2016"),
        sep = "",
        timevar = "year",
        direction = "long")
setorder(long,stkcd,year)
long
#     stkcd type year roa lev
# 1:     1    1 2013   2   6
# 2:     1    1 2014   4  NA
# 3:     1    1 2016  NA   8
# 4:     2    0 2013   3   7
# 5:     2    0 2014   5  NA
# 6:     2    0 2016  NA   9

2.str_extract str
library(data.table)
library(stringr)
market <- data.table(
  stkcd=c(1,2),
  type =c(1,0),
  roa2013=c(2,3),
  roa2014=c(4,5),
  lev2013=c(6,7),
  lev2016=c(8,9))
market
long <- melt(market,
             id.vars = c("stkcd","type"))
long[,`:=`(year=str_extract(variable,pattern = "[0-9]{4}"),
           vars=str_extract(variable,pattern = "[a-zA-Z]{1,}"))][,variable:=NULL]
long <- dcast(long, stkcd + type + year ~ vars, value.var = "value")
long
#     stkcd type year lev roa
# 1:     1    1 2013   6   2
# 2:     1    1 2014  NA   4
# 3:     1    1 2016   8  NA
# 4:     2    0 2013   7   3
# 5:     2    0 2014  NA   5
# 6:     2    0 2016   9  NA

...


text:
Q: getCheckedRadioButtonId() of RadioGroup returns 2131034181/2/3/4 as part of my application I have to create four radioButtons within a radiogroup and get the radio button clicked. I wrote the following code but my selectId attribute gives values  2131034181 when first option is selected and 2131034182 when second option is selected and so on, there's change in unit digit of value when 3 and 4 are clicked. Why is it so?
int selectId=rbg.getCheckedRadioButtonId();
RadioButton selected= (RadioButton) rbg.findViewById(selectId);

String selected_user = (String) selected.getText();

A: To get radiobutton,use findViewById from context instead of radiogroup,So change
RadioButton selected= (RadioButton) rbg.findViewById(selectId);
String selected_user = (String) selected.getText();

to
  RadioButton selected = (RadioButton)findViewById(selectId);
  String selected_user = selected.getText().toString();


text:
Q: How to click an image in a web page with selenium I am trying to click a button on the page ( https://www1.nseindia.com/products/content/equities/equities/eq_security.htm ) .
Background: I am not regular selenium user. Just trying to get some data from a website. Got to know about selenium from some help pages.
Some how i am not being able to click the "Get Data" button .
Here is my progress for the rest of the things which works fine.
url="https://www1.nseindia.com/products/content/equities/equities/eq_security.htm"

options = Options()
options.headless = False

browser = webdriver.Chrome(options=options, executable_path=r'/usr/bin/chromedriver')
browser.get(url)

select=Select(browser.find_element_by_id('dataType'))
select.select_by_value("priceVolumeDeliverable")

select=Select(browser.find_element_by_id('series'))
select.select_by_value("EQ")
#time.sleep(5)

select=browser.find_element_by_id('symbol')
select.clear()
select.send_keys("RELIANCE")

select=Select(browser.find_element_by_id('dateRange'))
select.select_by_value("3month")

I have tried the following to click "Get Data" .
submit_button = browser.find_element_by_xpath('//*[@id="submitMe"]')
submit_button.click()

browser.find_element_by_css_selector('.getdata-button').click()
browser.find_element_by_xpath("//button[@id='submitMe']").click();
browser.find_element_by_xpath('//a[img/@src="/common/images/btn-get-data.gif"]').click()
browser.find_element_by_id("get").click()
browser.find_element_by_id("submitMe").click()
browser.find_element_by_xpath("//div[@class='getdata-button']//div[@id='get']").click()

browser.find_element_by_css_selector('//*[@id="get"]').click()

browser.find_element_by_id("#get")
browser.execute_script("arguments[0].click();",browser.find_element_by_xpath('//input[@type="button" and @value="Get Results"]'))

Any suggestions friends ?

A: You can get data using requests and beautifulsoup. You can play with params to get data you need:
from bs4 import BeautifulSoup
import requests

headers = {
    'Accept': '*/*',
    'X-Requested-With': 'XMLHttpRequest',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
    'Referer': 'https://www1.nseindia.com/products/content/equities/equities/eq_security.htm',
}

params = (
    ('symbol', 'RELIANCE'),
    ('segmentLink', '3'),
    ('symbolCount', '2'),
    ('series', 'EQ'),
    ('dateRange', '3month'),
    ('fromDate', ''),
    ('toDate', ''),
    ('dataType', 'PRICEVOLUMEDELIVERABLE'),
)

response = requests.get('https://www1.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp',
                        headers=headers, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
rows = soup.select("tr")

for th in soup.select("th"):
    print(th.text)

for i in range(1, len(rows)):
    table_data = rows[i].select("td")
    for td in table_data:
        print(td.text)


text:
Q: Selecting data from Google App Engine datastore by field value I'm just staring off with GAE. So like many I'm used to standard SQL.
Typically when you want to select data that has a certain field value you use:
SELECT <columns> FROM <table> WHERE <column> = <wanted value>

Is the correct way to do this in GAE
<Model Class>.all().filter('<column> =', <wanted value>)

Or is there a more efficient way?
EDIT: Also I should note in this particular case I only want one result returned. So is there another command so that it doesn't keep looking after if finds a result?

A: Your code is pretty close to what you're looking for - it constructs a Query object which can be used to query the datastore.  To actually get a result, you'll need to execute the query.  To get a single result, you'll want to use the get() method:
result = <Model Class>.all().filter('<column> =', <wanted value>).get()

A: You probably want Model.gql('where column = :value', value=something) which returns a GqlQuery upon which a GqlQuery.get() returns a single item.


text:
Q: What Are the Possible Ways That URL Can Be Redirected I inherited a small web-project. It contains static HTML pages with some Javascript. One of these HTML pages contains a map with different areas of the map linked to various external pages. Here is an example of such a link. The custom fields are implemented using jQuery to make the map work:
   <area target="_blank" href="http://example.com" shape="poly" coords="212,367,226,373,227,373,226,379,224,380,224,383,227,383,227,384,229,391,230,391,230,395,231,395,231,396,239,396,239,397,243,398,235,429,249,432,241,468,206,460,210,444,211,444,211,440,212,440,212,437,213,437,213,434,214,434,214,430,215,430,215,426,216,426,218,416,219,416,219,415,222,415,222,416,225,415,223,400,219,399,218,394,219,394,219,390,218,390,218,388,217,388,216,385,210,381,212,380,211,378" />

Now, when this link is clicked, for 10 seconds there appears a redirect page which then redirects to http://example.com. The problem is that I cannot find where the re-direct occurs to eliminate it. I have scoured the Javascript and HTML files to no avail. I am suspecting that there may be some Apache re-directs setup.
The question is how else could this re-direct be implemented? Where else can I look?


text:
Q: Magento 1 vs Magento 2. Difference between solutions offered by Magento 1 and Magento 2 when is comes to web APIs
*

*Specific on the area of web APIs.

*Does Magento 2 offer something that Magento 1 does not.

*Are there any problems with Magento 1 Web APIs that Magento 2 has fixed

*What are the main differences between Magento 1 Web APIs and Magento 2 Web APIs

I've read the docs found here, found no obvious (or any other for that matter) differences

*

*https://devdocs.magento.com/guides/m1x/api/rest/introduction.html

*https://devdocs.magento.com/guides/v2.2/get-started/bk-get-started-api.html

A: Web-based APIs (REST and SOAP) is fully improved in Magento 2. In M2, Using Service Contract API and web both are using the same functionality to access any resource. You can check Architectural diagrams to get more understanding about the flow.
You can also check M2 overview of the Web API blog post.
Some Major difference Between M1 API and M2 API:

Source: inviqa: Magento 2 tutorial: an overview of the Web API Post


text:
Q: how to install filezilla on CentOS? I downloaded FILEZILLA from https://filezilla-project.org/download.php.Now how to install this on CentOs,please suggest me.

A: You need to first download and install epel-release package from here..
http://fedora.mirrors.pair.com/epel/6/i386/repoview/epel-release.html
then you can install by typing yum install filezilla
Thanks..

A: 100% working solution is here:
the question is very old.. but i m posting answer so that anyone else struggling to install fileZilla on centOS 6 or 5 may get help.
this works for me on centOS6.5 goto below link and follow the instruction:
note before following the instruction run this command on terminal:
su
sudo -i
cd /tmp
now follow the instruction from below link.
http://www.servermom.org/2-cents-tip-how-to-enable-epel-repo-on-centos-6-and-5/894/
then install filezilla like this:
yum install filezilla
and you done.
to start fileZilla goto Applications->Internet->FileZilla

A: For Cent OS 7
sudo yum -y install epel-release
sudo yum -y install filezilla

Go to Application > Internet > Filezilla


text:
Q: Embedding Youtube playlist but starting from random video I've done plenty of searching but can't find a olsution so far...
I have a Youtube playlist. I want to embed it on a website. But instead of always starting at the first video, I want it to start at either a random video, or a at least a specific video (which I can randomly select with server side code).
I have looked at the options for the iframe embed URL and can't see a parameter that allows me any control over this. Is it possible to do?
Otherwise I presume I would need to do something in JavaScript with the API. Can someone paste or point me to some example code that I could use to accomplish this as I haven't used the Youtube API before?

A: Based on the Greg answer I make this code, and works!
`
<?php
$min=1;  $max=8;  //the number of videos on your playlist
?>
<object width="746" height="413"><param name="movie" value="http://www.youtube.com/p/CAAA1242CA3E37B4?version=3&hl=es_ES&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<?php
//in index the script randomize the numbre between $min $max
echo "
<embed src=\"http://www.youtube.com/p/CAAA1242CA3E7B4?version=3&hl=es_ES&fs=1&index=".rand($min,$max)."\" type=\"application/x-shockwave-flash\" width=\"746\" height=\"413\" allowscriptaccess=\"always\" allowfullscreen=\"true\">
</embed>
";
?>
</object>
`

A: Generate a random number on your server and then use the index parameter in the url.  Here's an example where the playlist will start on the 7th item by adding index=7.
<iframe width="560" height="315" src="http://www.youtube.com/embed/videoseries?list=PL9C5815B418D1508E&index=7" frameborder="0" allowfullscreen></iframe>

The other option is to use the js api, and call loadPlaylist and include the index argument.
https://developers.google.com/youtube/js_api_reference#loadPlaylist
**Edit: Since Google introduced YouTube's 3.0 API, the index parameter is now zero-based. Therefore, if we wanted to start at the 7th video, we'd modify the example above using &index=6 instead of &index=7.
(Link: https://developers.google.com/youtube/iframe_api_reference#Queueing_Functions_for_Playlists)

A: In my context I slightly changed the coding by Mauricio:
 index=<?php print(rand(1,50)) ?>

(I put min and max in here directly)

A: You shoud check http://code.google.com/p/swfobject/
or http://popcornjs.org/ .
here is an example using PopCornJS:
http://www.seuratt.net/rhi-popcorn/demos/videojs-playlist.html


text:
Q: Querying for multiple columns with Gorm My db includes the following columns, "model_package" and "model_variant". I try to query the db with Gorm by specifying both of these columns inside .Select(), however, I keep getting a scan error. Normally, when I select a single column (i.e. .Select("model_package")), it returns to an array(slice) containing all the values, so I assumed it should return to a two-dimension array(slice) when I select multiple columns like in my code below.
My goal is to combine both fields into a string. For example, if a row in db has the following values "model_package" : "pkg1" and "model_variant" : "var1", then I want to create this string "pkg1_var1". How can I construct the correct query to get both values for each row on the db.
My code:
func (s *store) ListAllModelNames() ([][]string, error) {
    var modelNames [][]string
    result := s.db.Table(mfcTable).Select("model_package", "model_variant").Scan(&modelNames)
    if result.Error != nil {
        return nil, result.Error
    }
    return modelNames, nil
}

Error:
sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer; sql: Scan error on column index 0, name "model_package": destination not a pointer

A: A couple of options you can try out:
Option 1 - create a view model for your SELECT query and return that to do with it what you want.
type ModelName struct {
   ModelPackage string
   ModelVariant string
}

func (s *store) ListAllModelNames() ([]ModelName, error) {
    var modelNames []ModelName
    result := s.db.Table(mfcTable).Select("model_package", "model_variant").Scan(&modelNames)
    if result.Error != nil {
        return nil, result.Error
    }
    return modelNames, nil
}

Option 2 - do the concatenation with the CONCAT() function within your SELECT query.
func (s *store) ListAllModelNames() ([]string, error) {
    var modelNames []string
    result := s.db.Table(mfcTable).Select("CONCAT(model_package, "_", model_variant)").Where("model_package IS NOT NULL AND model_variant IS NOT NULL").Scan(&modelNames)
    if result.Error != nil {
        return nil, result.Error
    }
    return modelNames, nil
}


text:
Q: wpf datagrid drag row on Icollectionview which bind to collection I have a datagrid like this
        _productsPosition = new ObservableCollectionEx<NotifiedPositionInfo>();
        _itemSourceList = new CollectionViewSource() { Source = _productsPosition };
        _itemSourceList.Filter += new FilterEventHandler(FilteringProduct);
        PositionsGrid.ItemsSource = _itemSourceList.View;

and when I try to drag row on this datagrid, i can obtain the index of row on the collectionview. But this index can not help me get the same element in the collection _productsPosition, because the collectionView was modified by the filter.
Therefore, i have a question that how can i just move elements on the collectionview but not _productsPosition. Something like this which throws exception:
        NotifiedPositionInfo prev_position = PositionsGrid.ItemContainerGenerator.Items[_prevRowIndex] as NotifiedPositionInfo;
        PositionsGrid.Items.RemoveAt(_prevRowIndex);
        PositionsGrid.Items.Insert(index, prev_position);

the content of exception is:
Unhandled Exception: System.InvalidOperationException: Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
at System.Windows.Controls.ItemCollection.CheckIsUsingInnerView()
at System.Windows.Controls.ItemCollection.RemoveAt(Int32 removeIndex)
Working sample:
    <DataGrid Name="PositionsGrid" Background="AliceBlue" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding}"
              AllowDrop="True" GridLinesVisibility="Horizontal" HorizontalGridLinesBrush="#FFDEDEDE">
        <DataGrid.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#FF0096FD"/>
        </DataGrid.Resources>
        <DataGrid.Columns>
            <DataGridTextColumn Header="Product Name" Width="130" IsReadOnly="True" Binding="{Binding ProductName}"/>
            <DataGridTextColumn Header="Positions" Width="*" IsReadOnly="True" Binding="{Binding Position}"/>
        </DataGrid.Columns>
    </DataGrid>

Drag function:
    PositionsGrid.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(positionsGrid_PreviewMouseLeftButtonDown);
    PositionsGrid.Drop += new DragEventHandler(positionsGrid_Drop);

    private bool isTheMouseOnTargetRow(Visual target, GetDragDropPosition pos)
    {
        try
        {
            Rect posBounds = VisualTreeHelper.GetDescendantBounds(target);
            Point theMousePos = pos((IInputElement)target);
            return posBounds.Contains(theMousePos);
        }
        catch (Exception)
        {
            return false;
        }
    }

    private DataGridRow getDataGridRowItem(int index)
    {
        if (PositionsGrid.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
            return null;

        return PositionsGrid.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
    }

    private int getDataGridItemCurrentRowIndex(GetDragDropPosition pos)
    {
        int curIndex = -1;
        for (int i = 0; i < PositionsGrid.Items.Count; i++)
        {
            DataGridRow item = getDataGridRowItem(i);
            if (isTheMouseOnTargetRow(item, pos))
            {
                curIndex = i;
                break;
            }
        }
        return curIndex;
    }

    private int _prevRowIndex = -1;

    private void positionsGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        _prevRowIndex = getDataGridItemCurrentRowIndex(e.GetPosition);

        if (_prevRowIndex < 0)
            return;

        PositionsGrid.SelectedIndex = _prevRowIndex;

        NotifiedPositionInfo selected_positionInfo = PositionsGrid.Items[_prevRowIndex] as NotifiedPositionInfo;

        if (selected_positionInfo == null)
            return;

        DragDropEffects dragdrop_effects = DragDropEffects.Move;

        if (DragDrop.DoDragDrop(PositionsGrid, selected_positionInfo, dragdrop_effects) != DragDropEffects.None)
            PositionsGrid.SelectedItem = selected_positionInfo;
    }

    private void positionsGrid_Drop(object sender, DragEventArgs e)
    {
        if (_prevRowIndex < 0)
            return;

        int index = this.getDataGridItemCurrentRowIndex(e.GetPosition);

        if (index < 0)
            return;

        if (index == _prevRowIndex)
            return;

        if (index == PositionsGrid.Items.Count - 1)
        {
            MessageBox.Show("This row-index cannot be used for Drop Operations");
            return;
        }

        NotifiedPositionInfo prev_position = PositionsGrid.ItemContainerGenerator.Items[_prevRowIndex] as NotifiedPositionInfo;
        PositionsGrid.Items.RemoveAt(_prevRowIndex);
        PositionsGrid.Items.Insert(index, prev_position);
    }

A: ok, finally i solve this problem with a not clever operation. I reset the specific element's position in the collection while it is dragged on the collectionview. Besides, i change the sorting event make sure the collectionView will not controll the display which binds to the collection.


text:
Q: Use JSON attributes in a n-tuple QuerySet result in views.py in Django I am newbie in django (and python) and I having trouble accessing a JSON attribute for a Django QuerySet result. The code generating the QuerySet is the following:
 species_list = Iris.objects.values("species").annotate(total=Count("species"))
 species = json.dumps(species_list,cls=DjangoJSONEncoder)

The JSON output from species looks like the following:
 [{"total": 50, "species": "setosa"}, {"total": 50, "species": "versicolor"}, {"total": 50, "species": "virginica"}]

What I want to do is to separate the "total" attribute values and "species" values to use for plotting purposes but inside the views.py for n3dv. i.e
xdata = species['species']
ydata = species['total']

But I get the error:
Django Version:  1.6.5
Exception Type:  TypeError
Exception Value: string indices must be integers, not str

How do I properly extract this values?

A: species is a list, which contains dictionaries. The list as a whole doesn't have a species key. You'd need to iterate through the list and access that key on each of the dictionaries inside it.


text:
Q: ViewPager and TabLayout in Fragment. setAdapter on a null object reference I'm trying to add viewPager in Fragment. But when I start my application I receive this:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.ViewPager.setAdapter(android.support.v4.view.PagerAdapter)' on a null object reference

My MainFragment:
public class YourTasksFragment extends Fragment {

@Bind(R.id.viewpager)
ViewPager viewPager;

@Bind(R.id.tabs)
TabLayout tabLayout;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
    return v;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
    adapter.addFragment(new OneFragment(), "ONE");
    adapter.addFragment(new TwoFragment(), "TWO");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> fragmentList = new ArrayList<>();
    private final List<String> fragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager childFragmentManager) {
        super(childFragmentManager);
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        fragmentList.add(fragment);
        fragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentTitleList.get(position);
    }
}
}

Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill"/>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"  />

A: You forgot to add Butterknife.bind(this, v) on the method onCreateView.
It's required in order to bind the views.
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
    Butterknife.bind(this,v);
    return v;
}

A: You forgot to setup Butterknife in the onCreateView(), therefore the variable is never initialized.
Do this:
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_your_tasks, container, false);
    Butterknife.bind(this,v);
    return v;
}

Hope it helps!


text:
Q: How to check the dtypes of all columns in a df are same or not in python? I am new to Pandas, I wanted to check if all the columns of df are same or not. However, I tried to do but though I Am getting an error
print(df.columns)
Index(['age', 'car', 'car_name'], dtype='object')

where age, car is int, float and car_name is an object
for i in df:
    if df[i].dtypes == int or df[i].dtypes == float:
        print('yes')
    else:
        print('no')
this gives:
yes
yes
no

but what I want is to give on the whole, like if  all column have int or float it should print yes else no. (by using if else condition)
excepted output:
for i in df:
        if all column of df == int or all column of df == float:
            print('yes')
        else:
            print('no')
output: 'No'

A: def is_same(df):
    # this method returns true if all types are same, else returns false
    no_of_types = len(df.dtypes.unique())
    is_same = no_of_types == 1
    return is_same

diff_types1 = pd.DataFrame({"a": [1,2,3], "b": [2,3,4], "c": ["A", "C", "E"]})
diff_types2 = pd.DataFrame({"a": [1,2,3], "b": [2.0,3.1,4.2], "c": [2, 4, 5]})
same_types = pd.DataFrame({"a": [1,2,3], "b": [2,3,4], "c": [2, 4, 5]})
same_types2 = pd.DataFrame({"a": ["A", "C", "E"], "b": ["A", "C", "E"], "c": ["A", "C", "E"]})

is_same(diff_types1)
# False

is_same(diff_types2)
# False

is_same(same_types1)
# True

is_same(same_types2)
# True

A: Or perhaps check whether where are more than 1 dtypes:
df.dtypes.nunique()>1

Will return True if your df has different dtypes.

A: You may use
df.dtypes.drop_duplicates().shape[0]== 1

Here's an example:
>>> import pandas as pd
>>> df = pd.DataFrame()
>>> df['a'] = 1, 2, 3
>>> df['b'] = 4, 5, 6
>>> df.dtypes.drop_duplicates().shape[0]== 1
True
>>> df['b'] = 0.1, 0.2, 0.3
>>> df.dtypes.drop_duplicates().shape[0]== 1
False

A: from pandas.api.types import is_numeric_dtype
def is_int_or_float(df):
    # this method returns true if all types are numeric
    is_numeric_types = sum([is_numeric_dtype(x) for x in df])
    return is_numeric_types

diff_types1 = pd.DataFrame({"a": [1,2,3], "b": [2,3,4], "c": ["A", "C", "E"]})
diff_types2 = pd.DataFrame({"a": [1,2,3], "b": [2.0,3.1,4.2], "c": [2, 4, 5]})
same_types = pd.DataFrame({"a": [1,2.2,3], "b": [2,3,4], "c": [2, 4, 5]})
same_types2 = pd.DataFrame({"a": ["A", "C", "E"], "b": ["A", "C", "E"], "c": ["A", "C", "E"]})

print(is_same(diff_types1))
# False

print(is_same(diff_types2))
# False

print(is_same(same_types1))
# True

print(is_same(same_types2))
# True

A: There are many approaches to solve this. Here is one solution:
all(x == df.dtypes[0] for x in df.dtypes)

It returns true if all the columns have the same data type.
This single liner first creates a list of booleans by comparing all the entries in df.dtypes to the data type of the first element. The all() function returns true if all the entries are True


text:
Q: How to create a HTML form from a Json
I'm using Activiti and I have a form like this:

When I use Rest API, that form will be returned with Json like this:
{
    "formKey": null,
    "deploymentId": "21151",
    "processDefinitionId": null,
    "processDefinitionUrl": null,
    "taskId": "21159",
    "taskUrl": "http://localhost:8080/activiti-rest/service/runtime/tasks/21159",
    "formProperties": [
        {
            "id": "firstName",
            "name": "First Name",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": true,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "lastName",
            "name": "Last Name",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "phoneNumber",
            "name": "Phone Number",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "dateTime",
            "name": "Date Time",
            "type": "date",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": "dd/MM/yyyy",
            "enumValues": []
        },
        {
            "id": "city",
            "name": "City",
            "type": "enum",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": [
                {
                    "id": "0",
                    "name": "TPHCM"
                },
                {
                    "id": "1",
                    "name": "HN"
                }
            ]
        }
    ]
}

I want to convert this Json into a Html Form with that inputs in Json result. I search many post about using library but I can't make my Json result like that library required. So any way to do this?
Thank you very much!

A:     **Store your json response in a variable.eg:var json;**
As the json is getting from a Rest API,it can be stored in a variable.So that we can use that to proceed the form creation.We can iterate the formProperties to create the form inputs.
    <!DOCTYPE html>

    <form id="form">
      <input type="submit" name="mysubmit" value="Submit" />
    </form>

A: First a comment, you really should be showing in your question what you have tried so far and elaborate on what specifically you are having trouble with.
This technique uses DOM objects to create the form. It uses a document fragment to limit the number of actual updates to the DOM. Hopefully the comments in the code are self explanatory.

//Just for demo purposes - this would be your API Call
var data = getData();

//Get the bit we need
var formData = data.formProperties;

//Call our function to carete the form
createForm(formData);

//The magic
function createForm(data){
  //Create a fragment so we aren't constantly updating the DOM
  var container = document.createDocumentFragment();

  data.forEach(function(formProp){
  //Create a row div with a class
  var rowDiv = document.createElement("div");
  rowDiv.classList.add("rowDiv");

  //Create a label
  var label = document.createElement("label");
  label.setAttribute("for", formProp.id);
  label.innerHTML = formProp.name;

  //Create a form element
  var formElement = document.createElement(formProp.type == "enum" ? "select" : "input");
  //Set it's properties
  formElement.id = formProp.id;
  formElement.name = formProp.id;
  formElement.required = formProp.required;
  formElement.readOnly = !formProp.writable;

  //Do some stuff if the form element is required
  if(formProp.required){
    rowDiv.classList.add("required");
  }

  //Do stuf for not select
  if(formProp.type != "enum"){
    formElement.value = formProp.value;

    if(formProp.type == "date") {
      formElement.type = "date";
    }
    //Add any other types here
    else {
      //falback to text
      formElement.type = "text";
    }
  }
  //Add the enum values
  else {
    formProp.enumValues.forEach(function(formEnum){
      var opt = document.createElement("option");
      opt.value = formEnum.id;
      opt.text = formEnum.name;
      opt.selected = formEnum.id == formProp.value;
      formElement.appendChild(opt);
    });
  }

  //Add label and element to div
  rowDiv.append(label);
  rowDiv.append(formElement);

  //Apend div to fragment
  container.appendChild(rowDiv);
  });
  //Add fragment to form
  document.getElementById("mainForm").appendChild(container);
}

function getData(){
var data = {
    "formKey": null,
    "deploymentId": "21151",
    "processDefinitionId": null,
    "processDefinitionUrl": null,
    "taskId": "21159",
    "taskUrl": "http://localhost:8080/activiti-rest/service/runtime/tasks/21159",
    "formProperties": [
        {
            "id": "firstName",
            "name": "First Name",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": true,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "lastName",
            "name": "Last Name",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "phoneNumber",
            "name": "Phone Number",
            "type": "string",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": []
        },
        {
            "id": "dateTime",
            "name": "Date Time",
            "type": "date",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": "dd/MM/yyyy",
            "enumValues": []
        },
        {
            "id": "city",
            "name": "City",
            "type": "enum",
            "value": null,
            "readable": true,
            "writable": true,
            "required": false,
            "datePattern": null,
            "enumValues": [
                {
                    "id": "0",
                    "name": "TPHCM"
                },
                {
                    "id": "1",
                    "name": "HN"
                }
            ]
        }
    ]
}
return data;
};
/*Add some styling for required*/
.required::after {
  content: " *";
  color:#F00;
}

.rowDiv {
  padding:2px;
}

.rowDiv label {
  display:inline-block;
  width: 20%;
}
<form id="form">
  <fieldset id="mainForm">
  </fieldset>
  <fieldset id="buttons">
  <input type="submit" value="Complete Task">
  <input type="reset" value="Reset From">
  </fieldset>
</form>


text:
Q: converting the Picklist to Read only field in Visual Force Hi I have a Field on VF
    <apex:inputfield value="{!opObj.Product_Family__c}" required="false"  rendered="{!!isEdit}" onkeypress="return handlerKeyPress(event);"/>
 <apex:outputfield value="{!opObj.Product_Family__c}"   rendered="{!isEdit}"/>

changed it to
<apex:outputlabel value="{!opObj.Product_Family__c}" onmousemove="return handlerKeyPress(event);"  />

but the field value is not being displayed.
also using this field value i am having another lookup field to pull related records. that is also not working. earlier it used to work fine.
What went wrong?

A: According to what you have described in your comment. I believe you simply need to change the rendering logic in your original code:
 <apex:inputfield value="{!opObj.Product_Family__c}" required="false"  rendered="{!isEdit}" onkeypress="return handlerKeyPress(event);"/>
 <apex:outputfield value="{!opObj.Product_Family__c}"   rendered="{!!isEdit}"/>

This will work as a readonly field when it is not edit mode and an input field when it is.

A: Atrribute html-disabled="true" solved the issue.


text:
Q: Socket.io handle receiving synchronously For some reason, socket.io is being such a pain when it comes to this. I've been at this problem for around an hour and their is not much information anywhere online, because JavaScript is synchronous it is really hard to find information on this event.
So basically I'm receiving disconnect's in socket.io like any other programmer would, as such:
client.on('disconnect', function() {
    console.log("Client left");
    removeClient(client);
    console.log("Client completely removed");
  });

Now, here is the problem. Users disconnect and it works fine, unless of course multiple users disconnect right after eachother. I used debug messages and this is what's happening.
Scenario: We have two users leaving at the same time. When a user leaves, it runs 5 different functions on the server.
USER1 leaves:
function 1.
function 2.
function 3.
USER2 LEAVES:
function 1.
function 2.
function 3.
function 4.
function 5.
User 2 has successfully completely left
function 4.
function 5.
User 1 has successfully completely left
Problem: For some reason while user 1 is being removed, it will receive a disconnect from user 2 then start removing user 2. I'm trying to make it so that if user 2 disconnects while the server is removing user 1, it will wait until the 5 functions for user 1 are completed before executing them for user 2.
Edit: the title says "receiving" rather than disconnects because it will do this for any event.

A: It's pretty hard to suggest a code fix when you don't show the relevant code, but if according to your comment, the issue is that your array gets changed out from under you while you're in the middle of iterating on it, then the typical way to handle that is to make a temporary copy of the array for purposes of iterating it.  Your copy won't get changed then.  If you need to check if a socket might have been already removed from the original array, then you can check for that too.
Here's the idea:
// suppose your array of sockets is in socketList

// make a copy of the sockets array
var copyList = socketList.slice(0);
var socket;

for (var i = 0; i < copyList.length; i++) {
    socket = copyList[i];
    // make sure this socket is still in the original array
    if (socketList.indexOf(socket) !== -1) {
        // do your operation here on socket
    }
}

If you're using an object instead of an array to store your list of sockets, then you can prefetch the keys with Object.keys() and iterate those keys, checking to see if the key is still in the object when it comes time to process it.
FYI, I haven't proven this myself, but the MDN documentation for .forEach() suggests that using it to iterate an array is also safe from concurrent modifications.  Since we don't have the exact code, I don't know exactly how it behaves so I'd probably rather use my own copy as above.

A: A possible cause of this could also be that you have async code which is infact running synchronously. This means that you have to go up and down the call stack before any other handlers can be called. You can force the stack to unwind and then resume using process.nextTick but should probably be aware of the performace consequences since I think there is a limit of how many callbacks can happen on one cycle while the rest will queue up.
var callback = function (err, data) {
   // will now be next on the stack
   process.nextTick(function() {
        // will be on a clean(ish) stack
   });
}
a(callback); // should be async but is sync


text:
Q: Include custom file into header with org-mode I have a LaTeX file with some directives for my TeX documents (\usepackage and such things). Now I want to reuse this file in different org-mode files. I know I can include files with #+include: 'path/to/some/file.tex', but this puts the content of the file after \begin{document}.
Can I somehow include a file into the header?
As suggested, here an example:
A template.tex file that holds the header:
\documentclass[a4paper]{customClass}
\usepackage{etex}
\title{Some Title}
\supervisor{Someone}

As also shown here, this uses a custom document class, which is one of the reasons why I just want to be able to include it.
Then I have a file which contains all the content (content.org):
#+INCLUDE: template.tex

* Chapter 1
** Subchapter 1
   Some content
** Subchapter 2
   More content

Which currently outputs (content.tex):

\documentclass[11pt]{article}
\usepackage[latin1]{inputenc}
% a lot more org-mode standard header stuff
% ...

\begin{document}

\maketitle

\setcounter{tocdepth}{3}
\tableofcontents
\vspace*{1cm}

% my template.tex file
% not where I wanted it
\documentclass[a4paper]{customClass}
\usepackage{etex}
\title{Some Title}
\supervisor{Someone}

\section{Chapter 1}
% rest of the document
% ...

\end{document}

So in short: I want to reuse my template.tex file in a few org documents to have consistent formatting. Is this possible?

A: While I do not know a way to do this with a LaTeX file, you can use #+SETUPFILE: file (http://orgmode.org/manual/In_002dbuffer-settings.html) to include an external org file in exporting. Then you can use #+LaTeX_HEADER: in the external org file.
For example, with the following in content.org:
#+SETUPFILE: template.org

and with the following in template.org:
#+LaTeX_CLASS: customClass
#+LaTeX_CLASS_OPTIONS: [a4paper]
#+LaTeX_HEADER: \usepackage{etex}
#+LaTeX_HEADER: \title{Some Title}
#+LaTeX_HEADER: \supervisor{Someone}

When you export content.org, they will be included as a part of the preamble of content.tex.

A: The latex header org uses for export is stored in org-format-latex-header, which you can modify as you like.  According to the help:

It is imperative that this header make sure that no page number
  appears on the page.  The package defined in the variables
  org-latex-default-packages-alist' andorg-latex-packages-alist'
  will either replace the placeholder "[PACKAGES]" in this
  header, or they will be appended.

A: You can create file local variable in your org file to disable default header,then there is no it's own header outputs which confuses latex code that you want.
# Local Variables:
# org-latex-default-packages-alist: nil
# org-latex-with-hyperref: nil
# org-latex-packages-alist: nil
# End:


text:
Q: addition within sum case when
How to sum all the customers in DS01,02,03 into DS?

select
sum(case when Ticket='DS01' OR 'DSO2' OR 'DS03' THEN customer ELSE 0 END) AS DS
sum(case when Ticket='MSO2' OR 'MS03' THEN customer ELSE 0 END) AS MS
from table
group by ticket
unsure how to bring in addition condition within "THEN and ELSE " part

A: You can use left():
select left(ticket, 2), sum(customers)
from t
group by left(ticket, 2);

Or, if you want explicit lists:
select (case when ticket in ('DS01', 'DS02', 'DS03') then 'DS'
             when ticket in ('MS02', 'MS03') then 'MS'
        end), sum(customers)
from t
group by 1;


text:
Q: Using the POST Method with HTML Anchor Tags I am certain the answer will be 'NO', but I wanted to ask anyway just
incase I have missed something.
Everyone knows that one pass data to a page in an anchor tag by using
the GET method:

What I am wondering is if there was a way to do the same thing, but use
the POST Method instead?
My purpose in doing so is to keep the URLs the user sees clean by not
putting anything in them that they do not need to see.
This has nothing to do with security concerns as I already know there
would be ways to obtain the data being passed.
If the answer is indeed no, then what methods do people use to pass data
when there is a desire to keep the URLs clean? Cookies? Something else?
and how to deal with the scenarios when the URL length exceeds the permissible GET request length
I am facing this issue while implementing sorting/pagination with displaytag, all the request parameters are appending in the sort/pagination url which is more then the permissible length of the GET request.

A: This behaviour is specific to display tag library. It allows for easily bookmarkable search results. If you really intend to change this to make use of POST, then you'd need to rewrite the display tag library or bring in some jQuery to manipulate the links.
The remnant of your questions boils nowhere. If you want GET (idempotent requests, bookmarkable URLs, searchbot-crawable URLs, etc), then use GET. If you want POST (non-idempotent requests, non-bookmarkable URLs, non-crawlable URLs, etc), then use POST.
Usually, POST is mandatory when the request can modify the data in the server. Think of a SQL INSERT, UPDATE, DELETE, etc. You certainly won't make this kind of requests GET. Imagine that you've a table with all "delete row" links which do GET and then a searchbot comes along...

A: You can use javascript. On onclick of link do form.submit
The only way I know of to deal with lenghty URL is to instead use POST.

A: You could do something like this:
<form method="post" action="target.html">
  <input type="hidden" name="name" value="value" />
  click here
</form>

A: You may create a temporary form and submit it while onclick event of  tag.

A: It will work as post ,the name value can be through anchor  tag and value of name="" can be access to $_POST[] globl var


text:
Q: How do I call REST API with bearer token from an Android app? I'm new in Android and programming as well. I would like to build an Android app with user login and registration. What's the easiest way to make REST API calls on Android for a beginner?
I also have to pass a bearer token in the header and two parameter in body (name and password).

A: You can use retrofit

Retrofit is a REST Client for Java and Android. It makes it relatively
easy to retrieve and upload JSON (or other structured data) via a REST
based webservice. source

also check this answer


text:
Q: What's the absolute largest paper size permissible with pdflatex? I've had occasion to typeset extraordinarily large matrices, which I didn't seriously expect anyone to expect in detail (without a computer) or print, but I needed it to be obvious that they were completely explicit and written down somewhere.
By trial and error, I found a really large paper size that would compile (about 5.5m) in pdflatex and fit my matrices on a reasonable number of sheets. (I used the geometry package to choose custom page sizes.) But it would have been easier if I'd been able to find out:

What are the limitations on paper sizes in pdflatex?

A: From the immensely useful TeX by Topic:

\maxdimen 16383.99999pt; the largest legal dimension.

and

Internally TEX works with multiples of a smallest dimension: the scaled point. Dimensions larger
  (in absolute value) than 2^30 − 1sp, which is about 5.75 metres or 18.9 feet, are illegal.

Knuth delivered a beautiful extended dig at "modern" software development practices at the 2010 TUG meeting, during the early part of which he referred to the value of \maxdimen.  I can't work out if he was serious when he suggested it had been a mistake to fix the largest dimension in TeX at this rather small value.

Perhaps it is worth mentioning that as far as I know, pdflatex does not apply any more restrictive limits than TeX itself for this application.  So the limitation that is relevant here is the internal TeX one.

A: Since you mention pdfTeX, I assume that you want to produce PDFs. The PDF norm mentions this "architectural limit":

The minimum page size should be 3 by 3 units in default user space; the maximum should be 14,400 by
  14,400 units. In versions of PDF earlier than 1.6, the size of the default user space unit was fixed at 1⁄72
  inch, yielding a minimum of approximately 0.04 by 0.04 inch and a maximum of 200 by 200 inches.
  Beginning with PDF 1.6, the size of the unit may be set on a page-by-page basis; the default remains at 1/
  72 inch.

200 inches are 508 cm. While this limit is probably not enforced by any PDF-producing program in the TeX world, I'd advise against exceeding it.


text:
Q: What is the relation between energy density ($\Omega$) and the number density of neutrinos ($n$)? What is the numerical relation between energy density ( $\Omega_\text{s}, \Omega_\alpha$), and the number density of neutrinos (sterile - $n_s$ , active - $n_\alpha$)?

Background info that might help better understand my question:
This is based on an equation derived through the relationship of sterile neutrinos distribution function and the active neutrinos distribution function:
$$f_s = k \sin^2 2\theta f_\alpha \tag{1}$$
integrating in terms of momentum gives:
$$\int \frac{d^3 p}{(2\pi)^3} f_s= \int \frac{d^3 p}{(2\pi)^3} k \sin^2 2\theta f_\alpha \tag{2}$$
where $k$ is a numerical constant, $f_i$ is the distribution function of $i$ neutrinos and $\theta$ is the collision angle of neutrinos.
Based on the definition of number density, $n_i= \int \frac{d^3 p}{(2\pi)^3} f_i$ ,  we get:
$$\frac{n_s}{n_\alpha}= \gamma \tag{3}$$
where $\gamma = \frac{1}{n_\alpha}\int \frac{d^3 p}{(2\pi)^3} \sin^2 2\theta f_\alpha$
**I'm trying to connect this last equation to $\Omega$ but I need to understand the relation in  my question first. **

I've seen in the following article the following statement, based on $(4)$ below:
$$f_s = k f_\alpha \tag{4}$$
$f_s$ has the same functional form as $f_\alpha$ and therefore
$\Omega_s/ \Omega_\alpha = (m_s/m_\alpha) (f_s/f_\alpha)$.
I still don't understand where this equation was deduced from.

A: If I'm not mistaken, the quantities $\Omega$ represent the energy density of the corresponding particle relative to the critical density $\rho_\text{crit} = 3 H_0^2 m_\text{pl}^2$. Thus, to understand the claim, let's write down the number density
$$n_i = \int\frac{{\rm d}^3p}{(2\pi)^3}f_i\,.$$
Once whatever process is generating the particles shuts off, the number of species $i$ per co-moving volume is fixed as long as it doesn't decay. When the universe cools below the mass of the species, it becomes non-relativistic, and its energy denisty scales like $m_i n_i$. Therefore,
$$\Omega_i = \frac{m_i n_i}{\rho_\text{crit}}\,.$$
Now let's take the ratio of species for which we know $f_a\propto f_s$. Suppose that $\alpha \equiv f_a/f_s$ is the constant of proportionality. Then
$$\frac{n_a}{n_s} = \frac{\int\frac{{\rm d}^3 p}{(2\pi)^3}f_a}{\int\frac{{\rm d}^3 p}{(2\pi)^3}f_s} = \frac{\alpha\int\frac{{\rm d}^3 p}{(2\pi)^3}f_s}{\int\frac{{\rm d}^3 p}{(2\pi)^3}f_s} = \alpha\,.$$
Hence
$$\frac{\Omega_a}{\Omega_s} = \frac{m_a n_a}{m_s n_s} = \frac{m_a}{m_s}\alpha = \frac{m_a f_a}{m_s f_s}\,.$$


text:
Q: Selenium ChromeDriver explicit wait for visibility_of_element_located throws TimeOut exception when presence_of_element_located doesn't, for Select Please help me to understand why visibility_of_element_located throws TimeOut exception, especially for dropdown elements, but other elements are fine and calls to presence_of_element_located are fine also. I also tried scrolling to the element but this it would intermittently fail. I've attached the code that consistently reproduced the timeout for me. I'm running on MacOS, Version 93.0.4577.82 (Official Build) (x86_64). Thank you in advance!
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class TestCode():
  _email_create = (By.CSS_SELECTOR, '#email_create')
  _register_button = (By.CSS_SELECTOR, '#SubmitCreate')

  _title = (By.CSS_SELECTOR, '.radio-inline label')
  _first_name = (By.CSS_SELECTOR, '#customer_firstname')
  _last_name = (By.CSS_SELECTOR, '#customer_lastname')
  _email = (By.CSS_SELECTOR, '#email')
  _password = (By.CSS_SELECTOR, '#passwd')

  # date of birth
  _day = (By.CSS_SELECTOR, '#days')
  _month = (By.CSS_SELECTOR, '#months')
  _year = (By.CSS_SELECTOR, '#years')

  # address
  _first_name_address = (By.CSS_SELECTOR, '#firstname')
  _last_name_address = (By.CSS_SELECTOR, '#lastname')
  _company = (By.CSS_SELECTOR, '#company')
  _address = (By.CSS_SELECTOR, '#address1')
  _city = (By.CSS_SELECTOR, '#city')
  _state = (By.CSS_SELECTOR, '#id_state')

  def test_is_visible(self):
    driver = webdriver.Chrome()
    driver.get("http://automationpractice.com/index.php?controller=authentication&back=my-account#account-creation")
    driver.find_element(*self._email_create).send_keys("test+1@test.com")
    driver.find_element(*self._register_button).click();

    wait = WebDriverWait(driver, 20);
    wait.until(EC.visibility_of_element_located(self._title))
    wait.until(EC.visibility_of_element_located(self._first_name))
    wait.until(EC.visibility_of_element_located(self._last_name))
    wait.until(EC.visibility_of_element_located(self._email))
    wait.until(EC.visibility_of_element_located(self._password))

    #wait.until(EC.presence_of_element_located(self._day))
    wait.until(EC.visibility_of_element_located(self._day))
    wait.until(EC.visibility_of_element_located(self._month))
    wait.until(EC.visibility_of_element_located(self._year))

    wait.until(EC.visibility_of_element_located(self._first_name_address))
    wait.until(EC.visibility_of_element_located(self._last_name_address))
    wait.until(EC.visibility_of_element_located(self._company))
    wait.until(EC.visibility_of_element_located(self._address))
    wait.until(EC.visibility_of_element_located(self._city))
    wait.until(EC.visibility_of_element_located(self._state))

A: visibility_of_element_located: Returns the WebElement once it is located and visible.

*

*An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.

 expected_conditions.visibility_of_element_located((By.ID, "id_of_button_a"))

presence_of_element_located: Returns the WebElement if element is present on DOM and not even visible.

*

*An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.

expected_conditions.presence_of_element_located((By.ID, "id_of_button_a"))

In your case, the drop-down values are present on DOM but not visible so only you are getting TimeOutException


text:
Q: rancher-webhook pod does not exist in rancher deployment I am running a rancher instance on docker. I started getting certificate problems which prevent me to do any modifications or adding new users.
The problem is described here: https://githubhot.com/repo/rancher/rancher/issues/35068?page=2
I have tried the solutions that were described there and also on the official docs here.
But then I found out I don't even have the rancher-webhook pod AT ALL!!!
I am trying to find a way to deploy it but until now unsuccessfully.
If anyone can help me would be great! I appreciate any tipps


text:
Q: Counting Thrown Exceptions I have a WelcomeException class and I have thrown my exception, but now I'm trying to figure out how to count the number of times that exception is thrown and then print the count.
Here is the code:
public class WelcomeException extends Exception {

    public WelcomeException( String message ) {
         super( message );
    }

}

A: public class WelcomeException extends Exception {
    private static int count = 0;
    private static final Object countLock = new Object();

    public WelcomeException(String message)
    {
        super(message);
        synchronized(countLock)
        {
            count++;
        }
    }

    public static int getCount()
    {
        return count; //atomic. Doesn't need synchro.
    }
}

Your comment on another answer:

Now if I want to print the count in my error message to look this: I
  know I put: Error printing message {count} times how might I go about
  that? I'm sorry if this question is basic. I'm very new.

To do this, override the getMessage() method like so:
public String getMessage()
{
    return
          super.getMessage() +
          ", This exception has occurred " +
          getCount() +
          " times";
}

A: You can have a static variable (class variable) to count the times the exception is being thrown:
private static int count = 0;

and increase it in the constructor
public WelcomeException(String message) {
    super(message);
    count++;
}

so it will increase when you throw the exception like
throw new WelcomeException("...");

Then you can define a getter method:
public static int getCount() {
    return count;
}

and print the result like:
System.out.println("WelcomeException has been thrown " + WelcomeException.getCount() + " times.");


text:
Q: How to flush "socket mobile" scanner buffer in IOS development? I have made an iOS Application using the Socket Mobile SDK. When I open my view, the scanner delegate receives data scanned before the viewdidload function.
How can I send a buffer reset or flush to the scanner?
I haven't found a function or command in ScanApiHelper library.

A: Your application should be able to do whatever it wants with the incoming data. If the application isn't ready to receive scans, can't it just ignore the data and maybe ask the user to scan again?


text:
Q: ChartJS Print several points between a range of time I wanted to print several point among the time using ChartJS.
When I set the data like this:
chartData: {
                datasets: [{
                    data: [
                        {x: '10:30', y: 20},
                        {x: '11:30', y: 20},
                        {x: '11:44', y: 20},
                        {x: '13:30', y: 20},
                        {x: '14:30', y: 20},
                        {x: '11:11', y: 20},
                        {x: '12:35', y: 20},
                        {x: '10:44', y: 20}
                    ]
                }]
            }

I get a chart that look like this:

I'd like that the 11:11 point was printed between 10:30-11:30, and so with 12:25 and 10:44 points

A: You could use time cartesian axis as index axis. In this way you should achieve your goal. The data has been sorted, ascendingly.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [{
           data: [
             {x: '10:30', y: 20},
             {x: '10:44', y: 20},
             {x: '11:11', y: 20},
             {x: '11:30', y: 20},
             {x: '11:44', y: 20},
             {x: '12:35', y: 20},
             {x: '13:30', y: 20},
             {x: '14:30', y: 20},
          ],
          borderColor: 'red',
          pointRadius: 5
        }]
    },
    options: {
      plugins: {
        legend: false
      },
      scales: {
        x: {
          type: 'time',
          time: {
            unit: 'hour',
            paser: 'HH:mm'
          }
        }
      }
    }
});
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@3.0.1/build/global/luxon.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.2.0/dist/chartjs-adapter-luxon.min.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>


text:
Q: How to get the primary key to execute an select statement I'm trying to update my table using Java JDBC. But I don't have any idea how can I call my primary key using prepared statement. I try to make an USER_ID object for the column of my database but don't know how where to start. How will I determine if I already updated my Database?
INSERT
   private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
   String inputEmployee = employeeTf.getText();
   String inputDepartment = departmentTf.getText();

   if(inputEmployee.isEmpty() && inputDepartment.isEmpty()){
         JOptionPane.showMessageDialog(null, "Please fill up!");
    }
    else if(inputEmployee.isEmpty()){
        JOptionPane.showMessageDialog(null, "Please enter your username");
    }
    else if(inputDepartment.isEmpty()){
        JOptionPane.showMessageDialog(null, "Please enter your password");
    }
    else{
        String myQuery = "INSERT INTO SAMPLE (EMPLOYEENAME,DEPARTMENT) VALUES (?,?)";

        try(Connection con = DBUtilities.getConnection(DBType.JDBC);
        PreparedStatement myPs = con.prepareStatement(myQuery);
            ){

            myPs.setString(1, employeeTf.getText());
            myPs.setString(2, departmentTf.getText());

            myPs.executeUpdate();

            System.out.print("Record is inserted");

        } catch (SQLException ex) {
            DBUtilities.processException(ex);
       }
    }
   }

Here if I insert a new value it will load the new values to database.
SELECT
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
String searchEmployee = searchName.getText(); //SWING COMPONENTS
String searchDept = searchDepartment.getText();//SWING COMPONENTS

    String selectQuery = "SELECT EMPLOYEENAME,DEPARTMENT FROM SAMPLE WHERE USER_ID = ?";

    try {
        Connection con = DBUtilities.getConnection(DBType.JDBC);
        PreparedStatement myPs = con.prepareStatement(selectQuery,ResultSet.CONCUR_UPDATABLE,ResultSet.TYPE_SCROLL_INSENSITIVE);

        ResultSet myRs = myPs.executeQuery();

        while(myRs.next()){
           String name = myRs.getString(1);
           String department = myRs.getString(2);
        }

    } catch (SQLException ex) {
        DBUtilities.processException(ex);
    }
  }

SCREENSHOT

After filling out the fields for searchName and searchDepartment textfields. As you can see here I here hit the "Search" button.
I want the value of searchName and searchDepartment will print out to the textfield of employeeTf and departmentTf
How will I use the setText here?

A:  while(myRs.next()){
    String name = myRs.getString(1);
    String department = myRs.getString(2);
    nameText.setText(name);
    deptText.setText(department);
 }

i supposed nameText and deptText are the object of swing text component
if these are not accessible here..then you can create object of all field and put data from result set and return the object and use there.


text:
Q: Python - assign lists within nest to variable I am new to python and would appreciate a little help.
How does one do the following:

*

*Having converted each line within a file to a nested list,
e.g. [['line 1', 'a'], ['line 2','b']] how do I flatten the list so that each line is associated with a variable. Assume that the first member in each list, i.e. i[:][0], is known.

*Is it possible to associate more than one list with one variable, i.e. can x = [list1], [list2]?

*Having used a for loop on a list, how those one associate aspects of that list with a variable? See example below.
Example:
for i in list_1:
    if i[:][0] == 'm':
        i[2] = a
        i[3] = b
        i[4] = c

The above returns NameError, a, b, c, not defined. How does one define variables resulting from iterations in a for loop or loops in general?
Hope I was clear and succinct as I am perplexed!
Update:
To clarify:
I have a nested list, where each list within the nest holds strings. These strings are actually numbers. I wish to convert the strings to integers in order to perform arithmetic operations.
Example:
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Now, to convert each string to an integer, is abs() appropriate? How should this be implemented?
Also, to sum the third item of each list within the nest and assign the total to a variable? Should I define a function for this?
Any suggestions on how to deal with this are much appreciated!
Also, the earlier suggestions, made me realise that my thinking was creating the problem! Thanks!

A: # Answer to question 1 - just use the built-in functionality of lists.
#
# There is no need to use variables when lists let you do so much more
#   in a quick and organised fashion.
lines = []
for line in open_file:
   lines.append(line)

Since Li0liQ already answered questions 2 and 3, I'd just like to add a recommendation regarding question 3.  You really don't need to make a copy of the list via i[:] since you're just testing a value in the list.

A: No. 2: I can't see how that would be possible - surely you can only assign one value to a variable?

A: *

*Why do you want to associate each
item in a list with a variable? You
cannot tell the number of list
entries beforehand thus you do not
know the exact number of variables
to use.

*You can use tuple: x = ([list1],
[list2])

*You should write assignment vice-a-versa:
for i in list_1:
    if i[:][0] == 'm':
        a = i[2]
        b = i[3]
        c = i[4]

A: do you want:
a, b, c = i[2:5]

A: if I understand well, you have a list of lists, which can have length 2 or 1 (when the variable name is not known)
you would probably want to use a dict to store the lines
yet to mention i[:][0] means something different you wanted, it's the same as i[0] (i[:] would be a copy of list i)
list_1 = [['line 1', 'a'], ['line 2','b'], ['line 3']]
d = {}

for i in list_1:
    if len(i) != 2:
        continue
    key = i[1]
    value = i[0]
    d[key] = value

then for a, you would use d[a]
if you eventually want to convert them to variables, you can call locals().update(d)


text:
Q: Is there a good (free) benchmarking tool for Windows platform? Is there a good performance tool for benchmarking like Siege for Windows?

A: There is one by Microsoft called the Microsoft Web Application Stress Tool.
Unfortunately the download link for it seems to be broken.
Ah, found it at download.com : http://download.cnet.com/Microsoft-Web-Application-Stress-Tool/3000-2196_4-14556.html?tag=mncol
It appears that the Team System versions of Visual Studio have support for load testing as well and may be intended to replace the Web Application Stress Tool.  That's the only reason I can think of for it not to be in Microsoft Downloads anymore.


text:
Q: Sentinel while loop displaying the sentinel value when it ends total = 0
count = 0
grade = input("Enter the grade between 0 and 100 or type stop to display average: ")

while grade != "stop":
    x = float(grade)
    total += x
    count += 1
    grade = input("Enter the grade between 0 and 100 or type stop to display average: ")

average = total/count
print(f'\nYour average grade is {average}')

When I enter stop, I don't want stop to be printed next to the last input.
My current output is:

Enter the grade between 0 and 100 or type stop to display average: 10
Enter the grade between 0 and 100 or type stop to display average: 50
Enter the grade between 0 and 100 or type stop to display average: 100
Enter the grade between 0 and 100 or type stop to display average: stop
Your average grade is 53.333333333333336

A: It is always a good to practice 'don't repeat yourself' style. Also to be little defensive while taking user input - what should happen if user enters something which can't be converted into float?
One can repeatedly ask for grades and try to convert answer into float and perform calculation. If user input can't be converted into float then check whether it's 'stop' - if so print average and break else print that entered value is not allowed.
total = 0
count = 0

while True:
    grade = input('Enter the grade between 0 and 100 or type "stop" to display average: ')
    try:
        total += float(grade)
        count += 1
    except ValueError:
        if grade.lower() == 'stop':
            print(f'Your average grade is {total/count:.2f}')
            break
        else:
            print(f'Input {grade!r} is not allowed')


text:
Q: How do i modify a raw data object returned by an ExtJS AJAX proxy into a JSON object to be consumed by a Tree Store In an effort to create a treepanel, i configure it with a treestore whose AJAX proxy url receives json data i have no control of. But using Ext.data.reader.Json's transform property invokable before readRecords executes, gives an option to modify the passed raw (deserialized) data object from the AJAX proxy into a modified or a completely new data object. The transform config, gives the code snippet below:
Ext.create('Ext.data.Store', {
    model: 'User',
    proxy: {
        type: 'ajax',
        url : 'users.json',
        reader: {
            type: 'json',
            transform: {
                fn: function(data) {
                    // do some manipulation of the raw data object
                    return data;
                },
                scope: this
            }
        }
    },
});

I would please like an example on how to go about modifying the return JSON object
[
{
    "id": 3,
    "attributes":
    {},
    "name": "user_one",
    "login": "",
    "email": "user_one@ats",
    "phone": "0751223344",
    "readonly": false,
    "administrator": false,
    "password": null
},
{
    "id": 4,
    "attributes":
    {},
    "name": "user_two",
    "login": "",
    "email": "user_two@ats",
    "phone": "0751556677",
    "readonly": false,
    "administrator": false,
    "password": null
}
]

into  a JSON object fit for a treestore.
The hierarchical tree is to be rendered to show which user is under which admin using a condition administrator==true from the returned JSON, then a second AJAX request that returns that admin's users shown here.
[
    {
        "user_id": 3,
        "admin_id": 1,
    },
    {
        "user_id": 4,
        "admin_id": 2,
    }
    ]

A: Is the data nested at all? Otherwise why use a treepanel instead of a grid? To your question though, it'll depend on how you configure your treepanel but it would probably be something like this:
        transform: {
            fn: function(data) {
                var treeRecords = Ext.Array.map(data, function(i){
                    return {
                        text: i.name,
                        leaf: true
                        //any other properties you want
                    }
                });

                var treeData = {
                    root: {
                        expanded: true,
                        children: treeRecords
                    }
                };

                return treeData;
            },
            scope: this
        }


text:
Q: How to open a link in UIWebView I am having a chat application, which occasionally receives a link. On clicking that link, I can view the webpage in Safari, I would like to open that link in a UIWebview in my app instead.
I was going through this article, And its all good but it is giving in a hard coded link. I want to be able to open the link that user just clicked upon. whats the best way to achieve this?

A: Basically, you need to first ask your textView to recognize urls
textView.text = "example www.google.com"
textView.isSelectable = true
textView.dataDetectorTypes = UIDataDetectorTypes.link

But then in delegate method shouldInteractWithURL, return false so that your URL is clickable but you will not jump to Safari.
extension ViewController: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        print(url)
        //load url to YOUR web view here!
        return false
    }
}

Don't forget to set delegate!
textView.delegate = self

A: Jus setup a delegate to the UITextView and implement this function:
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    // open URL in UIWebView
}

Remember to extend the UITextViewDelegate and set the delegate to self:
@IBOutlet var textview: UITextView!
class SomeVC: UIViewController, UITextViewDelegate {
   override func viewDidLoad() {
    super.viewDidLoad()
    textview.delegate = self
   }
}


text:
Q: Fatal error in Dev-Pascal I am using Linux to write Pascal and C++ program. I have a problem. The compiler told me that I have an error :

IMPLEMENTATION expected.

Please help me. I'm still an amateur(sorry if I have a wrong dictate)`
unit GLOBAL;

interface

 CONST
  M_Text = 500;
  DoDaiDong = 80;

  SoDongManHinh: byte = 24;

  DongBatDau: byte = 1;

  ESC         = #27;
  PHome       = #71;
  PEnd        = #79;
  PPgUp       = #73;
  PPgDn       = #81;
  PLeft       = #75;
  PRight      = #77;
  PDown       = #80;
  PUp         = #72;
  PIns        = #82;
  PDel        = #83;

  F1          = #59;
  F2          = #60;
  F3          = #61;
  F4          = #62;
  F5          = #63;
  F6          = #64;
  F7          = #65;
  F8          = #66;
  F9          = #67;
  F10         = #68;
 TYPE
  T_TEXT = 0..M_TEXT;
  St80 = String[80];

 VAR

  TEXTE : ARRAY[T_TEXT] OF STRING[DoDaiDong];
  N_TEXT : T_TEXT;
  Y_TEXT : T_TEXT;

  X_TEXT : byte;

  X, Y : byte;
  Dong1, I_TEXT: Integer;

  InsOvr : (Inserte, Overwrite);

  Name : String[80];
  F: Text;

  KetThuc, VeDOS: Boolean;

  LookFlag : Boolean;

  Ch: Char;
  ChByte : Byte;
(----------------------------------------------------------------------)
Implementation

End.

A: Actually I have just compiled the given code successfully. There was only one problem. You need either to remove the line
(----------------------------------------------------------------------)
either to comment it properly (using proper brackets). The three following ways are allowed in Pascal:
{----------------------------------------------------------------------}
(*----------------------------------------------------------------------*)
//----------------------------------------------------------------------

If the error persists you need to find the problem more precisely and start a new question. The given sample does not contain other syntax errors except mentioned above.


text:
Q: OData client not rehydrating using $expand I've been using OData for a while now and am finding it a fantastic tool for setting up my server. Today I've come across something I haven't seen before and it's absolutely confounding me.
I'm using .Expand on the client to request a tree of data for a report when it's fetched. I've used the exact query in a prototype and it worked perfectly (ie fully hydrated). When I use Fiddler to send the query the response packet is perfect and includes all of the data I'm looking for.
The problem is that none of the expanded properties have been hydrated by the client (with a service reference completely up-to-date with the current service). In order to try and work out what's going on I've narrowed the scope right back to a single property and it's still not working.
var report = (serviceContext.Reports.Expand("ReportAreas").Where(r=>r.ReportID==reportID)).SingleOrDefault();

gives me the report but ReportAreas contains 0 items.  If I then try:
serviceContext.LoadProperty(report,"ReportAreas");

then ReportAreas contains 20 or so items.
It's driving me absolutely crazy because Expand is working for a different object tree (different query but same functional code) without any issues at all. Does anyone have suggestions as to how I can work out what on earth is going on here???
Update:
Some new information on this one today which is possibly wierder and suggests to me a bug in the OData client. I've discovered that only a subset of the Report objects come back without the expanded properties being populated. MOST of the reports in the database are perfectly fine. ie If I request all Reports with ReportAreas expanded (instead of refining to a single reportID) about 80-90% have a non-zero count for ReportAreas where the remainder have 0.
When a report comes back without any of the properties populated (null or 0 count) the actual property objects are being instantiated AND their properties are being set (from breakpoints in the Reference.cs file for the service reference) so, for example the ReportID, PropertyAreaID and History values belonging to ReportArea objects are set 16 times during the query resolution but the ReportAreas list has a count of 0 when it is requested. When I use _service.LoadProperty it returns 16 ReportAreas.
It smells to me of a reference mismatch in the Expand query but it is too consistent to be a simple problem. Reports that work ALWAYS work and Reports that don't work NEVER work. Really hoping someone can help me pinpoint this so I can move on to some useful coding...

A: The solution to this problem (at least until I understand it better) is to set
serviceContext.MergeOption = MergeOption.OverwriteChanges;

I've been told this relates to the client not rehydrating links if they're already being tracked. I'll update this answer if I find out more/understand the problem better.


text:
Q: missing methods from iostream I am currently trying to do some simple IO however i am running into some methods being unresolved.
#include <iostream>
#include <fstream>

std::string filename = "\random\location\blah";
std::ifstream test;  // is defined
test.open(filename);  //all others not resolvable
bool doesntwork = test.is_open();
bool alsodoesnt = test.good();
test.close();

I am currently using Mingw-w64, i have checked in MinGW\lib\gcc\x86_64-w64-mingw32\4.7.2\include\c++\fstream and they are there for members such as basic_ifstream.
(sorry for forgetting to compile)
c:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/../../../../x86_64-w64-mingw32/include/_mingw_secapi.h:47:8: error: expected unqualified-id before string constant
c:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/../../../../x86_64-w64-mingw32/include/vadefs.h:12:32: error: expected '}' before end of line
c:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/../../../../x86_64-w64-mingw32/include/vadefs.h:12:32: error: expected unqualified-id before end of line
c:\mingw\bin\../lib/gcc/x86_64-w64-mingw32/4.7.2/../../../../x86_64-w64-mingw32/include/vadefs.h:12:32: error: expected declaration before end of line

error 1:
#ifdef __cplusplus
extern "C++" {   // the error location, not sure what to do
template <bool __test, typename __dsttype>
 struct __if_array;
template <typename __dsttype>
struct __if_array <true, __dsttype> {
typedef __dsttype __type;
};
}
#endif /*__cplusplus*/

error 2-4
#ifdef __cplusplus
extern "C" {  //not sure what they wanted here
#endif


text:
Q: Wordpress Admin Tables in Post View I'm trying to add my custom Wordpress table (similar to the links table) into the "New Post" view of a custom post type. I hope that makes sense.

A: Ok. So the only way that I found to do this is wrap the WordPress table in a custom meta box. This is not ideal, because I would like to see the table span the entire container, but it works.


text:
Q: Как лучше хранить много текстовых данных в Android? Нужно сделать приложение, в котором должно быть много текстовых данных, около 120 string`ов. Каждый "пункт" должен  иметь несколько строк, например: id, name, question. Первое, что пришло в голову это засовывать строки в HashMap и там их по ключу вытаскивать. Еще в голову пришла идея с SQLite, засовывать данные туда, а потом вытаскивать. С использованием готовых БД SQLite в андроид все плохо, только через костыли (созданием новой и перезаписыванием в нее и т.д.) . Так вот вопрос, как сделать лучше? Может есть какие-то другие функции, которые мне сильно помогут, но я о них не знаю?
A: Данные то статичные или динамически подгружаются?
Если статичны, то можно просто в файле хранить xml/json.
Если динамично подгружаются, то я бы SQLite рекомендовал.


text:
Q: JEditorPane - switching back to the default editor kit If you change the editor kit of a JEditorPane to HTMLEditorKit, how do you change it back to the default (plain text) editor kit, like how it is when you first instantiate one? I want it to do this so that I can load all of the html and display it as plain text, not as formatted text, when the user switches to html mode (I'm making a dreamweaver-type app).
I tried:
DefaultEditorKit kit = new DefaultEditorKit();
page.setEditorKit(kit);

But that makes the editor pane uneditable. How can I switch the editor kit back to plain text?

A: As discussed in Editor Panes vs. Text Panes, "Be aware that the document and editor kit might change when using the setPage() method." For plain text, they recommend a DefaultStyledDocument and StyledEditorKit.


text:
Q: How to convert string parameters to integer at one time on Phoenix I have following error, when I get parameters from form, then using Multi.insert(:insert, game);
value `"12"` for `Server.Sample.Game.team_id` in `insert` does not match type :id

I got params like this. Then put team_id on Game map.
game = %Game{team_id: attrs["team_id"], ....}
Multi.new()
  |> Multi.insert(:insert, game)
  |> Repo.transaction()

Of course, I thought type error team_id should be integer, but string.
My question is if there are lot of strings, should I convert string to integer each?
I would like to find best way convert to integer each items.
Thanks.

A: As Ashley said, you can use the changeset with an custom function, like this:
def changeset(struct, params) do
  struct
  |> cast(params, [:name]) # your fields
  |> team_id_to_integer()
end

def team_id_to_integer(changeset) do
  team_id = get_field(changeset, :team_id)

  if is_bitstring(team_id) do
    put_change(changeset, :team_id, String.to_integer(team_id)
  else
    changeset
  end
end


text:
Q: How do I merge Gerrit instances without losing history We have a couple Gerrit (v2.8 and v2.9) instances in our company we want to merge into one. We want to do this without losing history regarding reviews etc. Moving the git repos won't be an issue, but when it comes to the Gerrit data it might be more complicated. Any advice on how to do this?
Thanks in advance.

A: You'll have to merge the databases by hand, which will include re-indexing at least one of the databases so you don't have ID collisions.  When you change the IDs in one of the databases, you'll have to change the data in the repository to match (all the refs/changes/* identifiers, etc).  You'll need to keep the server down during this transition.  It won't be an easy or fast task.


text:
Q: Problems converting an entity property to HiddenField in MVC I have a Supplier Entitiy that contains
ID - int
Status - string
Name - string
CreateDate- datetime

I am using the partial class method to create Data Annotations for the above Entity.as described here
[MetadataType(typeof(SupplierMetadata))]
public partial class Supplier
{
    // Note this class has nothing in it.  It's just here to add the class-level attribute.
}

public class SupplierMetadata
{
    // Name the field the same as EF named the property - "FirstName" for example.
    // Also, the type needs to match.  Basically just redeclare it.
    // Note that this is a field.  I think it can be a property too, but fields definitely should work.

    [HiddenInput]
    public Int32 ID;

    [Required]
    [UIHint("StatusList")]
    [Display(Name = "Status")]
    public string Status;

    [Required]
    [Display(Name = "Supplier Name")]
    public string Name;
}

the HiddenInput annotation throws an error saying "Attribute 'HiddenInput' is not valid on this declaration type. It is only valid on 'class, property, indexer' declarations."
Please help

A: The error states that that attribute can only be added to 'class, property, or indexer declarations'.
public Int32 ID; is none of these - it is a field.
If you change it to a property
public Int32 ID { get; set; } you will be able to decorate it with that attribute.

A: All of your properties are defined incorrectly as they are missing the get/set accessors. All properties in .NET require getter and/or setter accessors. Change your code to this:
public class SupplierMetadata
{
    [HiddenInput]
    public Int32 ID { get; set; }

    [Required]
    [UIHint("StatusList")]
    [Display(Name = "Status")]
    public string Status { get; set; }

    [Required]
    [Display(Name = "Supplier Name")]
    public string Name { get; set; }
}


text:
Q: Measure of Improvement in Math Skills from Remediation with ALEKS I am analyzing some data on ALEKS for my home institution. Specifically, I am analyzing placement scores for ALEKS where the students are allowed to take the placement test multiple times and are given the chance to improve their background (i.e. remediate) using ALEKS in between test attempts. My data set consists of the ALEKS placement test scores and the total time spent in remediation with ALEKS (for each student).
I am trying to find a ballpark estimate for the expected average rate of improvement (in terms of number of new topics learned or % increase in score) a student should see from remediation. I would like to have some benchmark with which to compare the rate of improvement from my data set. In other words, are my students doing better, worse , or about the same as expected using the remediation available via ALEKS?
Thank you,
Matthew Brenneman